diff --git a/.gitignore b/.gitignore index 537db5a3e98..986c9c558cd 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,6 @@ *.pyc *.pyo __pycache__/ + +# Exclude OS X .DS_Store files. +.DS_Store diff --git a/Accelerators/Piston/vtkDataSetToPiston.cxx b/Accelerators/Piston/vtkDataSetToPiston.cxx index 804b251d977..b4aeda156a8 100644 --- a/Accelerators/Piston/vtkDataSetToPiston.cxx +++ b/Accelerators/Piston/vtkDataSetToPiston.cxx @@ -110,7 +110,7 @@ int vtkDataSetToPiston::RequestData(vtkInformation *vtkNotUsed(request), return 1; } int association; - vtkFloatArray *inArray = vtkFloatArray::SafeDownCast( + vtkFloatArray *inArray = vtkArrayDownCast( this->GetInputArrayToProcess(0,id, association)); //this filter expects that input has point associated float scalars if (!inArray diff --git a/Accelerators/Piston/vtkPistonDataObject.h b/Accelerators/Piston/vtkPistonDataObject.h index c1ca8eecc2c..01e49fa4977 100644 --- a/Accelerators/Piston/vtkPistonDataObject.h +++ b/Accelerators/Piston/vtkPistonDataObject.h @@ -55,11 +55,10 @@ class VTKACCELERATORSPISTON_EXPORT vtkPistonDataObject : public vtkDataObject // A convenience handle to get whatever is actually stored in the reference. void * GetReferredData(); -//BTX // Description: // GPU level representation and storage this manages. vtkPistonReference *GetReference() { return this->Reference; }; -//ETX + // Description: // Shallow/deep copy the data from src into this object. virtual void ShallowCopy(vtkDataObject* src); @@ -101,12 +100,10 @@ class VTKACCELERATORSPISTON_EXPORT vtkPistonDataObject : public vtkDataObject // Set scalars range. void SetScalarsRange(double range[2]); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkPistonDataObject* GetData(vtkInformation* info); static vtkPistonDataObject* GetData(vtkInformationVector* v, int i=0); - //ETX protected: vtkPistonDataObject(); diff --git a/Accelerators/Piston/vtkPistonMapper.cxx b/Accelerators/Piston/vtkPistonMapper.cxx index 76c5d225843..0b855778e34 100644 --- a/Accelerators/Piston/vtkPistonMapper.cxx +++ b/Accelerators/Piston/vtkPistonMapper.cxx @@ -241,15 +241,15 @@ void vtkPistonMapper::RenderOnCPU() int vertsPer = vtkpiston::QueryVertsPer(id); - vtkFloatArray *normals = vtkFloatArray::SafeDownCast( + vtkFloatArray *normals = vtkArrayDownCast( od->GetPointData()->GetNormals()); if (!normals) { - normals = vtkFloatArray::SafeDownCast( + normals = vtkArrayDownCast( od->GetPointData()->GetArray("Normals")); } - vtkFloatArray *scalars = vtkFloatArray::SafeDownCast( + vtkFloatArray *scalars = vtkArrayDownCast( od->GetPointData()->GetScalars()); if (scalars) { diff --git a/CMake/CTestCustom.cmake.in b/CMake/CTestCustom.cmake.in index c985d41c1ae..b664224a3c8 100644 --- a/CMake/CTestCustom.cmake.in +++ b/CMake/CTestCustom.cmake.in @@ -94,6 +94,7 @@ SET(CTEST_CUSTOM_WARNING_EXCEPTION "vcruntime_exception.h\\(43\\): note: see declaration" "Utilities/vtktiff/" "json/json" + "shadows a member of 'OGRRawPoint'" "list.[0-9]+. : warning C4702: unreachable code" "xtree.[0-9]+. : warning C4702: unreachable code" "vector.[0-9]+. : warning C4702: unreachable code" diff --git a/CMake/FindOSPRay.cmake b/CMake/FindOSPRay.cmake new file mode 100644 index 00000000000..071ee64d252 --- /dev/null +++ b/CMake/FindOSPRay.cmake @@ -0,0 +1,77 @@ +## ======================================================================================= ## +## Copyright 2014-2015 Texas Advanced Computing Center, The University of Texas at Austin ## +## All rights reserved. ## +## ## +## Licensed under the BSD 3-Clause License, (the "License"); you may not use this file ## +## except in compliance with the License. ## +## A copy of the License is included with this software in the file LICENSE. ## +## If your copy does not contain the License, you may obtain a copy of the License at: ## +## ## +## http://opensource.org/licenses/BSD-3-Clause ## +## ## +## Unless required by applicable law or agreed to in writing, software distributed under ## +## the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ## +## KIND, either express or implied. ## +## See the License for the specific language governing permissions and limitations under ## +## limitations under the License. ## +## ======================================================================================= ## + + +############################################################################### +# Find OSPRay +# defines: +# OSPRAY_FOUND +# OSPRAY_INCLUDE_DIRS +# OSPRAY_LIBRARIES + +set(OSPRAY_INSTALL_DIR "" CACHE PATH "install location of ospray") +mark_as_advanced(OSPRAY_INSTALL_DIR) +set(OSPRAY_BUILD_DIR "" CACHE PATH "build location of ospray") +mark_as_advanced(OSPRAY_BUILD_DIR) +if (OSPRAY_INSTALL_DIR AND OSPRAY_BUILD_DIR) + message("Ignoring the ospray build location in favor of the intall location.") +endif() + +if (OSPRAY_INSTALL_DIR) + + find_package(ospray CONFIG REQUIRED HINTS ${OSPRAY_INSTALL_DIR}) + +else() + + if (OSPRAY_BUILD_DIR) + #find corresponding source directory + load_cache(${OSPRAY_BUILD_DIR} READ_WITH_PREFIX OSP_ + CMAKE_HOME_DIRECTORY + ) + set(OSPRAY_SOURCE_DIR ${OSP_CMAKE_HOME_DIRECTORY}) + + set(OSPRAY_INCLUDE_DIRS + ${OSPRAY_BUILD_DIR} + ${OSPRAY_BUILD_DIR}/include + ${OSPRAY_SOURCE_DIR} + ${OSPRAY_SOURCE_DIR}/ospray/include + ) + + set(LIB_OSPRAY_EMBREE LIB_OSPRAY_EMBREE-NOTFOUND) + find_library(LIB_OSPRAY_EMBREE NAMES ospray_embree embree + PATHS ${OSPRAY_BUILD_DIR} NO_DEFAULT_PATH) + mark_as_advanced(LIB_OSPRAY_EMBREE) + + set(LIB_OSPRAY_COMMON LIB_OSPRAY_COMMON-NOTFOUND) + find_library(LIB_OSPRAY_COMMON ospray_common + PATHS ${OSPRAY_BUILD_DIR} NO_DEFAULT_PATH) + mark_as_advanced(LIB_OSPRAY_COMMON) + + set(LIB_OSPRAY LIB_OSPRAY-NOTFOUND) + find_library(LIB_OSPRAY ospray PATHS ${OSPRAY_BUILD_DIR} NO_DEFAULT_PATH) + mark_as_advanced(LIB_OSPRAY) + + set(OSPRAY_LIBRARIES ${LIB_OSPRAY_EMBREE} ${LIB_OSPRAY_COMMON} ${LIB_OSPRAY}) + + else() + + message("Supply OSPRAY_INSTALL_DIR or OSPRAY_BUILD_DIR to find OSPRay") + + endif() + +endif() diff --git a/CMake/FindTBB.cmake b/CMake/FindTBB.cmake index c81a735e3b8..bf558b0fb9c 100644 --- a/CMake/FindTBB.cmake +++ b/CMake/FindTBB.cmake @@ -191,8 +191,8 @@ if (WIN32 AND MSVC) endforeach () endif () -# For OS X binary distribution, choose libc++ based libraries for Maverics and -# above and AppleClang +# For OS X binary distribution, choose libc++ based libraries for Mavericks (10.9) +# and above and AppleClang if (${CMAKE_SYSTEM_NAME} STREQUAL "Darwin" AND NOT ${CMAKE_SYSTEM_VERSION} LESS 13.0) set (USE_LIBCXX OFF) diff --git a/CMake/GenerateExportHeader.cmake b/CMake/GenerateExportHeader.cmake index ecfae31ef21..11e7fad88fc 100644 --- a/CMake/GenerateExportHeader.cmake +++ b/CMake/GenerateExportHeader.cmake @@ -163,10 +163,10 @@ endmacro() macro(_test_compiler_hidden_visibility) if(CMAKE_COMPILER_IS_GNUCXX) - execute_process(COMMAND ${CMAKE_C_COMPILER} ARGS --version + execute_process(COMMAND ${CMAKE_C_COMPILER} --version OUTPUT_VARIABLE _gcc_version_info ERROR_VARIABLE _gcc_version_info) - string(REGEX MATCH "[345]\\.[0-9]\\.[0-9]*" + string(REGEX MATCH "[3456]\\.[0-9]\\.[0-9]*" _gcc_version "${_gcc_version_info}") # gcc on mac just reports: "gcc (GCC) 3.3 20030304 ..." without the # patch level, handle this here: @@ -175,13 +175,13 @@ macro(_test_compiler_hidden_visibility) _gcc_version "${_gcc_version_info}") endif() - if(${_gcc_version} VERSION_LESS "4.2") + if(_gcc_version VERSION_LESS "4.2") set(GCC_TOO_OLD TRUE) endif() endif() if(CMAKE_CXX_COMPILER_ID MATCHES "Intel") - execute_process(COMMAND ${CMAKE_CXX_COMPILER} ARGS -V + execute_process(COMMAND ${CMAKE_CXX_COMPILER} -V OUTPUT_VARIABLE _intel_version_info ERROR_VARIABLE _intel_version_info) string(REGEX REPLACE ".*Version ([0-9]+(\\.[0-9]+)+).*" "\\1" diff --git a/CMake/VTKConfig.cmake.in b/CMake/VTKConfig.cmake.in index 8042930a7bd..999ae91dd89 100644 --- a/CMake/VTKConfig.cmake.in +++ b/CMake/VTKConfig.cmake.in @@ -11,6 +11,7 @@ if (VTK_USE_CXX11_FEATURES) if (CMAKE_VERSION VERSION_LESS "3.1") message(FATAL_ERROR "VTK was built with C++11 features using CMake's CXX_STANDARD_REQUIRED feature. Configuring projects this way requires a newer version of CMake. Please update to CMake 3.1 or newer") endif() + set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED 11) endif() @@ -83,6 +84,7 @@ SET(VTK_WRAP_PYTHON "@VTK_WRAP_PYTHON@") SET(VTK_WRAP_TCL "@VTK_WRAP_TCL@") SET(VTK_WRAP_JAVA "@VTK_WRAP_JAVA@") SET(VTK_QT_VERSION "@VTK_QT_VERSION@") +SET(VTK_ENABLE_KITS "@VTK_ENABLE_KITS@") # Do not add options or information here that is specific to a # particular module. Instead set _EXPORT_OPTIONS and/or diff --git a/CMake/VTKcppcheckSuppressions.txt b/CMake/VTKcppcheckSuppressions.txt index ebc8d4f8ce5..66448749383 100644 --- a/CMake/VTKcppcheckSuppressions.txt +++ b/CMake/VTKcppcheckSuppressions.txt @@ -25,26 +25,39 @@ // Similarly, these aren't really part of VTK proper. *:Utilities/KWSys/* *:Utilities/MetaIO/* +*:Utilities/DICOMParser/* // Can't fix in portable way for all VTK-supported platforms. duplicateExpression:IO/PostgreSQL/vtkPostgreSQLQuery.cxx unpreciseMathCall +// Using reallocf() would be a good solution, but it's not available on all platforms. +memleakOnRealloc + // VTK assumes IEEE 754 floats, so this warning isn't useful. memsetClassFloat // There are just too many of these to manage, so suppress them all. Can look again one day. +// 2364 warnings +variableScope +// 1109 warnings +uninitMemberVar +// 231 warnings cstyleCast -invalidscanf -noCopyConstructor +// 182 warnings noExplicitConstructor -operatorEqVarError -passedByValue -redundantAssignment -uninitMemberVar +// 169 warnings +invalidscanf +// 137 warnings unreadVariable +// 60 warnings +redundantAssignment +// 46 warnings +operatorEqVarError +// 34 warnings +noCopyConstructor +// 20 warnings useInitializationList -variableScope // Gives too many false positives. assertWithSideEffect @@ -109,15 +122,27 @@ uselessAssignmentPtrArg:Filters/General/vtkYoungsMaterialInterface.cxx uselessAssignmentPtrArg:IO/Parallel/vtkPImageWriter.cxx uselessAssignmentPtrArg:Wrapping/Tools/vtkParse.tab.c zerodiv:Filters/ParallelFlowPaths/Testing/Cxx/TestPStreamGeometry.cxx +unusedStructMember:Common/Core/vtkTypeList.txx +CastIntegerToAddressAtReturn:Geovis/Core/vtkGeoTreeNode.h + +// Not worth fixing, but not actually false positives. +passedByValue:Filters/General/vtkYoungsMaterialInterface.cxx +knownConditionTrueFalse:Rendering/OpenGL/vtkXGPUInfoList.cxx +knownConditionTrueFalse:GUISupport/Qt/QVTKWidget.cxx // There are a fair number of these, but they are probably worth working through. +// 217 warnings +postfixOperator +// 30 warnings duplInheritedMember +// 12 warnings invalidPointerCast -memleakOnRealloc +// 6 warnings noConstructor -operatorEq -postfixOperator // To investigate further... memleak:Wrapping/Tools/vtkParsePreprocess.c nullPointerRedundantCheck:IO/Exodus/vtkExodusIIReaderParser.cxx +redundantAssignment:Rendering/Volume/vtkGPUVolumeRayCastMapper.cxx: +redundantAssignment:Rendering/Volume/vtkFixedPointVolumeRayCastMapper.cxx +redundantAssignment:Filters/General/vtkBoxClipDataSet.cxx diff --git a/CMake/vtkCompilerExtras.cmake b/CMake/vtkCompilerExtras.cmake index e39bd3021f1..68c59806a3d 100644 --- a/CMake/vtkCompilerExtras.cmake +++ b/CMake/vtkCompilerExtras.cmake @@ -28,11 +28,11 @@ if(CMAKE_COMPILER_IS_GNUCXX) endif() # Now check if we can use visibility to selectively export symbols - execute_process(COMMAND ${CMAKE_C_COMPILER} ARGS --version + execute_process(COMMAND ${CMAKE_C_COMPILER} --version OUTPUT_VARIABLE _gcc_version_info ERROR_VARIABLE _gcc_version_info) - string (REGEX MATCH "[345]\\.[0-9]\\.[0-9]*" + string (REGEX MATCH "[3456]\\.[0-9]\\.[0-9]*" _gcc_version "${_gcc_version_info}") if(NOT _gcc_version) string (REGEX REPLACE ".*\\(GCC\\).*([34]\\.[0-9]).*" "\\1.0" @@ -44,7 +44,7 @@ if(CMAKE_COMPILER_IS_GNUCXX) option(VTK_USE_GCC_VISIBILITY "Use GCC visibility support if available." OFF) mark_as_advanced(VTK_USE_GCC_VISIBILITY) - if(${_gcc_version} VERSION_GREATER 4.2.0 AND BUILD_SHARED_LIBS + if(_gcc_version VERSION_GREATER 4.2.0 AND BUILD_SHARED_LIBS AND HAVE_GCC_VISIBILITY AND VTK_USE_GCC_VISIBILITY AND NOT MINGW AND NOT CYGWIN) # Should only be set if GCC is newer than 4.2.0 diff --git a/CMake/vtkCreateArrayDispatchArrayList.cmake b/CMake/vtkCreateArrayDispatchArrayList.cmake new file mode 100644 index 00000000000..def437cf4b4 --- /dev/null +++ b/CMake/vtkCreateArrayDispatchArrayList.cmake @@ -0,0 +1,213 @@ +# This file contains macros that are used by VTK to generate the list of +# default arrays used by the vtkArrayDispatch system. +# +# There are a number of CMake variables that control the final array list. At +# the high level, the following options enable/disable predefined categories of +# arrays: +# +# - VTK_DISPATCH_AOS_ARRAYS (default: ON) +# Include vtkAOSDataArrayTemplate for the basic types supported +# by VTK. This should probably not be turned off. +# - VTK_DISPATCH_SOA_ARRAYS (default: OFF) +# Include vtkSOADataArrayTemplate for the basic types supported +# by VTK. +# - VTK_DISPATCH_TYPED_ARRAYS (default: OFF) +# Include vtkTypedDataArray for the basic types supported +# by VTK. This enables the old-style in-situ vtkMappedDataArray subclasses +# to be used. +# +# At a lower level, specific arrays can be added to the list individually in +# two ways: +# +# For templated classes, set the following variables: +# - vtkArrayDispatch_containers: +# List of template class names. +# - vtkArrayDispatch_[template class name]_types: +# For the specified template class, add an entry to the array list that +# instantiates the container for each type listed here. +# - vtkArrayDispatch_[template class name]_header +# Specifies the header file to include for the specified template class. +# +# Both templated and non-templated arrays can be added using these variables: +# - vtkArrayDispatch_extra_arrays: +# List of arrays to add to the list. +# - vtkArrayDispatch_extra_headers: +# List of headers to include. +# +################################ Example ####################################### +# +# The cmake call below instantiates the array list that follows: +# +# cmake [path to VTK source] +# -DvtkArrayDispatch_containers="MyCustomArray1;MyCustomArray2" +# -DvtkArrayDispatch_MyCustomArray1_header="MyCustomArray1.h" +# -DvtkArrayDispatch_MyCustomArray1_types="float;double" +# -DvtkArrayDispatch_MyCustomArray2_header="MyCustomArray2.h" +# -DvtkArrayDispatch_MyCustomArray2_types="int;unsigned char" +# -DvtkArrayDispatch_extra_headers="ExtraHeader1.h;ExtraHeader2.h" +# -DvtkArrayDispatch_extra_arrays="ExtraArray1;ExtraArray2;ExtraArray2" +# +# Generated header: +# +# #ifndef vtkArrayDispatchArrayList_h +# #define vtkArrayDispatchArrayList_h +# +# #include "vtkTypeList.h" +# #include "MyCustomArray1.h" +# #include "MyCustomArray2.h" +# #include "vtkAOSDataArrayTemplate.h" +# #include "ExtraHeader1.h" +# #include "ExtraHeader2.h" +# +# namespace vtkArrayDispatch { +# +# typedef vtkTypeList::Unique< +# vtkTypeList_Create_21( +# MyCustomArray1, +# MyCustomArray1, +# MyCustomArray2, +# MyCustomArray2, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# vtkAOSDataArrayTemplate, +# ExtraArray1, +# ExtraArray2, +# ExtraArray2 +# ) +# >::Result Arrays; +# +# } // end namespace vtkArrayDispatch +# +# #endif // vtkArrayDispatchArrayList_h +# + +# Populate the environment so that vtk_array_dispatch_generate_array_header will +# create the array TypeList with all known array types. +macro(vtkArrayDispatch_default_array_setup) + +# The default set of scalar types: +set(vtkArrayDispatch_all_types + "char" + "double" + "float" + "int" + "long" + "long long" + "short" + "signed char" + "unsigned char" + "unsigned int" + "unsigned long" + "unsigned long long" + "unsigned short" + "vtkIdType" +) + +# For each container, define a header and a list of types: +if (VTK_DISPATCH_AOS_ARRAYS) + list(APPEND vtkArrayDispatch_containers vtkAOSDataArrayTemplate) + set(vtkArrayDispatch_vtkAOSDataArrayTemplate_header vtkAOSDataArrayTemplate.h) + set(vtkArrayDispatch_vtkAOSDataArrayTemplate_types + ${vtkArrayDispatch_all_types} + ) +endif() + +if (VTK_DISPATCH_SOA_ARRAYS) + list(APPEND vtkArrayDispatch_containers vtkSOADataArrayTemplate) + set(vtkArrayDispatch_vtkSOADataArrayTemplate_header vtkSOADataArrayTemplate.h) + set(vtkArrayDispatch_vtkSOADataArrayTemplate_types + ${vtkArrayDispatch_all_types} + ) +endif() + +if (VTK_DISPATCH_TYPED_ARRAYS) + list(APPEND vtkArrayDispatch_containers vtkTypedDataArray) + set(vtkArrayDispatch_vtkTypedDataArray_header vtkTypedDataArray.h) + set(vtkArrayDispatch_vtkTypedDataArray_types + ${vtkArrayDispatch_all_types} + ) +endif() + +endmacro() + +# Concatenates a list of strings into a single string, since string(CONCAT ...) +# is not currently available for VTK's cmake version. +# Internal method. +function(CollapseString input output) + set(temp "") + foreach(line ${input}) + set(temp ${temp}${line}) + endforeach() + set(${output} "${temp}" PARENT_SCOPE) +endfunction() + +# Create a header that declares the vtkArrayDispatch::Arrays TypeList. +macro(vtkArrayDispatch_generate_array_header result) + +set(vtkAD_headers vtkTypeList.h) +set(vtkAD_arrays) +foreach(container ${vtkArrayDispatch_containers}) + list(APPEND vtkAD_headers ${vtkArrayDispatch_${container}_header}) + foreach(value_type ${vtkArrayDispatch_${container}_types}) + list(APPEND vtkAD_arrays "${container}<${value_type}>") + endforeach() +endforeach() + +# Include externally specified headers/arrays: +list(APPEND vtkAD_headers ${vtkArrayDispatch_extra_headers}) +list(APPEND vtkAD_arrays ${vtkArrayDispatch_extra_arrays}) + +set(temp + "// This file is autogenerated by vtkCreateArrayDispatchArrayList.cmake.\n" + "// Do not edit this file. Your changes will not be saved.\n" + "\n" + "#ifndef vtkArrayDispatchArrayList_h\n" + "#define vtkArrayDispatchArrayList_h\n" + "\n" +) + +foreach(header ${vtkAD_headers}) + list(APPEND temp "#include \"${header}\"\n") +endforeach() + +list(LENGTH vtkAD_arrays vtkAD_numArrays) + +list(APPEND temp + "\n" + "namespace vtkArrayDispatch {\n" + "\n" + "typedef vtkTypeList::Unique<\n" + " vtkTypeList_Create_${vtkAD_numArrays}(\n" +) + +foreach(array ${vtkAD_arrays}) + list(APPEND temp " ${array},\n") +endforeach() + +# Remove the final comma from the array list: +CollapseString("${temp}" temp) +string(REGEX REPLACE ",\n$" "\n" temp "${temp}") + +list(APPEND temp + " )\n" + ">::Result Arrays\;\n" + "\n" + "} // end namespace vtkArrayDispatch\n" + "\n" + "#endif // vtkArrayDispatchArrayList_h\n" +) + +CollapseString("${temp}" ${result}) + +endmacro() diff --git a/CMake/vtkCreateTypeListMacros.cmake b/CMake/vtkCreateTypeListMacros.cmake new file mode 100644 index 00000000000..78a78edde62 --- /dev/null +++ b/CMake/vtkCreateTypeListMacros.cmake @@ -0,0 +1,119 @@ +# This file contains functions used to generate a list of macros that are used +# to create fixed-size typelists. See vtkTypeList for details. + +# Concatenates a list of strings into a single string, since string(CONCAT ...) +# is not currently available for VTK's cmake version. +# Internal method. +function(CollapseString input output) + set(temp "") + foreach(line ${input}) + set(temp ${temp}${line}) + endforeach() + set(${output} "${temp}" PARENT_SCOPE) +endfunction() + +# Create list of numbers, start to end _inclusive_, storing the list in result. +# Internal method +function(CreateTypeListMacros_range start end result) + set(temp) + set(i ${start}) + while(i LESS end OR i EQUAL end) + list(APPEND temp ${i}) + math(EXPR i "${i} + 1") + endwhile() + set(${result} ${temp} PARENT_SCOPE) +endfunction() + +# Creates a macro for case n = 1 +# Internal method +function(CreateTypeListMacros_create_macro_1 macroPrefix typeList nullType result) + set(temp + "#define ${macroPrefix}_1(t1) \\\n" + " ${typeList}\n" + ) + CollapseString("${temp}" temp) + set(${result} ${temp} PARENT_SCOPE) +endfunction() + +# Creates a macro for case ${num}, where ${num} > 1 +# Internal method +function(CreateTypeListMacros_create_macro num macroPrefix typeList nullType result) + set(nums) + CreateTypeListMacros_range(2 ${num} nums) + math(EXPR lastNum "${num} - 1") + set(decl "#define ${macroPrefix}_${num}") + set(macroArgs "t1") + set(lastMacroArgs "") + set(delim "") + foreach(i ${nums}) + set(macroArgs "${macroArgs}, t${i}") + set(lastMacroArgs "${lastMacroArgs}${delim}t${i}") + set(delim ", ") + endforeach() + + set(temp + "${decl}(${macroArgs}) \\\n" + " ${typeList}\n" + ) + CollapseString("${temp}" temp) + set(${result} ${temp} PARENT_SCOPE) +endfunction() + +# This function generates a header file that generates TypeList creator macros. +# +# Usage: +# HEADER = output string variable that will contain the complete header. +# MAX_SIZE = largest typelist macro to create. +# MACRO_PREFIX = prefix to use for macro names +# TYPELIST_T = type for TypeList implementation +# NULLTYPE_T = type for NullType implementation +# +# The output is generated to look like: +# +# #define ${MACRO_PREFIX}_1(t1) \ +# ${TYPELIST_T} +# #define ${MACRO_PREFIX}_2(t1, t2) \ +# ${TYPELIST_T} ) +# 2) vtk_add_python_wrapping("[ ]" ) +# +# Legacy code may call this function with a single argument. In that case, +# vtk_add_python_wrapping_library() is called internally to maintain backwards +# compatibility. +function(vtk_add_python_wrapping module_names) + if(${ARGC} EQUAL 1) + set(_legacy TRUE) + message(AUTHOR_WARNING + "Calling vtk_add_python_wrapping() with a single argument is deprecated.\n" + "Replace calls like:\n" + " vtk_add_python_wrapping(\${module})\n" + "with:\n" + " vtk_add_python_wrapping(\${module} module_srcs)\n" + " vtk_add_python_wrapping_library(\${module} module_srcs \${module})") + endif() + if("${ARGV1}" MATCHES ".+") + set(sources_var ${ARGV1}) + endif() + if("${ARGV2}" MATCHES ".+") + list(REMOVE_AT ARGN 0) + set(target ${ARGN}) + else() + set(target ${module_names}) + endif() if(NOT VTK_WRAP_PYTHON_INIT_EXE) if(TARGET vtkWrapPythonInit) set (VTK_WRAP_PYTHON_INIT_EXE vtkWrapPythonInit) @@ -16,6 +43,37 @@ function(vtk_add_python_wrapping module_name) message(FATAL_ERROR "VTK must be built with Python wrapping turned on.") endif() endif() + + set(EXTRA_PYTHON_INCLUDE_DIRS) + set(KIT_HIERARCHY_FILE) + set(VTK_WRAP_HINTS_FILES) + + foreach(module_name IN LISTS module_names) + list(APPEND EXTRA_PYTHON_INCLUDE_DIRS ${${module_name}_PYTHON_INCLUDE_DIRS}) + + if(NOT ${module_name}_EXCLUDE_FROM_WRAP_HIERARCHY) + list(APPEND KIT_HIERARCHY_FILE ${${module_name}_WRAP_HIERARCHY_FILE}) + endif() + + if(${module_name}_WRAP_HINTS AND EXISTS "${${module_name}_WRAP_HINTS}") + list(APPEND VTK_WRAP_HINTS_FILES "${${module_name}_WRAP_HINTS}") + endif() + endforeach() + + if(VTK_WRAP_HINTS_FILES) + set(VTK_WRAP_HINTS ${VTK_WRAP_HINTS_FILES}) + endif() + + vtk_wrap_python(${target}Python Python_SRCS "${module_names}") + if(_legacy) + set(_sources "${Python_SRCS}" "${extra_srcs}") + vtk_add_python_wrapping_library(${module_names} _sources ${module_names}) + else() + set(${sources_var} "${Python_SRCS}" "${extra_srcs}" PARENT_SCOPE) + endif() +endfunction() + +function(vtk_add_python_wrapping_library module srcs) # Need to add the Wrapping/Python to the include directory set(_python_include_dirs ${VTK_SOURCE_DIR}/Wrapping/Python @@ -23,57 +81,52 @@ function(vtk_add_python_wrapping module_name) ${VTK_SOURCE_DIR}/Utilities/Python ${VTK_BINARY_DIR}/Utilities/Python ${PYTHON_INCLUDE_DIRS}) + set(XY ${PYTHON_MAJOR_VERSION}${PYTHON_MINOR_VERSION}) if(NOT CMAKE_HAS_TARGET_INCLUDES) include_directories(${_python_include_dirs}) endif() - if(NOT ${module_name}_EXCLUDE_FROM_WRAP_HIERARCHY) - set(KIT_HIERARCHY_FILE ${${module_name}_WRAP_HIERARCHY_FILE}) - endif() - - string(REGEX REPLACE "^vtk" "" kit_name "${module_name}") - set(KIT ${kit_name}) - set(XY ${PYTHON_MAJOR_VERSION}${PYTHON_MINOR_VERSION}) - # Figure out the dependent PythonXYD libraries for the module - unset(extra_links) - set(EXTRA_PYTHON_INCLUDE_DIRS ${${module_name}_PYTHON_INCLUDE_DIRS}) - foreach(dep ${${module_name}_DEPENDS}) - if(NOT "${module_name}" STREQUAL "${dep}" AND TARGET ${dep}PythonD) + set(extra_links) + foreach(dep IN LISTS ${module}_DEPENDS) + if(NOT "${module}" STREQUAL "${dep}" AND TARGET ${dep}PythonD) list(APPEND extra_links ${dep}PythonD) endif() endforeach() - if(${module_name}_WRAP_HINTS AND EXISTS "${${module_name}_WRAP_HINTS}") - set(VTK_WRAP_HINTS "${${module_name}_WRAP_HINTS}") - endif() - - vtk_wrap_python(${module_name}Python Python_SRCS ${module_name}) - vtk_add_library(${module_name}PythonD ${Python_SRCS} ${extra_srcs}) - get_property(output_name TARGET ${module_name}PythonD PROPERTY OUTPUT_NAME) + vtk_add_library(${module}PythonD ${${srcs}}) + get_property(output_name TARGET ${module}PythonD PROPERTY OUTPUT_NAME) string(REPLACE "PythonD" "Python${XY}D" output_name "${output_name}") - set_property(TARGET ${module_name}PythonD PROPERTY OUTPUT_NAME ${output_name}) + set_property(TARGET ${module}PythonD PROPERTY OUTPUT_NAME ${output_name}) if(CMAKE_HAS_TARGET_INCLUDES) - set_property(TARGET ${module_name}PythonD APPEND + set_property(TARGET ${module}PythonD APPEND PROPERTY INCLUDE_DIRECTORIES ${_python_include_dirs}) endif() - if(${module_name}_IMPLEMENTS) - set_property(TARGET ${module_name}PythonD PROPERTY COMPILE_DEFINITIONS - "${module_name}_AUTOINIT=1(${module_name})") - endif() - target_link_libraries(${module_name}PythonD LINK_PUBLIC ${module_name} + target_link_libraries(${module}PythonD LINK_PUBLIC vtkWrappingPythonCore ${extra_links} ${VTK_PYTHON_LIBRARIES}) if (MSVC) - set_target_properties(${module_name}PythonD + set_target_properties(${module}PythonD PROPERTIES STATIC_LIBRARY_FLAGS ${CMAKE_MODULE_LINKER_FLAGS}) endif() - _vtk_add_python_module(${module_name}Python ${module_name}PythonInit.cxx) - target_link_libraries(${module_name}Python ${module_name}PythonD) + foreach (submodule IN LISTS ARGN) + if(${submodule}_IMPLEMENTS) + set_property(TARGET ${module}PythonD APPEND PROPERTY COMPILE_DEFINITIONS + "${submodule}_AUTOINIT=1(${submodule})") + endif() + target_link_libraries(${module}PythonD LINK_PUBLIC ${submodule}) + endforeach () + + set(prefix ${module}) + if(_${module}_is_kit) + set(prefix ${prefix}${VTK_KIT_SUFFIX}) + endif() + _vtk_add_python_module(${module}Python ${prefix}PythonInit.cxx) + target_link_libraries(${module}Python ${module}PythonD) if(CMAKE_HAS_TARGET_INCLUDES) - set_property(TARGET ${module_name}Python APPEND + set_property(TARGET ${module}Python APPEND PROPERTY INCLUDE_DIRECTORIES ${_python_include_dirs}) endif() endfunction() @@ -143,6 +196,22 @@ endfunction() # the header file should link against (using target_link_libraries()). function(vtk_write_python_modules_header_for_wrapped_modules filename out_var) get_property(python_wrapped_modules GLOBAL PROPERTY VTK_PYTHON_WRAPPED) + if(VTK_ENABLE_KITS) + # Process VTK_PYTHON_WRAPPED to generate a list of Python wrapped kits and + # modules. + set(_kits_and_modules) + foreach(module IN LISTS python_wrapped_modules) + vtk_module_load("${module}") + if(${module}_KIT) + set(kit ${${module}_KIT}) + list(APPEND _kits_and_modules ${kit}Kit) + else() + list(APPEND _kits_and_modules ${module}) + endif() + endforeach() + list(REMOVE_DUPLICATES _kits_and_modules) + set(python_wrapped_modules ${_kits_and_modules}) + endif() vtk_write_python_modules_header( "${filename}" ${python_wrapped_modules}) set (dependencies) diff --git a/CMake/vtkWrapPython.cmake b/CMake/vtkWrapPython.cmake index e550a6c0a69..eecb44c2dc7 100644 --- a/CMake/vtkWrapPython.cmake +++ b/CMake/vtkWrapPython.cmake @@ -36,12 +36,12 @@ macro(VTK_WRAP_PYTHON3 TARGET SRC_LIST_NAME SOURCES) # collect the common wrapper-tool arguments set(_common_args) - if(VTK_WRAP_HINTS) - set(_common_args "${_common_args}--hints \"${VTK_WRAP_HINTS}\"\n") - endif() - if(KIT_HIERARCHY_FILE) - set(_common_args "${_common_args}--types \"${KIT_HIERARCHY_FILE}\"\n") - endif() + foreach(file IN LISTS VTK_WRAP_HINTS) + set(_common_args "${_common_args}--hints \"${file}\"\n") + endforeach() + foreach(file IN LISTS KIT_HIERARCHY_FILE) + set(_common_args "${_common_args}--types \"${file}\"\n") + endforeach() if(NOT CMAKE_VERSION VERSION_LESS 3.1 AND NOT VTK_ENABLE_KITS) # write wrapper-tool arguments to a file @@ -56,13 +56,21 @@ $<$>: ") else() # all the include directories - string(REGEX REPLACE "Python\$" "" module "${TARGET}") - if(${module}_INCLUDE_DIRS) - set(TMP_INCLUDE_DIRS ${${module}_INCLUDE_DIRS}) - elseif(VTK_WRAP_INCLUDE_DIRS) - set(TMP_INCLUDE_DIRS ${VTK_WRAP_INCLUDE_DIRS}) + set(TMP_INCLUDE_DIRS) + set(_modules ${ARGN}) + if(NOT _modules) + string(REGEX REPLACE "Python\$" "" module "${TARGET}") + set(_modules ${module}) + endif() + foreach(module IN LISTS ${_modules}) + if(${module}_INCLUDE_DIRS) + list(APPEND TMP_INCLUDE_DIRS ${${module}_INCLUDE_DIRS}) + endif() + endforeach() + if(VTK_WRAP_INCLUDE_DIRS) + list(APPEND TMP_INCLUDE_DIRS ${VTK_WRAP_INCLUDE_DIRS}) else() - set(TMP_INCLUDE_DIRS ${VTK_INCLUDE_DIRS}) + list(APPEND TMP_INCLUDE_DIRS ${VTK_INCLUDE_DIRS}) endif() if(EXTRA_PYTHON_INCLUDE_DIRS) list(APPEND TMP_INCLUDE_DIRS ${EXTRA_PYTHON_INCLUDE_DIRS}) @@ -220,11 +228,13 @@ macro(vtk_find_header header include_dirs full_path) endforeach() endmacro() -# Macro that just takes the name of the module, figure the rest out from there. -macro(vtk_wrap_python TARGET SRC_LIST_NAME module) +# Macro that just takes the a list of module names, figure the rest out from there. +macro(vtk_wrap_python TARGET SRC_LIST_NAME) # List of all headers to wrap. set(headers_to_wrap) + foreach(module ${ARGN}) + # Decide what to do for each header. foreach(header ${${module}_HEADERS}) # Everything in this block is for headers that will be wrapped. @@ -241,6 +251,8 @@ macro(vtk_wrap_python TARGET SRC_LIST_NAME module) endif() endforeach() + endforeach() # end ARGN loop + # Delegate to vtk_wrap_python3 - vtk_wrap_python3(${TARGET} ${SRC_LIST_NAME} "${headers_to_wrap}") + vtk_wrap_python3(${TARGET} ${SRC_LIST_NAME} "${headers_to_wrap}" ${ARGN}) endmacro() diff --git a/CMake/vtkiOS.cmake b/CMake/vtkiOS.cmake index cf091e4b906..f959b1d4bc5 100644 --- a/CMake/vtkiOS.cmake +++ b/CMake/vtkiOS.cmake @@ -82,7 +82,17 @@ mark_as_advanced( # expose some module options option(Module_vtkRenderingOpenGL2 "Include Polygonal Rendering Support" ON) -option(Module_vtkInteractionWidgets "Include INteractionWidgets module" OFF) +option(Module_vtkInteractionWidgets "Include InteractionWidgets module" OFF) +option(Module_vtkIOXML "Include IO/XML Module" OFF) +option(Module_vtkFiltersModeling "Turn on or off this module" OFF) +option(Module_vtkFiltersSources "Turn on or off this module" OFF) +option(Module_vtkIOGeometry "Turn on or off this module" OFF) +option(Module_vtkIOLegacy "Turn on or off this module" OFF) +option(Module_vtkIOImage "Turn on or off this module" OFF) +option(Module_vtkIOPLY "Turn on or off this module" OFF) +option(Module_vtkIOInfovis "Turn on or off this module" OFF) +option(Module_vtkRenderingFreeType "Turn on or off this module" OFF) + # add volume rendering option for ES 3.0 if (OPENGL_ES_VERSION STREQUAL "3.0" AND Module_vtkRenderingOpenGL2) @@ -105,21 +115,16 @@ set(ios_cmake_flags -DVTK_Group_Qt:BOOL=OFF -DVTK_Group_Tk:BOOL=OFF -DVTK_Group_Web:BOOL=OFF -# -DModule_vtkFiltersCore:BOOL=ON -# -DModule_vtkFiltersModeling:BOOL=ON -# -DModule_vtkFiltersSources:BOOL=ON -# -DModule_vtkFiltersGeometry:BOOL=ON -# -DModule_vtkIOGeometry:BOOL=ON -# -DModule_vtkIOLegacy:BOOL=ON -# -DModule_vtkIOImage:BOOL=ON -# -DModule_vtkIOPLY:BOOL=ON -# -DModule_vtkIOInfovis:BOOL=ON -# -DModule_vtkImagingCore:BOOL=ON -# -DModule_vtkInteractionStyle:BOOL=ON -# -DModule_vtkParallelCore:BOOL=ON -# -DModule_vtkRenderingFreeType:BOOL=OFF -DModule_vtkRenderingOpenGL2:BOOL=${Module_vtkRenderingOpenGL2} -DModule_vtkInteractionWidgets:BOOL=${Module_vtkInteractionWidgets} + -DModule_vtkFiltersModeling:BOOL=${Module_vtkFiltersModeling} + -DModule_vtkFiltersSources:BOOL=${Module_vtkFiltersSources} + -DModule_vtkIOGeometry:BOOL=${Module_vtkIOGeometry} + -DModule_vtkIOLegacy:BOOL=${Module_vtkIOLegacy} + -DModule_vtkIOImage:BOOL=${Module_vtkIOImage} + -DModule_vtkIOPLY:BOOL=${Module_vtkIOPLY} + -DModule_vtkIOInfovis:BOOL=${Module_vtkIOInfovis} + -DModule_vtkRenderingFreeType:BOOL=${Module_vtkRenderingFreeType} ) if (Module_vtkRenderingOpenGL2) @@ -150,6 +155,17 @@ macro(crosscompile target toolchain_file archs) -DCMAKE_INSTALL_PREFIX:PATH=${INSTALL_DIR}/${target} ${ios_cmake_flags} ) + # + # add an INSTALL_ALLWAYS since we want it and cmake lacks it + # + ExternalProject_Get_Property(${target} binary_dir) + _ep_get_build_command(${target} INSTALL cmd) + ExternalProject_Add_Step(${target} always-install + COMMAND ${cmd} + WORKING_DIRECTORY ${binary_dir} + DEPENDEES build install + ALWAYS 1 + ) endmacro() crosscompile(vtk-ios-simulator diff --git a/CMakeLists.txt b/CMakeLists.txt index fc7e357510f..3ac2e22467d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,6 +28,17 @@ endif() project(VTK) +if (NOT CMAKE_VERSION VERSION_LESS "3.1") + option(VTK_USE_CXX11_FEATURES "Build VTK using C++11 features (if available)" + OFF) +else() + set(VTK_USE_CXX11_FEATURES OFF) +endif() +if (VTK_USE_CXX11_FEATURES) + set(CMAKE_CXX_STANDARD 11) + set(CMAKE_CXX_STANDARD_REQUIRED 11) +endif() + # Objective-C++ compile flags. # CMake has no equivalent of CMAKE_CXX_FLAGS for Objective-C++ (bug #4756) # so we provide this in case the user needs to specify flags specifically @@ -455,9 +466,6 @@ set(VTK_PYTHON_VERSION 2 CACHE STRING # Add the option for build the Python wrapping to VTK. option(VTK_WRAP_JAVA "Should VTK Java wrapping be built?" OFF) -# FIXME: This variable should not be necessary once we are done -set(VTK_IGNORE_BTX ON CACHE INTERNAL "VTK modular always ignores BTX") - # Force reset of hints file location in cache if it was moved if(VTK_WRAP_HINTS) if(NOT EXISTS ${VTK_WRAP_HINTS}) diff --git a/Charts/Core/Testing/Cxx/TestMultipleScalarsToColors.cxx b/Charts/Core/Testing/Cxx/TestMultipleScalarsToColors.cxx index 2b800a051a0..26f0ba0aef6 100644 --- a/Charts/Core/Testing/Cxx/TestMultipleScalarsToColors.cxx +++ b/Charts/Core/Testing/Cxx/TestMultipleScalarsToColors.cxx @@ -29,6 +29,7 @@ #include "vtkPiecewiseControlPointsItem.h" #include "vtkPiecewiseFunction.h" #include "vtkPiecewiseFunctionItem.h" +#include "vtkRenderingOpenGLConfigure.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" @@ -152,7 +153,14 @@ int TestMultipleScalarsToColors(int , char * []) // OpenGL 1.2, but further granularity must be added to the device to detect // down to there. For now disable is < OpenGL 2, should fix Mesa segfaults. renwin->Render(); - if (actor->GetContext()->GetDevice()->IsA("vtkOpenGL2ContextDevice2D")) + +#if defined(VTK_OPENGL2) + bool openGL2Backend = true; +#else + bool openGL2Backend = false; +#endif + + if (openGL2Backend || actor->GetContext()->GetDevice()->IsA("vtkOpenGL2ContextDevice2D")) { iren->Initialize(); iren->Start(); diff --git a/Charts/Core/Testing/Cxx/TestScalarsToColors.cxx b/Charts/Core/Testing/Cxx/TestScalarsToColors.cxx index 039b7e34129..fc31a5977aa 100644 --- a/Charts/Core/Testing/Cxx/TestScalarsToColors.cxx +++ b/Charts/Core/Testing/Cxx/TestScalarsToColors.cxx @@ -24,6 +24,7 @@ #include "vtkLookupTable.h" #include "vtkPiecewiseControlPointsItem.h" #include "vtkPiecewiseFunction.h" +#include "vtkRenderingOpenGLConfigure.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" @@ -75,7 +76,14 @@ int TestScalarsToColors(int , char * []) // Finally render the scene and compare the image to a reference image view->GetRenderWindow()->SetMultiSamples(1); - if (view->GetContext()->GetDevice()->IsA("vtkOpenGL2ContextDevice2D")) + +#if defined(VTK_OPENGL2) + bool openGL2Backend = true; +#else + bool openGL2Backend = false; +#endif + + if (openGL2Backend || view->GetContext()->GetDevice()->IsA("vtkOpenGL2ContextDevice2D")) { view->GetInteractor()->Initialize(); view->GetInteractor()->Start(); diff --git a/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_1.png.md5 b/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_1.png.md5 new file mode 100644 index 00000000000..ba5fa73ddf4 --- /dev/null +++ b/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_1.png.md5 @@ -0,0 +1 @@ +2e4eadc6096c5dbcebe721b1d7f2033e diff --git a/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_2.png.md5 b/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_2.png.md5 new file mode 100644 index 00000000000..eb77374c8f5 --- /dev/null +++ b/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_2.png.md5 @@ -0,0 +1 @@ +078ecabb9e6f6fcfc4ffc1797963a2a7 diff --git a/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_3.png.md5 b/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_3.png.md5 new file mode 100644 index 00000000000..499a2d26c03 --- /dev/null +++ b/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_3.png.md5 @@ -0,0 +1 @@ +68914afd7f6bc94206651280a2fc19d0 diff --git a/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_4.png.md5 b/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_4.png.md5 new file mode 100644 index 00000000000..7cf6d077ded --- /dev/null +++ b/Charts/Core/Testing/Data/Baseline/TestScalarsToColors_4.png.md5 @@ -0,0 +1 @@ +1fbe4eaeb342d08407c48d0fc8cf3a25 diff --git a/Charts/Core/vtkAxis.h b/Charts/Core/vtkAxis.h index 6cc9b63950d..c9a1645b28a 100644 --- a/Charts/Core/vtkAxis.h +++ b/Charts/Core/vtkAxis.h @@ -433,7 +433,6 @@ class VTKCHARTSCORE_EXPORT vtkAxis : public vtkContextItem // is TICK_SIMPLE. vtkStdString GenerateSimpleLabel(double val); -//BTX protected: vtkAxis(); ~vtkAxis(); @@ -602,7 +601,6 @@ class VTKCHARTSCORE_EXPORT vtkAxis : public vtkContextItem // Return true if the value is in range, false otherwise. bool InRange(double value); -//ETX }; #endif //vtkAxis_h diff --git a/Charts/Core/vtkChart.h b/Charts/Core/vtkChart.h index 4d208d1c360..0e200175bcb 100644 --- a/Charts/Core/vtkChart.h +++ b/Charts/Core/vtkChart.h @@ -44,7 +44,6 @@ class VTKCHARTSCORE_EXPORT vtkChart : public vtkContextItem vtkTypeMacro(vtkChart, vtkContextItem); virtual void PrintSelf(ostream &os, vtkIndent indent); -//BTX // Description: // Enum of the available chart types enum { @@ -81,7 +80,6 @@ class VTKCHARTSCORE_EXPORT vtkChart : public vtkContextItem enum EventIds { UpdateRange = 1002 }; -//ETX // Description: // Paint event for the chart, called whenever the chart needs to be drawn diff --git a/Charts/Core/vtkChartBox.cxx b/Charts/Core/vtkChartBox.cxx index 38d22d50dfa..8acb519095d 100644 --- a/Charts/Core/vtkChartBox.cxx +++ b/Charts/Core/vtkChartBox.cxx @@ -123,7 +123,7 @@ void vtkChartBox::Update() for (int i = 0; i < nbCols; ++i) { vtkDataArray* array = - vtkDataArray::SafeDownCast(table->GetColumnByName( + vtkArrayDownCast(table->GetColumnByName( this->VisibleColumns->GetValue(i))); if (array) { @@ -172,7 +172,7 @@ bool vtkChartBox::Paint(vtkContext2D *painter) this->AnnotationLink->GetMTime() > this->Storage->Plot->GetMTime()) { vtkSelectionNode *node = selection->GetNode(0); - idArray = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + idArray = vtkArrayDownCast(node->GetSelectionList()); this->Storage->Plot->SetSelection(idArray); } } diff --git a/Charts/Core/vtkChartBox.h b/Charts/Core/vtkChartBox.h index 16ab529cd2f..e0a4e148b85 100644 --- a/Charts/Core/vtkChartBox.h +++ b/Charts/Core/vtkChartBox.h @@ -102,7 +102,6 @@ class VTKCHARTSCORE_EXPORT vtkChartBox : public vtkChart // only contain one plot, this will replace the previous plot. virtual void SetPlot(vtkPlotBox *plot); -//BTX // Description: // Return true if the supplied x, y coordinate is inside the item. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -119,8 +118,6 @@ class VTKCHARTSCORE_EXPORT vtkChartBox : public vtkChart // Mouse button release event. virtual bool MouseButtonReleaseEvent(const vtkContextMouseEvent &mouse); -//ETX - // Description: // Set the vtkTooltipItem object that will be displayed by the chart. virtual void SetTooltip(vtkTooltipItem *tooltip); @@ -135,7 +132,7 @@ class VTKCHARTSCORE_EXPORT vtkChartBox : public vtkChart const vtkVector2d &, vtkIdType, vtkPlot*, vtkIdType segmentIndex = -1); -//BTX + protected: vtkChartBox(); ~vtkChartBox(); @@ -187,7 +184,7 @@ class VTKCHARTSCORE_EXPORT vtkChartBox : public vtkChart private: vtkChartBox(const vtkChartBox &); // Not implemented. void operator=(const vtkChartBox &); // Not implemented. -//ETX + }; // Description: diff --git a/Charts/Core/vtkChartParallelCoordinates.cxx b/Charts/Core/vtkChartParallelCoordinates.cxx index 14a65dc637b..e3bf7c7103e 100644 --- a/Charts/Core/vtkChartParallelCoordinates.cxx +++ b/Charts/Core/vtkChartParallelCoordinates.cxx @@ -139,7 +139,8 @@ void vtkChartParallelCoordinates::Update() { double range[2]; vtkDataArray* array = - vtkDataArray::SafeDownCast(table->GetColumnByName(this->VisibleColumns->GetValue(i))); + vtkArrayDownCast(table->GetColumnByName( + this->VisibleColumns->GetValue(i))); if (array) { array->GetRange(range); @@ -181,7 +182,8 @@ bool vtkChartParallelCoordinates::Paint(vtkContext2D *painter) { vtkSelectionNode *node = selection->GetNumberOfNodes() > 0? selection->GetNode(0) : NULL; - idArray = node? vtkIdTypeArray::SafeDownCast(node->GetSelectionList()) : NULL; + idArray = node? vtkArrayDownCast(node->GetSelectionList()) + : NULL; this->Storage->Plot->SetSelection(idArray); } } diff --git a/Charts/Core/vtkChartParallelCoordinates.h b/Charts/Core/vtkChartParallelCoordinates.h index 5d444a77525..d568a9d8713 100644 --- a/Charts/Core/vtkChartParallelCoordinates.h +++ b/Charts/Core/vtkChartParallelCoordinates.h @@ -92,7 +92,6 @@ class VTKCHARTSCORE_EXPORT vtkChartParallelCoordinates : public vtkChart // only contain one plot, this will replace the previous plot. virtual void SetPlot(vtkPlotParallelCoordinates *plot); -//BTX // Description: // Return true if the supplied x, y coordinate is inside the item. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -120,9 +119,7 @@ class VTKCHARTSCORE_EXPORT vtkChartParallelCoordinates : public vtkChart // Description: // Mouse wheel event, positive delta indicates forward movement of the wheel. virtual bool MouseWheelEvent(const vtkContextMouseEvent &mouse, int delta); -//ETX -//BTX protected: vtkChartParallelCoordinates(); ~vtkChartParallelCoordinates(); @@ -154,7 +151,7 @@ class VTKCHARTSCORE_EXPORT vtkChartParallelCoordinates : public vtkChart private: vtkChartParallelCoordinates(const vtkChartParallelCoordinates &); // Not implemented. void operator=(const vtkChartParallelCoordinates &); // Not implemented. -//ETX + }; #endif //vtkChartParallelCoordinates_h diff --git a/Charts/Core/vtkChartPie.h b/Charts/Core/vtkChartPie.h index 219e510a56c..b460737db88 100644 --- a/Charts/Core/vtkChartPie.h +++ b/Charts/Core/vtkChartPie.h @@ -78,7 +78,6 @@ class VTKCHARTSCORE_EXPORT vtkChartPie : public vtkChart // Set the vtkContextScene for the item, always set for an item in a scene. virtual void SetScene(vtkContextScene *scene); -//BTX // Description: // Return true if the supplied x, y coordinate is inside the item. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -106,9 +105,7 @@ class VTKCHARTSCORE_EXPORT vtkChartPie : public vtkChart // Description: // Mouse wheel event, positive delta indicates forward movement of the wheel. virtual bool MouseWheelEvent(const vtkContextMouseEvent &mouse, int delta); -//ETX -//BTX protected: vtkChartPie(); ~vtkChartPie(); @@ -141,7 +138,6 @@ class VTKCHARTSCORE_EXPORT vtkChartPie : public vtkChart // Private implementation details vtkChartPiePrivate *Private; -//ETX }; #endif //vtkChartPie_h diff --git a/Charts/Core/vtkChartXY.cxx b/Charts/Core/vtkChartXY.cxx index b85b1e11f86..d8ef39c1b85 100644 --- a/Charts/Core/vtkChartXY.cxx +++ b/Charts/Core/vtkChartXY.cxx @@ -223,7 +223,7 @@ void vtkChartXY::Update() vtkSelectionNode *node = selection->GetNumberOfNodes() > 0? selection->GetNode(0) : NULL; vtkIdTypeArray *idArray = node? - vtkIdTypeArray::SafeDownCast(node->GetSelectionList()) : NULL; + vtkArrayDownCast(node->GetSelectionList()) : NULL; std::vector::iterator it = this->ChartPrivate->plots.begin(); for ( ; it != this->ChartPrivate->plots.end(); ++it) @@ -238,7 +238,7 @@ void vtkChartXY::Update() { vtkSelectionNode *node = selection->GetNode(i); vtkIdTypeArray *idArray = - vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkArrayDownCast(node->GetSelectionList()); vtkPlot *selectionPlot = vtkPlot::SafeDownCast(node->GetProperties()->Get(vtkSelectionNode::PROP())); // Now iterate through the plots to update selection data @@ -261,7 +261,7 @@ void vtkChartXY::Update() { vtkSelectionNode *node = selection->GetNode(i); vtkIdTypeArray *selectedColumns = - vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkArrayDownCast(node->GetSelectionList()); vtkIdType* ptr = reinterpret_cast(selectedColumns->GetVoidPointer(0)); for (vtkIdType j = 0; j < selectedColumns->GetNumberOfTuples(); ++j) { @@ -2062,7 +2062,7 @@ bool vtkChartXY::MouseButtonReleaseEvent(const vtkContextMouseEvent &mouse) selection->GetNode(0) : NULL; if (node) { - oldSelection->DeepCopy(vtkIdTypeArray::SafeDownCast(node->GetSelectionList())); + oldSelection->DeepCopy(vtkArrayDownCast(node->GetSelectionList())); } } vtkNew plotSelection; diff --git a/Charts/Core/vtkChartXY.h b/Charts/Core/vtkChartXY.h index 09c20d62cdc..32f7c544cbc 100644 --- a/Charts/Core/vtkChartXY.h +++ b/Charts/Core/vtkChartXY.h @@ -211,7 +211,6 @@ class VTKCHARTSCORE_EXPORT vtkChartXY : public vtkChart vtkIdType, vtkPlot*, vtkIdType segmentIndex = -1); -//BTX // Description: // Return true if the supplied x, y coordinate is inside the item. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -243,9 +242,7 @@ class VTKCHARTSCORE_EXPORT vtkChartXY : public vtkChart // Description: // Key press event. virtual bool KeyPressEvent(const vtkContextKeyEvent &key); -//ETX -//BTX protected: vtkChartXY(); ~vtkChartXY(); @@ -378,7 +375,6 @@ class VTKCHARTSCORE_EXPORT vtkChartXY : public vtkChart vtkVector2f &min, vtkVector2f &max, vtkContextPolygon &polygon); -//ETX }; // Description: diff --git a/Charts/Core/vtkChartXYZ.cxx b/Charts/Core/vtkChartXYZ.cxx index bd4840e125f..9d0078afef0 100644 --- a/Charts/Core/vtkChartXYZ.cxx +++ b/Charts/Core/vtkChartXYZ.cxx @@ -219,7 +219,7 @@ void vtkChartXYZ::Update() { vtkSelectionNode *node = selection->GetNode(0); vtkIdTypeArray *idArray = - vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkArrayDownCast(node->GetSelectionList()); for (size_t i = 0; i < this->Plots.size(); ++i) { this->Plots[i]->SetSelection(idArray); diff --git a/Charts/Core/vtkChartXYZ.h b/Charts/Core/vtkChartXYZ.h index 52974ccb498..7492a42fc6c 100644 --- a/Charts/Core/vtkChartXYZ.h +++ b/Charts/Core/vtkChartXYZ.h @@ -117,7 +117,6 @@ class VTKCHARTSCORE_EXPORT vtkChartXYZ : public vtkContextItem // properly render the data within the chart. void RecalculateTransform(); - //BTX // Description: // Returns true if the transform is interactive, false otherwise. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -139,7 +138,6 @@ class VTKCHARTSCORE_EXPORT vtkChartXYZ : public vtkContextItem // different 2D views. "x" changes the view so we're looking down the X axis. // Similar behavior occurs for "y" or "z". virtual bool KeyPressEvent(const vtkContextKeyEvent &key); - //ETX protected: vtkChartXYZ(); diff --git a/Charts/Core/vtkPiecewisePointHandleItem.h b/Charts/Core/vtkPiecewisePointHandleItem.h index cfa7888545d..d9ffd135de5 100644 --- a/Charts/Core/vtkPiecewisePointHandleItem.h +++ b/Charts/Core/vtkPiecewisePointHandleItem.h @@ -81,7 +81,6 @@ class VTKCHARTSCORE_EXPORT vtkPiecewisePointHandleItem : public vtkContextItem // Mouse button release event. virtual bool MouseButtonReleaseEvent(const vtkContextMouseEvent &mouse); -//BTX protected: vtkPiecewisePointHandleItem(); ~vtkPiecewisePointHandleItem(); @@ -103,7 +102,7 @@ class VTKCHARTSCORE_EXPORT vtkPiecewisePointHandleItem : public vtkContextItem class InternalPiecewisePointHandleInfo; InternalPiecewisePointHandleInfo* Internal; -//ETX + }; #endif //vtkPiecewisePointHandleItem_h diff --git a/Charts/Core/vtkPlot.h b/Charts/Core/vtkPlot.h index 16099b4d595..7015cf2874f 100644 --- a/Charts/Core/vtkPlot.h +++ b/Charts/Core/vtkPlot.h @@ -87,7 +87,6 @@ class VTKCHARTSCORE_EXPORT vtkPlot : public vtkContextItem virtual void SetTooltipPrecision(int precision); virtual int GetTooltipPrecision(); -//BTX // Description: // Generate and return the tooltip label string for this plot // The segmentIndex parameter is ignored, except for vtkPlotBar @@ -110,7 +109,6 @@ class VTKCHARTSCORE_EXPORT vtkPlot : public vtkContextItem // Description: // Select all points in the specified polygon. virtual bool SelectPointsInPolygon(const vtkContextPolygon &polygon); -//ETX // Description: // Set the plot color @@ -296,15 +294,12 @@ class VTKCHARTSCORE_EXPORT vtkPlot : public vtkContextItem // Default implementation is empty. virtual void UpdateCache() {} -//BTX // Description: // A General setter/getter that should be overridden. It can silently drop // options, case is important virtual void SetProperty(const vtkStdString &property, const vtkVariant &var); virtual vtkVariant GetProperty(const vtkStdString &property); -//ETX -//BTX protected: vtkPlot(); ~vtkPlot(); @@ -392,7 +387,6 @@ class VTKCHARTSCORE_EXPORT vtkPlot : public vtkContextItem vtkPlot(const vtkPlot &); // Not implemented. void operator=(const vtkPlot &); // Not implemented. -//ETX }; #endif //vtkPlot_h diff --git a/Charts/Core/vtkPlot3D.cxx b/Charts/Core/vtkPlot3D.cxx index e0b513104fa..862b12cb449 100644 --- a/Charts/Core/vtkPlot3D.cxx +++ b/Charts/Core/vtkPlot3D.cxx @@ -134,11 +134,11 @@ void vtkPlot3D::SetInputData(vtkTable *input, const vtkStdString &xName, { // Copy the points into our data structure for rendering - pack x, y, z... vtkDataArray *xArr = - vtkDataArray::SafeDownCast(input->GetColumnByName(xName.c_str())); + vtkArrayDownCast(input->GetColumnByName(xName.c_str())); vtkDataArray *yArr = - vtkDataArray::SafeDownCast(input->GetColumnByName(yName.c_str())); + vtkArrayDownCast(input->GetColumnByName(yName.c_str())); vtkDataArray *zArr = - vtkDataArray::SafeDownCast(input->GetColumnByName(zName.c_str())); + vtkArrayDownCast(input->GetColumnByName(zName.c_str())); // Ensure that we have valid data arrays, and that they are of the same length. assert(xArr); @@ -190,7 +190,7 @@ void vtkPlot3D::SetInputData(vtkTable *input, const vtkStdString &xName, this->SetInputData(input, xName, yName, zName); vtkDataArray *colorArr = - vtkDataArray::SafeDownCast(input->GetColumnByName(colorName.c_str())); + vtkArrayDownCast(input->GetColumnByName(colorName.c_str())); this->SetColors(colorArr); } @@ -230,9 +230,9 @@ void vtkPlot3D::SetColors(vtkDataArray *colorArr) double value = colorArr->GetComponent(i, 0); unsigned char *rgb = lookupTable->MapValue(value); const unsigned char constRGB[3] = { rgb[0], rgb[1], rgb[2] }; - this->Colors->InsertNextTupleValue(&constRGB[0]); - this->Colors->InsertNextTupleValue(&constRGB[1]); - this->Colors->InsertNextTupleValue(&constRGB[2]); + this->Colors->InsertNextTypedTuple(&constRGB[0]); + this->Colors->InsertNextTypedTuple(&constRGB[1]); + this->Colors->InsertNextTypedTuple(&constRGB[2]); } this->Modified(); diff --git a/Charts/Core/vtkPlot3D.h b/Charts/Core/vtkPlot3D.h index 87496fd1687..70c60c52b02 100644 --- a/Charts/Core/vtkPlot3D.h +++ b/Charts/Core/vtkPlot3D.h @@ -103,7 +103,6 @@ class VTKCHARTSCORE_EXPORT vtkPlot3D : public vtkContextItem virtual void SetSelection(vtkIdTypeArray *id); virtual vtkIdTypeArray* GetSelection(); -//BTX protected: vtkPlot3D(); ~vtkPlot3D(); @@ -165,7 +164,6 @@ class VTKCHARTSCORE_EXPORT vtkPlot3D : public vtkContextItem vtkPlot3D(const vtkPlot3D &); // Not implemented. void operator=(const vtkPlot3D &); // Not implemented. -//ETX }; #endif //vtkPlot3D_h diff --git a/Charts/Core/vtkPlotArea.cxx b/Charts/Core/vtkPlotArea.cxx index 5dc372de573..cf137788144 100644 --- a/Charts/Core/vtkPlotArea.cxx +++ b/Charts/Core/vtkPlotArea.cxx @@ -14,13 +14,13 @@ =========================================================================*/ #include "vtkPlotArea.h" +#include "vtkArrayDispatch.h" #include "vtkAxis.h" #include "vtkBoundingBox.h" #include "vtkBrush.h" #include "vtkCharArray.h" #include "vtkContext2D.h" #include "vtkContextMapper2D.h" -#include "vtkDataArrayIteratorMacro.h" #include "vtkFloatArray.h" #include "vtkMath.h" #include "vtkNew.h" @@ -140,101 +140,175 @@ class vtkPlotArea::vtkTableCache vtkRectd ShiftScale; vtkTuple GetDataRange(vtkDataArray* array) - { + { assert(array); if (this->ValidPointMask) { assert(array->GetNumberOfTuples() == this->ValidPointMask->GetNumberOfTuples()); - switch (array->GetDataType()) + assert(array->GetNumberOfComponents() == this->ValidPointMask->GetNumberOfComponents()); + + vtkArrayDispatch::Dispatch2ByArray< + vtkArrayDispatch::Arrays, // First array is input, can be anything. + vtkTypeList_Create_1(vtkCharArray) // Second is always vtkCharArray. + > dispatcher; + ComputeArrayRange worker; + + if (!dispatcher.Execute(array, this->ValidPointMask, worker)) { - vtkDataArrayIteratorMacro(array, - return this->ComputeArrayRange(vtkDABegin, vtkDAEnd, this->ValidPointMask)); + vtkGenericWarningMacro( + <<"Error computing range. Unsupported array type: " + << array->GetClassName() + << " (" << array->GetDataTypeAsString() << ")."); } + + return worker.Result; } else { - switch (array->GetDataType()) + vtkArrayDispatch::Dispatch dispatcher; + ComputeArrayRange worker; + + if (!dispatcher.Execute(array, worker)) { - vtkDataArrayIteratorMacro(array, - return this->ComputeArrayRange(vtkDABegin, vtkDAEnd)); + vtkGenericWarningMacro( + <<"Error computing range. Unsupported array type: " + << array->GetClassName() + << " (" << array->GetDataTypeAsString() << ")."); } + + return worker.Result; } - vtkTuple range; - range[0] = VTK_DOUBLE_MAX; - range[1] = VTK_DOUBLE_MIN; - return range; + + } + + struct ComputeArrayRange + { + vtkTuple Result; + + ComputeArrayRange() + { + Result[0] = VTK_DOUBLE_MAX; + Result[1] = VTK_DOUBLE_MIN; } - template - vtkTuple ComputeArrayRange(Iterator begin, Iterator end, vtkCharArray* mask) + // Use mask: + template + void operator()(ArrayT *array, vtkCharArray* mask) { - vtkTuple range; - range[0] = VTK_DOUBLE_MAX; - range[1] = VTK_DOUBLE_MIN; - vtkIdType index=0; - for (Iterator iter=begin; iter != end; ++iter, ++index) - { - if (mask->GetValue(index) != 0) + vtkIdType numTuples = array->GetNumberOfTuples(); + int numComps = array->GetNumberOfComponents(); + + for (vtkIdType tupleIdx = 0; tupleIdx < numTuples; ++tupleIdx) { - range[0] = std::min(range[0], static_cast(*iter)); - range[1] = std::max(range[1], static_cast(*iter)); + for (int compIdx = 0; compIdx < numComps; ++compIdx) + { + if (mask->GetTypedComponent(tupleIdx, compIdx) != 0) + { + typename ArrayT::ValueType val = + array->GetTypedComponent(tupleIdx, compIdx); + Result[0] = std::min(Result[0], static_cast(val)); + Result[1] = std::max(Result[1], static_cast(val)); + } + } } - } - return range; } - template - vtkTuple ComputeArrayRange(Iterator begin, Iterator end) + // No mask: + template + void operator()(ArrayT *array) { - vtkTuple range; - range[0] = VTK_DOUBLE_MAX; - range[1] = VTK_DOUBLE_MIN; - vtkIdType index=0; - for (Iterator iter=begin; iter != end; ++iter, ++index) - { - range[0] = std::min(range[0], static_cast(*iter)); - range[1] = std::max(range[1], static_cast(*iter)); - } - return range; + vtkIdType numTuples = array->GetNumberOfTuples(); + int numComps = array->GetNumberOfComponents(); + + for (vtkIdType tupleIdx = 0; tupleIdx < numTuples; ++tupleIdx) + { + for (int compIdx = 0; compIdx < numComps; ++compIdx) + { + typename ArrayT::ValueType val = + array->GetTypedComponent(tupleIdx, compIdx); + Result[0] = std::min(Result[0], static_cast(val)); + Result[1] = std::max(Result[1], static_cast(val)); + } + } } - template - void CopyToPoints( - float* data, int data_increment, Iterator begin, Iterator end, const vtkVector2d& ss, bool useLog) + }; + + struct CopyToPoints + { + float *Data; + int DataIncrement; + vtkIdType NumValues; + vtkVector2d Transform; + bool UseLog; + + CopyToPoints(float *data, int data_increment, vtkIdType numValues, + const vtkVector2d &ss, bool useLog) + : Data(data), + DataIncrement(data_increment), + NumValues(numValues), + Transform(ss), + UseLog(useLog) + {} + + // Silence warning C4512 on MSVC2015: "assignment operator could not be + // generated.". This class is never copied, so no need for assignment. + CopyToPoints& operator=(const CopyToPoints &) { return *this; } + + // Use input array: + template + void operator()(ArrayT *array) { - if (useLog) + if (this->UseLog) { - for (Iterator iter = begin; iter != end; ++iter, data+= data_increment) + float *data = this->Data; + for (vtkIdType valIdx = 0; valIdx < this->NumValues; + ++valIdx, data += this->DataIncrement) { - *data = log10(static_cast((*iter + ss[0]) * ss[1])); + *data = log10(static_cast( + (array->GetValue(valIdx) + this->Transform[0]) + * this->Transform[1])); } } else { - for (Iterator iter = begin; iter != end; ++iter, data+= data_increment) + float *data = this->Data; + for (vtkIdType valIdx = 0; valIdx < this->NumValues; + ++valIdx, data += this->DataIncrement) { - *data = static_cast((*iter + ss[0]) * ss[1]); + *data = static_cast( + (array->GetValue(valIdx) + this->Transform[0]) + * this->Transform[1]); } } } - template - class RangeIterator + // No array, just iterate to number of values + void operator()() { - T Value; - public: - RangeIterator(const T& val) : Value(val) - {} - T operator*() const - { return this->Value; } - bool operator==(const RangeIterator& other) const - { return this->Value == other.Value; } - bool operator!=(const RangeIterator& other) const - { return this->Value != other.Value; } - RangeIterator& operator++() - { ++this->Value; return (*this); } - }; + if (this->UseLog) + { + float *data = this->Data; + for (vtkIdType valIdx = 0; valIdx < this->NumValues; + ++valIdx, data += this->DataIncrement) + { + *data = log10(static_cast((valIdx + this->Transform[0]) + * this->Transform[1])); + } + } + else + { + float *data = this->Data; + for (vtkIdType valIdx = 0; valIdx < this->NumValues; + ++valIdx, data += this->DataIncrement) + { + *data = static_cast((valIdx + this->Transform[0]) + * this->Transform[1]); + } + } + } + }; VectorPIMPL SortedPoints; public: @@ -343,37 +417,54 @@ class vtkPlotArea::vtkTableCache float* data = reinterpret_cast(this->Points->GetVoidPointer(0)); if (this->InputArrays[0]) { - switch (this->InputArrays[0]->GetDataType()) + vtkDataArray *array = this->InputArrays[0].GetPointer(); + vtkIdType numValues = array->GetNumberOfTuples() * + array->GetNumberOfComponents(); + + CopyToPoints worker1(data, 4, numValues, vtkVector2d(ss[0], ss[2]), + useLog[0]); + CopyToPoints worker2(&data[2], 4, numValues, vtkVector2d(ss[0], ss[2]), + useLog[0]); + + vtkArrayDispatch::Dispatch dispatcher; + + if (!dispatcher.Execute(array, worker1) || + !dispatcher.Execute(array, worker2)) { - vtkDataArrayIteratorMacro(this->InputArrays[0], - this->CopyToPoints( - data, 4, vtkDABegin, vtkDAEnd, vtkVector2d(ss[0], ss[2]), useLog[0]); - this->CopyToPoints( - &data[2], 4, vtkDABegin, vtkDAEnd, vtkVector2d(ss[0], ss[2]), useLog[0]); - ); + vtkGenericWarningMacro("Error creating points, unsupported array type: " + << array->GetClassName() + << " (" << array->GetDataTypeAsString() << ")."); } } else { - this->CopyToPoints( - data, 4, RangeIterator(0), RangeIterator(numTuples), - vtkVector2d(ss[0], ss[2]), useLog[0]); - this->CopyToPoints( - &data[2], 4, RangeIterator(0), RangeIterator(numTuples), - vtkVector2d(ss[0], ss[2]), useLog[0]); + CopyToPoints worker1(data, 4, numTuples, vtkVector2d(ss[0], ss[2]), + useLog[0]); + CopyToPoints worker2(&data[2], 4, numTuples, vtkVector2d(ss[0], ss[2]), + useLog[0]); + // No array, no need to dispatch: + worker1(); + worker2(); } - switch (this->InputArrays[1]->GetDataType()) - { - vtkDataArrayIteratorMacro(this->InputArrays[1], - this->CopyToPoints( - &data[1], 4, vtkDABegin, vtkDAEnd, vtkVector2d(ss[1], ss[3]), useLog[1])); - } - switch (this->InputArrays[2]->GetDataType()) + vtkDataArray *array1 = this->InputArrays[1].GetPointer(); + vtkDataArray *array2 = this->InputArrays[2].GetPointer(); + vtkIdType numValues1 = array1->GetNumberOfTuples() * + array1->GetNumberOfComponents(); + vtkIdType numValues2 = array2->GetNumberOfTuples() * + array2->GetNumberOfComponents(); + + CopyToPoints worker1(&data[1], 4, numValues1, vtkVector2d(ss[1], ss[3]), + useLog[1]); + CopyToPoints worker2(&data[3], 4, numValues2, vtkVector2d(ss[1], ss[3]), + useLog[1]); + + vtkArrayDispatch::Dispatch dispatcher; + + if (!dispatcher.Execute(array1, worker1) || + !dispatcher.Execute(array2, worker2)) { - vtkDataArrayIteratorMacro(this->InputArrays[2], - this->CopyToPoints( - &data[3], 4, vtkDABegin, vtkDAEnd, vtkVector2d(ss[1], ss[3]), useLog[1])); + vtkGenericWarningMacro("Error creating points: Array dispatch failed."); } // Set the bad-points mask. @@ -456,7 +547,7 @@ void vtkPlotArea::Update() cache.Reset(); cache.ValidPointMask = (this->ValidPointMaskName.empty() == false)? - vtkCharArray::SafeDownCast(table->GetColumnByName(this->ValidPointMaskName)) : NULL; + vtkArrayDownCast(table->GetColumnByName(this->ValidPointMaskName)) : NULL; cache.SetPoints( this->UseIndexForXSeries? NULL: this->Data->GetInputArrayToProcess(0, table), this->Data->GetInputArrayToProcess(1, table), diff --git a/Charts/Core/vtkPlotArea.h b/Charts/Core/vtkPlotArea.h index 818ff18b608..d8f44f063f7 100644 --- a/Charts/Core/vtkPlotArea.h +++ b/Charts/Core/vtkPlotArea.h @@ -78,8 +78,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotArea : public vtkPlot virtual bool PaintLegend(vtkContext2D *painter, const vtkRectf& rect, int legendIndex); -//BTX - // Description: // Function to query a plot for the nearest point to the specified coordinate. // Returns the index of the data series with which the point is associated, or @@ -110,7 +108,7 @@ class VTKCHARTSCORE_EXPORT vtkPlotArea : public vtkPlot vtkTableCache* TableCache; vtkTimeStamp UpdateTime; -//ETX + }; #endif diff --git a/Charts/Core/vtkPlotBag.cxx b/Charts/Core/vtkPlotBag.cxx index 0ce86008451..cfb0fdb8f58 100644 --- a/Charts/Core/vtkPlotBag.cxx +++ b/Charts/Core/vtkPlotBag.cxx @@ -83,7 +83,7 @@ void vtkPlotBag::Update() // Check if we have an input vtkTable *table = this->Data->GetInput(); - vtkDataArray *density = vtkDataArray::SafeDownCast( + vtkDataArray *density = vtkArrayDownCast( this->Data->GetInputAbstractArrayToProcess(2, this->GetInput())); if (!table || !density) { @@ -311,7 +311,7 @@ vtkStringArray* vtkPlotBag::GetLabels() else if (this->Data->GetInput()) { this->AutoLabels = vtkSmartPointer::New(); - vtkDataArray *density = vtkDataArray::SafeDownCast( + vtkDataArray *density = vtkArrayDownCast( this->Data->GetInputAbstractArrayToProcess(2, this->GetInput())); if (density) { @@ -332,7 +332,7 @@ vtkStdString vtkPlotBag::GetTooltipLabel(const vtkVector2d &plotPos, this->TooltipDefaultLabelFormat : this->TooltipLabelFormat; // Parse TooltipLabelFormat and build tooltipLabel bool escapeNext = false; - vtkDataArray *density = vtkDataArray::SafeDownCast( + vtkDataArray *density = vtkArrayDownCast( this->Data->GetInputAbstractArrayToProcess(2, this->GetInput())); for (size_t i = 0; i < format.length(); ++i) { @@ -372,7 +372,7 @@ vtkStdString vtkPlotBag::GetTooltipLabel(const vtkVector2d &plotPos, break; case 'C': { - vtkAbstractArray *colName = vtkAbstractArray::SafeDownCast( + vtkAbstractArray *colName = vtkArrayDownCast( this->GetInput()->GetColumnByName("ColName")); std::stringstream ss; if (colName) diff --git a/Charts/Core/vtkPlotBar.cxx b/Charts/Core/vtkPlotBar.cxx index 7dd86da8a9a..5c5f0fe6b6e 100644 --- a/Charts/Core/vtkPlotBar.cxx +++ b/Charts/Core/vtkPlotBar.cxx @@ -187,11 +187,11 @@ class vtkPlotBarSegment : public vtkObject { painter->ApplyBrush(brush); int n = this->Points->GetNumberOfPoints(); float *f = - vtkFloatArray::SafeDownCast(this->Points->GetData())->GetPointer(0); + vtkArrayDownCast(this->Points->GetData())->GetPointer(0); float *p = NULL; if (this->Previous) { - p = vtkFloatArray::SafeDownCast( + p = vtkArrayDownCast( this->Previous->Points->GetData())->GetPointer(0); } @@ -689,7 +689,7 @@ void vtkPlotBar::GetBounds(double bounds[4], bool unscaled) for ( it = this->Private->AdditionalSeries.begin(); it != this->Private->AdditionalSeries.end(); ++it ) { - y = vtkDataArray::SafeDownCast(table->GetColumnByName((*it).second.c_str())); + y = vtkArrayDownCast(table->GetColumnByName((*it).second.c_str())); y->GetRange(yRange); bounds[valuesHigh] += yRange[1]; } @@ -870,7 +870,7 @@ bool vtkPlotBar::UpdateTableCache(vtkTable *table) if (this->ScalarVisibility && !this->ColorArrayName.empty()) { vtkDataArray* c = - vtkDataArray::SafeDownCast(table->GetColumnByName(this->ColorArrayName)); + vtkArrayDownCast(table->GetColumnByName(this->ColorArrayName)); // TODO: Should add support for categorical coloring & try enum lookup if (c) { @@ -896,7 +896,7 @@ bool vtkPlotBar::UpdateTableCache(vtkTable *table) for ( it = this->Private->AdditionalSeries.begin(); it != this->Private->AdditionalSeries.end(); ++it ) { - y = vtkDataArray::SafeDownCast(table->GetColumnByName((*it).second.c_str())); + y = vtkArrayDownCast(table->GetColumnByName((*it).second.c_str())); prev = this->Private->AddSegment(x,y, this->GetXAxis(), this->GetYAxis(),prev); } @@ -1025,7 +1025,7 @@ void vtkPlotBar::SelectColorArray(vtkIdType arrayNum) vtkWarningMacro(<< "SelectColorArray called with no input table set."); return; } - vtkDataArray *col = vtkDataArray::SafeDownCast(table->GetColumn(arrayNum)); + vtkDataArray *col = vtkArrayDownCast(table->GetColumn(arrayNum)); // TODO: Should add support for categorical coloring & try enum lookup if (!col) { diff --git a/Charts/Core/vtkPlotBar.h b/Charts/Core/vtkPlotBar.h index cd81eaf8b73..1b792422c1e 100644 --- a/Charts/Core/vtkPlotBar.h +++ b/Charts/Core/vtkPlotBar.h @@ -172,7 +172,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotBar : public vtkPlot // Select all points in the specified rectangle. virtual bool SelectPoints(const vtkVector2f& min, const vtkVector2f& max); -//BTX // Description: // Function to query a plot for the nearest point to the specified coordinate. // Returns the index of the data series with which the point is associated or @@ -241,7 +240,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotBar : public vtkPlot vtkPlotBarPrivate *Private; -//ETX }; #endif //vtkPlotBar_h diff --git a/Charts/Core/vtkPlotBox.cxx b/Charts/Core/vtkPlotBox.cxx index 74cc4d3ac9d..2e1ba25c264 100644 --- a/Charts/Core/vtkPlotBox.cxx +++ b/Charts/Core/vtkPlotBox.cxx @@ -336,7 +336,7 @@ bool vtkPlotBox::UpdateTableCache(vtkTable *table) std::vector& col = this->Storage->at(i); col.resize(rows); vtkSmartPointer data = - vtkDataArray::SafeDownCast(table->GetColumnByName(cols->GetValue(i))); + vtkArrayDownCast(table->GetColumnByName(cols->GetValue(i))); if (!data) { continue; diff --git a/Charts/Core/vtkPlotBox.h b/Charts/Core/vtkPlotBox.h index b507d4974be..10842397a02 100644 --- a/Charts/Core/vtkPlotBox.h +++ b/Charts/Core/vtkPlotBox.h @@ -105,7 +105,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotBox : public vtkPlot // Get the vtkTextProperty that governs how the plot title is displayed. vtkGetObjectMacro(TitleProperties, vtkTextProperty); -//BTX protected: vtkPlotBox(); ~vtkPlotBox(); @@ -141,7 +140,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotBox : public vtkPlot vtkPlotBox(const vtkPlotBox &); // Not implemented. void operator=(const vtkPlotBox &); // Not implemented. -//ETX }; #endif //vtkPlotBox_h diff --git a/Charts/Core/vtkPlotFunctionalBag.cxx b/Charts/Core/vtkPlotFunctionalBag.cxx index 2370c485f0d..5a89d11f1f1 100644 --- a/Charts/Core/vtkPlotFunctionalBag.cxx +++ b/Charts/Core/vtkPlotFunctionalBag.cxx @@ -133,7 +133,7 @@ bool vtkPlotFunctionalBag::UpdateTableCache(vtkTable *table) { // The input array has 2 components, this must be a bag // with {miny,maxy} tuples - vtkDoubleArray* darr = vtkDoubleArray::SafeDownCast(array[1]); + vtkDoubleArray* darr = vtkArrayDownCast(array[1]); this->LogX = this->XAxis->GetLogScaleActive(); this->LogY = this->YAxis->GetLogScaleActive(); diff --git a/Charts/Core/vtkPlotFunctionalBag.h b/Charts/Core/vtkPlotFunctionalBag.h index 88665596669..469cb11c6ce 100644 --- a/Charts/Core/vtkPlotFunctionalBag.h +++ b/Charts/Core/vtkPlotFunctionalBag.h @@ -95,7 +95,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotFunctionalBag : public vtkPlot // is available with the scalar data. virtual void CreateDefaultLookupTable(); -//BTX // Description: // Function to query a plot for the nearest point to the specified coordinate. // Returns the index of the data series with which the point is associated or @@ -103,7 +102,7 @@ class VTKCHARTSCORE_EXPORT vtkPlotFunctionalBag : public vtkPlot virtual vtkIdType GetNearestPoint(const vtkVector2f& point, const vtkVector2f& tolerance, vtkVector2f* location); -//ETX + // Description: // Select all points in the specified rectangle. virtual bool SelectPoints(const vtkVector2f& min, const vtkVector2f& max); diff --git a/Charts/Core/vtkPlotGrid.h b/Charts/Core/vtkPlotGrid.h index f683291d229..cd626979fc7 100644 --- a/Charts/Core/vtkPlotGrid.h +++ b/Charts/Core/vtkPlotGrid.h @@ -54,7 +54,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotGrid : public vtkContextItem // Paint event for the axis, called whenever the axis needs to be drawn virtual bool Paint(vtkContext2D *painter); -//BTX protected: vtkPlotGrid(); ~vtkPlotGrid(); @@ -68,7 +67,7 @@ class VTKCHARTSCORE_EXPORT vtkPlotGrid : public vtkContextItem private: vtkPlotGrid(const vtkPlotGrid &); // Not implemented. void operator=(const vtkPlotGrid &); // Not implemented. -//ETX + }; #endif //vtkPlotGrid_h diff --git a/Charts/Core/vtkPlotHistogram2D.h b/Charts/Core/vtkPlotHistogram2D.h index 7d6f66fa964..ad639fa1083 100644 --- a/Charts/Core/vtkPlotHistogram2D.h +++ b/Charts/Core/vtkPlotHistogram2D.h @@ -75,7 +75,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotHistogram2D : public vtkPlot virtual void SetPosition(const vtkRectf& pos); virtual vtkRectf GetPosition(); -//BTX // Description: // Generate and return the tooltip label string for this plot // The segmentIndex parameter is ignored. @@ -125,7 +124,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotHistogram2D : public vtkPlot vtkPlotHistogram2D(const vtkPlotHistogram2D &); // Not implemented. void operator=(const vtkPlotHistogram2D &); // Not implemented. -//ETX }; #endif //vtkPlotHistogram2D_h diff --git a/Charts/Core/vtkPlotLine.h b/Charts/Core/vtkPlotLine.h index 6eee087cee0..d44cafdacf7 100644 --- a/Charts/Core/vtkPlotLine.h +++ b/Charts/Core/vtkPlotLine.h @@ -57,7 +57,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotLine : public vtkPlotPoints vtkGetMacro(PolyLine,bool); vtkBooleanMacro(PolyLine,bool); -//BTX protected: vtkPlotLine(); ~vtkPlotLine(); @@ -70,7 +69,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotLine : public vtkPlotPoints vtkPlotLine(const vtkPlotLine &); // Not implemented. void operator=(const vtkPlotLine &); // Not implemented. -//ETX }; #endif //vtkPlotLine_h diff --git a/Charts/Core/vtkPlotLine3D.h b/Charts/Core/vtkPlotLine3D.h index 090e2808c4e..37a85757727 100644 --- a/Charts/Core/vtkPlotLine3D.h +++ b/Charts/Core/vtkPlotLine3D.h @@ -45,7 +45,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotLine3D : public vtkPlotPoints3D // Paint event for the XYZ plot, called whenever the chart needs to be drawn. virtual bool Paint(vtkContext2D *painter); -//BTX protected: vtkPlotLine3D(); ~vtkPlotLine3D(); @@ -54,7 +53,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotLine3D : public vtkPlotPoints3D vtkPlotLine3D(const vtkPlotLine3D &); // Not implemented. void operator=(const vtkPlotLine3D &); // Not implemented. -//ETX }; #endif //vtkPlotLine3D_h diff --git a/Charts/Core/vtkPlotParallelCoordinates.cxx b/Charts/Core/vtkPlotParallelCoordinates.cxx index 569c14d8360..0abf2046f1c 100644 --- a/Charts/Core/vtkPlotParallelCoordinates.cxx +++ b/Charts/Core/vtkPlotParallelCoordinates.cxx @@ -144,7 +144,7 @@ bool vtkPlotParallelCoordinates::Paint(vtkContext2D *painter) selectionSize = this->Selection->GetNumberOfTuples(); if (selectionSize) { - this->Selection->GetTupleValue(selection, &id); + this->Selection->GetTypedTuple(selection, &id); } } @@ -187,7 +187,7 @@ bool vtkPlotParallelCoordinates::Paint(vtkContext2D *painter) { for (size_t j = 0; j < cols; ++j) { - this->Selection->GetTupleValue(i, &id); + this->Selection->GetTypedTuple(i, &id); line[j].Set(this->Storage->AxisPos[j], (*this->Storage)[j][id]); } painter->DrawPoly(line[0].GetData(), static_cast(cols)); @@ -233,7 +233,7 @@ bool vtkPlotParallelCoordinates::SetSelectionRange(int axis, float low, for (vtkIdType i = 0; i < this->Selection->GetNumberOfTuples(); ++i) { vtkIdType id = 0; - this->Selection->GetTupleValue(i, &id); + this->Selection->GetTypedTuple(i, &id); if (col[id] >= low && col[id] <= high) { // Remove this point - no longer selected @@ -324,7 +324,7 @@ bool vtkPlotParallelCoordinates::UpdateTableCache(vtkTable *table) vtkAxis* axis = parent->GetAxis(i); col.resize(rows); vtkSmartPointer data = - vtkDataArray::SafeDownCast(table->GetColumnByName(cols->GetValue(i))); + vtkArrayDownCast(table->GetColumnByName(cols->GetValue(i))); if (!data) { if (table->GetColumnByName(cols->GetValue(i))->IsA("vtkStringArray")) @@ -341,12 +341,12 @@ bool vtkPlotParallelCoordinates::UpdateTableCache(vtkTable *table) vtkTable* stringTable = vtkTable::SafeDownCast(stoc->GetOutput(1)); if (table2) { - data = vtkDataArray::SafeDownCast(table2->GetColumnByName("enumPC")); + data = vtkArrayDownCast(table2->GetColumnByName("enumPC")); } if (stringTable && stringTable->GetColumnByName("Strings")) { vtkStringArray* strings = - vtkStringArray::SafeDownCast(stringTable->GetColumnByName("Strings")); + vtkArrayDownCast(stringTable->GetColumnByName("Strings")); vtkSmartPointer arr = vtkSmartPointer::New(); for (vtkIdType j = 0; j < strings->GetNumberOfTuples(); ++j) @@ -389,7 +389,7 @@ bool vtkPlotParallelCoordinates::UpdateTableCache(vtkTable *table) if (this->ScalarVisibility && !this->ColorArrayName.empty()) { vtkDataArray* c = - vtkDataArray::SafeDownCast(table->GetColumnByName(this->ColorArrayName)); + vtkArrayDownCast(table->GetColumnByName(this->ColorArrayName)); // TODO: Should add support for categorical coloring & try enum lookup if (c) { @@ -497,7 +497,7 @@ void vtkPlotParallelCoordinates::SelectColorArray(vtkIdType arrayNum) vtkDebugMacro(<< "SelectColorArray called with no input table set."); return; } - vtkDataArray *col = vtkDataArray::SafeDownCast(table->GetColumn(arrayNum)); + vtkDataArray *col = vtkArrayDownCast(table->GetColumn(arrayNum)); // TODO: Should add support for categorical coloring & try enum lookup if (!col) { diff --git a/Charts/Core/vtkPlotParallelCoordinates.h b/Charts/Core/vtkPlotParallelCoordinates.h index d23e3b71532..7204ebc0992 100644 --- a/Charts/Core/vtkPlotParallelCoordinates.h +++ b/Charts/Core/vtkPlotParallelCoordinates.h @@ -109,7 +109,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotParallelCoordinates : public vtkPlot // Get the array name to color by. vtkStdString GetColorArrayName(); -//BTX protected: vtkPlotParallelCoordinates(); ~vtkPlotParallelCoordinates(); @@ -138,7 +137,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotParallelCoordinates : public vtkPlot vtkPlotParallelCoordinates(const vtkPlotParallelCoordinates &); // Not implemented. void operator=(const vtkPlotParallelCoordinates &); // Not implemented. -//ETX }; #endif //vtkPlotParallelCoordinates_h diff --git a/Charts/Core/vtkPlotPie.h b/Charts/Core/vtkPlotPie.h index 520dcf387a7..1b6fe604fac 100644 --- a/Charts/Core/vtkPlotPie.h +++ b/Charts/Core/vtkPlotPie.h @@ -72,7 +72,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotPie : public vtkPlot // Get the color series used. vtkColorSeries *GetColorSeries(); -//BTX // Description: // Function to query a plot for the nearest point to the specified coordinate. // Returns the index of the data series with which the point is associated or @@ -108,7 +107,7 @@ class VTKCHARTSCORE_EXPORT vtkPlotPie : public vtkPlot void operator=(const vtkPlotPie &); // Not implemented. vtkPlotPiePrivate *Private; -//ETX + }; #endif //vtkPlotPie_h diff --git a/Charts/Core/vtkPlotPoints.cxx b/Charts/Core/vtkPlotPoints.cxx index 97249651238..b22143569a4 100644 --- a/Charts/Core/vtkPlotPoints.cxx +++ b/Charts/Core/vtkPlotPoints.cxx @@ -121,7 +121,7 @@ void vtkPlotPoints::Update() if (table && !this->ValidPointMaskName.empty() && table->GetColumnByName(this->ValidPointMaskName)) { - this->ValidPointMask = vtkCharArray::SafeDownCast( + this->ValidPointMask = vtkArrayDownCast( table->GetColumnByName(this->ValidPointMaskName)); } else @@ -238,7 +238,7 @@ bool vtkPlotPoints::Paint(vtkContext2D *painter) if (this->Selection->GetMTime() > this->SelectedPoints->GetMTime() || this->GetMTime() > this->SelectedPoints->GetMTime()) { - float *f = vtkFloatArray::SafeDownCast( + float *f = vtkArrayDownCast( this->Points->GetData())->GetPointer(0); int nSelected(static_cast(this->Selection->GetNumberOfTuples())); this->SelectedPoints->SetNumberOfComponents(2); @@ -731,7 +731,7 @@ bool vtkPlotPoints::UpdateTableCache(vtkTable *table) if (this->ScalarVisibility && !this->ColorArrayName.empty()) { vtkDataArray* c = - vtkDataArray::SafeDownCast(table->GetColumnByName(this->ColorArrayName)); + vtkArrayDownCast(table->GetColumnByName(this->ColorArrayName)); // TODO: Should add support for categorical coloring & try enum lookup if (c) { @@ -1008,7 +1008,7 @@ void vtkPlotPoints::SelectColorArray(vtkIdType arrayNum) vtkDebugMacro(<< "SelectColorArray called with no input table set."); return; } - vtkDataArray *col = vtkDataArray::SafeDownCast(table->GetColumn(arrayNum)); + vtkDataArray *col = vtkArrayDownCast(table->GetColumn(arrayNum)); // TODO: Should add support for categorical coloring & try enum lookup if (!col) { diff --git a/Charts/Core/vtkPlotPoints.h b/Charts/Core/vtkPlotPoints.h index 8a018796f86..2e11991f78c 100644 --- a/Charts/Core/vtkPlotPoints.h +++ b/Charts/Core/vtkPlotPoints.h @@ -107,7 +107,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotPoints : public vtkPlot // Get the array name to color by. vtkStdString GetColorArrayName(); -//BTX // Description: // Function to query a plot for the nearest point to the specified coordinate. // Returns the index of the data series with which the point is associated or @@ -134,7 +133,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotPoints : public vtkPlot CIRCLE = VTK_MARKER_CIRCLE, DIAMOND = VTK_MARKER_DIAMOND }; -//ETX // Description: // Get/set the marker style that should be used. The default is none, the enum @@ -153,7 +151,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotPoints : public vtkPlot vtkGetMacro(ValidPointMaskName, vtkStdString) vtkSetMacro(ValidPointMaskName, vtkStdString) -//BTX protected: vtkPlotPoints(); ~vtkPlotPoints(); @@ -241,7 +238,7 @@ class VTKCHARTSCORE_EXPORT vtkPlotPoints : public vtkPlot // #define VTK_COLOR_MODE_DEFAULT 0 // #define VTK_COLOR_MODE_MAP_SCALARS 1 -//ETX + }; #endif //vtkPlotPoints_h diff --git a/Charts/Core/vtkPlotPoints3D.h b/Charts/Core/vtkPlotPoints3D.h index a42608abec4..c5b6b9bbcf2 100644 --- a/Charts/Core/vtkPlotPoints3D.h +++ b/Charts/Core/vtkPlotPoints3D.h @@ -42,7 +42,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotPoints3D : public vtkPlot3D // Paint event for the XY plot, called whenever the chart needs to be drawn virtual bool Paint(vtkContext2D *painter); -//BTX protected: vtkPlotPoints3D(); ~vtkPlotPoints3D(); @@ -58,7 +57,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotPoints3D : public vtkPlot3D private: vtkPlotPoints3D(const vtkPlotPoints3D &); // Not implemented. void operator=(const vtkPlotPoints3D &); // Not implemented. -//ETX }; diff --git a/Charts/Core/vtkPlotStacked.cxx b/Charts/Core/vtkPlotStacked.cxx index 5833ca6df48..14ebcdf48e0 100644 --- a/Charts/Core/vtkPlotStacked.cxx +++ b/Charts/Core/vtkPlotStacked.cxx @@ -338,10 +338,10 @@ class vtkPlotStackedSegment : public vtkObject { painter->ApplyPen(pen); painter->ApplyBrush(brush); int n = this->Points->GetNumberOfPoints(); - float *data_extent = vtkFloatArray::SafeDownCast(this->Points->GetData())->GetPointer(0); + float *data_extent = vtkArrayDownCast(this->Points->GetData())->GetPointer(0); float *data_base = 0; if (this->Previous) - data_base = vtkFloatArray::SafeDownCast(this->Previous->Points->GetData())->GetPointer(0); + data_base = vtkArrayDownCast(this->Previous->Points->GetData())->GetPointer(0); if (n >= 2) { @@ -796,7 +796,7 @@ bool vtkPlotStacked::UpdateTableCache(vtkTable *table) for ( it = this->Private->AdditionalSeries.begin(); it != this->Private->AdditionalSeries.end(); ++it ) { - y = vtkDataArray::SafeDownCast(table->GetColumnByName((*it).second.c_str())); + y = vtkArrayDownCast(table->GetColumnByName((*it).second.c_str())); prev = this->Private->AddSegment(x,y,prev); } diff --git a/Charts/Core/vtkPlotStacked.h b/Charts/Core/vtkPlotStacked.h index 77702fbfac2..bcca5c9b5d2 100644 --- a/Charts/Core/vtkPlotStacked.h +++ b/Charts/Core/vtkPlotStacked.h @@ -95,7 +95,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotStacked : public vtkPlot // Get the plot labels. virtual vtkStringArray *GetLabels(); -//BTX // Description: // Function to query a plot for the nearest point to the specified coordinate. // Returns the index of the data series with which the point is associated or @@ -108,7 +107,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotStacked : public vtkPlot // Select all points in the specified rectangle. virtual bool SelectPoints(const vtkVector2f& min, const vtkVector2f& max); -//BTX protected: vtkPlotStacked(); ~vtkPlotStacked(); @@ -153,7 +151,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotStacked : public vtkPlot vtkPlotStackedPrivate *Private; -//ETX }; #endif //vtkPlotStacked_h diff --git a/Charts/Core/vtkPlotSurface.cxx b/Charts/Core/vtkPlotSurface.cxx index 4da14cb7bbc..003e2dc2d09 100644 --- a/Charts/Core/vtkPlotSurface.cxx +++ b/Charts/Core/vtkPlotSurface.cxx @@ -237,9 +237,9 @@ void vtkPlotSurface::InsertSurfaceVertex(float *data, float value, int i, unsigned char *rgb = this->LookupTable->MapValue(data[pos-1]); const unsigned char constRGB[3] = { rgb[0], rgb[1], rgb[2] }; - this->Colors->InsertNextTupleValue(&constRGB[0]); - this->Colors->InsertNextTupleValue(&constRGB[1]); - this->Colors->InsertNextTupleValue(&constRGB[2]); + this->Colors->InsertNextTypedTuple(&constRGB[0]); + this->Colors->InsertNextTypedTuple(&constRGB[1]); + this->Colors->InsertNextTypedTuple(&constRGB[2]); } //----------------------------------------------------------------------------- diff --git a/Charts/Core/vtkPlotSurface.h b/Charts/Core/vtkPlotSurface.h index f343e489919..73422968f1b 100644 --- a/Charts/Core/vtkPlotSurface.h +++ b/Charts/Core/vtkPlotSurface.h @@ -73,7 +73,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotSurface : public vtkPlot3D // to call it before SetInputData() when possible. void SetYRange(float min, float max); -//BTX protected: vtkPlotSurface(); ~vtkPlotSurface(); @@ -146,7 +145,6 @@ class VTKCHARTSCORE_EXPORT vtkPlotSurface : public vtkPlot3D vtkPlotSurface(const vtkPlotSurface &); // Not implemented. void operator=(const vtkPlotSurface &); // Not implemented. -//ETX }; #endif //vtkPlotSurface_h diff --git a/Charts/Core/vtkScatterPlotMatrix.cxx b/Charts/Core/vtkScatterPlotMatrix.cxx index 339b8b17ee8..f40b3038924 100644 --- a/Charts/Core/vtkScatterPlotMatrix.cxx +++ b/Charts/Core/vtkScatterPlotMatrix.cxx @@ -219,7 +219,7 @@ bool PopulateHistograms(vtkTable *input, vtkTable *output, vtkStringArray *s, double minmax[2] = { 0.0, 0.0 }; vtkStdString name(s->GetValue(i)); vtkDataArray *in = - vtkDataArray::SafeDownCast(input->GetColumnByName(name.c_str())); + vtkArrayDownCast(input->GetColumnByName(name.c_str())); if (in) { // The bin values are the centers, extending +/- half an inc either side @@ -231,7 +231,7 @@ bool PopulateHistograms(vtkTable *input, vtkTable *output, vtkStringArray *s, double inc = (minmax[1] - minmax[0]) / (NumberOfBins) * 1.001; double halfInc = inc / 2.0; vtkSmartPointer extents = - vtkFloatArray::SafeDownCast( + vtkArrayDownCast( output->GetColumnByName(vtkStdString(name + "_extents").c_str())); if (!extents) { @@ -246,7 +246,7 @@ bool PopulateHistograms(vtkTable *input, vtkTable *output, vtkStringArray *s, extents->SetValue(j, min + j * inc); } vtkSmartPointer populations = - vtkIntArray::SafeDownCast( + vtkArrayDownCast( output->GetColumnByName(vtkStdString(name + "_pops").c_str())); if (!populations) { @@ -829,7 +829,7 @@ void vtkScatterPlotMatrix::SetColumnVisibility(const vtkStdString &name, } // Add the column to the end of the list if it is a numeric column if (this->Input && this->Input->GetColumnByName(name.c_str()) && - vtkDataArray::SafeDownCast(this->Input->GetColumnByName(name.c_str()))) + vtkArrayDownCast(this->Input->GetColumnByName(name.c_str()))) { this->VisibleColumns->InsertNextValue(name); this->Private->VisibleColumnsModified = true; @@ -1300,7 +1300,7 @@ void vtkScatterPlotMatrix::UpdateAxes() double range[2] = { 0, 0 }; std::string name(this->VisibleColumns->GetValue(i)); vtkDataArray *arr = - vtkDataArray::SafeDownCast(this->Input->GetColumnByName(name.c_str())); + vtkArrayDownCast(this->Input->GetColumnByName(name.c_str())); if (arr) { PIMPL::ColumnSetting settings; diff --git a/Common/Color/vtkColorSeries.h b/Common/Color/vtkColorSeries.h index 43ce226a427..cd71679fce4 100644 --- a/Common/Color/vtkColorSeries.h +++ b/Common/Color/vtkColorSeries.h @@ -55,7 +55,6 @@ class VTKCOMMONCOLOR_EXPORT vtkColorSeries : public vtkObject // Create a new vtkColorSeries with the SPECTRUM color scheme. static vtkColorSeries* New(); -//BTX // Description: // Enum of the available color schemes enum ColorSchemes { @@ -186,9 +185,7 @@ class VTKCOMMONCOLOR_EXPORT vtkColorSeries : public vtkObject /// User specified color scheme. CUSTOM }; -//ETX -//BTX // Description: // An enum defining how lookup tables should be used: either as a // list of discrete colors to choose from (categorical), or as an @@ -199,7 +196,6 @@ enum LUTMode { /// indexed lookup is on CATEGORICAL }; -//ETX // Description: // Set the color scheme that should be used. @@ -236,7 +232,6 @@ enum LUTMode { // to be duplicated to a new custom scheme. virtual void SetNumberOfColors(int numColors); -//BTX // Description: // Get the color at the specified index. If the index is out of range then // black will be returned. @@ -259,7 +254,6 @@ enum LUTMode { // Description: // Inserts the color at the specified index in the list. virtual void InsertColor(int index, const vtkColor3ub &color); -//ETX // Description: // Removes the color at the specified index in the list. @@ -289,9 +283,9 @@ enum LUTMode { // The default behavior is to return categorical data. Set lutIndexing // to ORDINAL to return ordinal data. Any other value for lutIndexing // is treated as CATEGORICAL. + VTK_NEWINSTANCE vtkLookupTable* CreateLookupTable(int lutIndexing = CATEGORICAL); -//BTX protected: vtkColorSeries(); virtual ~vtkColorSeries(); @@ -316,7 +310,7 @@ enum LUTMode { private: vtkColorSeries(const vtkColorSeries &); // Not implemented. void operator=(const vtkColorSeries &); // Not implemented. -//ETX + }; #endif //vtkColorSeries_h diff --git a/Common/ComputationalGeometry/vtkKochanekSpline.h b/Common/ComputationalGeometry/vtkKochanekSpline.h index 3253d4bb98f..48ae16cb33d 100644 --- a/Common/ComputationalGeometry/vtkKochanekSpline.h +++ b/Common/ComputationalGeometry/vtkKochanekSpline.h @@ -14,7 +14,7 @@ =========================================================================*/ // .NAME vtkKochanekSpline - computes an interpolating spline using a Kochanek basis. // .SECTION Description -// Implements the Kochenek interpolating spline described in: Kochanek, D., +// Implements the Kochanek interpolating spline described in: Kochanek, D., // Bartels, R., "Interpolating Splines with Local Tension, Continuity, and // Bias Control," Computer Graphics, vol. 18, no. 3, pp. 33-41, July 1984. // These splines give the user more control over the shape of the curve than diff --git a/Common/ComputationalGeometry/vtkParametricRandomHills.cxx b/Common/ComputationalGeometry/vtkParametricRandomHills.cxx index 4c03ee2ed4f..60cadd65448 100644 --- a/Common/ComputationalGeometry/vtkParametricRandomHills.cxx +++ b/Common/ComputationalGeometry/vtkParametricRandomHills.cxx @@ -257,14 +257,6 @@ void vtkParametricRandomHills::CopyParameters() this->previousAllowRandomGeneration = this->AllowRandomGeneration; } -#ifndef VTK_LEGACY_REMOVE -//---------------------------------------------------------------------------- -void vtkParametricRandomHills::GenerateTheHills() -{ - VTK_LEGACY_BODY(vtkParametricRandomHills::GenerateTheHills, "VTK 6.2"); -} -#endif - //---------------------------------------------------------------------------- void vtkParametricRandomHills::PrintSelf(ostream& os, vtkIndent indent) { diff --git a/Common/ComputationalGeometry/vtkParametricRandomHills.h b/Common/ComputationalGeometry/vtkParametricRandomHills.h index 2d51a9af529..e513b04d68c 100644 --- a/Common/ComputationalGeometry/vtkParametricRandomHills.h +++ b/Common/ComputationalGeometry/vtkParametricRandomHills.h @@ -131,14 +131,6 @@ class VTKCOMMONCOMPUTATIONALGEOMETRY_EXPORT vtkParametricRandomHills : public vt vtkSetMacro(AmplitudeScaleFactor,double); vtkGetMacro(AmplitudeScaleFactor,double); - // Description: - // Generate the centers of the hills, their standard deviations and - // their amplitudes. This function creates a series of vectors representing - // the u, v coordinates of each hill, its variance in the u, v directions and - // the amplitude. - // \deprecated 6.2 This function is no longer needed. - VTK_LEGACY(void GenerateTheHills(void)); - // Description: // Construct a terrain consisting of hills on a surface. // diff --git a/Common/ComputationalGeometry/vtkParametricSpline.h b/Common/ComputationalGeometry/vtkParametricSpline.h index 554fed934c6..8ad434053f2 100644 --- a/Common/ComputationalGeometry/vtkParametricSpline.h +++ b/Common/ComputationalGeometry/vtkParametricSpline.h @@ -17,7 +17,7 @@ // vtkParametricSpline is a parametric function for 1D interpolating splines. // vtkParametricSpline maps the single parameter u into a 3D point (x,y,z) // using three instances of interpolating splines. This family of 1D splines -// is quaranteed to be parameterized in the interval [0,1]. Attempting to +// is guaranteed to be parameterized in the interval [0,1]. Attempting to // evaluate outside this interval will cause the parameter u to be clamped in // the range [0,1]. // diff --git a/Common/Core/CMakeLists.txt b/Common/Core/CMakeLists.txt index a23faf78141..963c906fdfb 100644 --- a/Common/Core/CMakeLists.txt +++ b/Common/Core/CMakeLists.txt @@ -98,19 +98,64 @@ endforeach() list(APPEND VTK_SMP_HEADERS vtkSMPTools.h vtkSMPThreadLocalObject.h) +#------------------------------------------------------------------------------- +# Generate the vtkTypeList_Create macros: +include(vtkCreateTypeListMacros) +CreateTypeListMacros( + VTK_TYPELISTMACRO_HEADER_CONTENTS + 99 + vtkTypeList_Create + "vtkTypeList::TypeList" + "vtkTypeList::NullType" +) +configure_file(vtkTypeListMacros.h.in vtkTypeListMacros.h) + +#------------------------------------------------------------------------------- +# And the ArrayDispatch array list header: +option(VTK_DISPATCH_AOS_ARRAYS + "Include array-of-structs vtkDataArray subclasses in dispatcher." + ON +) +option(VTK_DISPATCH_SOA_ARRAYS + "Include struct-of-arrays vtkDataArray subclasses in dispatcher." + OFF +) +option(VTK_DISPATCH_TYPED_ARRAYS + "Include vtkTypedDataArray subclasses (e.g. old mapped arrays) in dispatcher." + OFF +) +include(vtkCreateArrayDispatchArrayList) +vtkArrayDispatch_default_array_setup() +vtkArrayDispatch_generate_array_header(VTK_ARRAYDISPATCH_ARRAY_LIST) +configure_file(vtkArrayDispatchArrayList.h.in vtkArrayDispatchArrayList.h) + +option(VTK_WARN_ON_DISPATCH_FAILURE + "If enabled, vtkArrayDispatch will print a warning when a dispatch fails." + OFF +) + +mark_as_advanced( + VTK_DISPATCH_AOS_ARRAYS + VTK_DISPATCH_SOA_ARRAYS + VTK_DISPATCH_TYPED_ARRAYS + VTK_WARN_ON_DISPATCH_FAILURE +) + #----------------------------------------------------------------------------- include_directories(${VTK_SOURCE_DIR}/ThirdParty/utf8/source) SET(Module_SRCS vtkAbstractArray.cxx - vtkAnimationCue.cxx vtkAngularPeriodicDataArray.txx + vtkAnimationCue.cxx + vtkAOSDataArrayTemplate.txx vtkArrayCoordinates.cxx vtkArray.cxx vtkArrayExtents.cxx vtkArrayExtentsList.cxx vtkArrayIterator.cxx + vtkArrayIteratorTemplate.txx vtkArrayRange.cxx vtkArraySort.cxx vtkArrayWeights.cxx @@ -158,6 +203,7 @@ SET(Module_SRCS vtkInformationIntegerVectorKey.cxx vtkInformationIterator.cxx vtkInformationKey.cxx + vtkInformationKeyLookup.cxx vtkInformationKeyVectorKey.cxx vtkInformationObjectBaseKey.cxx vtkInformationObjectBaseVectorKey.cxx @@ -200,6 +246,8 @@ SET(Module_SRCS vtkSignedCharArray.cxx vtkSimpleCriticalSection.cxx vtkSmartPointerBase.cxx + vtkSOADataArrayTemplate.txx + vtkSOADataArrayTemplateInstantiate.cxx vtkSortDataArray.cxx vtkStdString.cxx vtkStringArray.cxx @@ -221,14 +269,13 @@ SET(Module_SRCS vtkWeakPointerBase.cxx vtkWindow.cxx vtkXMLFileOutputWindow.cxx - vtkDataArrayTemplate.txx - vtkDataArrayTemplateHelper.cxx vtkDenseArray.txx vtkSparseArray.txx vtkTypedArray.txx vtkTypeTemplate.h vtkType.h vtkSystemIncludes.h + vtkWrappingHints.h ${VTK_SMP_SOURCES} ${VTK_SMP_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/vtkConfigure.h @@ -239,19 +286,25 @@ SET(Module_SRCS set(${vtk-module}_HDRS vtkABI.h vtkAngularPeriodicDataArray.h + vtkArrayDispatch.h + vtkArrayDispatch.txx vtkArrayInterpolate.h vtkArrayInterpolate.txx vtkArrayIteratorIncludes.h - vtkArrayIteratorTemplate.h - vtkArrayIteratorTemplate.txx vtkArrayIteratorTemplateImplicit.txx vtkArrayPrint.h vtkArrayPrint.txx + vtkAssume.h vtkAtomicTypeConcepts.h vtkAtomicTypes.h vtkAutoInit.h + vtkBuffer.h + vtkDataArrayAccessor.h vtkDataArrayIteratorMacro.h - vtkDataArrayTemplateImplicit.txx + vtkDataArrayTemplate.h + vtkGenericDataArray.h + vtkGenericDataArrayLookupHelper.h + vtkGenericDataArray.txx vtkIOStream.h vtkIOStreamFwd.h vtkInformationInternals.h @@ -261,7 +314,12 @@ set(${vtk-module}_HDRS vtkPeriodicDataArray.h vtkSetGet.h vtkSmartPointer.h + vtkSOADataArrayTemplate.h + vtkSOADataArrayTemplate.txx vtkTemplateAliasMacro.h + vtkTestDataArray.h + vtkTypeList.h + vtkTypeList.txx vtkTypeTraits.h vtkTypedDataArray.h vtkTypedDataArrayIterator.h @@ -272,7 +330,9 @@ set(${vtk-module}_HDRS vtkWeakPointer.h vtkWin32Header.h vtkWindows.h + ${CMAKE_CURRENT_BINARY_DIR}/vtkArrayDispatchArrayList.h ${CMAKE_CURRENT_BINARY_DIR}/vtkToolkits.h + ${CMAKE_CURRENT_BINARY_DIR}/vtkTypeListMacros.h ) if(vtkCommonDataModel_ENABLED) @@ -325,17 +385,6 @@ if (WIN32) check_symbol_exists(InterlockedAdd "windows.h" VTK_HAS_INTERLOCKEDADD) endif() -if (NOT CMAKE_VERSION VERSION_LESS "3.1") - option(VTK_USE_CXX11_FEATURES "Build VTK using C++11 features (if available)" - OFF) -else() - set(VTK_USE_CXX11_FEATURES OFF) -endif() -if (VTK_USE_CXX11_FEATURES) - set(CMAKE_CXX_STANDARD_REQUIRED 11) -endif() - - configure_file(vtkVersionMacros.h.in vtkVersionMacros.h @ONLY) configure_file(vtkConfigure.h.in vtkConfigure.h @ONLY) configure_file(vtkToolkits.h.in vtkToolkits.h @ONLY) @@ -488,9 +537,8 @@ configure_file( set_source_files_properties( # vtkObjectBase is marked ABSTRACT so that instantiators are happy. vtkAbstractArray - vtkArrayIterator - vtkArrayIteratorTemplate vtkArray + vtkArrayIterator vtkCallbackCommand vtkCommand vtkCommonInformationKeyManager @@ -528,6 +576,8 @@ set_source_files_properties( ) set_source_files_properties( + vtkAOSDataArrayTemplate.h + vtkAOSDataArrayTemplate.txx vtkArrayCoordinates.cxx vtkArrayExtents.cxx vtkArrayExtentsList.cxx @@ -535,6 +585,7 @@ set_source_files_properties( vtkArrayRange.cxx vtkArraySort.cxx vtkArrayWeights.cxx + vtkBuffer.h vtkBoundingBox.cxx vtkBreakPoint.cxx vtkCallbackCommand.cxx @@ -550,12 +601,14 @@ set_source_files_properties( vtkOldStyleCallbackCommand.cxx vtkSimpleCriticalSection.cxx vtkSmartPointerBase.cxx + vtkSOADataArrayTemplate.h + vtkSOADataArrayTemplate.txx + vtkSOADataArrayTemplateInstantiate.cxx # Has no API vtkStdString.cxx vtkTimeStamp.cxx vtkVariant.cxx vtkWeakPointerBase.cxx vtkUnicodeString.cxx - vtkDataArrayTemplate.h vtkDataArrayPrivate.txx vtkABI.h @@ -564,20 +617,19 @@ set_source_files_properties( vtkArrayInterpolate.txx vtkArrayIteratorIncludes.h vtkArrayIteratorTemplate.h - vtkArrayIteratorTemplate.txx vtkArrayIteratorTemplateImplicit.txx + vtkArrayIteratorTemplate.txx vtkArrayPrint.h vtkArrayPrint.txx vtkAtomicTypeConcepts.h vtkAtomicTypes.h vtkAutoInit.h - vtkDataArrayTemplate.txx - vtkDataArrayTemplateHelper.cxx - vtkDataArrayTemplateImplicit.txx vtkDenseArray.txx + vtkGenericDataArrayHelpers.h + vtkInformationInternals.h vtkIOStream.h vtkIOStreamFwd.h - vtkInformationInternals.h + vtkIOStreamFwd.h vtkMathUtilities.h vtkMappedDataArray.txx vtkNew.h @@ -603,8 +655,10 @@ set_source_files_properties( vtkMathConfigure.h vtkVersionMacros.h vtkTypeTemplate.h + vtkWrappingHints.h ${VTK_SMP_SOURCES} ${VTK_SMP_HEADERS} + "${VTK_TYPELISTMACROS_HEADER}" WRAP_EXCLUDE ) @@ -612,12 +666,10 @@ set_source_files_properties( # python uses WRAP_EXCLUDE_PYTHON and ignores WRAP_EXCLUDE set_source_files_properties( vtkABI.h + vtkAOSDataArrayTemplate.txx vtkAtomic.h vtkAutoInit.h - vtkDataArrayTemplate.txx - vtkDataArrayTemplateHelper.cxx - vtkDataArrayTemplateImplicit.txx - vtkIOStream.h + vtkIOStream.cxx vtkIOStreamFwd.h vtkLargeInteger.cxx vtkOldStyleCallbackCommand.cxx @@ -627,11 +679,14 @@ set_source_files_properties( vtkSetGet.h vtkSmartPointer.h vtkSmartPointerBase.h + vtkSOADataArrayTemplate.txx + vtkSOADataArrayTemplateInstantiate.cxx # Has no API vtkStdString.cxx vtkUnicodeString.cxx vtkWeakPointer.h vtkWeakPointerBase.cxx vtkWin32Header.h + vtkWrappingHints.h PROPERTIES WRAP_EXCLUDE_PYTHON 1 ) @@ -641,9 +696,15 @@ set_source_files_properties( vtkSparseArray.h vtkTypedArray.h vtkTypeTemplate.h + "${VTK_TYPELISTMACROS_HEADER}" HEADER_FILE_ONLY ) +set_source_files_properties( + vtkSOADataArrayTemplateInstantiate.cxx # Has no header + PROPERTIES SKIP_HEADER_INSTALL 1 +) + # Need nsl to resolve gethostbyname on SunOS-5.8 # and socket also if(CMAKE_SYSTEM MATCHES "SunOS.*") diff --git a/Common/Core/SMP/OpenMP/vtkAtomic.h.in b/Common/Core/SMP/OpenMP/vtkAtomic.h.in index 8ea773c68c6..0fdf37f7067 100644 --- a/Common/Core/SMP/OpenMP/vtkAtomic.h.in +++ b/Common/Core/SMP/OpenMP/vtkAtomic.h.in @@ -25,7 +25,7 @@ #include -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ namespace detail { @@ -62,7 +62,7 @@ public: }; } // detail -#endif // __WRAP__ +#endif // __VTK_WRAP__ template class vtkAtomic : private vtk::atomic::detail::IntegralType diff --git a/Common/Core/SMP/OpenMP/vtkSMPToolsInternal.h.in b/Common/Core/SMP/OpenMP/vtkSMPToolsInternal.h.in index 58e8bd9d88b..1ad936f5b37 100644 --- a/Common/Core/SMP/OpenMP/vtkSMPToolsInternal.h.in +++ b/Common/Core/SMP/OpenMP/vtkSMPToolsInternal.h.in @@ -20,7 +20,7 @@ #include //for std::sort() -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ namespace vtk { namespace detail @@ -92,7 +92,7 @@ static void vtkSMPTools_Impl_Sort(RandomAccessIterator begin, }//namespace detail }//namespace vtk -#endif // __WRAP__ +#endif // __VTK_WRAP__ #endif // VTK-HeaderTest-Exclude: vtkSMPToolsInternal.h diff --git a/Common/Core/SMP/Sequential/vtkAtomic.h.in b/Common/Core/SMP/Sequential/vtkAtomic.h.in index 4464a9e9f32..1e71c9beab0 100644 --- a/Common/Core/SMP/Sequential/vtkAtomic.h.in +++ b/Common/Core/SMP/Sequential/vtkAtomic.h.in @@ -78,7 +78,7 @@ class vtkSimpleCriticalSection; -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ namespace detail { @@ -350,7 +350,7 @@ public: #endif } -#endif // __WRAP__ +#endif // __VTK_WRAP__ template class vtkAtomic : private vtk::atomic::detail::IntegralType { diff --git a/Common/Core/Testing/Cxx/CMakeLists.txt b/Common/Core/Testing/Cxx/CMakeLists.txt index b0da0b3cc92..07baa7486b9 100644 --- a/Common/Core/Testing/Cxx/CMakeLists.txt +++ b/Common/Core/Testing/Cxx/CMakeLists.txt @@ -1,3 +1,76 @@ +# Add the vtkDataArrayAPI tests. These are split up to separately test each +# array class, as testing all in a single translation unit led to heavy +# memory consumption and excessively long compile times. +set(data_array_tests) +function(add_data_array_test test_name array_header array_valuetype array_type) + set(VTK_TESTDATAARRAYAPI_HEADER "${array_header}") + set(VTK_TESTDATAARRAYAPI_VALUETYPE "${array_valuetype}") + set(VTK_TESTDATAARRAYAPI_ARRAYTYPE "${array_type}") + set(VTK_TESTDATAARRAYAPI_TESTNAME "TestDataArrayAPI_${test_name}") + set(test_source "${VTK_TESTDATAARRAYAPI_TESTNAME}.cxx") + + configure_file(TestDataArrayAPI.cxx.in "${test_source}") + + set(data_array_tests ${data_array_tests} "${test_source}.cxx" PARENT_SCOPE) +endfunction() + +# Legacy -- test that the vtkDataArrayTemplate interface still works: +if(NOT VTK_LEGACY_REMOVE) + add_data_array_test( + vtkDataArrayTemplate_LEGACY + vtkDataArrayTemplate.h + float + vtkDataArrayTemplate + ) +endif() + +# Non-templated classes: +add_data_array_test(vtkCharArray vtkCharArray.h "char" vtkCharArray) +add_data_array_test(vtkDoubleArray vtkDoubleArray.h "double" vtkDoubleArray) +add_data_array_test(vtkFloatArray vtkFloatArray.h "float" vtkFloatArray) +add_data_array_test(vtkIntArray vtkIntArray.h "int" vtkIntArray) +add_data_array_test(vtkLongArray vtkLongArray.h "long" vtkLongArray) +add_data_array_test(vtkLongLongArray vtkLongLongArray.h "long long" vtkLongLongArray) +add_data_array_test(vtkShortArray vtkShortArray.h "short" vtkShortArray) +add_data_array_test(vtkSignedCharArray vtkSignedCharArray.h "signed char" vtkSignedCharArray) +add_data_array_test(vtkUnsignedCharArray vtkUnsignedCharArray.h "unsigned char" vtkUnsignedCharArray) +add_data_array_test(vtkUnsignedIntArray vtkUnsignedIntArray.h "unsigned int" vtkUnsignedIntArray) +add_data_array_test(vtkUnsignedLongArray vtkUnsignedLongArray.h "unsigned long" vtkUnsignedLongArray) +add_data_array_test(vtkUnsignedLongLongArray vtkUnsignedLongLongArray.h "unsigned long long" vtkUnsignedLongLongArray) +add_data_array_test(vtkUnsignedShortArray vtkUnsignedShortArray.h "unsigned short" vtkUnsignedShortArray) +add_data_array_test(vtkIdTypeArray vtkIdTypeArray.h "vtkIdType" vtkIdTypeArray) +set(value_types + char + double + float + int + long + "long long" + short + "signed char" + "unsigned char" + "unsigned int" + "unsigned long" + "unsigned long long" + "unsigned short" + vtkIdType +) + +# Templated data array subclasses can be done in a loop: +foreach(value_type ${value_types}) + string(REPLACE " " "_" pretty_value_type "${value_type}") + add_data_array_test( + "AoS_${pretty_value_type}" + vtkAOSDataArrayTemplate.h + "${value_type}" + "vtkAOSDataArrayTemplate<${value_type}>") + add_data_array_test( + "SoA_${pretty_value_type}" + vtkSOADataArrayTemplate.h + "${value_type}" + "vtkSOADataArrayTemplate<${value_type}>") +endforeach() + # Tell TestSystemInformation where to find the build trees. set(TestSystemInformation_ARGS ${CMAKE_BINARY_DIR}) @@ -13,6 +86,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestArrayAPIDense.cxx TestArrayAPISparse.cxx TestArrayBool.cxx + TestArrayDispatchers.cxx TestAtomic.cxx TestScalarsToColors.cxx # TestArrayCasting.cxx # Uses Boost in its own separate test. @@ -28,10 +102,11 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestConditionVariable.cxx # TestCxxFeatures.cxx # This is in its own exe too. TestDataArray.cxx - TestDataArrayAPI.cxx TestDataArrayComponentNames.cxx TestDataArrayIterators.cxx TestGarbageCollector.cxx + TestGenericDataArrayAPI.cxx + TestInformationKeyLookup.cxx # TestInstantiator.cxx # Have not enabled instantiators. TestLookupTable.cxx TestLookupTableThreaded.cxx @@ -63,7 +138,10 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests #otherLookupTable.cxx #otherLookupTableWithEnabling.cxx otherStringArray.cxx + + ${data_array_tests} ) + vtk_test_cxx_executable(${vtk-module}CxxTests tests vtkTestNewVar.cxx ) diff --git a/Common/Core/Testing/Cxx/TestAngularPeriodicDataArray.cxx b/Common/Core/Testing/Cxx/TestAngularPeriodicDataArray.cxx index 33786350ffd..706f281bd27 100644 --- a/Common/Core/Testing/Cxx/TestAngularPeriodicDataArray.cxx +++ b/Common/Core/Testing/Cxx/TestAngularPeriodicDataArray.cxx @@ -43,9 +43,9 @@ int TestAngularPeriodicDataArray(int, char * []) angularPeriodicDataArray2->SetAxis(VTK_PERIODIC_ARRAY_AXIS_Y); double pTmp[3]; - angularPeriodicDataArray->GetTupleValue(0, pTmp); + angularPeriodicDataArray->GetTypedTuple(0, pTmp); float pTmp2[3]; - angularPeriodicDataArray2->GetTupleValue(0, pTmp2); + angularPeriodicDataArray2->GetTypedTuple(0, pTmp2); double dEpsilon = std::numeric_limits::epsilon() * 20.0; float fEpsilon = std::numeric_limits::epsilon() * 20.f; @@ -85,7 +85,7 @@ int TestAngularPeriodicDataArray(int, char * []) tmp[1] = 1.; tmp[2] = 1.; angularPeriodicDataArray2->SetCenter(tmp); - angularPeriodicDataArray2->GetTupleValue(0, pTmp2); + angularPeriodicDataArray2->GetTypedTuple(0, pTmp2); if (std::abs(pTmp2[0] - 4.7902297) >= fEpsilon || std::abs(pTmp2[1] - 12.3) >= fEpsilon || @@ -122,7 +122,7 @@ int TestAngularPeriodicDataArray(int, char * []) tensorPArray->SetCenter(tmp); double pTmp3[9]; - tensorPArray->GetTupleValue(0, pTmp3); + tensorPArray->GetTypedTuple(0, pTmp3); if (std::abs(pTmp3[0] - 2.0096597239047708783) >= dEpsilon || std::abs(pTmp3[1] - 13.555918489185591724) >= dEpsilon || std::abs(pTmp3[2] - -8.6693107531410973365) >= dEpsilon || diff --git a/Common/Core/Testing/Cxx/TestArrayDispatchers.cxx b/Common/Core/Testing/Cxx/TestArrayDispatchers.cxx new file mode 100644 index 00000000000..fe7f28ecad2 --- /dev/null +++ b/Common/Core/Testing/Cxx/TestArrayDispatchers.cxx @@ -0,0 +1,792 @@ +/*============================================================================== + + Program: Visualization Toolkit + Module: TestArrayDispatchers.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +==============================================================================*/ + +// We define our own set of arrays for the dispatch list. This allows the test +// to run regardless of the compiled dispatch configuration. Note that this is +// only possible because we do not use dispatches that are compiled into other +// translation units, but only explicit dispatches that we generate here. +#define vtkArrayDispatchArrayList_h // Skip loading the actual header + +#include "vtkAOSDataArrayTemplate.h" +#include "vtkSOADataArrayTemplate.h" +#include "vtkTypeList.h" + +namespace vtkArrayDispatch { +typedef vtkTypeList::Unique< + vtkTypeList_Create_10( + vtkAOSDataArrayTemplate, + vtkAOSDataArrayTemplate, + vtkAOSDataArrayTemplate, + vtkAOSDataArrayTemplate, + vtkAOSDataArrayTemplate, + vtkSOADataArrayTemplate, + vtkSOADataArrayTemplate, + vtkSOADataArrayTemplate, + vtkSOADataArrayTemplate, + vtkSOADataArrayTemplate + ) +>::Result Arrays; +} // end namespace vtkArrayDispatch + +#include "vtkArrayDispatch.h" +#include "vtkNew.h" + +#include +#include +#include + +namespace { + +//============================================================================== +// Our functor for testing. +struct TestWorker +{ + TestWorker() + : Array1(NULL), Array2(NULL), Array3(NULL) + {} + + void Reset() + { + this->Array1 = NULL; + this->Array2 = NULL; + this->Array3 = NULL; + } + + template + void operator()(Array1T *array1) + { + this->Array1 = array1; + } + + template + void operator()(Array1T *array1, Array2T *array2) + { + this->Array1 = array1; + this->Array2 = array2; + } + + template + void operator()(Array1T *array1, Array2T *array2, Array3T *array3) + { + this->Array1 = array1; + this->Array2 = array2; + this->Array3 = array3; + } + + vtkDataArray *Array1; + vtkDataArray *Array2; + vtkDataArray *Array3; +}; + +//============================================================================== +// Container for testing arrays. +struct Arrays +{ + Arrays(); + ~Arrays(); + + static vtkAOSDataArrayTemplate *aosDouble; + static vtkAOSDataArrayTemplate *aosFloat; + static vtkAOSDataArrayTemplate *aosInt; + static vtkAOSDataArrayTemplate *aosUnsignedChar; + static vtkAOSDataArrayTemplate *aosIdType; + + static vtkSOADataArrayTemplate *soaDouble; + static vtkSOADataArrayTemplate *soaFloat; + static vtkSOADataArrayTemplate *soaInt; + static vtkSOADataArrayTemplate *soaUnsignedChar; + static vtkSOADataArrayTemplate *soaIdType; + + static std::vector aosArrays; + static std::vector soaArrays; + static std::vector allArrays; +}; + +vtkAOSDataArrayTemplate *Arrays::aosDouble; +vtkAOSDataArrayTemplate *Arrays::aosFloat; +vtkAOSDataArrayTemplate *Arrays::aosInt; +vtkAOSDataArrayTemplate *Arrays::aosUnsignedChar; +vtkAOSDataArrayTemplate *Arrays::aosIdType; +vtkSOADataArrayTemplate *Arrays::soaDouble; +vtkSOADataArrayTemplate *Arrays::soaFloat; +vtkSOADataArrayTemplate *Arrays::soaInt; +vtkSOADataArrayTemplate *Arrays::soaUnsignedChar; +vtkSOADataArrayTemplate *Arrays::soaIdType; + +std::vector Arrays::aosArrays; +std::vector Arrays::soaArrays; +std::vector Arrays::allArrays; + +//============================================================================== +// Miscellaneous Debris +typedef std::vector::iterator ArrayIter; + +typedef vtkTypeList_Create_5(vtkAOSDataArrayTemplate, + vtkAOSDataArrayTemplate, + vtkAOSDataArrayTemplate, + vtkAOSDataArrayTemplate, + vtkAOSDataArrayTemplate) AoSArrayList; +typedef vtkTypeList_Create_5(vtkSOADataArrayTemplate, + vtkSOADataArrayTemplate, + vtkSOADataArrayTemplate, + vtkSOADataArrayTemplate, + vtkSOADataArrayTemplate) SoAArrayList; + +typedef vtkTypeList::Append::Result AllArrayList; + +//------------------------------------------------------------------------------ +// Return true if the VTK type tag is an integral type. +inline bool isIntegral(int vtkType) +{ + switch (vtkType) + { + case VTK_CHAR: + case VTK_SIGNED_CHAR: + case VTK_UNSIGNED_CHAR: + case VTK_SHORT: + case VTK_UNSIGNED_SHORT: + case VTK_INT: + case VTK_UNSIGNED_INT: + case VTK_LONG: + case VTK_UNSIGNED_LONG: + case VTK_ID_TYPE: + case VTK_LONG_LONG: + case VTK_UNSIGNED_LONG_LONG: + case VTK___INT64: + case VTK_UNSIGNED___INT64: + return true; + } + return false; +} + +//------------------------------------------------------------------------------ +// Return true if the VTK type tag is a real (e.g. floating-point) type. +inline bool isReal(int vtkType) +{ + switch (vtkType) + { + case VTK_FLOAT: + case VTK_DOUBLE: + return true; + } + return false; +} + +//------------------------------------------------------------------------------ +// Check condition during test. +#define testAssert(expr, errorMessage) \ + if (!(expr)) \ + { \ + ++errors; \ + vtkGenericWarningMacro(<<"Assertion failed: " #expr << "\n" \ + << errorMessage); \ + } + +//------------------------------------------------------------------------------ +int TestDispatch() +{ + int errors = 0; + + vtkArrayDispatch::Dispatch dispatcher; + TestWorker worker; + + for (ArrayIter it = Arrays::allArrays.begin(), + itEnd = Arrays::allArrays.end(); it != itEnd; ++it) + { + vtkDataArray *array = *it; + testAssert(dispatcher.Execute(array, worker), "Dispatch failed."); + testAssert(worker.Array1 == array, "Array 1 does not match input."); + worker.Reset(); + } + + return errors; +} + +//------------------------------------------------------------------------------ +int TestDispatchByArray() +{ + int errors = 0; + + vtkArrayDispatch::DispatchByArray dispatcher; + TestWorker worker; + + // AoS arrays: All should pass: + for (ArrayIter it = Arrays::aosArrays.begin(), + itEnd = Arrays::aosArrays.end(); it != itEnd; ++it) + { + vtkDataArray *array = *it; + testAssert(dispatcher.Execute(array, worker), "Dispatch failed."); + testAssert(worker.Array1 == array, "Array 1 does not match input."); + worker.Reset(); + } + + // AoS arrays: All should fail: + for (ArrayIter it = Arrays::soaArrays.begin(), + itEnd = Arrays::soaArrays.end(); it != itEnd; ++it) + { + vtkDataArray *array = *it; + testAssert(!dispatcher.Execute(array, worker), + "Dispatch should have failed."); + testAssert(worker.Array1 == NULL, "Array 1 should be NULL."); + worker.Reset(); + } + + return errors; +} + +//------------------------------------------------------------------------------ +int TestDispatchByValueType() +{ + int errors = 0; + + // Create dispatcher that only generates code paths for arrays with reals. + vtkArrayDispatch::DispatchByValueType dispatcher; + TestWorker worker; + + for (ArrayIter it = Arrays::allArrays.begin(), + itEnd = Arrays::allArrays.end(); it != itEnd; ++it) + { + vtkDataArray *array = *it; + bool isValid = isReal(array->GetDataType()); + + if (isValid) + { + testAssert(dispatcher.Execute(array, worker), "Dispatch failed."); + testAssert(worker.Array1 == array, "Array 1 does not match input."); + } + else + { + testAssert(!dispatcher.Execute(array, worker), + "Dispatch should have failed."); + testAssert(worker.Array1 == NULL, "Array 1 should be NULL."); + } + + worker.Reset(); + } + + return errors; +} + +//------------------------------------------------------------------------------ +int TestDispatch2ByArray() +{ + int errors = 0; + + // Restrictions: + // Array1: SoA + // Array2: AoS + vtkArrayDispatch::Dispatch2ByArray< + SoAArrayList, + AoSArrayList + > dispatcher; + TestWorker worker; + + for (ArrayIter it1 = Arrays::allArrays.begin(), + itEnd1 = Arrays::allArrays.end(); it1 != itEnd1; ++it1) + { + vtkDataArray *array1 = *it1; + bool array1Valid = + array1->GetArrayType() == vtkAbstractArray::SoADataArrayTemplate; + + for (ArrayIter it2 = Arrays::allArrays.begin(), + itEnd2 = Arrays::allArrays.end(); it2 != itEnd2; ++it2) + { + vtkDataArray *array2 = *it2; + bool array2Valid = + array2->GetArrayType() == vtkAbstractArray::AoSDataArrayTemplate; + + if (array1Valid && array2Valid) + { + testAssert(dispatcher.Execute(array1, array2, worker), + "Dispatch failed."); + testAssert(worker.Array1 == array1, "Array 1 does not match input."); + testAssert(worker.Array2 == array2, "Array 2 does not match input."); + } + else + { + testAssert(!dispatcher.Execute(array1, array2, worker), + "Dispatch should have failed."); + testAssert(worker.Array1 == NULL, "Array 1 should be NULL."); + testAssert(worker.Array2 == NULL, "Array 2 should be NULL."); + } + + worker.Reset(); + } + } + + return errors; +} + +//------------------------------------------------------------------------------ +int TestDispatch2ByValueType() +{ + int errors = 0; + + // Restrictions: + // Array1: Integers + // Array2: Reals + vtkArrayDispatch::Dispatch2ByValueType< + vtkArrayDispatch::Integrals, + vtkArrayDispatch::Reals + > dispatcher; + TestWorker worker; + + for (ArrayIter it1 = Arrays::allArrays.begin(), + itEnd1 = Arrays::allArrays.end(); it1 != itEnd1; ++it1) + { + vtkDataArray *array1 = *it1; + bool array1Valid = isIntegral(array1->GetDataType()); + + for (ArrayIter it2 = Arrays::allArrays.begin(), + itEnd2 = Arrays::allArrays.end(); it2 != itEnd2; ++it2) + { + vtkDataArray *array2 = *it2; + bool array2Valid = isReal(array2->GetDataType()); + + if (array1Valid && array2Valid) + { + testAssert(dispatcher.Execute(array1, array2, worker), + "Dispatch failed."); + testAssert(worker.Array1 == array1, "Array 1 does not match input."); + testAssert(worker.Array2 == array2, "Array 2 does not match input."); + } + else + { + testAssert(!dispatcher.Execute(array1, array2, worker), + "Dispatch should have failed."); + testAssert(worker.Array1 == NULL, "Array 1 should be NULL."); + testAssert(worker.Array2 == NULL, "Array 2 should be NULL."); + } + + worker.Reset(); + } + } + + return errors; +} + +//------------------------------------------------------------------------------ +int TestDispatch2ByArrayWithSameValueType() +{ + int errors = 0; + + // Restrictions: + // - Types must match + vtkArrayDispatch::Dispatch2ByArrayWithSameValueType< + AoSArrayList, + SoAArrayList + > dispatcher; + TestWorker worker; + + for (ArrayIter it1 = Arrays::allArrays.begin(), + itEnd1 = Arrays::allArrays.end(); it1 != itEnd1; ++it1) + { + vtkDataArray *array1 = *it1; + bool array1Valid = + array1->GetArrayType() == vtkAbstractArray::AoSDataArrayTemplate; + + for (ArrayIter it2 = Arrays::allArrays.begin(), + itEnd2 = Arrays::allArrays.end(); it2 != itEnd2; ++it2) + { + vtkDataArray *array2 = *it2; + bool array2Valid = + array2->GetArrayType() == vtkAbstractArray::SoADataArrayTemplate && + vtkDataTypesCompare(array1->GetDataType(), array2->GetDataType()); + + if (array1Valid && array2Valid) + { + testAssert(dispatcher.Execute(array1, array2, worker), + "Dispatch failed."); + testAssert(worker.Array1 == array1, "Array 1 does not match input."); + testAssert(worker.Array2 == array2, "Array 2 does not match input."); + } + else + { + testAssert(!dispatcher.Execute(array1, array2, worker), + "Dispatch should have failed."); + testAssert(worker.Array1 == NULL, "Array 1 should be NULL."); + testAssert(worker.Array2 == NULL, "Array 2 should be NULL."); + } + + worker.Reset(); + } + } + + return errors; +} + +//------------------------------------------------------------------------------ +int TestDispatch2BySameValueType() +{ + int errors = 0; + + // Restrictions: + // - Types must match + // - Only integral types. + vtkArrayDispatch::Dispatch2BySameValueType< + vtkArrayDispatch::Integrals + > dispatcher; + TestWorker worker; + + for (ArrayIter it1 = Arrays::allArrays.begin(), + itEnd1 = Arrays::allArrays.end(); it1 != itEnd1; ++it1) + { + vtkDataArray *array1 = *it1; + bool array1Valid = isIntegral(array1->GetDataType()); + + for (ArrayIter it2 = Arrays::allArrays.begin(), + itEnd2 = Arrays::allArrays.end(); it2 != itEnd2; ++it2) + { + vtkDataArray *array2 = *it2; + bool array2Valid = vtkDataTypesCompare(array1->GetDataType(), + array2->GetDataType()) != 0; + + if (array1Valid && array2Valid) + { + testAssert(dispatcher.Execute(array1, array2, worker), + "Dispatch failed."); + testAssert(worker.Array1 == array1, "Array 1 does not match input."); + testAssert(worker.Array2 == array2, "Array 2 does not match input."); + } + else + { + testAssert(!dispatcher.Execute(array1, array2, worker), + "Dispatch should have failed."); + testAssert(worker.Array1 == NULL, "Array 1 should be NULL."); + testAssert(worker.Array2 == NULL, "Array 2 should be NULL."); + } + + worker.Reset(); + } + } + + return errors; +} + +//------------------------------------------------------------------------------ +int TestDispatch3ByArray() +{ + int errors = 0; + + // Restrictions: + // Array1: SoA + // Array2: AoS + // Array3: AoS/SoA float arrays + vtkArrayDispatch::Dispatch3ByArray< + SoAArrayList, + AoSArrayList, + vtkTypeList_Create_2(vtkAOSDataArrayTemplate, + vtkSOADataArrayTemplate) + > dispatcher; + TestWorker worker; + + for (ArrayIter it1 = Arrays::allArrays.begin(), + itEnd1 = Arrays::allArrays.end(); it1 != itEnd1; ++it1) + { + vtkDataArray *array1 = *it1; + bool array1Valid = + array1->GetArrayType() == vtkAbstractArray::SoADataArrayTemplate; + + for (ArrayIter it2 = Arrays::allArrays.begin(), + itEnd2 = Arrays::allArrays.end(); it2 != itEnd2; ++it2) + { + vtkDataArray *array2 = *it2; + bool array2Valid = + array2->GetArrayType() == vtkAbstractArray::AoSDataArrayTemplate; + + for (ArrayIter it3 = Arrays::allArrays.begin(), + itEnd3 = Arrays::allArrays.end(); it3 != itEnd3; ++it3) + { + vtkDataArray *array3 = *it3; + bool array3Valid = array3->GetDataType() == VTK_FLOAT; + + if (array1Valid && array2Valid && array3Valid) + { + testAssert(dispatcher.Execute(array1, array2, array3, worker), + "Dispatch failed."); + testAssert(worker.Array1 == array1, "Array 1 does not match input."); + testAssert(worker.Array2 == array2, "Array 2 does not match input."); + testAssert(worker.Array3 == array3, "Array 3 does not match input."); + } + else + { + testAssert(!dispatcher.Execute(array1, array2, array3, worker), + "Dispatch should have failed."); + testAssert(worker.Array1 == NULL, "Array 1 should be NULL."); + testAssert(worker.Array2 == NULL, "Array 2 should be NULL."); + testAssert(worker.Array3 == NULL, "Array 3 should be NULL."); + } + + worker.Reset(); + } + } + } + + return errors; +} + +//------------------------------------------------------------------------------ +int TestDispatch3ByValueType() +{ + int errors = 0; + + // Restrictions: + // Array1: Must be real type. + // Array2: Must be integer type. + // Array3: Must be unsigned char type. + vtkArrayDispatch::Dispatch3ByValueType< + vtkArrayDispatch::Reals, + vtkArrayDispatch::Integrals, + vtkTypeList_Create_1(unsigned char) + > dispatcher; + TestWorker worker; + + for (ArrayIter it1 = Arrays::allArrays.begin(), + itEnd1 = Arrays::allArrays.end(); it1 != itEnd1; ++it1) + { + vtkDataArray *array1 = *it1; + bool array1Valid = isReal(array1->GetDataType()); + + for (ArrayIter it2 = Arrays::allArrays.begin(), + itEnd2 = Arrays::allArrays.end(); it2 != itEnd2; ++it2) + { + vtkDataArray *array2 = *it2; + bool array2Valid = isIntegral(array2->GetDataType()); + + for (ArrayIter it3 = Arrays::allArrays.begin(), + itEnd3 = Arrays::allArrays.end(); it3 != itEnd3; ++it3) + { + vtkDataArray *array3 = *it3; + bool array3Valid = vtkDataTypesCompare(array3->GetDataType(), + VTK_UNSIGNED_CHAR) != 0; + + if (array1Valid && array2Valid && array3Valid) + { + testAssert(dispatcher.Execute(array1, array2, array3, worker), + "Dispatch failed."); + testAssert(worker.Array1 == array1, "Array 1 does not match input."); + testAssert(worker.Array2 == array2, "Array 2 does not match input."); + testAssert(worker.Array3 == array3, "Array 3 does not match input."); + } + else + { + testAssert(!dispatcher.Execute(array1, array2, array3, worker), + "Dispatch should have failed."); + testAssert(worker.Array1 == NULL, "Array 1 should be NULL."); + testAssert(worker.Array2 == NULL, "Array 2 should be NULL."); + testAssert(worker.Array3 == NULL, "Array 3 should be NULL."); + } + + worker.Reset(); + } + } + } + + return errors; +} + +//------------------------------------------------------------------------------ +int TestDispatch3ByArrayWithSameValueType() +{ + int errors = 0; + + // Restrictions: + // - Array1: SoA + // - Array2: AoS + // - Array3: Any array type + // - All arrays have same ValueType + vtkArrayDispatch::Dispatch3ByArrayWithSameValueType< + SoAArrayList, + AoSArrayList, + AllArrayList + > dispatcher; + TestWorker worker; + + for (ArrayIter it1 = Arrays::allArrays.begin(), + itEnd1 = Arrays::allArrays.end(); it1 != itEnd1; ++it1) + { + vtkDataArray *array1 = *it1; + bool array1Valid = + array1->GetArrayType() == vtkAbstractArray::SoADataArrayTemplate; + + for (ArrayIter it2 = Arrays::allArrays.begin(), + itEnd2 = Arrays::allArrays.end(); it2 != itEnd2; ++it2) + { + vtkDataArray *array2 = *it2; + bool array2Valid = + array2->GetArrayType() == vtkAbstractArray::AoSDataArrayTemplate && + vtkDataTypesCompare(array1->GetDataType(), array2->GetDataType()); + + for (ArrayIter it3 = Arrays::allArrays.begin(), + itEnd3 = Arrays::allArrays.end(); it3 != itEnd3; ++it3) + { + vtkDataArray *array3 = *it3; + bool array3Valid = vtkDataTypesCompare(array1->GetDataType(), + array3->GetDataType()) != 0; + + if (array1Valid && array2Valid && array3Valid) + { + testAssert(dispatcher.Execute(array1, array2, array3, worker), + "Dispatch failed."); + testAssert(worker.Array1 == array1, "Array 1 does not match input."); + testAssert(worker.Array2 == array2, "Array 2 does not match input."); + testAssert(worker.Array3 == array3, "Array 3 does not match input."); + } + else + { + testAssert(!dispatcher.Execute(array1, array2, array3, worker), + "Dispatch should have failed."); + testAssert(worker.Array1 == NULL, "Array 1 should be NULL."); + testAssert(worker.Array2 == NULL, "Array 2 should be NULL."); + testAssert(worker.Array3 == NULL, "Array 3 should be NULL."); + } + + worker.Reset(); + } + } + } + + return errors; +} + +//------------------------------------------------------------------------------ +int TestDispatch3BySameValueType() +{ + int errors = 0; + + // Restrictions: + // - All arrays must have same ValueType + // - ValueType must be float, double, or unsigned char. + vtkArrayDispatch::Dispatch3BySameValueType< + vtkTypeList::Append::Result + > dispatcher; + TestWorker worker; + + for (ArrayIter it1 = Arrays::allArrays.begin(), + itEnd1 = Arrays::allArrays.end(); it1 != itEnd1; ++it1) + { + vtkDataArray *array1 = *it1; + bool array1Valid = isReal(array1->GetDataType()) || + vtkDataTypesCompare(array1->GetDataType(), + VTK_UNSIGNED_CHAR); + + for (ArrayIter it2 = Arrays::allArrays.begin(), + itEnd2 = Arrays::allArrays.end(); it2 != itEnd2; ++it2) + { + vtkDataArray *array2 = *it2; + bool array2Valid = vtkDataTypesCompare(array1->GetDataType(), + array2->GetDataType()) != 0; + + for (ArrayIter it3 = Arrays::allArrays.begin(), + itEnd3 = Arrays::allArrays.end(); it3 != itEnd3; ++it3) + { + vtkDataArray *array3 = *it3; + bool array3Valid = vtkDataTypesCompare(array1->GetDataType(), + array3->GetDataType()) != 0; + + if (array1Valid && array2Valid && array3Valid) + { + testAssert(dispatcher.Execute(array1, array2, array3, worker), + "Dispatch failed."); + testAssert(worker.Array1 == array1, "Array 1 does not match input."); + testAssert(worker.Array2 == array2, "Array 2 does not match input."); + testAssert(worker.Array3 == array3, "Array 3 does not match input."); + } + else + { + testAssert(!dispatcher.Execute(array1, array2, array3, worker), + "Dispatch should have failed."); + testAssert(worker.Array1 == NULL, "Array 1 should be NULL."); + testAssert(worker.Array2 == NULL, "Array 2 should be NULL."); + testAssert(worker.Array3 == NULL, "Array 3 should be NULL."); + } + + worker.Reset(); + } + } + } + + return errors; +} + +//------------------------------------------------------------------------------ +Arrays::Arrays() +{ + aosDouble = vtkAOSDataArrayTemplate::New(); + aosFloat = vtkAOSDataArrayTemplate::New(); + aosInt = vtkAOSDataArrayTemplate::New(); + aosUnsignedChar = vtkAOSDataArrayTemplate::New(); + aosIdType = vtkAOSDataArrayTemplate::New(); + + soaDouble = vtkSOADataArrayTemplate::New(); + soaFloat = vtkSOADataArrayTemplate::New(); + soaInt = vtkSOADataArrayTemplate::New(); + soaUnsignedChar = vtkSOADataArrayTemplate::New(); + soaIdType = vtkSOADataArrayTemplate::New(); + + aosArrays.push_back(aosDouble); + aosArrays.push_back(aosFloat); + aosArrays.push_back(aosInt); + aosArrays.push_back(aosUnsignedChar); + aosArrays.push_back(aosIdType); + + soaArrays.push_back(soaDouble); + soaArrays.push_back(soaFloat); + soaArrays.push_back(soaInt); + soaArrays.push_back(soaUnsignedChar); + soaArrays.push_back(soaIdType); + + std::copy(aosArrays.begin(), aosArrays.end(), std::back_inserter(allArrays)); + std::copy(soaArrays.begin(), soaArrays.end(), std::back_inserter(allArrays)); +} + +//------------------------------------------------------------------------------ +Arrays::~Arrays() +{ + aosDouble->Delete(); + aosFloat->Delete(); + aosInt->Delete(); + aosUnsignedChar->Delete(); + aosIdType->Delete(); + soaDouble->Delete(); + soaFloat->Delete(); + soaInt->Delete(); + soaUnsignedChar->Delete(); + soaIdType->Delete(); +} + +} // end anon namespace + +//------------------------------------------------------------------------------ +int TestArrayDispatchers(int, char *[]) +{ + int errors = 0; + Arrays arrays; + (void)arrays; // unused, just manages static memory + + errors += TestDispatch(); + errors += TestDispatchByArray(); + errors += TestDispatchByValueType(); + errors += TestDispatch2ByArray(); + errors += TestDispatch2ByValueType(); + errors += TestDispatch2ByArrayWithSameValueType(); + errors += TestDispatch2BySameValueType(); + errors += TestDispatch3ByArray(); + errors += TestDispatch3ByValueType(); + errors += TestDispatch3ByArrayWithSameValueType(); + errors += TestDispatch3BySameValueType(); + + return errors == 0 ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/Common/Core/Testing/Cxx/TestDataArrayAPI.cxx b/Common/Core/Testing/Cxx/TestDataArrayAPI.cxx.in similarity index 56% rename from Common/Core/Testing/Cxx/TestDataArrayAPI.cxx rename to Common/Core/Testing/Cxx/TestDataArrayAPI.cxx.in index f2ea6dd0650..95cf47dd716 100644 --- a/Common/Core/Testing/Cxx/TestDataArrayAPI.cxx +++ b/Common/Core/Testing/Cxx/TestDataArrayAPI.cxx.in @@ -16,52 +16,56 @@ #include "vtkDataArray.h" // Helpers: +#include "vtkAOSDataArrayTemplate.h" +#include "vtkArrayDispatch.h" +#include "vtkArrayIterator.h" +#include "vtkConfigure.h" +#include "vtkDoubleArray.h" #include "vtkIdList.h" +#include "vtkIdTypeArray.h" #include "vtkMath.h" #include "vtkNew.h" #include "vtkSmartPointer.h" -#include "vtkTypedDataArray.h" +#include "vtkSOADataArrayTemplate.h" +#include "vtkType.h" #include "vtkTypeTraits.h" +#include "vtkVariant.h" +#include "vtkVariantCast.h" #include #include +#include #include #include #include #include // Concrete classes for testing: -#include "vtkCharArray.h" -#include "vtkFloatArray.h" -#include "vtkDoubleArray.h" -#include "vtkIdTypeArray.h" -#include "vtkIntArray.h" -#include "vtkLongArray.h" -#include "vtkLongLongArray.h" -#include "vtkShortArray.h" -#include "vtkSignedCharArray.h" -#include "vtkUnsignedCharArray.h" -#include "vtkUnsignedIntArray.h" -#include "vtkUnsignedLongArray.h" -#include "vtkUnsignedLongLongArray.h" -#include "vtkUnsignedShortArray.h" +#include "@VTK_TESTDATAARRAYAPI_HEADER@" + +// Needed for portable setenv on MSVC... +#include "vtksys/SystemTools.hxx" // About this test: // // This test runs a battery of unit tests that exercise the vtkDataArray API // on concrete implementations of their subclasses. It is designed to be easily -// extended to cover new array implementations and addition unit tests. +// extended to cover new array implementations and additional unit tests. +// +// This also tests the vtkAbstractArray API. The vtkGenericDataArray API is +// tested in TestGenericDataArrayAPI. // // This test has three main components: -// - Entry point: TestDataArrayAPI(). Add new array classes here. +// - Entry point: TestDataArrayAPI_[ARRAYNAME]() // - Unit test caller: ExerciseDataArray(). Templated on value and array types. // Calls individual unit test functions to excerise the array methods. -// Add new unit test calls here. +// Add new unit test calls here. Note that the ExerciseGetRange runner has +// been split out to fix compilation on less robust compilers that struggle +// with the heavy templating (known issue on llvm-gcc 4.2.1). // - Unit test functions: Test_[methodSignature](). Templated on value type, // array type, and possibly other parameters to simplify implementations. // These should use the DataArrayAPI macros as needed - // Forward declare the test function: namespace { template @@ -74,46 +78,20 @@ int ExerciseGetRange(); //-------------Test Entry Point------------------------------------------------- //------------------------------------------------------------------------------ -int TestDataArrayAPI(int, char *[]) +int @VTK_TESTDATAARRAYAPI_TESTNAME@(int, char *[]) { int errors = 0; - // Add array classes here: - // Defaults: - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - errors += ExerciseDataArray(); - - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); - errors += ExerciseGetRange(); + errors += ExerciseDataArray<@VTK_TESTDATAARRAYAPI_VALUETYPE@, + @VTK_TESTDATAARRAYAPI_ARRAYTYPE@ >(); + errors += ExerciseGetRange<@VTK_TESTDATAARRAYAPI_VALUETYPE@, + @VTK_TESTDATAARRAYAPI_ARRAYTYPE@ >(); if (errors > 0) { std::cerr << "Test failed! Error count: " << errors << std::endl; } + return errors == 0 ? EXIT_SUCCESS : EXIT_FAILURE; } @@ -131,18 +109,19 @@ int TestDataArrayAPI(int, char *[]) #define DataArrayAPIFinish() return errors #define DataArrayAPICreateTestArray(name) vtkNew name +#define DataArrayAPICreateTestArrayByType(name, type) vtkNew name #define DataArrayAPICreateReferenceArray(name) \ vtkSmartPointer name##DA = CreateDataArray(); \ - vtkTypedDataArray *name = \ - vtkTypedDataArray::SafeDownCast(name##DA.GetPointer()); \ - assert("Reference array is vtkTypedDataArray" && name != NULL) + vtkAOSDataArrayTemplate *name = \ + vtkAOSDataArrayTemplate::SafeDownCast(name##DA.GetPointer()); \ + assert("Reference array is vtkAOSDataArrayTemplate" && name != NULL) #define DataArrayAPICreateReferenceArrayWithType(name, valueType) \ vtkSmartPointer name##DA = CreateDataArray(); \ - vtkTypedDataArray *name = \ - vtkTypedDataArray::SafeDownCast(name##DA.GetPointer()); \ - assert("Reference array is vtkTypedDataArray" && name != NULL) + vtkAOSDataArrayTemplate *name = \ + vtkAOSDataArrayTemplate::SafeDownCast(name##DA.GetPointer()); \ + assert("Reference array is vtkAOSDataArrayTemplate" && name != NULL) #define DataArrayAPINonFatalError(x) \ { \ @@ -159,6 +138,10 @@ int TestDataArrayAPI(int, char *[]) DataArrayAPINonFatalError(x) \ DataArrayAPIFinish(); +#define DataArrayAPIAssert(x, mess) \ + if (x) {} \ + else { DataArrayAPIError("Test assertion '" #x "' failed: " << mess) } + namespace { // Convenience function to create a concrete data array from a template type: @@ -176,6 +159,289 @@ vtkSmartPointer CreateDataArray() //------------------Unit Test Implementations----------------------------------- //------------------------------------------------------------------------------ +//------------------------vtkAbstactArray API----------------------------------- + +// int Allocate(vtkIdType numValues, vtkIdType ext=1000) +// Sets MaxId == -1 +// Sets Size >= numValues +// If numValues == 0, delete the array. +// ext is not used. +// Result is 1/0 for success/failure. +template +int Test_int_Allocate_numValues_ext() +{ + DataArrayAPIInit("int Allocate(vtkIdType numValues, vtkIdType ext)"); + DataArrayAPICreateTestArray(array); + + int success = array->Allocate(0); + DataArrayAPIAssert(success, "Allocation failed."); + DataArrayAPIAssert(array->GetSize() == 0, + "Invalid Size (" << array->GetSize() << ")."); + DataArrayAPIAssert(array->GetMaxId() == -1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + success = array->Allocate(100); + DataArrayAPIAssert(success, "Allocation failed."); + DataArrayAPIAssert(array->GetSize() >= 100, + "Invalid Size (" << array->GetSize() << ")."); + DataArrayAPIAssert(array->GetMaxId() == -1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + array->SetNumberOfComponents(1); + array->SetNumberOfTuples(50); + DataArrayAPIAssert(array->GetMaxId() == 49, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + success = array->Allocate(0); + DataArrayAPIAssert(success, "Allocation failed."); + DataArrayAPIAssert(array->GetSize() == 0, + "Invalid Size (" << array->GetSize() << ")."); + DataArrayAPIAssert(array->GetMaxId() == -1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + DataArrayAPIFinish(); +} + +// void Initialize() +// Release data and reset state. +template +int Test_void_Initialize() +{ + DataArrayAPIInit("void Initialize()"); + DataArrayAPICreateTestArray(array); + + array->SetNumberOfComponents(1); + array->SetNumberOfTuples(50); + DataArrayAPIAssert(array->GetMaxId() == 49, + "Invalid MaxId (" << array->GetMaxId() << ")."); + DataArrayAPIAssert(array->GetSize() >= 50, + "Invalid Size (" << array->GetSize() << ")."); + + array->Initialize(); + DataArrayAPIAssert(array->GetMaxId() == -1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + DataArrayAPIAssert(array->GetSize() == 0, + "Invalid Size (" << array->GetSize() << ")."); + + DataArrayAPIFinish(); +} + +// int GetDataType() +template +int Test_int_GetDataType() +{ + DataArrayAPIInit("int GetDataType()"); + DataArrayAPICreateTestArray(array); + + DataArrayAPIAssert(vtkDataTypesCompare(array->GetDataType(), + vtkTypeTraits::VTKTypeID()), + "Incorrect data type. Expected " + << vtkTypeTraits::VTKTypeID() << ", got " + << array->GetDataType() << "."); + + // Special case: vtkIdTypeArray must return VTK_ID_TYPE, not the actual type: + if (typeid(ArrayT) == typeid(vtkIdTypeArray)) + { + DataArrayAPIAssert(vtkDataTypesCompare(array->GetDataType(), VTK_ID_TYPE), + "Incorrect data type for vtkIdTypeArray. Expected " + "VTK_ID_TYPE (" << VTK_ID_TYPE << "), got " + << array->GetDataType() << "."); + } + + DataArrayAPIFinish(); +} + +// int GetDataTypeSize() +template +int Test_int_GetDataTypeSize() +{ + DataArrayAPIInit("int GetDataTypeSize()"); + DataArrayAPICreateTestArray(array); + + DataArrayAPIAssert(array->GetDataTypeSize() == sizeof(ScalarT), + "Incorrect data type size. Expected " + << sizeof(ScalarT) << ", got " + << array->GetDataTypeSize() << "."); + + DataArrayAPIFinish(); +} + +// int GetElementComponentSize() +// Same as GetDataTypeSize for data arrays: +template +int Test_int_GetElementComponentSize() +{ + DataArrayAPIInit("int GetElementComponentSize()"); + DataArrayAPICreateTestArray(array); + + DataArrayAPIAssert(array->GetElementComponentSize() == sizeof(ScalarT), + "Incorrect element component size. Expected " + << sizeof(ScalarT) << ", got " + << array->GetElementComponentSize() << "."); + + DataArrayAPIFinish(); +} + +// void SetNumberOfComponents(int comps) +// int GetNumberOfComponents() +template +int Test_NumberOfComponents() +{ + DataArrayAPIInit("void SetNumberOfComponents(int comps)"); + DataArrayAPICreateTestArray(array); + DataArrayAPIAssert(array->GetNumberOfComponents() == 1, + "Initial number of components expected to be 1, but is " + << array->GetNumberOfComponents() << "."); + + array->SetNumberOfComponents(12); + DataArrayAPIAssert(array->GetNumberOfComponents() == 12, + "Number of components expected to be 12, but is " + << array->GetNumberOfComponents() << "."); + + DataArrayAPIFinish(); +} + +// void SetComponentName( vtkIdType component, const char *name ) +// const char* GetComponentName( vtkIdType component ) +// bool HasAComponentName() +// int CopyComponentNames( vtkAbstractArray *da ) +template +int Test_ComponentNames() +{ + DataArrayAPIInit("bool HasAComponentName()"); + DataArrayAPICreateTestArray(array); + DataArrayAPIAssert(!array->HasAComponentName(), + "New array has a named components."); + + int comps = 5; + array->SetNumberOfComponents(comps); + + std::ostringstream str; + + for (vtkIdType c = 0; c < static_cast(comps); ++c) + { + DataArrayAPIUpdateSignature("const char* GetComponentName(vtkIdType comp)"); + DataArrayAPIAssert(array->GetComponentName(c) == NULL, + "New array has a named component."); + str.str(""); + str << "Component " << c; + DataArrayAPIUpdateSignature("const char* SetComponentName(vtkIdType comp)"); + array->SetComponentName(c, str.str().c_str()); + DataArrayAPIAssert(str.str() == array->GetComponentName(c), + "Component " << c << " name is '" + << array->GetComponentName(c) << "', expected " + << str.str() << "'."); + DataArrayAPIUpdateSignature("bool HasAComponentName()"); + DataArrayAPIAssert(array->HasAComponentName(), "Invalid result."); + } + + DataArrayAPICreateTestArray(copy); + copy->SetNumberOfComponents(comps); + DataArrayAPIUpdateSignature("int CopyComponentNames(vtkAbstractArray*)"); + int success = copy->CopyComponentNames(array.GetPointer()); + + DataArrayAPIAssert(success != 0, + "CopyComponentNames returned " << success << "."); + DataArrayAPIAssert(array->HasAComponentName(), "Invalid result."); + + for (vtkIdType c = 0; c < static_cast(comps); ++c) + { + str.str(""); + str << "Component " << c; + DataArrayAPIAssert(str.str() == copy->GetComponentName(c), + "Copied array component " << c << " name is '" + << array->GetComponentName(c) << "', expected " + << str.str() << "'."); + } + + DataArrayAPIFinish(); +} + +// void SetNumberOfTuples(vtkIdType number) +// vtkIdType GetNumberOfTuples() +template +int Test_NumberOfTuples() +{ + DataArrayAPIInit("void SetNumberOfTuples(int comps)"); + DataArrayAPICreateTestArray(array); + DataArrayAPIAssert(array->GetNumberOfTuples() == 0, + "Initial number of tuples expected to be 0, but is " + << array->GetNumberOfTuples() << "."); + + vtkIdType tuples = 12; + int comps = 5; + array->SetNumberOfComponents(comps); + array->SetNumberOfTuples(tuples); + DataArrayAPIAssert(array->GetNumberOfTuples() == tuples, + "Number of tuples expected to be " << tuples + << ", but is " << array->GetNumberOfTuples() << "."); + + DataArrayAPIAssert(array->GetSize() >= tuples * comps, + "Size expected to be at least " << tuples * comps + << ", but is " << array->GetSize() << "."); + + DataArrayAPIAssert(array->GetMaxId() == tuples * comps - 1, + "MaxId expected to be " << tuples * comps - 1 + << ", but is " << array->GetMaxId() << "."); + + array->SetNumberOfTuples(0); + DataArrayAPIAssert(array->GetNumberOfTuples() == 0, + "Number of tuples expected to be 0, but is " + << array->GetNumberOfTuples() << "."); + + DataArrayAPIAssert(array->GetSize() >= 0, + "Size expected to be at least 0, but is " + << array->GetSize() << "."); + + DataArrayAPIAssert(array->GetMaxId() == -1, + "MaxId expected to be " << -1 + << ", but is " << array->GetMaxId() << "."); + + DataArrayAPIFinish(); +} + +// void SetNumberOfValues(vtkIdType number) +template +int Test_void_SetNumberOfValues_number() +{ + DataArrayAPIInit("void SetNumberOfValues(vtkIdType number)"); + DataArrayAPICreateTestArray(array); + DataArrayAPIAssert(array->GetNumberOfTuples() == 0, + "Initial number of tuples expected to be 0, but is " + << array->GetNumberOfTuples() << "."); + + vtkIdType tuples = 12; + int comps = 5; + array->SetNumberOfComponents(comps); + array->SetNumberOfTuples(tuples); + DataArrayAPIAssert(array->GetNumberOfTuples() == tuples, + "Number of tuples expected to be " << tuples + << ", but is " << array->GetNumberOfTuples() << "."); + + DataArrayAPIAssert(array->GetSize() >= tuples * comps, + "Size expected to be at least " << tuples * comps + << ", but is " << array->GetSize() << "."); + + DataArrayAPIAssert(array->GetMaxId() == tuples * comps - 1, + "MaxId expected to be " << tuples * comps - 1 + << ", but is " << array->GetMaxId() << "."); + + array->SetNumberOfTuples(0); + DataArrayAPIAssert(array->GetNumberOfTuples() == 0, + "Number of tuples expected to be 0, but is " + << array->GetNumberOfTuples() << "."); + + DataArrayAPIAssert(array->GetSize() >= 0, + "Size expected to be at least 0, but is " + << array->GetSize() << "."); + + DataArrayAPIAssert(array->GetMaxId() == -1, + "MaxId expected to be " << -1 + << ", but is " << array->GetMaxId() << "."); + + DataArrayAPIFinish(); +} + // void SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray *source); // Set the tuple at i in this array using tuple j from source. // Types must match. @@ -214,8 +480,8 @@ int Test_void_SetTuple_i_j_source() std::vector destTuple(comps); for (vtkIdType i = 0; i < tuples; ++i) { - source->GetTupleValue(i, &srcTuple[0]); - dest->GetTupleValue(tupleMap[i], &destTuple[0]); + source->GetTypedTuple(i, &srcTuple[0]); + dest->GetTypedTuple(tupleMap[i], &destTuple[0]); if (!std::equal(srcTuple.begin(), srcTuple.end(), destTuple.begin())) { std::ostringstream srcTupleStr; @@ -262,9 +528,21 @@ int Test_void_InsertTuple_i_j_source() // dest is empty -- this call should allocate memory as needed. dest->SetNumberOfComponents(comps); - for (vtkIdType i = 0; i < tuples; ++i) + vtkIdType maxTuple = 0; + for (vtkIdType t = 0; t < tuples; ++t) { - dest->InsertTuple(tupleMap[i], i, source); + dest->InsertTuple(tupleMap[t], t, source); + maxTuple = std::max(maxTuple, tupleMap[t]); + if (dest->GetSize() < ((maxTuple + 1) * comps)) + { + DataArrayAPIError("Size should be at least " << (maxTuple * comps) + << " values, but is only " << dest->GetSize() << "."); + } + if (dest->GetMaxId() != ((maxTuple + 1) * comps) - 1) + { + DataArrayAPIError("MaxId should be " << (maxTuple * comps) - 1 + << ", but is " << dest->GetMaxId() << " instead."); + } } // Verify: @@ -272,8 +550,8 @@ int Test_void_InsertTuple_i_j_source() std::vector destTuple(comps); for (vtkIdType i = 0; i < tuples; ++i) { - source->GetTupleValue(i, &srcTuple[0]); - dest->GetTupleValue(tupleMap[i], &destTuple[0]); + source->GetTypedTuple(i, &srcTuple[0]); + dest->GetTypedTuple(tupleMap[i], &destTuple[0]); if (!std::equal(srcTuple.begin(), srcTuple.end(), destTuple.begin())) { std::ostringstream srcTupleStr; @@ -293,6 +571,120 @@ int Test_void_InsertTuple_i_j_source() DataArrayAPIFinish(); } +// void InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, vtkAbstractArray* source) +template +int Test_void_InsertTuples_dstIds_srcIds_source() +{ + DataArrayAPIInit("void InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, " + "vtkAbstractArray* source)"); + DataArrayAPICreateTestArray(src); + DataArrayAPICreateTestArray(dst); + vtkIdType comps = 9; + vtkIdType tuples = 14; + src->SetNumberOfComponents(comps); + src->SetNumberOfTuples(tuples); + + // Initialize source: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + src->SetValue(i, static_cast(i % 16)); + } + + // Copy 5 tuples from src to dest + vtkNew srcIds; + vtkNew dstIds; + + srcIds->InsertNextId(5); + dstIds->InsertNextId(0); + + srcIds->InsertNextId(2); + dstIds->InsertNextId(1); + + srcIds->InsertNextId(4); + dstIds->InsertNextId(3); + + srcIds->InsertNextId(9); + dstIds->InsertNextId(2); + + srcIds->InsertNextId(11); + dstIds->InsertNextId(4); + + // dest is empty -- this call should allocate memory as needed. + vtkIdType numIds = srcIds->GetNumberOfIds(); + dst->SetNumberOfComponents(comps); + dst->InsertTuples(dstIds.GetPointer(), srcIds.GetPointer(), + src.GetPointer()); + + DataArrayAPIAssert(dst->GetNumberOfTuples() == numIds, + "Destination array too small! Expected " << numIds + << " tuples, got " << dst->GetNumberOfTuples() << "."); + + // Verify: + std::vector srcTuple(comps); + std::vector dstTuple(comps); + for (vtkIdType t = 0; t < numIds; ++t) + { + vtkIdType srcTupleId = srcIds->GetId(t); + vtkIdType dstTupleId = dstIds->GetId(t); + src->GetTypedTuple(srcTupleId, &srcTuple[0]); + dst->GetTypedTuple(dstTupleId, &dstTuple[0]); + DataArrayAPIAssert(std::equal(srcTuple.begin(), srcTuple.end(), + dstTuple.begin()), + "Copied tuple does not match input."); + } + + DataArrayAPIFinish(); +} + +// void InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, vtkAbstractArray* source) +template +int Test_void_InsertTuples_dstStart_n_srcStart_source() +{ + DataArrayAPIInit("void InsertTuples(vtkIdType dstStart, vtkIdType n, " + "vtkIdType srcStart, vtkAbstractArray* source)"); + DataArrayAPICreateTestArray(src); + DataArrayAPICreateTestArray(dst); + vtkIdType comps = 9; + vtkIdType tuples = 14; + src->SetNumberOfComponents(comps); + src->SetNumberOfTuples(tuples); + + // Initialize source: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + src->SetValue(i, static_cast(i % 16)); + } + + // Copy 5 tuples from src to dest + vtkIdType srcStart = 8; + vtkIdType n = 5; + vtkIdType dstStart = 0; + + // dest is empty -- this call should allocate memory as needed. + dst->SetNumberOfComponents(comps); + dst->InsertTuples(dstStart, n, srcStart, src.GetPointer()); + + DataArrayAPIAssert(dst->GetNumberOfTuples() == n, + "Destination array size invalid. Expected " << n + << " tuples, got " << dst->GetNumberOfTuples() << "."); + + // Verify: + std::vector srcTuple(comps); + std::vector dstTuple(comps); + for (vtkIdType t = 0; t < n; ++t) + { + vtkIdType srcTupleId = srcStart + t; + vtkIdType dstTupleId = dstStart + t; + src->GetTypedTuple(srcTupleId, &srcTuple[0]); + dst->GetTypedTuple(dstTupleId, &dstTuple[0]); + DataArrayAPIAssert(std::equal(srcTuple.begin(), srcTuple.end(), + dstTuple.begin()), + "Copied tuple does not match input."); + } + + DataArrayAPIFinish(); +} + // vtkIdType InsertNextTuple(vtkIdType j, vtkAbstractArray *source) // Insert the jth tuple in the source array at the end of this array. // Allocate memory as needed. @@ -322,13 +714,23 @@ int Test_vtkIdType_InsertNextTuple_j_source() // dest is empty -- this call should allocate memory as needed. dest->SetNumberOfComponents(comps); - for (vtkIdType i = 0; i < tuples; ++i) + for (vtkIdType t = 0; t < tuples; ++t) { - vtkIdType tupleIdx = dest->InsertNextTuple(tupleMap[i], source); - if (i != tupleIdx) + vtkIdType tupleIdx = dest->InsertNextTuple(tupleMap[t], source); + if (t != tupleIdx) { DataArrayAPIError("Returned tuple index incorrect. Returned '" - << tupleIdx << "', expected '" << i << "'."); + << tupleIdx << "', expected '" << t << "'."); + } + if (dest->GetSize() < ((t + 1) * comps)) + { + DataArrayAPIError("Size should be at least " << ((t + 1) * comps) + << " values, but is only " << dest->GetSize() << "."); + } + if (dest->GetMaxId() != ((t + 1) * comps) - 1) + { + DataArrayAPIError("MaxId should be " << ((t + 1) * comps) - 1 + << ", but is " << dest->GetMaxId() << " instead."); } } @@ -337,8 +739,8 @@ int Test_vtkIdType_InsertNextTuple_j_source() std::vector destTuple(comps); for (vtkIdType i = 0; i < tuples; ++i) { - source->GetTupleValue(tupleMap[i], &srcTuple[0]); - dest->GetTupleValue(i, &destTuple[0]); + source->GetTypedTuple(tupleMap[i], &srcTuple[0]); + dest->GetTypedTuple(i, &destTuple[0]); if (!std::equal(srcTuple.begin(), srcTuple.end(), destTuple.begin())) { std::ostringstream srcTupleStr; @@ -358,6 +760,7 @@ int Test_vtkIdType_InsertNextTuple_j_source() DataArrayAPIFinish(); } + // void GetTuples(vtkIdList *ptIds, vtkAbstractArray *output) // Output array is preallocated. template @@ -397,8 +800,8 @@ int Test_void_GetTuples_ptIds_output() for (vtkIdType i = 0; i < ids->GetNumberOfIds(); ++i) { vtkIdType tupleIdx = ids->GetId(i); - source->GetTupleValue(tupleIdx, &srcTuple[0]); - output->GetTupleValue(i, &outTuple[0]); + source->GetTypedTuple(tupleIdx, &srcTuple[0]); + output->GetTypedTuple(i, &outTuple[0]); if (!std::equal(srcTuple.begin(), srcTuple.end(), outTuple.begin())) { std::ostringstream srcTupleStr; @@ -458,8 +861,8 @@ int Test_void_GetTuples_p1_p2_output() for (vtkIdType i = p1; i < outTupleCount; ++i) { vtkIdType tupleIdx = p1 + i; - source->GetTupleValue(tupleIdx, &srcTuple[0]); - output->GetTupleValue(i, &outTuple[0]); + source->GetTypedTuple(tupleIdx, &srcTuple[0]); + output->GetTypedTuple(i, &outTuple[0]); if (!std::equal(srcTuple.begin(), srcTuple.end(), outTuple.begin())) { std::ostringstream srcTupleStr; @@ -479,74 +882,1054 @@ int Test_void_GetTuples_p1_p2_output() DataArrayAPIFinish(); } -// double* GetTuple(vtkIdType i) +// void *GetVoidPointer(vtkIdType id) template -int Test_doubleptr_GetTuple_i() +int Test_voidPtr_GetVoidPointer() { - DataArrayAPIInit("double* GetTuple(vtkIdType i)"); + DataArrayAPIInit("void* GetVoidPointer(vtkIdType id)"); DataArrayAPICreateTestArray(source); // Initialize source array: - vtkIdType comps = 9; + vtkIdType comps = 5; vtkIdType tuples = 10; source->SetNumberOfComponents(comps); source->SetNumberOfTuples(tuples); - for (vtkIdType i = 0; i < comps * tuples; ++i) + for (vtkIdType t = 0; t < tuples; ++t) { - source->SetValue(i, static_cast(i % 17)); + std::vector tuple; + for (int c = 0; c < comps; ++c) + { + tuple.push_back(static_cast(((t * comps) + c) % 17)); + } + source->SetTypedTuple(t, &tuple[0]); } - // Test the returned tuples: - vtkIdType refValue = 0; - for (vtkIdType tupleIdx = 0; tupleIdx < tuples; ++tupleIdx) + // Verify: + for (vtkIdType t = 0; t < tuples; ++t) { - double *tuple = source->GetTuple(tupleIdx); - for (int compIdx = 0; compIdx < comps; ++compIdx) + // Silence the void pointer warnings for these calls + const char *oldWarning = + vtksys::SystemTools::GetEnv("VTK_SILENCE_GET_VOID_POINTER_WARNINGS"); + vtksys::SystemTools::PutEnv("VTK_SILENCE_GET_VOID_POINTER_WARNINGS=1"); + + ScalarT *ptr = static_cast(source->GetVoidPointer(t * comps)); + + // Restore state: + if (oldWarning) { - if (tuple[compIdx] != static_cast(refValue)) - { - DataArrayAPIError("Data mismatch at tuple " << tupleIdx << ", " - "component " << compIdx << ": Expected '" << refValue - << "', got '" << tuple[compIdx] << "'."); + std::ostringstream envArg; + envArg << "VTK_SILENCE_GET_VOID_POINTER_WARNINGS=" << oldWarning; + vtksys::SystemTools::PutEnv(envArg.str()); + } + else + { + vtksys::SystemTools::UnPutEnv("VTK_SILENCE_GET_VOID_POINTER_WARNINGS"); + } + + DataArrayAPIAssert(ptr != NULL, "GetVoidPointer returned NULL!"); + for (int c = 0; c < comps; ++c) + { + ScalarT test = *ptr++; + ScalarT ref = static_cast(((t * comps) + c) % 17); + DataArrayAPIAssert(test == ref, + "Data mismatch at tuple " << t << " component " << c + << ": Expected " << ref << ", got " << test << "."); } - ++refValue; - refValue %= 17; } - } + DataArrayAPIFinish(); } -// void GetTuple(vtkIdType i, double *tuple) -// tuple must be large enough, of course -// double* GetTuple(vtkIdType i) -template -int Test_void_GetTuple_i_tuple() +// operator() returns true if the memory is shared between two arrays, if +// the arrays support true shallow copies. +// NOTE: This will NOT properly test the case where, e.g., vtkFloatArray is +// used, as template resolution will not cast vtkFloatArray into +// vtkAOSDataArrayTemplate. This will go through the generic +// implementation which always returns true. This is fine, however, since +// we explicitly test vtkAOSDataArrayTemplates as well as the vtk{type}Arrays, +// so the explicit AOS tests will detect failures. +struct CheckShallowCopy { - DataArrayAPIInit("void GetTuple(vtkIdType i, double *tuple)"); + // Mismatched arrays -- these will not shallow copy, always return true. + template + bool operator()(Array1T *, Array2T *) { return true; } + + // AOS same-ValueType case: + template + bool operator()(vtkAOSDataArrayTemplate *a1, + vtkAOSDataArrayTemplate *a2) + { + return a1->GetPointer(0) == a2->GetPointer(0); + } + + // SOA same-ValueType case: + template + bool operator()(vtkSOADataArrayTemplate *a1, + vtkSOADataArrayTemplate *a2) + { + assert(a1->GetNumberOfComponents() == a2->GetNumberOfComponents()); + for (int c = 0; c < a1->GetNumberOfComponents(); ++c) + { + if (a1->GetComponentArrayPointer(c) != a2->GetComponentArrayPointer(c)) + { + return false; + } + } + return true; + } +}; + +// void ShallowCopy(vtkDataArray *other) +// Shallow copies AOS/SOA arrays if and only if arrays are the same type, +// otherwise deep copies. +// Test copying into and from the target array type. +// Allocates memory as needed. +// ArgT switches between the two overloads. +// OtherT is the type of array that will be copied to/from. +template +int Test_void_ShallowCopy_array() +{ + DataArrayAPIInit("void ShallowCopy(vtkDataArray *other)"); + + typedef typename OtherArrayT::ValueType OtherScalarT; + + std::string testType = vtkTypeTraits::Name(); + std::string otherType = vtkTypeTraits::Name(); DataArrayAPICreateTestArray(source); + DataArrayAPICreateTestArrayByType(middle, OtherArrayT); + DataArrayAPICreateTestArray(target); + + CheckShallowCopy memChecker; // Initialize source array: vtkIdType comps = 9; - vtkIdType tuples = 10; + vtkIdType tuples = 40; source->SetNumberOfComponents(comps); source->SetNumberOfTuples(tuples); - for (vtkIdType i = 0; i < comps * tuples; ++i) + for (vtkIdType t = 0; t < tuples; ++t) { - source->SetValue(i, static_cast(i % 17)); + for (int c = 0; c < comps; ++c) + { + source->SetComponent(t, c, static_cast(((t * comps) + c) % 17)); + } } - // Test the returned tuples: - vtkIdType refValue = 0; - std::vector tuple(comps); - for (vtkIdType tupleIdx = 0; tupleIdx < tuples; ++tupleIdx) + // Copy to intermediate: + middle->ShallowCopy(source.GetPointer()); + + // Verify intermediate: + if (middle->GetNumberOfComponents() != comps || + middle->GetNumberOfTuples() != tuples) { - source->GetTuple(tupleIdx, &tuple[0]); - for (int compIdx = 0; compIdx < comps; ++compIdx) - { - if (tuple[compIdx] != static_cast(refValue)) + DataArrayAPIError("Incorrect size of array after copying from test array " + "(scalar type: '" << testType << "') to reference array " + "(scalar type: '" << otherType << "'): Expected number " + "of (tuples, components): " << "(" << tuples << ", " + << comps << "), got (" << middle->GetNumberOfTuples() + << ", " << middle->GetNumberOfComponents() << ")."); + } + + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + double ref = ((t * comps) + c) % 17; + double test = middle->GetComponent(t, c); + if (ref != test) + { + DataArrayAPIError("Data mismatch after copying from test array (scalar " + "type: '" << testType << "') to reference array " + "(scalar type: '" << otherType << "'): " "Data " + "mismatch at tuple " << t << " component " << c + << ": Expected " << ref << ", got " << test << "."); + } + } + } + + if (!memChecker(source.GetPointer(), middle.GetPointer())) + { + DataArrayAPIError("Memory is not shared following shallow copy.\n" + "Copying source --> middle;\n" + "source = " << source->GetClassName() << " (" + << testType << ")\n" + "middle = " << middle->GetClassName() << " (" + << otherType << ")"); + } + + // Copy to final: + target->ShallowCopy(middle.GetPointer()); + + // Verify final: + if (target->GetNumberOfComponents() != comps || + target->GetNumberOfTuples() != tuples) + { + DataArrayAPIError("Incorrect size of array after copying from reference " + "array (scalar type: '" << otherType << "') to test " + "array (scalar type: '" << testType << "'): " + "Expected number of (tuples, components): " + << "(" << tuples << ", " << comps << "), got (" + << target->GetNumberOfTuples() << ", " + << target->GetNumberOfComponents() << ")."); + } + + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + double ref = ((t * comps) + c) % 17; + double test = target->GetComponent(t, c); + if (ref != test) + { + DataArrayAPIError("Data mismatch after copying from reference array " + "(scalar type: '" << otherType << "') to test array " + "(scalar type: '" << testType << "'): " "Data " + "mismatch at tuple " << t << " component " << c + << ": Expected " << ref << ", got " << test << "."); + } + } + } + + if (!memChecker(middle.GetPointer(), target.GetPointer())) + { + DataArrayAPIError("Memory is not shared following shallow copy.\n" + "Copying middle --> target;\n" + "middle = " << middle->GetClassName() << " (" + << otherType << ")\n" + "target = " << target->GetClassName() << " (" + << testType << ")"); + } + + DataArrayAPIFinish(); +} + +// void DeepCopy(vtkAbstractArray *aa) +// void DeepCopy(vtkDataArray *da) +// Test copying into and from the target array type. +// Allocates memory as needed. +// ArgT switches between the two overloads. +// OtherT is the type of array that will be copied to/from. +template +int Test_void_DeepCopy_array() +{ + std::string argTName = (typeid(ArgT) == typeid(vtkAbstractArray) + ? "vtkAbstractArray" : "vtkDataArray"); + std::ostringstream sigBuilder; + sigBuilder << "void DeepCopy(" << argTName << " *array)"; + DataArrayAPIInit(sigBuilder.str()); + + std::string testType = vtkTypeTraits::Name(); + std::string otherType = vtkTypeTraits::Name(); + + DataArrayAPICreateTestArray(source); + DataArrayAPICreateReferenceArrayWithType(middle, OtherT); + DataArrayAPICreateTestArray(target); + + // Initialize source array: + vtkIdType comps = 9; + vtkIdType tuples = 40; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + source->SetComponent(t, c, static_cast(((t * comps) + c) % 17)); + } + } + + // Copy to intermediate: + middle->DeepCopy(static_cast(source.GetPointer())); + + // Verify intermediate: + if (middle->GetNumberOfComponents() != comps || + middle->GetNumberOfTuples() != tuples) + { + DataArrayAPIError("Incorrect size of array after copying from test array " + "(scalar type: '" << testType << "') to reference array " + "(scalar type: '" << otherType << "'): Expected number " + "of (tuples, components): " << "(" << tuples << ", " + << comps << "), got (" << middle->GetNumberOfTuples() + << ", " << middle->GetNumberOfComponents() << ")."); + } + + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + double ref = ((t * comps) + c) % 17; + double test = middle->GetComponent(t, c); + if (ref != test) + { + DataArrayAPIError("Data mismatch after copying from test array (scalar " + "type: '" << testType << "') to reference array " + "(scalar type: '" << otherType << "'): " "Data " + "mismatch at tuple " << t << " component " << c + << ": Expected " << ref << ", got " << test << "."); + } + } + } + + // Copy to final: + target->DeepCopy(static_cast(middle)); + + // Verify final: + if (target->GetNumberOfComponents() != comps || + target->GetNumberOfTuples() != tuples) + { + DataArrayAPIError("Incorrect size of array after copying from reference " + "array (scalar type: '" << otherType << "') to test " + "array (scalar type: '" << testType << "'): " + "Expected number of (tuples, components): " + << "(" << tuples << ", " << comps << "), got (" + << target->GetNumberOfTuples() << ", " + << target->GetNumberOfComponents() << ")."); + } + + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + double ref = ((t * comps) + c) % 17; + double test = target->GetComponent(t, c); + if (ref != test) + { + DataArrayAPIError("Data mismatch after copying from reference array " + "(scalar type: '" << otherType << "') to test array " + "(scalar type: '" << testType << "'): " "Data " + "mismatch at tuple " << t << " component " << c + << ": Expected " << ref << ", got " << test << "."); + } + } + } + + DataArrayAPIFinish(); +} + +// void InterpolateTuple(vtkIdType i, vtkIdList *ptIndices, +// vtkAbstractArray *source, double *weights) +// Sets the ith tuple in this array, using the source data, indices, and weights +// provided. +// Should allocate memory. +template +int Test_void_InterpolateTuple_i_indices_source_weights() +{ + DataArrayAPIInit("void InterpolateTuple(vtkIdType i, vtkIdList *ptIndices, " + "vtkAbstractArray *source, double *weights)"); + + DataArrayAPICreateReferenceArray(source); + DataArrayAPICreateTestArray(output); + + // Initialize source array: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source->SetValue(i, static_cast(i % 17)); + } + + // Tuples to interpolate: + vtkNew ids; + ids->InsertNextId(0); + ids->InsertNextId(1); + ids->InsertNextId(5); + ids->InsertNextId(7); + ids->InsertNextId(8); + double weights[] = {0.5, 1.0, 0.25, 1.0, 0.8}; + + output->SetNumberOfComponents(comps); + + output->InterpolateTuple(0, ids.GetPointer(), source, weights); + + // Validate result: + for (int c = 0; c < comps; ++c) + { + // Compute component: + double ref = 0.; + for (vtkIdType t = 0; t < ids->GetNumberOfIds(); ++t) + { + ref += weights[t] * source->GetComponent(ids->GetId(t), c); + } + + // Clamp to ScalarT range: + ref = std::max(ref, static_cast(vtkTypeTraits::Min())); + ref = std::min(ref, static_cast(vtkTypeTraits::Max())); + + // Round for non-floating point types: + ScalarT refT; + if (vtkTypeTraits::VTK_TYPE_ID == VTK_FLOAT || + vtkTypeTraits::VTK_TYPE_ID == VTK_DOUBLE) + { + refT = static_cast(ref); + } + else + { + refT = static_cast((ref >= 0.) ? (ref + 0.5) : (ref - 0.5)); + } + + ScalarT testT = output->GetValue(c); + + if (refT != testT) + { + DataArrayAPIError("Interpolated value incorrect: Got '" + << static_cast(testT) << "', expected '" + << static_cast(refT) << "'."); + } + } // foreach component + + DataArrayAPIFinish(); +} + +// void InterpolateTuple(vtkIdType i, +// vtkIdType id1, vtkAbstractArray *source1, +// vtkIdType id2, vtkAbstractArray *source2, double t) +// Interpolate tuple id1 from source1 and id2 form source2 and store the result +// in this tuple at tuple index i. t belongs to [0,1] and is the interpolation +// weight, with t=0 meaning 100% from source1. +// Should allocate memory. +template +int Test_void_InterpolateTuple_i_id1_source1_id2_source2_t() +{ + DataArrayAPIInit("void InterpolateTuple(vtkIdType i, " + "vtkIdType id1, vtkAbstractArray *source1, " + "vtkIdType id2, vtkAbstractArray *source2, double t)"); + + DataArrayAPICreateReferenceArray(source1); + DataArrayAPICreateReferenceArray(source2); + DataArrayAPICreateTestArray(output); + + // Initialize source arrays: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source1->SetNumberOfComponents(comps); + source1->SetNumberOfTuples(tuples); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source1->SetValue(i, static_cast(i % 17)); + } + + source2->SetNumberOfComponents(comps); + source2->SetNumberOfTuples(tuples); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source2->SetValue(i, static_cast(((i + 3) * 2) % 17)); + } + + output->SetNumberOfComponents(comps); + + vtkIdType id1 = 4; + vtkIdType id2 = 8; + double t = 0.25; + output->InterpolateTuple(0, id1, source1, id2, source2, t); + + // Validate result: + for (int c = 0; c < comps; ++c) + { + // Compute component: + double ref = source1->GetValue(id1 * comps + c) * (1. - t) + + source2->GetValue(id2 * comps + c) * t; + + // Clamp to ScalarT range: + ref = std::max(ref, static_cast(vtkTypeTraits::Min())); + ref = std::min(ref, static_cast(vtkTypeTraits::Max())); + + // Round for non-floating point types: + ScalarT refT; + if (vtkTypeTraits::VTK_TYPE_ID == VTK_FLOAT || + vtkTypeTraits::VTK_TYPE_ID == VTK_DOUBLE) + { + refT = static_cast(ref); + } + else + { + refT = static_cast((ref >= 0.) ? (ref + 0.5) : (ref - 0.5)); + } + + ScalarT test = output->GetValue(c); + + if (refT != test) + { + DataArrayAPIError("Interpolated value incorrect: Got '" + << static_cast(test) << "', expected '" + << static_cast(refT) << "'."); + } + } // foreach component + + DataArrayAPIFinish(); +} + +// int Resize(vtkIdType numTuples) +// Preserve data +// Return 1 on success, 0 otherwise +template +int Test_int_Resize_numTuples() +{ + DataArrayAPIInit("int Resize(vtkIdType numTuples)"); + DataArrayAPICreateTestArray(array); + int comps = 5; + vtkIdType tuples = 0; + array->SetNumberOfComponents(comps); + + int success = array->Resize(tuples); + DataArrayAPIAssert(success, "Resize failed."); + DataArrayAPIAssert(array->GetSize() == tuples * comps, + "Invalid Size (" << array->GetSize() << ")."); + DataArrayAPIAssert(array->GetMaxId() == -1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + tuples = 100; + success = array->Resize(tuples); + DataArrayAPIAssert(success, "Resize failed."); + // May be larger than requested for size increases: + DataArrayAPIAssert(array->GetSize() >= tuples * comps, + "Invalid Size (" << array->GetSize() << ")."); + // MaxId should not be changed: + DataArrayAPIAssert(array->GetMaxId() == -1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + // Fill with data + vtkIdType filledTuples = tuples; + array->SetNumberOfTuples(filledTuples); + DataArrayAPIAssert(array->GetSize() >= filledTuples * comps, + "Invalid Size (" << array->GetSize() << ")."); + DataArrayAPIAssert(array->GetMaxId() == filledTuples * comps - 1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + for (vtkIdType t = 0; t < filledTuples; t++) + { + for (int c = 0; c < comps; ++c) + { + array->SetTypedComponent(t, c, + static_cast((t * comps + c) % 17)); + } + } + + // resize larger + tuples = 200; + success = array->Resize(tuples); + DataArrayAPIAssert(success, "Resize failed."); + // May be larger than requested for size increases: + DataArrayAPIAssert(array->GetSize() >= tuples * comps, + "Invalid Size (" << array->GetSize() << ")."); + // MaxId should not change: + DataArrayAPIAssert(array->GetMaxId() == filledTuples * comps - 1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + // validate original data + for (vtkIdType t = 0; t < filledTuples; t++) + { + for (int c = 0; c < comps; ++c) + { + ScalarT ref = static_cast((t * comps + c) % 17); + ScalarT test = array->GetTypedComponent(t, c); + DataArrayAPIAssert(ref == test, + "Data changed after resize for tuple " << t + << " component " << c << ": Expected " << ref + << " got " << test << "."); + } + } + + // resize smaller + filledTuples = tuples = 50; + success = array->Resize(tuples); + DataArrayAPIAssert(success, "Resize failed."); + // Both Size and MaxId should be truncated to the exact new size. + DataArrayAPIAssert(array->GetSize() == tuples * comps, + "Invalid Size (" << array->GetSize() << ")."); + DataArrayAPIAssert(array->GetMaxId() == filledTuples * comps - 1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + // validate truncated data + for (vtkIdType t = 0; t < filledTuples; t++) + { + for (int c = 0; c < comps; ++c) + { + ScalarT ref = static_cast((t * comps + c) % 17); + ScalarT test = array->GetTypedComponent(t, c); + DataArrayAPIAssert(ref == test, + "Data changed after resize for tuple " << t + << " component " << c << ": Expected " << ref + << " got " << test << "."); + } + } + + // Set to zero, should delete array + filledTuples = tuples = 0; + success = array->Resize(tuples); + DataArrayAPIAssert(success, "Resize failed."); + DataArrayAPIAssert(array->GetSize() == 0, + "Invalid Size (" << array->GetSize() << ")."); + DataArrayAPIAssert(array->GetMaxId() == -1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + DataArrayAPIFinish(); +} + +// void Reset() +// Don't free memory, just reset MaxId. +template +int Test_void_Reset() +{ + DataArrayAPIInit("void Reset()"); + DataArrayAPICreateTestArray(array); + int comps = 5; + vtkIdType tuples = 0; + array->SetNumberOfComponents(comps); + + // Reseting a new array shouldn't cause issues + array->Reset(); + DataArrayAPIAssert(array->GetMaxId() == -1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + tuples = 100; + array->SetNumberOfTuples(tuples); + DataArrayAPIAssert(array->GetSize() >= tuples * comps, + "Invalid Size (" << array->GetSize() << ")."); + int oldSize = array->GetSize(); + DataArrayAPIAssert(array->GetMaxId() == tuples * comps - 1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + array->Reset(); + tuples = 0; + // Size should not change, but MaxId should + DataArrayAPIAssert(array->GetSize() == oldSize, + "Invalid Size (" << array->GetSize() << ")."); + DataArrayAPIAssert(array->GetMaxId() == -1, + "Invalid MaxId (" << array->GetMaxId() << ")."); + + DataArrayAPIFinish(); +} + +// void ExportToVoidPointer(void *out_ptr) +template +int Test_void_ExportToVoidPointer_voidPtr() +{ + DataArrayAPIInit("void ExportToVoidPointer(void *out_ptr)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array: + vtkIdType comps = 5; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType t = 0; t < tuples; ++t) + { + std::vector tuple; + for (int c = 0; c < comps; ++c) + { + tuple.push_back(static_cast(((t * comps) + c) % 17)); + } + source->SetTypedTuple(t, &tuple[0]); + } + + std::vector buffer(comps * tuples); + source->ExportToVoidPointer(static_cast(&buffer[0])); + + // Verify: + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + ScalarT test = buffer[t * comps + c]; + ScalarT ref = static_cast(((t * comps) + c) % 17); + DataArrayAPIAssert(test == ref, + "Data mismatch at tuple " << t << " component " << c + << ": Expected " << ref << ", got " << test << "."); + } + } + + DataArrayAPIFinish(); +} + +// unsigned long GetActualMemorySize() +// Returns size in kibibytes (1024 bytes) for MaxId + 1 elements of ValueType. +template +int Test_ulong_GetActualMemorySize() +{ + DataArrayAPIInit("unsigned long GetActualMemorySize()"); + + DataArrayAPICreateTestArray(source); + + vtkIdType comps = 5; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + + DataArrayAPIAssert(source->GetActualMemorySize() >= + (source->GetMaxId() + 1) * sizeof(ScalarT) / 1024, + "Invalid result. Expected at least " + << (source->GetMaxId() + 1) * sizeof(ScalarT) / 1024 + << " kB, but got " << source->GetActualMemorySize() + << " kB."); + + DataArrayAPIFinish(); +} + +// int IsNumeric() +// Should be true for all data array subclasses: +template +int Test_int_IsNumeric() +{ + DataArrayAPIInit("int IsNumeric()"); + + DataArrayAPICreateTestArray(source); + + if (!source->IsNumeric()) + { + DataArrayAPIError("IsNumeric() is false."); + } + + DataArrayAPIFinish(); +} + +// vtkArrayIterator* NewIterator() +// Just test that the returned iterator is non-NULL and the data types match. +template +int Test_vtkArrayIteratorPtr_NewIterator() +{ + DataArrayAPIInit("vtkArrayIterator* NewIterator()"); + + DataArrayAPICreateTestArray(source); + + // Silence the void pointer warnings for these calls. The + // vtkArrayIteratorTemplate implementation relies on GetVoidPointer. + const char *oldWarning = + vtksys::SystemTools::GetEnv("VTK_SILENCE_GET_VOID_POINTER_WARNINGS"); + vtksys::SystemTools::PutEnv("VTK_SILENCE_GET_VOID_POINTER_WARNINGS=1"); + + vtkArrayIterator *iter = source->NewIterator(); + + // Restore state: + if (oldWarning) + { + std::ostringstream envArg; + envArg << "VTK_SILENCE_GET_VOID_POINTER_WARNINGS=" << oldWarning; + vtksys::SystemTools::PutEnv(envArg.str()); + } + else + { + vtksys::SystemTools::UnPutEnv("VTK_SILENCE_GET_VOID_POINTER_WARNINGS"); + } + + DataArrayAPIAssert(iter != NULL, + "NewIterator() returns NULL."); + + int iterDataType = iter->GetDataType(); + iter->Delete(); + + DataArrayAPIAssert(iterDataType == source->GetDataType(), + "Iterator datatype does not match array."); + + DataArrayAPIFinish(); +} + +// vtkIdType GetDataSize() +// Same as GetNumberOfValues() +// TODO this is another good candidate for deprecation. +template +int Test_vtkIdType_GetDataSize() +{ + DataArrayAPIInit("vtkIdType GetDataSize()"); + + DataArrayAPICreateTestArray(source); + + vtkIdType comps = 5; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + + DataArrayAPIAssert(source->GetDataSize() == comps * tuples, + "Invalid data size (number of values). Expected " + << comps * tuples << ", but got " << source->GetDataSize() + << "."); + + DataArrayAPIFinish(); +} + +// vtkIdType LookupValue(vtkVariant value) +// void LookupValue(vtkVariant value, vtkIdList* ids) +template +int Test_LookupValue_allSigs() +{ + DataArrayAPIInit("LookupValue"); + + DataArrayAPICreateTestArray(array); + + // Map Value --> ValueIdxs. We'll use this to validate the lookup results. + typedef std::map RefMap; + typedef typename RefMap::iterator RefMapIterator; + RefMap refMap; + // These are the values we'll be looking for. + for (ScalarT val = 0; val < 17; ++val) + { + refMap.insert(std::make_pair(val, vtkIdList::New())); + } + + // Initialize source array: + vtkIdType comps = 9; + vtkIdType tuples = 10; + array->SetNumberOfComponents(comps); + array->SetNumberOfTuples(tuples); + for (vtkIdType valIdx = 0; valIdx < comps * tuples; ++valIdx) + { + ScalarT val = static_cast(valIdx % 17); + array->SetValue(valIdx, val); + // Update our reference map: + RefMapIterator it = refMap.find(val); + assert("Value exists in reference map." && it != refMap.end()); + it->second->InsertNextId(valIdx); + } + + // Test the lookup functions. + vtkNew testIdList; + for (RefMapIterator it = refMap.begin(), itEnd = refMap.end(); it != itEnd; + ++it) + { + const ScalarT &val = it->first; + vtkIdList *refIdList = it->second; // Presorted due to insertion order + vtkIdType *refIdBegin = refIdList->GetPointer(0); + vtkIdType *refIdEnd = refIdList->GetPointer(refIdList->GetNumberOfIds()); + + // Docs are unclear about this. Does it return the first value, or just any? + // We'll assume any since it's unspecified. + DataArrayAPIUpdateSignature("vtkIdType LookupValue(vtkVariant value)"); + vtkIdType testId = array->LookupValue(vtkVariant(val)); + if (!std::binary_search(refIdBegin, refIdEnd, testId)) + { + // NonFatal + break so we can clean up. + DataArrayAPINonFatalError("Looking up value '" << val + << "' returned valueIdx '" << testId + << "', which maps to value '" + << array->GetValue(testId) << "'."); + break; + } + + // Now for the list overload: + DataArrayAPIUpdateSignature( + "void LookupValue(vtkVariant value, vtkIdList* ids)"); + array->LookupValue(vtkVariant(val), testIdList.GetPointer()); + if (testIdList->GetNumberOfIds() != refIdList->GetNumberOfIds()) + { + // NonFatal + break so we can clean up. + DataArrayAPINonFatalError("Looking up value '" << val << "' returned " + << testIdList->GetNumberOfIds() << " ids, but " + << refIdList->GetNumberOfIds() + << "were expected."); + break; + } + vtkIdType *testIdBegin = testIdList->GetPointer(0); + vtkIdType *testIdEnd = testIdList->GetPointer(refIdList->GetNumberOfIds()); + // Ensure the test ids are sorted + std::sort(testIdBegin, testIdEnd); + if (!std::equal(testIdBegin, testIdEnd, refIdBegin)) + { + // NonFatal + break so we can clean up. + DataArrayAPINonFatalError("Looking up all value indices for value '" + << val + << "' did not return the expected result."); + break; + } + } + + // Cleanup: + for (RefMapIterator it = refMap.begin(), itEnd = refMap.end(); it != itEnd; + ++it) + { + it->second->Delete(); + it->second = NULL; + } + + DataArrayAPIFinish(); +} + +// vtkVariant GetVariantValue(vtkIdType idx) +template +int Test_vtkVariant_GetVariantValue_valueIdx() +{ + DataArrayAPIInit("vtkVariant GetVariantValue(vtkIdType valueIdx)"); + + DataArrayAPICreateTestArray(array); + vtkIdType comps = 9; + vtkIdType tuples = 5; + array->SetNumberOfComponents(comps); + array->SetNumberOfTuples(tuples); + + // Initialize: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + array->SetValue(i, static_cast(i % 16)); + } + + // Verify: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + vtkVariant testVar = array->GetVariantValue(i); + bool valid = false; + ScalarT test = vtkVariantCast(testVar, &valid); + DataArrayAPIAssert(valid == true, + "vtkVariantCast failed."); + ScalarT ref = static_cast(i % 16); + if (test != ref) + { + DataArrayAPIError("Data mismatch at value index '" << i << "'. Expected '" + << ref << "', got '" << test << "'."); + } + } + + DataArrayAPIFinish(); +} + +// void InsertVariantValue(vtkIdType idx, vtkVariant value) +template +int Test_void_InsertVariantValue_idx_v() +{ + DataArrayAPIInit("void InsertVariantValue(vtkIdType idx, vtkVariant v)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array using tested function: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source->InsertVariantValue(i, vtkVariant(static_cast(i % 17))); + + if (source->GetSize() < i + 1) + { + DataArrayAPIError("Size should be at least " << i + 1 + << " values, but is only " << source->GetSize() << "."); + } + if (source->GetMaxId() != i) + { + DataArrayAPIError("MaxId should be " << i << ", but is " + << source->GetMaxId() << " instead."); + } + } + + // Validate: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + ScalarT ref = static_cast(i % 17); + const typename ArrayT::ValueType test = source->GetValue(i); + if (ref != test) + { + DataArrayAPIError("Data mismatch at value " << i << ": Expected '" + << ref << "', got '" << test << "'."); + } + } + + DataArrayAPIFinish(); +} + +// void SetVariantValue(vtkIdType idx, vtkVariant value) +template +int Test_void_SetVariantValue_idx_v() +{ + DataArrayAPIInit("void SetVariantValue(vtkIdType valueIdx, vtkVariant v)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array using tested function: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source->SetVariantValue(i, vtkVariant( + static_cast(((i + 1) * (i + 2)) % 17))); + } + + // Validate: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + ScalarT ref = static_cast(((i + 1) * (i + 2)) % 17); + const typename ArrayT::ValueType test = source->GetValue(i); + if (ref != test) + { + DataArrayAPIError("Data mismatch at value " << i << ": Expected '" + << ref << "', got '" << test << "'."); + } + } + + DataArrayAPIFinish(); +} + +//------------------------vtkDataArray API-------------------------------------- + +// double* GetTuple(vtkIdType i) +template +int Test_doubleptr_GetTuple_i() +{ + DataArrayAPIInit("double* GetTuple(vtkIdType i)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source->SetValue(i, static_cast(i % 17)); + } + + // Test the returned tuples: + vtkIdType refValue = 0; + for (vtkIdType tupleIdx = 0; tupleIdx < tuples; ++tupleIdx) + { + double *tuple = source->GetTuple(tupleIdx); + for (int compIdx = 0; compIdx < comps; ++compIdx) + { + if (tuple[compIdx] != static_cast(refValue)) + { + DataArrayAPIError("Data mismatch at tuple " << tupleIdx << ", " + "component " << compIdx << ": Expected '" << refValue + << "', got '" << tuple[compIdx] << "'."); + } + ++refValue; + refValue %= 17; + } + } + + DataArrayAPIFinish(); +} + +// void GetTuple(vtkIdType i, double *tuple) +// tuple must be large enough, of course +// double* GetTuple(vtkIdType i) +template +int Test_void_GetTuple_i_tuple() +{ + DataArrayAPIInit("void GetTuple(vtkIdType i, double *tuple)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source->SetValue(i, static_cast(i % 17)); + } + + // Test the returned tuples: + vtkIdType refValue = 0; + std::vector tuple(comps); + for (vtkIdType tupleIdx = 0; tupleIdx < tuples; ++tupleIdx) + { + source->GetTuple(tupleIdx, &tuple[0]); + for (int compIdx = 0; compIdx < comps; ++compIdx) + { + if (tuple[compIdx] != static_cast(refValue)) { DataArrayAPIError("Data mismatch at tuple " << tupleIdx << ", " "component " << compIdx << ": Expected '" << refValue @@ -655,12 +2038,24 @@ int Test_void_InsertComponent_i_j_c() vtkIdType comps = 9; vtkIdType tuples = 10; source->SetNumberOfComponents(comps); - for (vtkIdType i = 0; i < tuples; ++i) + for (vtkIdType t = 0; t < tuples; ++t) { - for (int j = 0; j < comps; ++j) + for (int c = 0; c < comps; ++c) { - source->InsertComponent(i, j, - static_cast(((i + 1) * (j + 1)) % 17)); + source->InsertComponent(t, c, + static_cast(((t + 1) * (c + 1)) % 17)); + + if (source->GetSize() < (t * comps) + c + 1) + { + DataArrayAPIError("Size should be at least " << (t * comps) + c + 1 + << " values, but is only " << source->GetSize() + << "."); + } + if (source->GetMaxId() != (t * comps) + c) + { + DataArrayAPIError("MaxId should be " << (t * comps) + c + << ", but is " << source->GetMaxId() << " instead."); + } } } @@ -732,6 +2127,15 @@ int Test_voidptr_WriteVoidPointer_id_number() { DataArrayAPIInit("void* WriteVoidPointer(vtkIdType id, vtkIdType number)"); + // Skip SoA arrays, as they do not allow this: + if (typeid(ArrayT) == typeid(vtkSOADataArrayTemplate)) + { + std::cerr << "Skipping WriteVoidPointer for " + << "vtkSOADataArrayTemplate<" << vtkTypeTraits::Name() + << ">.\n"; + DataArrayAPIFinish(); + } + DataArrayAPICreateTestArray(source); // Initialize source array: @@ -753,291 +2157,69 @@ int Test_voidptr_WriteVoidPointer_id_number() if (writeLength <= 0) { break; - } - - void *voidPtr = source->WriteVoidPointer(pos, writeLength); - - // Verify that conditions are met: - if (source->GetMaxId() != pos + writeLength - 1) - { - DataArrayAPIError("MaxId was not incremented to account for write length." - " MaxId is: " << source->GetMaxId() << ", expected: " - << (pos + writeLength - 1) << "."); - } - if (source->GetSize() < pos + writeLength) - { - DataArrayAPIError("Size was not increased to account for write length. " - "Size is: " << source->GetSize() << ", expected: " - << (pos + writeLength) << "."); - } - - // Cast the pointer and write to it: - ScalarT *ptr = static_cast(voidPtr); - for (int i = 0; i < writeLength; ++i) - { - ptr[i] = static_cast(((pos + 1) * pos) % 17); - ++pos; - } - writeLength += 1; - } - - // Test the returned tuples: - vtkIdType v = 0; - std::vector tuple(comps); - for (vtkIdType i = 0; i < tuples; ++i) - { - source->GetTuple(i, &tuple[0]); - for (int j = 0; j < comps; ++j) - { - if (tuple[j] != static_cast(((v + 1) * v) % 17)) - { - DataArrayAPIError("Data mismatch at tuple " << i << ", component " << j - << ": Expected '" << (((v + 1) * v) % 17) - << "', got '" << tuple[j] << "'."); - } - ++v; - } - } - - DataArrayAPIFinish(); -} - -// unsigned long GetActualMemorySize() -// Returns size in kilobytes (1024 bytes) that is >= the size needed to -// represent this array. -template -int Test_ulong_GetActualMemorySize() -{ - DataArrayAPIInit("unsigned long GetActualMemorySize()"); - - DataArrayAPICreateTestArray(source); - - // Initialize source array: - vtkIdType comps = 9; - vtkIdType tuples = 500; - vtkIdType values = comps * tuples; - source->SetNumberOfComponents(comps); - source->SetNumberOfTuples(tuples); - - unsigned long memSizeBytes = source->GetActualMemorySize() * 1024; - if (memSizeBytes < values * sizeof(ScalarT)) - { - DataArrayAPIError("Reported size is too small. Expected at least " - << (values * sizeof(ScalarT)) << " bytes, got: " - << memSizeBytes << " bytes."); - } - - DataArrayAPIFinish(); -} - -// void CreateDefaultLookupTable() -// GetLookupTable should be non-NULL after calling. -template -int Test_void_CreateDefaultLookupTable() -{ - DataArrayAPIInit("void CreateDefaultLookupTable()"); - - DataArrayAPICreateTestArray(source); - - source->CreateDefaultLookupTable(); - if (source->GetLookupTable() == NULL) - { - DataArrayAPIError("Lookup table was not created."); - } - - DataArrayAPIFinish(); -} - -// int IsNumeric() -// Should be true for all data array subclasses: -template -int Test_int_IsNumeric() -{ - DataArrayAPIInit("int IsNumeric()"); - - DataArrayAPICreateTestArray(source); - - if (!source->IsNumeric()) - { - DataArrayAPIError("IsNumeric() is false."); - } - - DataArrayAPIFinish(); -} - -// int GetElementComponentSize() -template -int Test_int_GetElementComponentSize() -{ - DataArrayAPIInit("int GetElementComponentSize()"); - - DataArrayAPICreateTestArray(source); - - if (source->GetElementComponentSize() != sizeof(ScalarT)) - { - DataArrayAPIError("Expected '" << sizeof(ScalarT) << "', got: '" - << source->GetElementComponentSize() << "'."); - } - - DataArrayAPIFinish(); -} - -// void InterpolateTuple(vtkIdType i, vtkIdList *ptIndices, -// vtkAbstractArray *source, double *weights) -// Sets the ith tuple in this array, using the source data, indices, and weights -// provided. -template -int Test_void_InterpolateTuple_i_indices_source_weights() -{ - DataArrayAPIInit("void InterpolateTuple(vtkIdType i, vtkIdList *ptIndices, " - "vtkAbstractArray *source, double *weights)"); - - DataArrayAPICreateReferenceArray(source); - DataArrayAPICreateTestArray(output); - - // Initialize source array: - vtkIdType comps = 9; - vtkIdType tuples = 10; - source->SetNumberOfComponents(comps); - source->SetNumberOfTuples(tuples); - for (vtkIdType i = 0; i < comps * tuples; ++i) - { - source->SetValue(i, static_cast(i % 17)); - } - - // Tuples to interpolate: - vtkNew ids; - ids->InsertNextId(0); - ids->InsertNextId(1); - ids->InsertNextId(5); - ids->InsertNextId(7); - ids->InsertNextId(8); - double weights[] = {0.5, 1.0, 0.25, 1.0, 0.8}; - - output->SetNumberOfComponents(comps); - output->SetNumberOfTuples(1); - - output->InterpolateTuple(0, ids.GetPointer(), source, weights); - - // Validate result: - for (int c = 0; c < comps; ++c) - { - // Compute component: - double ref = 0.; - for (vtkIdType t = 0; t < ids->GetNumberOfIds(); ++t) - { - ref += weights[t] * source->GetComponent(ids->GetId(t), c); - } - - // Clamp to ScalarT range: - ref = std::max(ref, static_cast(vtkTypeTraits::Min())); - ref = std::min(ref, static_cast(vtkTypeTraits::Max())); - - // Round for non-floating point types: - ScalarT refT; - if (vtkTypeTraits::VTK_TYPE_ID == VTK_FLOAT || - vtkTypeTraits::VTK_TYPE_ID == VTK_DOUBLE) - { - refT = static_cast(ref); - } - else - { - refT = static_cast((ref >= 0.) ? (ref + 0.5) : (ref - 0.5)); - } - - ScalarT testT = output->GetValue(c); - - if (refT != testT) - { - DataArrayAPIError("Interpolated value incorrect: Got '" - << static_cast(testT) << "', expected '" - << static_cast(refT) << "'."); - } - } // foreach component - - DataArrayAPIFinish(); -} - -// void InterpolateTuple(vtkIdType i, -// vtkIdType id1, vtkAbstractArray *source1, -// vtkIdType id2, vtkAbstractArray *source2, double t) -// Interpolate tuple id1 from source1 and id2 form source2 and store the result -// in this tuple at tuple index i. t belongs to [0,1] and is the interpolation -// weight, with t=0 meaning 100% from source1. -// TODO the implementation of this method could use some attention: -// - BIT implementation looks wrong (k is not used?) What does bit interpolation -// even mean? -// - Docs are unclear -- id1 and id2 are documented as "value indices", which -// is (sort of) how the bit implementation treats them, but they really seem -// like they should be tuple indices. -template -int Test_void_InterpolateTuple_i_id1_source1_id2_source2_t() -{ - DataArrayAPIInit("void InterpolateTuple(vtkIdType i, " - "vtkIdType id1, vtkAbstractArray *source1, " - "vtkIdType id2, vtkAbstractArray *source2, double t)"); - - DataArrayAPICreateReferenceArray(source1); - DataArrayAPICreateReferenceArray(source2); - DataArrayAPICreateTestArray(output); - - // Initialize source arrays: - vtkIdType comps = 9; - vtkIdType tuples = 10; - source1->SetNumberOfComponents(comps); - source1->SetNumberOfTuples(tuples); - for (vtkIdType i = 0; i < comps * tuples; ++i) - { - source1->SetValue(i, static_cast(i % 17)); - } - - source2->SetNumberOfComponents(comps); - source2->SetNumberOfTuples(tuples); - for (vtkIdType i = 0; i < comps * tuples; ++i) - { - source2->SetValue(i, static_cast(((i + 3) * 2) % 17)); - } - - output->SetNumberOfComponents(comps); - output->SetNumberOfTuples(1); - - vtkIdType id1 = 4; - vtkIdType id2 = 8; - double t = 0.25; - output->InterpolateTuple(0, id1, source1, id2, source2, t); - - // Validate result: - for (int c = 0; c < comps; ++c) - { - // Compute component: - double ref = source1->GetValue(id1 * comps + c) * (1. - t) + - source2->GetValue(id2 * comps + c) * t; - - // Clamp to ScalarT range: - ref = std::max(ref, static_cast(vtkTypeTraits::Min())); - ref = std::min(ref, static_cast(vtkTypeTraits::Max())); + } - // Round for non-floating point types: - ScalarT refT; - if (vtkTypeTraits::VTK_TYPE_ID == VTK_FLOAT || - vtkTypeTraits::VTK_TYPE_ID == VTK_DOUBLE) + void *voidPtr = source->WriteVoidPointer(pos, writeLength); + + // Verify that conditions are met: + if (source->GetMaxId() != pos + writeLength - 1) { - refT = static_cast(ref); + DataArrayAPIError("MaxId was not incremented to account for write length." + " MaxId is: " << source->GetMaxId() << ", expected: " + << (pos + writeLength - 1) << "."); } - else + if (source->GetSize() < pos + writeLength) { - refT = static_cast((ref >= 0.) ? (ref + 0.5) : (ref - 0.5)); + DataArrayAPIError("Size was not increased to account for write length. " + "Size is: " << source->GetSize() << ", expected: " + << (pos + writeLength) << "."); } - ScalarT test = output->GetValue(c); + // Cast the pointer and write to it: + ScalarT *ptr = static_cast(voidPtr); + for (int i = 0; i < writeLength; ++i) + { + ptr[i] = static_cast(((pos + 1) * pos) % 17); + ++pos; + } + writeLength += 1; + } - if (refT != test) + // Test the returned tuples: + vtkIdType v = 0; + std::vector tuple(comps); + for (vtkIdType i = 0; i < tuples; ++i) + { + source->GetTuple(i, &tuple[0]); + for (int j = 0; j < comps; ++j) { - DataArrayAPIError("Interpolated value incorrect: Got '" - << static_cast(test) << "', expected '" - << static_cast(refT) << "'."); + if (tuple[j] != static_cast(((v + 1) * v) % 17)) + { + DataArrayAPIError("Data mismatch at tuple " << i << ", component " << j + << ": Expected '" << (((v + 1) * v) % 17) + << "', got '" << tuple[j] << "'."); + } + ++v; } - } // foreach component + } + + DataArrayAPIFinish(); +} + +// void CreateDefaultLookupTable() +// GetLookupTable should be non-NULL after calling. +template +int Test_void_CreateDefaultLookupTable() +{ + DataArrayAPIInit("void CreateDefaultLookupTable()"); + + DataArrayAPICreateTestArray(source); + + source->CreateDefaultLookupTable(); + if (source->GetLookupTable() == NULL) + { + DataArrayAPIError("Lookup table was not created."); + } DataArrayAPIFinish(); } @@ -1255,6 +2437,16 @@ int Test_void_InsertTuple_i_tuple() tuple.push_back(static_cast(((t * comps) + c) % 17)); } source->InsertTuple(t, &tuple[0]); + if (source->GetSize() < ((t + 1) * comps)) + { + DataArrayAPIError("Size should be at least " << ((t + 1) * comps) + << " values, but is only " << source->GetSize() << "."); + } + if (source->GetMaxId() != ((t + 1) * comps) - 1) + { + DataArrayAPIError("MaxId should be " << ((t + 1) * comps) - 1 + << ", but is " << source->GetMaxId() << " instead."); + } } // Verify: @@ -1328,6 +2520,16 @@ int Test_void_InsertTupleN_i() default: DataArrayAPIError("Invalid N: " << N << "."); } + if (source->GetSize() < ((t + 1) * comps)) + { + DataArrayAPIError("Size should be at least " << ((t + 1) * comps) + << " values, but is only " << source->GetSize() << "."); + } + if (source->GetMaxId() != ((t + 1) * comps) - 1) + { + DataArrayAPIError("MaxId should be " << ((t + 1) * comps) - 1 + << ", but is " << source->GetMaxId() << " instead."); + } } // Verify: @@ -1374,6 +2576,16 @@ int Test_void_InsertNextTuple_tuple() tuple.push_back(static_cast(((t * comps) + c) % 17)); } source->InsertNextTuple(&tuple[0]); + if (source->GetSize() < ((t + 1) * comps)) + { + DataArrayAPIError("Size should be at least " << ((t + 1) * comps) + << " values, but is only " << source->GetSize() << "."); + } + if (source->GetMaxId() != ((t + 1) * comps) - 1) + { + DataArrayAPIError("MaxId should be " << ((t + 1) * comps) - 1 + << ", but is " << source->GetMaxId() << " instead."); + } } // Verify: @@ -1448,6 +2660,16 @@ int Test_void_InsertNextTupleN() default: DataArrayAPIError("Invalid N: " << N << "."); } + if (source->GetSize() < ((t + 1) * comps)) + { + DataArrayAPIError("Size should be at least " << ((t + 1) * comps) + << " values, but is only " << source->GetSize() << "."); + } + if (source->GetMaxId() != ((t + 1) * comps) - 1) + { + DataArrayAPIError("MaxId should be " << ((t + 1) * comps) - 1 + << ", but is " << source->GetMaxId() << " instead."); + } } // Verify: @@ -1665,110 +2887,6 @@ int Test_void_GetData_tupleMin_tupleMax_compMin_compMax_data() DataArrayAPIFinish(); } -// void DeepCopy(vtkAbstractArray *aa) -// void DeepCopy(vtkDataArray *da) -// Test copying into and from the target array type. -// Allocates memory as needed. -// ArgT switches between the two overloads. -// OtherT is the type of array that will be copied to/from. -template -int Test_void_DeepCopy_array() -{ - std::string argTName = (typeid(ArgT) == typeid(vtkAbstractArray) - ? "vtkAbstractArray" : "vtkDataArray"); - std::ostringstream sigBuilder; - sigBuilder << "void DeepCopy(" << argTName << " *array)"; - DataArrayAPIInit(sigBuilder.str()); - - std::string testType = vtkTypeTraits::Name(); - std::string otherType = vtkTypeTraits::Name(); - - DataArrayAPICreateTestArray(source); - DataArrayAPICreateReferenceArrayWithType(middle, OtherT); - DataArrayAPICreateTestArray(target); - - // Initialize source array: - vtkIdType comps = 9; - vtkIdType tuples = 40; - source->SetNumberOfComponents(comps); - source->SetNumberOfTuples(tuples); - for (vtkIdType t = 0; t < tuples; ++t) - { - for (int c = 0; c < comps; ++c) - { - source->SetComponent(t, c, static_cast(((t * comps) + c) % 17)); - } - } - - // Copy to intermediate: - middle->DeepCopy(static_cast(source.GetPointer())); - - // Verify intermediate: - if (middle->GetNumberOfComponents() != comps || - middle->GetNumberOfTuples() != tuples) - { - DataArrayAPIError("Incorrect size of array after copying from test array " - "(scalar type: '" << testType << "') to reference array " - "(scalar type: '" << otherType << "'): Expected number " - "of (tuples, components): " << "(" << tuples << ", " - << comps << "), got (" << middle->GetNumberOfTuples() - << ", " << middle->GetNumberOfComponents() << ")."); - } - - for (vtkIdType t = 0; t < tuples; ++t) - { - for (int c = 0; c < comps; ++c) - { - double ref = ((t * comps) + c) % 17; - double test = middle->GetComponent(t, c); - if (ref != test) - { - DataArrayAPIError("Data mismatch after copying from test array (scalar " - "type: '" << testType << "') to reference array " - "(scalar type: '" << otherType << "'): " "Data " - "mismatch at tuple " << t << " component " << c - << ": Expected " << ref << ", got " << test << "."); - } - } - } - - // Copy to final: - target->DeepCopy(static_cast(middle)); - - // Verify final: - if (target->GetNumberOfComponents() != comps || - target->GetNumberOfTuples() != tuples) - { - DataArrayAPIError("Incorrect size of array after copying from reference " - "array (scalar type: '" << otherType << "') to test " - "array (scalar type: '" << testType << "'): " - "Expected number of (tuples, components): " - << "(" << tuples << ", " << comps << "), got (" - << target->GetNumberOfTuples() << ", " - << target->GetNumberOfComponents() << ")."); - } - - for (vtkIdType t = 0; t < tuples; ++t) - { - for (int c = 0; c < comps; ++c) - { - double ref = ((t * comps) + c) % 17; - double test = target->GetComponent(t, c); - if (ref != test) - { - DataArrayAPIError("Data mismatch after copying from reference array " - "(scalar type: '" << otherType << "') to test array " - "(scalar type: '" << testType << "'): " "Data " - "mismatch at tuple " << t << " component " << c - << ": Expected " << ref << ", got " << test << "."); - } - } - } - - DataArrayAPIFinish(); -} - - // void CopyComponent(int j, vtkDataArray *from, int fromComponent) // For all tuples, copy the fromComponent component from the 'from' array // into the jth component in this. @@ -1916,28 +3034,112 @@ int Test_GetRange_all_overloads() //------------------------------------------------------------------------------ //-----------Unit Test Function Caller------------------------------------------ //------------------------------------------------------------------------------ +struct CanDispatch // Dummy for testing if we can dispatch an array type. +{ + template void operator()(ArrayT *) {} +}; + template int ExerciseDataArray() { int errors = 0; + // vtkAbstractArray API: + errors += Test_int_Allocate_numValues_ext(); + errors += Test_void_Initialize(); + errors += Test_int_GetDataType(); + errors += Test_int_GetDataTypeSize(); + errors += Test_int_GetElementComponentSize(); + errors += Test_NumberOfComponents(); + errors += Test_ComponentNames(); + errors += Test_NumberOfTuples(); + errors += Test_void_SetNumberOfValues_number(); errors += Test_void_SetTuple_i_j_source(); errors += Test_void_InsertTuple_i_j_source(); + errors += Test_void_InsertTuples_dstIds_srcIds_source(); + errors += Test_void_InsertTuples_dstStart_n_srcStart_source(); errors += Test_vtkIdType_InsertNextTuple_j_source(); errors += Test_void_GetTuples_ptIds_output(); errors += Test_void_GetTuples_p1_p2_output(); + errors += Test_voidPtr_GetVoidPointer(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_DeepCopy_array(); + errors += Test_void_InterpolateTuple_i_indices_source_weights(); + errors += Test_void_InterpolateTuple_i_id1_source1_id2_source2_t(); + errors += Test_int_Resize_numTuples(); + errors += Test_void_Reset(); + errors += Test_void_ExportToVoidPointer_voidPtr(); + errors += Test_ulong_GetActualMemorySize(); + errors += Test_int_IsNumeric(); + errors += Test_vtkArrayIteratorPtr_NewIterator(); + errors += Test_vtkIdType_GetDataSize(); + errors += Test_LookupValue_allSigs(); + errors += Test_vtkVariant_GetVariantValue_valueIdx(); + errors += Test_void_InsertVariantValue_idx_v(); + errors += Test_void_SetVariantValue_idx_v(); + + // vtkDataArray API: errors += Test_doubleptr_GetTuple_i(); errors += Test_void_GetTuple_i_tuple(); errors += Test_double_GetComponent_i_j(); errors += Test_void_SetComponent_i_j_c(); errors += Test_void_InsertComponent_i_j_c(); errors += Test_voidptr_WriteVoidPointer_id_number(); - errors += Test_ulong_GetActualMemorySize(); errors += Test_void_CreateDefaultLookupTable(); - errors += Test_int_IsNumeric(); - errors += Test_int_GetElementComponentSize(); - errors += Test_void_InterpolateTuple_i_indices_source_weights(); - errors += Test_void_InterpolateTuple_i_id1_source1_id2_source2_t(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); + errors += Test_void_ShallowCopy_array >(); errors += Test_doubleptr_GetTupleN_i(); errors += Test_doubleptr_GetTupleN_i(); errors += Test_doubleptr_GetTupleN_i(); @@ -1972,34 +3174,6 @@ int ExerciseDataArray() errors += Test_void_RemoveFirstTuple(); errors += Test_void_RemoveLastTuple(); errors += Test_void_GetData_tupleMin_tupleMax_compMin_compMax_data(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); - errors += Test_void_DeepCopy_array(); errors += Test_void_CopyComponent_j_from_fromComponent(); return errors; @@ -2016,3 +3190,13 @@ int ExerciseGetRange() } // end ExerciseGetRange } // end anon namespace + +#undef DataArrayAPIInit +#undef DataArrayAPIUpdateSignature +#undef DataArrayAPIFinish +#undef DataArrayAPICreateTestArray +#undef DataArrayAPICreateReferenceArray +#undef DataArrayAPICreateReferenceArrayWithType +#undef DataArrayAPINonFatalError +#undef DataArrayAPIError +#undef DataArrayAPIAssert diff --git a/Common/Core/Testing/Cxx/TestDataArrayComponentNames.cxx b/Common/Core/Testing/Cxx/TestDataArrayComponentNames.cxx index 165ed308a75..76343c40198 100644 --- a/Common/Core/Testing/Cxx/TestDataArrayComponentNames.cxx +++ b/Common/Core/Testing/Cxx/TestDataArrayComponentNames.cxx @@ -75,7 +75,7 @@ int TestDataArrayComponentNames(int,char *[]) //Test Down cast - vtkDoubleArray *downcast = vtkDoubleArray::SafeDownCast( farray ); + vtkDoubleArray *downcast = vtkArrayDownCast( farray ); if ( strcmp(downcast->GetComponentName(0),"a") != 0|| strcmp(downcast->GetComponentName(1),"b") != 0|| strcmp(downcast->GetComponentName(2),"c") != 0) diff --git a/Common/Core/Testing/Cxx/TestDataArrayIterators.cxx b/Common/Core/Testing/Cxx/TestDataArrayIterators.cxx index 211881b2dd8..b265ca3ea79 100644 --- a/Common/Core/Testing/Cxx/TestDataArrayIterators.cxx +++ b/Common/Core/Testing/Cxx/TestDataArrayIterators.cxx @@ -25,6 +25,43 @@ // undefine this to print benchmark results: #define SILENT +// Create a subclass of vtkTypedDataArray: +namespace +{ +class MyArray : public vtkTypedDataArray +{ + vtkFloatArray *Data; +public: + vtkTypeMacro(MyArray, vtkTypedDataArray) + static MyArray *New() { return new MyArray; } + void Init(vtkFloatArray *array) + { + this->Data = array; + this->NumberOfComponents = array->GetNumberOfComponents(); + this->MaxId = array->GetMaxId(); + } + ValueType& GetValueReference(vtkIdType idx) + { + return *this->Data->GetPointer(idx); + } + + // These pure virtuals are no-op -- all we care about is GetValueReference + // to test the iterator. + void SetTypedTuple(vtkIdType, const ValueType *) {} + void InsertTypedTuple(vtkIdType, const ValueType *) {} + vtkIdType InsertNextTypedTuple(const ValueType *) { return 0; } + vtkIdType LookupTypedValue(ValueType) { return 0; } + void LookupTypedValue(ValueType, vtkIdList*) {} + ValueType GetValue(vtkIdType) const { return 0; } + void SetValue(vtkIdType, ValueType) {} + void GetTypedTuple(vtkIdType, ValueType*) const {} + vtkIdType InsertNextValue(ValueType) { return 0; } + void InsertValue(vtkIdType, ValueType) {} + int Allocate(vtkIdType, vtkIdType) { return 0; } + int Resize(vtkIdType) { return 0; } +}; +} + int TestDataArrayIterators(int, char *[]) { vtkIdType numComps = 4; @@ -42,7 +79,12 @@ int TestDataArrayIterators(int, char *[]) array->SetValue(i, i % 97); } - // should be vtkDataArrayTemplate::Iterator (float*): + // Create the vtkTypedDataArray testing implementation: + vtkNew tdaContainer; + MyArray *tda = tdaContainer.GetPointer(); + tda->Init(array); + + // should be vtkAOSDataArrayTemplate::Iterator (float*): vtkFloatArray::Iterator datBegin = array->Begin(); vtkFloatArray::Iterator datIter = array->Begin(); if (typeid(datBegin) != typeid(float*)) @@ -53,9 +95,9 @@ int TestDataArrayIterators(int, char *[]) // should be vtkTypedDataArrayIterator: vtkTypedDataArray::Iterator tdaBegin = - vtkTypedDataArray::FastDownCast(array)->Begin(); + vtkTypedDataArray::FastDownCast(tda)->Begin(); vtkTypedDataArray::Iterator tdaIter = - vtkTypedDataArray::FastDownCast(array)->Begin(); + vtkTypedDataArray::FastDownCast(tda)->Begin(); if (typeid(tdaBegin) != typeid(vtkTypedDataArrayIterator)) { std::cerr << "Error: vtkTypedDataArray::Iterator is not a " @@ -93,7 +135,7 @@ int TestDataArrayIterators(int, char *[]) timer->StartTimer(); for (vtkIdType i = 0; i < numValues; ++i) { - lookupSum += array->GetValueReference(i); + lookupSum += *array->GetPointer(i); } timer->StopTimer(); double lookupTime = timer->GetElapsedTime(); @@ -110,8 +152,7 @@ int TestDataArrayIterators(int, char *[]) double datTime = timer->GetElapsedTime(); // vtkTypedDataArrayIterator: - vtkTypedDataArray::Iterator tdaEnd = - vtkTypedDataArray::FastDownCast(array)->End(); + vtkTypedDataArray::Iterator tdaEnd = tda->End(); float tdaSum = 0.f; timer->StartTimer(); while (tdaBegin != tdaEnd) diff --git a/Common/Core/Testing/Cxx/TestGenericDataArrayAPI.cxx b/Common/Core/Testing/Cxx/TestGenericDataArrayAPI.cxx new file mode 100644 index 00000000000..fd18bd94ae2 --- /dev/null +++ b/Common/Core/Testing/Cxx/TestGenericDataArrayAPI.cxx @@ -0,0 +1,865 @@ +/*============================================================================== + + Program: Visualization Toolkit + Module: TestGenericDataArrayAPI.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +==============================================================================*/ + +#include "vtkGenericDataArray.h" + +// Helpers: +#include "vtkAOSDataArrayTemplate.h" +#include "vtkArrayDispatch.h" +#include "vtkNew.h" +#include "vtkSmartPointer.h" +#include "vtkTypeTraits.h" + +#include +#include +#include +#include +#include +#include + +// Concrete classes for testing: +#include "vtkAOSDataArrayTemplate.h" +#include "vtkCharArray.h" +#include "vtkFloatArray.h" +#include "vtkDoubleArray.h" +#include "vtkIdTypeArray.h" +#include "vtkIntArray.h" +#include "vtkLongArray.h" +#include "vtkLongLongArray.h" +#include "vtkShortArray.h" +#include "vtkSignedCharArray.h" +#include "vtkSOADataArrayTemplate.h" +#include "vtkUnsignedCharArray.h" +#include "vtkUnsignedIntArray.h" +#include "vtkUnsignedLongArray.h" +#include "vtkUnsignedLongLongArray.h" +#include "vtkUnsignedShortArray.h" + +// About this test: +// +// This test runs a battery of unit tests that exercise the vtkGenericDataArray +// API on concrete implementations of their subclasses. It is designed to be +// easily extended to cover new array implementations and additional unit tests. +// +// This test has three main components: +// - Entry point: TestGenericDataArrayAPI(). Add new array classes here. +// - Unit test caller: ExerciseGenericDataArray(). Templated on value and array +// types. Calls individual unit test functions to excerise the array methods. +// Add new unit test calls here. +// - Unit test functions: Test_[methodSignature](). Templated on value type, +// array type, and possibly other parameters to simplify implementations. +// These should use the DataArrayAPI macros as needed + +// Forward declare the test function: +namespace { +template int ExerciseGenericDataArray(); +} // end anon namespace + +//------------------------------------------------------------------------------ +//-------------Test Entry Point------------------------------------------------- +//------------------------------------------------------------------------------ + +int TestGenericDataArrayAPI(int, char *[]) +{ + int errors = 0; + + // Add array classes here: + // Defaults: + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + errors += ExerciseGenericDataArray(); + + // Explicit AoS arrays: + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + + // Explicit SoA arrays: + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + errors += ExerciseGenericDataArray >(); + + if (errors > 0) + { + std::cerr << "Test failed! Error count: " << errors << std::endl; + } + return errors == 0 ? EXIT_SUCCESS : EXIT_FAILURE; +} + +//------------------------------------------------------------------------------ +//------------Unit Test Macros-------------------------------------------------- +//------------------------------------------------------------------------------ + +#define DataArrayAPIInit(_signature) \ + int errors = 0; \ + std::string signature = _signature + +#define DataArrayAPIUpdateSignature(_signature) \ + signature = _signature + +#define DataArrayAPIFinish() return errors + +#define DataArrayAPICreateTestArray(name) vtkNew name + +#define DataArrayAPICreateReferenceArray(name) \ + vtkSmartPointer name##DA = CreateDataArray(); \ + vtkAOSDataArrayTemplate *name = \ + vtkAOSDataArrayTemplate::SafeDownCast(name##DA.GetPointer()); \ + assert("Reference array is vtkAOSDataArrayTemplate" && name != NULL) + +#define DataArrayAPICreateReferenceArrayWithType(name, valueType) \ + vtkSmartPointer name##DA = CreateDataArray(); \ + vtkAOSDataArrayTemplate *name = \ + vtkAOSDataArrayTemplate::SafeDownCast(name##DA.GetPointer()); \ + assert("Reference array is vtkAOSDataArrayTemplate" && name != NULL) + +#define DataArrayAPINonFatalError(x) \ + { \ + ArrayT *errorTempArray = ArrayT::New(); \ + std::cerr << "Line " << __LINE__ << ": " \ + << "Failure in test of '" << signature << "' " \ + << "for array type '" << errorTempArray->GetClassName() << "'" \ + << ":\n" << x << std::endl; \ + errorTempArray->Delete(); \ + ++errors; \ + } + +#define DataArrayAPIError(x) \ + DataArrayAPINonFatalError(x) \ + return errors; + +namespace { + +// Convenience function to create a concrete data array from a template type: +template +vtkSmartPointer CreateDataArray() +{ + vtkSmartPointer array; + array.TakeReference(vtkDataArray::CreateDataArray( + vtkTypeTraits::VTK_TYPE_ID)); + assert("CreateArray failed for scalar type." && array.GetPointer()); + return array; +} + +//------------------------------------------------------------------------------ +//------------------Unit Test Implementations----------------------------------- +//------------------------------------------------------------------------------ + +// ValueType GetValue(vtkIdType valueIdx) const +// No range checking/allocation. +template +int Test_valT_GetValue_valueIdx_const() +{ + DataArrayAPIInit("ValueType GetValue(vtkIdType valueIdx) const"); + + DataArrayAPICreateTestArray(array); + vtkIdType comps = 9; + vtkIdType tuples = 5; + array->SetNumberOfComponents(comps); + array->SetNumberOfTuples(tuples); + + // Initialize: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + array->SetValue(i, static_cast(i % 16)); + } + + // Verify: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + ScalarT test = array->GetValue(i); + ScalarT ref = static_cast(i % 16); + if (test != ref) + { + DataArrayAPIError("Data mismatch at value index '" << i << "'. Expected '" + << ref << "', got '" << test << "'."); + } + } + + DataArrayAPIFinish(); +} + +//void GetTypedTuple(vtkIdType tupleIdx, ValueType* tuple) const +template +int Test_void_GetTypedTuple_tupleIdx_tuple() +{ + DataArrayAPIInit("void GetTypedTuple(vtkIdType tupleIdx, ValueType *tuple)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source->SetValue(i, static_cast(i % 17)); + } + + // Test the returned tuples: + vtkIdType refValue = 0; + std::vector tuple(comps); + for (vtkIdType tupleIdx = 0; tupleIdx < tuples; ++tupleIdx) + { + source->GetTypedTuple(tupleIdx, &tuple[0]); + for (int compIdx = 0; compIdx < comps; ++compIdx) + { + if (tuple[compIdx] != static_cast(refValue)) + { + DataArrayAPIError("Data mismatch at tuple " << tupleIdx << ", " + "component " << compIdx << ": Expected '" << refValue + << "', got '" << tuple[compIdx] << "'."); + } + ++refValue; + refValue %= 17; + } + } + + DataArrayAPIFinish(); +} + +// ValueType GetTypedComponent(vtkIdType tupleIdx, int comp) const +template +int Test_valT_GetTypedComponent_tupleIdx_comp_const() +{ + DataArrayAPIInit("ValueType GetTypedComponent(" + "vtkIdType tupleIdx, int comp) const"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source->SetValue(i, static_cast(i % 17)); + } + + // Test the returned tuples: + vtkIdType refValue = 0; + for (vtkIdType i = 0; i < tuples; ++i) + { + for (int j = 0; j < comps; ++j) + { + if (source->GetTypedComponent(i, j) != static_cast(refValue)) + { + DataArrayAPIError("Data mismatch at tuple " << i << ", " + "component " << j << ": Expected '" << refValue + << "', got '" << source->GetTypedComponent(i, j) + << "'."); + } + ++refValue; + refValue %= 17; + } + } + + DataArrayAPIFinish(); +} + +// void SetValue(vtkIdType valueIdx, ValueType value) +template +int Test_void_SetValue_valueIdx_value() +{ + DataArrayAPIInit("void SetValue(vtkIdType valueIdx, ValueType value)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array using tested function: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source->SetValue(i, static_cast(((i + 1) * (i + 2)) % 17)); + } + + // Validate: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + ScalarT ref = static_cast(((i + 1) * (i + 2)) % 17); + const typename ArrayT::ValueType test = source->GetValue(i); + if (ref != test) + { + DataArrayAPIError("Data mismatch at value " << i << ": Expected '" + << ref << "', got '" << test << "'."); + } + } + + DataArrayAPIFinish(); +} + +// void SetTypedTuple(vtkIdType tupleIdx, const ValueType* tuple) +template +int Test_void_SetTypedTuple_tupleIdx_tuple() +{ + DataArrayAPIInit("void SetTypedTuple(vtkIdType tupleIdx, " + "const ValueType* tuple)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array: + vtkIdType comps = 5; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType t = 0; t < tuples; ++t) + { + std::vector tuple; + for (int c = 0; c < comps; ++c) + { + tuple.push_back(static_cast(((t * comps) + c) % 17)); + } + source->SetTypedTuple(t, &tuple[0]); + } + + // Verify: + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + ScalarT ref = static_cast(((t * comps) + c) % 17); + ScalarT test = source->GetTypedComponent(t, c); + if (ref != test) + { + DataArrayAPIError("Data mismatch at tuple " << t << " component " << c + << ": Expected " << ref << ", got " << test << "."); + } + } + } + + DataArrayAPIFinish(); +} + +// void SetTypedComponent(vtkIdType tupleIdx, int comp, ValueType value) +template +int Test_void_SetTypedComponent_tupleIdx_comp_value() +{ + DataArrayAPIInit("void SetTypedComponent(vtkIdType tupleIdx, int comp, " + "ValueType value)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array using tested function: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + for (vtkIdType i = 0; i < tuples; ++i) + { + for (int j = 0; j < comps; ++j) + { + source->SetTypedComponent(i, j, + static_cast(((i + 1) * (j + 1)) % 17)); + } + } + + // Test the returned tuples: + std::vector tuple(comps); + for (vtkIdType i = 0; i < tuples; ++i) + { + source->GetTypedTuple(i, &tuple[0]); + for (int j = 0; j < comps; ++j) + { + ScalarT test = tuple[j]; + ScalarT ref = static_cast((i + 1) * (j + 1) % 17); + if (ref != test) + { + DataArrayAPIError("Data mismatch at tuple " << i << ", component " << j + << ": Expected '" << ref << "', got '" << test + << "'."); + } + } + } + + DataArrayAPIFinish(); +} + +// vtkIdType LookupTypedValue(ValueType value) +// void LookupTypedValue(ValueType value, vtkIdList* ids) +template +int Test_LookupTypedValue_allSigs() +{ + DataArrayAPIInit("LookupTypedValue"); + + DataArrayAPICreateTestArray(array); + + // Map Value --> ValueIdxs. We'll use this to validate the lookup results. + typedef std::map RefMap; + typedef typename RefMap::iterator RefMapIterator; + RefMap refMap; + // These are the values we'll be looking for. + for (ScalarT val = 0; val < 17; ++val) + { + refMap.insert(std::make_pair(val, vtkIdList::New())); + } + + // Initialize source array: + vtkIdType comps = 9; + vtkIdType tuples = 10; + array->SetNumberOfComponents(comps); + array->SetNumberOfTuples(tuples); + for (vtkIdType valIdx = 0; valIdx < comps * tuples; ++valIdx) + { + ScalarT val = static_cast(valIdx % 17); + array->SetValue(valIdx, val); + // Update our reference map: + RefMapIterator it = refMap.find(val); + assert("Value exists in reference map." && it != refMap.end()); + it->second->InsertNextId(valIdx); + } + + // Test the lookup functions. + vtkNew testIdList; + for (RefMapIterator it = refMap.begin(), itEnd = refMap.end(); it != itEnd; + ++it) + { + const ScalarT &val = it->first; + vtkIdList *refIdList = it->second; // Presorted due to insertion order + vtkIdType *refIdBegin = refIdList->GetPointer(0); + vtkIdType *refIdEnd = refIdList->GetPointer(refIdList->GetNumberOfIds()); + + // Docs are unclear about this. Does it return the first value, or just any? + // We'll assume any since it's unspecified. + DataArrayAPIUpdateSignature("vtkIdType LookupTypedValue(ValueType value)"); + vtkIdType testId = array->LookupTypedValue(val); + if (!std::binary_search(refIdBegin, refIdEnd, testId)) + { + // NonFatal + break so we can clean up. + DataArrayAPINonFatalError("Looking up value '" << val + << "' returned valueIdx '" << testId + << "', which maps to value '" + << array->GetValue(testId) << "'."); + break; + } + + // Now for the list overload: + DataArrayAPIUpdateSignature( + "void LookupTypedValue(ValueType value, vtkIdList* ids)"); + array->LookupTypedValue(val, testIdList.GetPointer()); + if (testIdList->GetNumberOfIds() != refIdList->GetNumberOfIds()) + { + // NonFatal + break so we can clean up. + DataArrayAPINonFatalError("Looking up value '" << val << "' returned " + << testIdList->GetNumberOfIds() << " ids, but " + << refIdList->GetNumberOfIds() + << "were expected."); + break; + } + vtkIdType *testIdBegin = testIdList->GetPointer(0); + vtkIdType *testIdEnd = testIdList->GetPointer(refIdList->GetNumberOfIds()); + // Ensure the test ids are sorted + std::sort(testIdBegin, testIdEnd); + if (!std::equal(testIdBegin, testIdEnd, refIdBegin)) + { + // NonFatal + break so we can clean up. + DataArrayAPINonFatalError("Looking up all value indices for value '" + << val + << "' did not return the expected result."); + break; + } + } + + // Cleanup: + for (RefMapIterator it = refMap.begin(), itEnd = refMap.end(); it != itEnd; + ++it) + { + it->second->Delete(); + it->second = NULL; + } + + DataArrayAPIFinish(); +} + +// vtkIdType InsertNextValue(ValueType v) +template +int Test_vtkIdType_InsertNextValue_v() +{ + DataArrayAPIInit("vtkIdType InsertNextValue(ValueType v)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array using tested function: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + vtkIdType insertLoc = source->InsertNextValue(static_cast(i % 17)); + if (insertLoc != i) + { + DataArrayAPIError("Returned location incorrect. Expected '" << i + << "', got '" << insertLoc << "'."); + } + if (source->GetSize() < i + 1) + { + DataArrayAPIError("Size should be at least " << i + 1 + << " values, but is only " << source->GetSize() << "."); + } + if (source->GetMaxId() != i) + { + DataArrayAPIError("MaxId should be " << i << ", but is " + << source->GetMaxId() << " instead."); + } + } + + // Validate: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + ScalarT ref = static_cast(i % 17); + const typename ArrayT::ValueType test = source->GetValue(i); + if (ref != test) + { + DataArrayAPIError("Data mismatch at value " << i << ": Expected '" + << ref << "', got '" << test << "'."); + } + } + + DataArrayAPIFinish(); +} + +// void InsertValue(vtkIdType idx, ValueType v) +template +int Test_void_InsertValue_idx_v() +{ + DataArrayAPIInit("void InsertValue(vtkIdType idx, ValueType v)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array using tested function: + vtkIdType comps = 9; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + source->InsertValue(i, static_cast(i % 17)); + + if (source->GetSize() < i + 1) + { + DataArrayAPIError("Size should be at least " << i + 1 + << " values, but is only " << source->GetSize() << "."); + } + if (source->GetMaxId() != i) + { + DataArrayAPIError("MaxId should be " << i << ", but is " + << source->GetMaxId() << " instead."); + } + } + + // Validate: + for (vtkIdType i = 0; i < comps * tuples; ++i) + { + ScalarT ref = static_cast(i % 17); + const typename ArrayT::ValueType test = source->GetValue(i); + if (ref != test) + { + DataArrayAPIError("Data mismatch at value " << i << ": Expected '" + << ref << "', got '" << test << "'."); + } + } + + DataArrayAPIFinish(); +} + +// void InsertTypedTuple(vtkIdType idx, const ValueType *t) +template +int Test_void_InsertTypedTuple_idx_t() +{ + DataArrayAPIInit("void InsertTypedTuple(vtkIdType idx, const ValueType *t)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array: + vtkIdType comps = 5; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + for (vtkIdType t = 0; t < tuples; ++t) + { + std::vector tuple; + for (int c = 0; c < comps; ++c) + { + tuple.push_back(static_cast(((t * comps) + c) % 17)); + } + source->InsertTypedTuple(t, &tuple[0]); + if (source->GetSize() < ((t + 1) * comps)) + { + DataArrayAPIError("Size should be at least " << ((t + 1) * comps) + << " values, but is only " << source->GetSize() << "."); + } + if (source->GetMaxId() != ((t + 1) * comps) - 1) + { + DataArrayAPIError("MaxId should be " << ((t + 1) * comps) - 1 + << ", but is " << source->GetMaxId() << " instead."); + } + } + + // Verify: + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + if (source->GetTypedComponent(t, c) != + static_cast(((t * comps) + c) % 17)) + { + DataArrayAPIError("Data mismatch at tuple " << t << " component " << c + << ": Expected " + << static_cast(((t * comps) + c) % 17) + << ", got " << source->GetTypedComponent(t, c) + << "."); + } + } + } + + DataArrayAPIFinish(); +} + +// vtkIdType InsertNextTypedTuple(const ValueType *t) +template +int Test_vtkIdType_InsertNextTypedTuple_t() +{ + DataArrayAPIInit("vtkIdType InsertNextTypedTuple(const ValueType *t)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array: + vtkIdType comps = 5; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + for (vtkIdType t = 0; t < tuples; ++t) + { + std::vector tuple; + for (int c = 0; c < comps; ++c) + { + tuple.push_back(static_cast(((t * comps) + c) % 17)); + } + vtkIdType insertLoc = source->InsertNextTypedTuple(&tuple[0]); + if (insertLoc != t) + { + DataArrayAPIError("Returned location incorrect. Expected '" << t + << "', got '" << insertLoc << "'."); + } + if (source->GetSize() < ((t + 1) * comps)) + { + DataArrayAPIError("Size should be at least " << ((t + 1) * comps) + << " values, but is only " << source->GetSize() << "."); + } + if (source->GetMaxId() != ((t + 1) * comps) - 1) + { + DataArrayAPIError("MaxId should be " << ((t + 1) * comps) - 1 + << ", but is " << source->GetMaxId() << " instead."); + } + } + + // Verify: + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + if (source->GetTypedComponent(t, c) != + static_cast(((t * comps) + c) % 17)) + { + DataArrayAPIError("Data mismatch at tuple " << t << " component " << c + << ": Expected " + << static_cast(((t * comps) + c) % 17) + << ", got " << source->GetTypedComponent(t, c) + << "."); + } + } + } + + DataArrayAPIFinish(); +} + +// vtkIdType GetNumberOfValues() +template +int Test_vtkIdType_GetNumberOfValues() +{ + DataArrayAPIInit("vtkIdType InsertNextTypedTuple(const ValueType *t)"); + + DataArrayAPICreateTestArray(source); + + // Initialize source array: + vtkIdType comps = 5; + vtkIdType tuples = 10; + source->SetNumberOfComponents(comps); + source->SetNumberOfTuples(tuples); + + if (source->GetNumberOfValues() != comps * tuples) + { + DataArrayAPIError("Returned number of values: " + << source->GetNumberOfValues() << ", expected " + << (comps * tuples) << "."); + } + + DataArrayAPIFinish(); +} + +// ValueType *GetValueRange() +// void GetValueRange(ValueType range[2]) +// ValueType *GetValueRange(int comp) +// void GetValueRange(ValueType range[2], int comp) +template +int Test_GetValueRange_all_overloads() +{ + DataArrayAPIInit("GetValueRange"); + + DataArrayAPICreateTestArray(array); + + // Initialize arrays: + vtkIdType comps = 6; + vtkIdType tuples = 9; + array->SetNumberOfComponents(comps); + array->SetNumberOfTuples(tuples); + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + array->SetComponent(t, c, (t + 1) * (c + 1)); + } + } + + // Just the range of the first component: + DataArrayAPIUpdateSignature("ValueType* GetValueRange()"); + ScalarT *rangePtr = array->GetValueRange(); + ScalarT expectedRange[2] = { static_cast(1), + static_cast(tuples) }; + if (rangePtr[0] != expectedRange[0] || + rangePtr[1] != expectedRange[1]) + { + DataArrayAPINonFatalError("First component range expected to be: [" + << expectedRange[0] << ", " << expectedRange[1] + << "], got [" << rangePtr[0] << ", " + << rangePtr[1] << "]."); + } + + DataArrayAPIUpdateSignature("void GetValueRange(ValueType range[2])"); + ScalarT rangeArray[2]; + array->GetValueRange(rangeArray); + if (rangeArray[0] != expectedRange[0] || + rangeArray[1] != expectedRange[1]) + { + DataArrayAPINonFatalError("First component range expected to be: [" + << expectedRange[0] << ", " << expectedRange[1] + << "], got [" << rangeArray[0] << ", " + << rangeArray[1] << "]."); + } + + DataArrayAPIUpdateSignature("ValueType* GetValueRange(int comp)"); + for (int c = 0; c < comps; ++c) + { + expectedRange[0] = static_cast(c + 1); + expectedRange[1] = static_cast(tuples * (c + 1)); + rangePtr = array->GetValueRange(c); + if (rangePtr[0] != expectedRange[0] || + rangePtr[1] != expectedRange[1]) + { + DataArrayAPINonFatalError("Component " << c << " range expected to be: [" + << expectedRange[0] << ", " << expectedRange[1] + << "], got [" << rangePtr[0] << ", " + << rangePtr[1] << "]."); + } + } + + DataArrayAPIUpdateSignature("void GetValueRange(ValueType range[2], int comp)"); + for (int c = 0; c < comps; ++c) + { + expectedRange[0] = static_cast(c + 1); + expectedRange[1] = static_cast(tuples * (c + 1)); + array->GetValueRange(rangeArray, c); + if (rangeArray[0] != expectedRange[0] || + rangeArray[1] != expectedRange[1]) + { + DataArrayAPINonFatalError("Component " << c << " range expected to be: [" + << expectedRange[0] << ", " << expectedRange[1] + << "], got [" << rangeArray[0] << ", " + << rangeArray[1] << "]."); + } + } + + DataArrayAPIFinish(); +} + +//------------------------------------------------------------------------------ +//-----------Unit Test Function Caller------------------------------------------ +//------------------------------------------------------------------------------ + +template +int ExerciseGenericDataArray() +{ + int errors = 0; + + errors += Test_valT_GetValue_valueIdx_const(); + errors += Test_void_GetTypedTuple_tupleIdx_tuple(); + errors += Test_valT_GetTypedComponent_tupleIdx_comp_const(); + errors += Test_void_SetValue_valueIdx_value(); + errors += Test_void_SetTypedTuple_tupleIdx_tuple(); + errors += Test_void_SetTypedComponent_tupleIdx_comp_value(); + errors += Test_LookupTypedValue_allSigs(); + errors += Test_vtkIdType_InsertNextValue_v(); + errors += Test_void_InsertValue_idx_v(); + errors += Test_void_InsertTypedTuple_idx_t(); + errors += Test_vtkIdType_InsertNextTypedTuple_t(); + errors += Test_vtkIdType_GetNumberOfValues(); + errors += Test_GetValueRange_all_overloads(); + + return errors; +} // end ExerciseDataArray + +} // end anon namespace + +#undef DataArrayAPIInit +#undef DataArrayAPIUpdateSignature +#undef DataArrayAPIFinish +#undef DataArrayAPICreateTestArray +#undef DataArrayAPICreateReferenceArray +#undef DataArrayAPICreateReferenceArrayWithType +#undef DataArrayAPINonFatalError +#undef DataArrayAPIError diff --git a/Common/Core/Testing/Cxx/TestInformationKeyLookup.cxx b/Common/Core/Testing/Cxx/TestInformationKeyLookup.cxx new file mode 100644 index 00000000000..7179aed160a --- /dev/null +++ b/Common/Core/Testing/Cxx/TestInformationKeyLookup.cxx @@ -0,0 +1,55 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestInformationKeyLookup.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkInformationKeyLookup.h" + +#include "vtkAbstractArray.h" +#include "vtkDataArray.h" +#include "vtkInformationDoubleVectorKey.h" +#include "vtkInformationIntegerKey.h" +#include "vtkInformationVariantVectorKey.h" +#include "vtkInformationInformationVectorKey.h" + +// Lookup a key and test that it matches what it should. +namespace { +bool VerifyKey(const std::string &name, + const std::string &location, + vtkInformationKey *key) +{ + return vtkInformationKeyLookup::Find(name, location) == key; +} +} // end anon namespace + +#define VERIFY_KEY(name, location) \ + if (!VerifyKey(#name, #location, location::name())) \ + { \ + std::cerr << "Error finding key: " << #location << "::" << #name << "\n"; \ + return EXIT_FAILURE; \ + } + +int TestInformationKeyLookup(int, char *[]) +{ + // Test some keys in vtkAbstractArray and vtkDataArray (those are currently + // the only ones available to this test, since the lookup only knows about + // keys in currently linked modules). + VERIFY_KEY(DISCRETE_VALUES, vtkAbstractArray) + VERIFY_KEY(DISCRETE_VALUE_SAMPLE_PARAMETERS, vtkAbstractArray) + VERIFY_KEY(GUI_HIDE, vtkAbstractArray) + VERIFY_KEY(PER_COMPONENT, vtkAbstractArray) + VERIFY_KEY(COMPONENT_RANGE, vtkDataArray) + VERIFY_KEY(L2_NORM_RANGE, vtkDataArray) + + return EXIT_SUCCESS; +} diff --git a/Common/Core/Testing/Python/CMakeLists.txt b/Common/Core/Testing/Python/CMakeLists.txt index 3a3cc0a9613..80bace11f65 100644 --- a/Common/Core/Testing/Python/CMakeLists.txt +++ b/Common/Core/Testing/Python/CMakeLists.txt @@ -9,7 +9,7 @@ vtk_add_test_python( TestEnums.py TestExecuteMethodFinalizeCrash.py TestGhost.py - TestIgnoreBTX.py + TestIterateCollection.py TestMutable.py TestNumpySupport.py TestNumpyInterface.py @@ -24,4 +24,5 @@ vtk_add_test_python( TestVariant.py TestWeakref.py TestCommand.py + TestInvokeEvent.py ) diff --git a/Common/Core/Testing/Python/TestArrayArguments.py b/Common/Core/Testing/Python/TestArrayArguments.py index a614f686e71..a2d6e508c9a 100644 --- a/Common/Core/Testing/Python/TestArrayArguments.py +++ b/Common/Core/Testing/Python/TestArrayArguments.py @@ -34,8 +34,8 @@ def testArrayArguments(self): a.SetNumberOfTuples(1) ti = [0, a.GetDataTypeValueMin(), a.GetDataTypeValueMax()] to = [0, 0, 0] - a.SetTupleValue(0, ti) - a.GetTupleValue(0, to); + a.SetTypedTuple(0, ti) + a.GetTypedTuple(0, to); self.assertEqual(ti, to) d1 = a.GetTuple(0) d2 = [float(x) for x in ti] @@ -50,8 +50,8 @@ def testUnsignedArrayArguments(self): a.SetNumberOfTuples(1) ti = [0, a.GetDataTypeValueMin(), a.GetDataTypeValueMax()] to = [0, 0, 0] - a.SetTupleValue(0, ti) - a.GetTupleValue(0, to); + a.SetTypedTuple(0, ti) + a.GetTypedTuple(0, to); self.assertEqual(ti, to) d1 = a.GetTuple(0) d2 = [float(x) for x in ti] @@ -64,10 +64,10 @@ def testCharArrayArguments(self): a.SetNumberOfComponents(3) a.SetNumberOfTuples(1) ti = "opn" - a.SetTupleValue(0, ti) + a.SetTypedTuple(0, ti) # python strings are immutable, so this should NOT work #to = "***" - #a.GetTupleValue(0, to); + #a.GetTypedTuple(0, to); d1 = list(a.GetTuple(0)) d2 = [ord(x) for x in ti] self.assertEqual(d1, d2) @@ -99,5 +99,26 @@ def testInformationVectorKeys(self): t = info.Get(vtk.vtkDataObject.SPACING()) self.assertEqual(t, spacing) + def testArrayIterator(self): + # try a string array + a = vtk.vtkStringArray() + a.InsertNextValue("hello") + i = a.NewIterator() + self.assertEqual(a.GetValue(0), i.GetValue(0)) + # try the various data array subclasses + for arrayClass in arrays: + a = arrayClass() + a.SetNumberOfComponents(2) + a.SetNumberOfTuples(1) + tupleIn = (a.GetDataTypeValueMin(), a.GetDataTypeValueMax()) + a.SetTypedTuple(0, tupleIn) + i = a.NewIterator() + # make sure iterator's GetTuple method is wrapped + tupleOut = i.GetTuple(0) + self.assertEqual(tupleIn, tupleOut) + # make sure the GetValue method returns expected result + self.assertEqual(tupleIn[0], i.GetValue(0)) + self.assertEqual(tupleIn[1], i.GetValue(1)) + if __name__ == "__main__": Testing.main([(TestArrayArguments, 'test')]) diff --git a/Common/Core/Testing/Python/TestBuffer.py b/Common/Core/Testing/Python/TestBuffer.py index 2417574846f..a6ee478caff 100644 --- a/Common/Core/Testing/Python/TestBuffer.py +++ b/Common/Core/Testing/Python/TestBuffer.py @@ -85,8 +85,8 @@ def testCharArray(self): # bit array is actually stored as a byte array a = vtk.vtkCharArray() a.SetNumberOfComponents(5) - a.InsertNextTupleValue("hello") - a.InsertNextTupleValue("world") + a.InsertNextTypedTuple("hello") + a.InsertNextTypedTuple("world") m = memoryview(a) self.assertEqual(m.format, 'c') self.assertEqual(m.itemsize, 1) diff --git a/Common/Core/Testing/Python/TestIgnoreBTX.py b/Common/Core/Testing/Python/TestIgnoreBTX.py deleted file mode 100644 index f7773e4186f..00000000000 --- a/Common/Core/Testing/Python/TestIgnoreBTX.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Test VTK_IGNORE_BTX setting to ensure that it is ON -""" - -import sys -import vtk -from vtk.test import Testing - -class TestIgnoreBTX(Testing.vtkTest): - def testIgnoreBTX(self): - """Try to call a method that is BTX'd, to ensure VTK_IGNORE_BTX=ON - """ - - stringArray = vtk.vtkStringArray() - information = vtk.vtkInformation() - stringArray.CopyInformation(information, 0) - -if __name__ == "__main__": - Testing.main([(TestIgnoreBTX, 'test')]) diff --git a/Common/Core/Testing/Python/TestInvokeEvent.py b/Common/Core/Testing/Python/TestInvokeEvent.py new file mode 100644 index 00000000000..93eaf07aabb --- /dev/null +++ b/Common/Core/Testing/Python/TestInvokeEvent.py @@ -0,0 +1,57 @@ +import unittest +import vtk + +from vtk.test import Testing + +testInt = 12 +testString = "test string" +testFloat = 5.4 + + +class VTKPythonObjectCalldataInvokeEventTest(Testing.vtkTest): + + @vtk.calldata_type(vtk.VTK_INT) + def callbackInt(self, caller, event, calldata): + self.calldata = calldata + + @vtk.calldata_type(vtk.VTK_STRING) + def callbackString(self, caller, event, calldata): + self.calldata = calldata + + @vtk.calldata_type(vtk.VTK_DOUBLE) + def callbackFloat(self, caller, event, calldata): + self.calldata = calldata + + @vtk.calldata_type(vtk.VTK_OBJECT) + def callbackObj(self, caller, event, calldata): + self.calldata = calldata + + def setUp(self): + self.vtkObj = vtk.vtkObject() + + self.vtkObjForCallData = vtk.vtkObject() + + def test_int(self): + self.vtkObj.AddObserver(vtk.vtkCommand.AnyEvent, self.callbackInt) + self.vtkObj.InvokeEvent(vtk.vtkCommand.ModifiedEvent, testInt) + self.assertEqual(self.calldata, testInt) + + def test_string(self): + self.vtkObj.AddObserver(vtk.vtkCommand.AnyEvent, self.callbackString) + self.vtkObj.InvokeEvent(vtk.vtkCommand.ModifiedEvent, testString) + self.assertEqual(self.calldata, testString) + + def test_float(self): + self.vtkObj.AddObserver(vtk.vtkCommand.AnyEvent, self.callbackFloat) + self.vtkObj.InvokeEvent(vtk.vtkCommand.ModifiedEvent, testFloat) + self.assertAlmostEqual(self.calldata, testFloat) + + def test_obj(self): + self.vtkObj.AddObserver(vtk.vtkCommand.AnyEvent, self.callbackObj) + self.vtkObj.InvokeEvent(vtk.vtkCommand.ModifiedEvent, self.vtkObjForCallData) + self.assertAlmostEqual(self.calldata, self.vtkObjForCallData) + + + +if __name__ == '__main__': + Testing.main([(VTKPythonObjectCalldataInvokeEventTest, 'test')]) diff --git a/Common/Core/Testing/Python/TestIterateCollection.py b/Common/Core/Testing/Python/TestIterateCollection.py new file mode 100644 index 00000000000..a143492c4a8 --- /dev/null +++ b/Common/Core/Testing/Python/TestIterateCollection.py @@ -0,0 +1,52 @@ +"""Test iterating through a vtkCollection with the standard python syntax""" + + +import vtk +from vtk.test import Testing + + +class TestIterateCollection(Testing.vtkTest): + def setUp(self): + self.vtkObjs = [vtk.vtkObject() for _ in range(30)] + self.collection = vtk.vtkCollection() + for obj in self.vtkObjs: + self.collection.AddItem(obj) + + self.emptyCollection = vtk.vtkCollection() + + def testIterateCollection(self): + newObjsList = [obj for obj in self.collection] + self.assertEqual(self.vtkObjs, newObjsList) + + counter = 0 + for _ in self.collection: + counter += 1 + self.assertEqual(counter, 30) + + counter = 0 + for _ in self.emptyCollection: + counter += 1 + self.assertEqual(counter, 0) + + def testCollectionChild(self): + #check that iteration is being inherited correctly + dataArray = vtk.vtkIntArray() + + dataArrayCollection = vtk.vtkDataArrayCollection() + dataArrayCollection.AddItem(dataArray) + + self.assertEqual([obj for obj in dataArrayCollection], + [dataArray]) + + def testOperators(self): + self.assertTrue(self.vtkObjs[0] in self.collection) + self.assertEqual(list(self.collection), self.vtkObjs) + + def testReferenceCounting(self): + initialReferenceCount = self.collection.GetReferenceCount() + list(self.collection) + self.assertEqual(self.collection.GetReferenceCount(), initialReferenceCount) + + +if __name__ == "__main__": + Testing.main([(TestIterateCollection, 'test')]) diff --git a/Common/Core/Testing/Tcl/CMakeLists.txt b/Common/Core/Testing/Tcl/CMakeLists.txt index 5c0c1a4fc4c..89b0b9b00b5 100644 --- a/Common/Core/Testing/Tcl/CMakeLists.txt +++ b/Common/Core/Testing/Tcl/CMakeLists.txt @@ -4,7 +4,6 @@ vtk_add_test_tcl( # TestEmptyInput.tcl # TestSetGet.tcl TestString.tcl - TestIgnoreBTX.tcl otherInterp.tcl otherPrint.tcl ) diff --git a/Common/Core/Testing/Tcl/TestIgnoreBTX.tcl b/Common/Core/Testing/Tcl/TestIgnoreBTX.tcl deleted file mode 100644 index 63cd89eee7e..00000000000 --- a/Common/Core/Testing/Tcl/TestIgnoreBTX.tcl +++ /dev/null @@ -1,26 +0,0 @@ -for {set i 0} {$i < [expr $argc - 1]} {incr i} { - if {[lindex $argv $i] == "-A"} { - set auto_path "$auto_path [lindex $argv [expr $i +1]]" - } -} - -package require vtk - -# A simple test to see if BTX'd methods are available -proc rtOtherTest { fileid } { - vtkStringArray stringArray - vtkInformation information - - if {[catch {stringArray CopyInformation information 0}] == 0} { - puts "VTK_IGNORE_BTX=ON test succeeded" - } else { - puts stderr "VTK_IGNORE_BTX=ON test failed" - exit 1 - } -} - -# All tests should end with the following... - -rtOtherTest stdout - -exit diff --git a/Common/Core/module.cmake b/Common/Core/module.cmake index 4bc8fd04341..b4aa0d32918 100644 --- a/Common/Core/module.cmake +++ b/Common/Core/module.cmake @@ -9,6 +9,7 @@ vtk_module(vtkCommonCore vtkTestingCore vtkCommonSystem vtkCommonTransforms + vtksys KIT vtkCommon ) diff --git a/Common/Core/vtkAOSDataArrayTemplate.h b/Common/Core/vtkAOSDataArrayTemplate.h new file mode 100644 index 00000000000..2806f44f48b --- /dev/null +++ b/Common/Core/vtkAOSDataArrayTemplate.h @@ -0,0 +1,311 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkAOSDataArrayTemplate.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkAOSDataArrayTemplate - Array-Of-Structs implementation of +// vtkGenericDataArray. +// +// .SECTION Description +// vtkGenericDataArray specialization that stores data array in the traditional +// VTK memory layout where a 3 component is stored in contiguous memory as +// \c A1A2A2B1B2B3C1C2C3 ... where A,B,C,... are tuples. +// +// This replaces vtkDataArrayTemplate. +// +// .SECTION See Also +// vtkGenericDataArray vtkSOADataArrayTemplate + +#ifndef vtkAOSDataArrayTemplate_h +#define vtkAOSDataArrayTemplate_h + +#include "vtkCommonCoreModule.h" // For export macro +#include "vtkGenericDataArray.h" +#include "vtkBuffer.h" // For storage buffer. + +// The export macro below makes no sense, but is necessary for older compilers +// when we export instantiations of this class from vtkCommonCore. +template +class VTKCOMMONCORE_EXPORT vtkAOSDataArrayTemplate : + public vtkGenericDataArray, ValueTypeT> +{ + typedef vtkGenericDataArray, ValueTypeT> + GenericDataArrayType; +public: + typedef vtkAOSDataArrayTemplate SelfType; + vtkTemplateTypeMacro(SelfType, GenericDataArrayType) + typedef typename Superclass::ValueType ValueType; + + enum DeleteMethod + { + VTK_DATA_ARRAY_FREE=vtkBuffer::VTK_DATA_ARRAY_FREE, + VTK_DATA_ARRAY_DELETE=vtkBuffer::VTK_DATA_ARRAY_DELETE + }; + + static vtkAOSDataArrayTemplate* New(); + + // Description: + // Get the value at @a valueIdx. @a valueIdx assumes AOS ordering. + inline ValueType GetValue(vtkIdType valueIdx) const + { + return this->Buffer->GetBuffer()[valueIdx]; + } + + // Description: + // Set the value at @a valueIdx to @a value. @a valueIdx assumes AOS ordering. + inline void SetValue(vtkIdType valueIdx, ValueType value) + { + this->Buffer->GetBuffer()[valueIdx] = value; + } + + // Description: + // Copy the tuple at @a tupleIdx into @a tuple. + inline void GetTypedTuple(vtkIdType tupleIdx, ValueType* tuple) const + { + const vtkIdType valueIdx = tupleIdx * this->NumberOfComponents; + std::copy(this->Buffer->GetBuffer() + valueIdx, + this->Buffer->GetBuffer() + valueIdx + this->NumberOfComponents, + tuple); + } + + // Description: + // Set this array's tuple at @a tupleIdx to the values in @a tuple. + inline void SetTypedTuple(vtkIdType tupleIdx, const ValueType* tuple) + { + const vtkIdType valueIdx = tupleIdx * this->NumberOfComponents; + std::copy(tuple, tuple + this->NumberOfComponents, + this->Buffer->GetBuffer() + valueIdx); + } + + // Description: + // Get component @a comp of the tuple at @a tupleIdx. + inline ValueType GetTypedComponent(vtkIdType tupleIdx, int comp) const + { + return this->Buffer->GetBuffer()[this->NumberOfComponents*tupleIdx + comp]; + } + + // Description: + // Set component @a comp of the tuple at @a tupleIdx to @a value. + inline void SetTypedComponent(vtkIdType tupleIdx, int comp, ValueType value) + { + const vtkIdType valueIdx = tupleIdx * this->NumberOfComponents + comp; + this->SetValue(valueIdx, value); + } + + // Description: + // Get the address of a particular data index. Make sure data is allocated + // for the number of items requested. Set MaxId according to the number of + // data values requested. + ValueType* WritePointer(vtkIdType valueIdx, vtkIdType numValues); + virtual void* WriteVoidPointer(vtkIdType valueIdx, vtkIdType numValues); + + // Description: + // Get the address of a particular data index. Performs no checks + // to verify that the memory has been allocated etc. + // Use of this method is discouraged, as newer arrays require a deep-copy of + // the array data in order to return a suitable pointer. See vtkArrayDispatch + // for a safer alternative for fast data access. + ValueType* GetPointer(vtkIdType valueIdx); + virtual void* GetVoidPointer(vtkIdType valueIdx); + + // Description: + // This method lets the user specify data to be held by the array. The + // array argument is a pointer to the data. size is the size of the + // array supplied by the user. Set save to 1 to keep the class from + // deleting the array when it cleans up or reallocates memory. The class + // uses the actual array provided; it does not copy the data from the + // suppled array. If specified, the delete method determines how the data + // array will be deallocated. If the delete method is + // VTK_DATA_ARRAY_FREE, free() will be used. If the delete method is + // DELETE, delete[] will be used. The default is FREE. + void SetArray(ValueType* array, vtkIdType size, int save, int deleteMethod); + void SetArray(ValueType* array, vtkIdType size, int save); + virtual void SetVoidArray(void* array, vtkIdType size, int save); + virtual void SetVoidArray(void* array, vtkIdType size, int save, + int deleteMethod); + + // Description: + // Tell the array explicitly that a single data element has + // changed. Like DataChanged(), then is only necessary when you + // modify the array contents without using the array's API. + // @note This is a legacy method from vtkDataArrayTemplate, and is only + // implemented for array-of-struct arrays. It currently just calls + // DataChanged() and does nothing clever. + // TODO this is only defined for AOS (vtkDataArrayTemplate leftover). + // Deprecate to favor DataChanged? + void DataElementChanged(vtkIdType) { this->DataChanged(); } + + // Description: + // Legacy support for array-of-structs value iteration. + // TODO Deprecate? + typedef ValueType* Iterator; + Iterator Begin() { return Iterator(this->GetVoidPointer(0)); } + Iterator End() { return Iterator(this->GetVoidPointer(this->MaxId + 1)); } + + // Description: + // Perform a fast, safe cast from a vtkAbstractArray to a + // vtkAOSDataArrayTemplate. + // This method checks if source->GetArrayType() returns DataArray + // or a more derived type, and performs a static_cast to return + // source as a vtkDataArray pointer. Otherwise, NULL is returned. + static vtkAOSDataArrayTemplate* + FastDownCast(vtkAbstractArray *source) + { + if (source) + { + switch (source->GetArrayType()) + { + case vtkAbstractArray::AoSDataArrayTemplate: + if (vtkDataTypesCompare(source->GetDataType(), + vtkTypeTraits::VTK_TYPE_ID)) + { + return static_cast*>(source); + } + break; + } + } + return NULL; + } + + virtual int GetArrayType() { return vtkAbstractArray::AoSDataArrayTemplate; } + virtual VTK_NEWINSTANCE vtkArrayIterator *NewIterator(); + virtual bool HasStandardMemoryLayout() { return true; } + virtual void ShallowCopy(vtkDataArray *other); + + // Description: + // @deprecated Replace TupleValue with TypedTuple to use the new method + // names. Note that the new signatures are also const-correct. + VTK_LEGACY(void GetTupleValue(vtkIdType tupleIdx, ValueType *tuple)); + VTK_LEGACY(void SetTupleValue(vtkIdType tupleIdx, const ValueType *tuple)); + VTK_LEGACY(void InsertTupleValue(vtkIdType tupleIdx, const ValueType *tuple)); + VTK_LEGACY(vtkIdType InsertNextTupleValue(const ValueType *tuple)); + + // Reimplemented for efficiency: + virtual void InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, + vtkAbstractArray* source); + // MSVC doesn't like 'using' here (error C2487). Just forward instead: +// using Superclass::InsertTuples; + virtual void InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, + vtkAbstractArray *source) + { this->Superclass::InsertTuples(dstIds, srcIds, source); } + +protected: + vtkAOSDataArrayTemplate(); + ~vtkAOSDataArrayTemplate(); + + // Description: + // Allocate space for numTuples. Old data is not preserved. If numTuples == 0, + // all data is freed. + bool AllocateTuples(vtkIdType numTuples); + + // Description: + // Allocate space for numTuples. Old data is preserved. If numTuples == 0, + // all data is freed. + bool ReallocateTuples(vtkIdType numTuples); + + vtkBuffer *Buffer; + +private: + vtkAOSDataArrayTemplate(const vtkAOSDataArrayTemplate&); // Not implemented. + void operator=(const vtkAOSDataArrayTemplate&); // Not implemented. + + friend class vtkGenericDataArray, + ValueTypeT>; + +}; + +// Declare vtkArrayDownCast implementations for AoS containers: +vtkArrayDownCast_TemplateFastCastMacro(vtkAOSDataArrayTemplate) + +# define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(T) \ + template class VTKCOMMONCORE_EXPORT vtkAOSDataArrayTemplate< T > + +// This macro is used by the subclasses to create dummy +// declarations for these functions such that the wrapper +// can see them. The wrappers ignore vtkAOSDataArrayTemplate. +#define vtkCreateWrappedArrayInterface(T) \ + int GetDataType(); \ + void GetTypedTuple(vtkIdType i, T* tuple); \ + void SetTypedTuple(vtkIdType i, const T* tuple); \ + void InsertTypedTuple(vtkIdType i, const T* tuple); \ + vtkIdType InsertNextTypedTuple(const T* tuple); \ + T GetValue(vtkIdType id); \ + void SetValue(vtkIdType id, T value); \ + void SetNumberOfValues(vtkIdType number); \ + void InsertValue(vtkIdType id, T f); \ + vtkIdType InsertNextValue(T f); \ + T *GetValueRange(int comp); \ + T *GetValueRange(); \ + T* WritePointer(vtkIdType id, vtkIdType number); \ + T* GetPointer(vtkIdType id)/*; \ + + * These methods are not wrapped to avoid wrappers exposing these + * easy-to-get-wrong methods because passing in the wrong value for 'save' is + * guaranteed to cause a memory issue down the line. Either the wrappers + * didn't use malloc to allocate the memory or the memory isn't actually + * persisted because a temporary array is used that doesn't persist like this + * method expects. + + void SetArray(T* array, vtkIdType size, int save); \ + void SetArray(T* array, vtkIdType size, int save, int deleteMethod) */ + +#endif // header guard + +// This portion must be OUTSIDE the include blockers. This is used to tell +// libraries other than vtkCommonCore that instantiations of +// vtkAOSDataArrayTemplate can be found externally. This prevents each library +// from instantiating these on their own. +#ifndef VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#if defined(VTK_BUILD_SHARED_LIBS) && defined(_MSC_VER) +#pragma warning (push) + +// C4091: 'extern ' : ignored on left of 'int' when no variable is declared +#pragma warning (disable: 4091) + +// Compiler-specific extension warning. +#pragma warning (disable: 4231) + +// We need to disable warning 4910 and do an extern dllexport +// anyway. When deriving vtkCharArray and other types from an +// instantiation of this template the compiler does an explicit +// instantiation of the base class. From outside the vtkCommon +// library we block this using an extern dllimport instantiation. +// For classes inside vtkCommon we should be able to just do an +// extern instantiation, but VS 2008 complains about missing +// definitions. We cannot do an extern dllimport inside vtkCommon +// since the symbols are local to the dll. An extern dllexport +// seems to be the only way to convince VS 2008 to do the right +// thing, so we just disable the warning. +#pragma warning (disable: 4910) // extern and dllexport incompatible + +// Use an "extern explicit instantiation" to give the class a DLL +// interface. This is a compiler-specific extension. +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(char); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(double); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(float); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(int); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(long); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(long long); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(short); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(signed char); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned char); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned int); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned long); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned long long); +extern VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned short); + +#pragma warning (pop) + +#endif // VTK_BUILD_SHARED_LIBS && _MSC_VER +#endif // VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING + +// VTK-HeaderTest-Exclude: vtkAOSDataArrayTemplate.h diff --git a/Common/Core/vtkAOSDataArrayTemplate.txx b/Common/Core/vtkAOSDataArrayTemplate.txx new file mode 100644 index 00000000000..899f26d9f2e --- /dev/null +++ b/Common/Core/vtkAOSDataArrayTemplate.txx @@ -0,0 +1,293 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkAOSDataArrayTemplate.txx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#ifndef vtkAOSDataArrayTemplate_txx +#define vtkAOSDataArrayTemplate_txx + +#include "vtkAOSDataArrayTemplate.h" + +#include "vtkArrayIteratorTemplate.h" + +//----------------------------------------------------------------------------- +template +vtkAOSDataArrayTemplate* +vtkAOSDataArrayTemplate::New() +{ + VTK_STANDARD_NEW_BODY(vtkAOSDataArrayTemplate); +} + +//----------------------------------------------------------------------------- +template +vtkAOSDataArrayTemplate::vtkAOSDataArrayTemplate() +{ + this->Buffer = vtkBuffer::New(); +} + +//----------------------------------------------------------------------------- +template +vtkAOSDataArrayTemplate::~vtkAOSDataArrayTemplate() +{ + this->SetArray(NULL, 0, 0); + this->Buffer->Delete(); +} + +//----------------------------------------------------------------------------- +template +void vtkAOSDataArrayTemplate +::SetArray(ValueType* array, vtkIdType size, int save, int deleteMethod) +{ + this->Buffer->SetBuffer(array, size, save != 0, deleteMethod); + this->Size = size; + this->MaxId = this->Size - 1; + this->DataChanged(); +} + +//----------------------------------------------------------------------------- +template +void vtkAOSDataArrayTemplate +::SetArray(ValueType *array, vtkIdType size, int save) +{ + this->SetArray(array, size, save, VTK_DATA_ARRAY_FREE); +} + +//----------------------------------------------------------------------------- +template +void vtkAOSDataArrayTemplate +::SetVoidArray(void *array, vtkIdType size, int save) +{ + this->SetArray(static_cast(array), size, save); +} + +//----------------------------------------------------------------------------- +template +void vtkAOSDataArrayTemplate +::SetVoidArray(void *array, vtkIdType size, int save, int deleteMethod) +{ + this->SetArray(static_cast(array), size, save, deleteMethod); +} + +//----------------------------------------------------------------------------- +template +vtkArrayIterator* vtkAOSDataArrayTemplate::NewIterator() +{ + vtkArrayIterator *iter = vtkArrayIteratorTemplate::New(); + iter->Initialize(this); + return iter; +} + +//----------------------------------------------------------------------------- +template +void vtkAOSDataArrayTemplate::ShallowCopy(vtkDataArray *other) +{ + SelfType *o = SelfType::FastDownCast(other); + if (o) + { + this->Size = o->Size; + this->MaxId = o->MaxId; + this->SetName(o->Name); + this->SetNumberOfComponents(o->NumberOfComponents); + this->CopyComponentNames(o); + if (this->Buffer != o->Buffer) + { + this->Buffer->Delete(); + this->Buffer = o->Buffer; + this->Buffer->Register(NULL); + } + this->DataChanged(); + } + else + { + this->Superclass::ShallowCopy(other); + } +} + +//----------------------------------------------------------------------------- +template +void vtkAOSDataArrayTemplate::InsertTuples( + vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, + vtkAbstractArray *source) +{ + // First, check for the common case of typeid(source) == typeid(this). This + // way we don't waste time redoing the other checks in the superclass, and + // can avoid doing a dispatch for the most common usage of this method. + SelfType *other = vtkArrayDownCast(source); + if (!other) + { + // Let the superclass handle dispatch/fallback. + this->Superclass::InsertTuples(dstStart, n, srcStart, source); + return; + } + + if (n == 0) + { + return; + } + + int numComps = this->GetNumberOfComponents(); + if (other->GetNumberOfComponents() != numComps) + { + vtkErrorMacro("Number of components do not match: Source: " + << other->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + + vtkIdType maxSrcTupleId = srcStart + n - 1; + vtkIdType maxDstTupleId = dstStart + n - 1; + + if (maxSrcTupleId >= other->GetNumberOfTuples()) + { + vtkErrorMacro("Source array too small, requested tuple at index " + << maxSrcTupleId << ", but there are only " + << other->GetNumberOfTuples() << " tuples in the array."); + return; + } + + vtkIdType newSize = (maxDstTupleId + 1) * this->NumberOfComponents; + if (this->Size < newSize) + { + if (!this->Resize(maxDstTupleId + 1)) + { + vtkErrorMacro("Resize failed."); + return; + } + } + + this->MaxId = std::max(this->MaxId, newSize - 1); + + ValueType *srcBegin = other->GetPointer(srcStart * numComps); + ValueType *srcEnd = srcBegin + (n * numComps); + ValueType *dstBegin = this->GetPointer(dstStart * numComps); + + std::copy(srcBegin, srcEnd, dstBegin); +} + +//----------------------------------------------------------------------------- +template +typename vtkAOSDataArrayTemplate::ValueType* +vtkAOSDataArrayTemplate +::WritePointer(vtkIdType valueIdx, vtkIdType numValues) +{ + vtkIdType newSize = valueIdx + numValues; + if (newSize > this->Size) + { + if (!this->Resize(newSize / this->NumberOfComponents + 1)) + { + return NULL; + } + this->MaxId = (newSize - 1); + } + + // For extending the in-use ids but not the size: + this->MaxId = std::max(this->MaxId, newSize - 1); + + this->DataChanged(); + return this->GetPointer(valueIdx); +} + +//----------------------------------------------------------------------------- +template +void* vtkAOSDataArrayTemplate +::WriteVoidPointer(vtkIdType valueIdx, vtkIdType numValues) +{ + return this->WritePointer(valueIdx, numValues); +} + +//----------------------------------------------------------------------------- +template +typename vtkAOSDataArrayTemplate::ValueType * +vtkAOSDataArrayTemplate::GetPointer(vtkIdType valueIdx) +{ + return this->Buffer->GetBuffer() + valueIdx; +} + +//----------------------------------------------------------------------------- +template +void* vtkAOSDataArrayTemplate::GetVoidPointer(vtkIdType valueIdx) +{ + return this->GetPointer(valueIdx); +} + +// Deprecated API: +#ifndef VTK_LEGACY_REMOVE + +//------------------------------------------------------------------------------ +template +void vtkAOSDataArrayTemplate::GetTupleValue(vtkIdType tupleIdx, + ValueType *tuple) +{ + VTK_LEGACY_REPLACED_BODY(vtkAOSDataArrayTemplate::GetTupleValue, "VTK 7.1", + vtkGenericDataArray::GetTypedTuple); + this->GetTypedTuple(tupleIdx, tuple); +} + +//------------------------------------------------------------------------------ +template +void vtkAOSDataArrayTemplate::SetTupleValue(vtkIdType tupleIdx, + const ValueType *tuple) +{ + VTK_LEGACY_REPLACED_BODY(vtkAOSDataArrayTemplate::SetTupleValue, "VTK 7.1", + vtkGenericDataArray::SetTypedTuple); + this->SetTypedTuple(tupleIdx, tuple); +} + +//------------------------------------------------------------------------------ +template +void vtkAOSDataArrayTemplate:: +InsertTupleValue(vtkIdType tupleIdx, const ValueType *tuple) +{ + VTK_LEGACY_REPLACED_BODY(vtkAOSDataArrayTemplate::InsertTupleValue, "VTK 7.1", + vtkGenericDataArray::InsertTypedTuple); + this->InsertTypedTuple(tupleIdx, tuple); +} + +//------------------------------------------------------------------------------ +template +vtkIdType vtkAOSDataArrayTemplate:: +InsertNextTupleValue(const ValueType *tuple) +{ + VTK_LEGACY_REPLACED_BODY(vtkAOSDataArrayTemplate::InsertNextTupleValue, + "VTK 7.1", + vtkGenericDataArray::InsertNextTypedTuple); + return this->InsertNextTypedTuple(tuple); +} + +#endif // VTK_LEGACY_REMOVE + +//----------------------------------------------------------------------------- +template +bool vtkAOSDataArrayTemplate::AllocateTuples(vtkIdType numTuples) +{ + vtkIdType numValues = numTuples * this->GetNumberOfComponents(); + if (this->Buffer->Allocate(numValues)) + { + this->Size = this->Buffer->GetSize(); + return true; + } + return false; +} + +//----------------------------------------------------------------------------- +template +bool vtkAOSDataArrayTemplate::ReallocateTuples(vtkIdType numTuples) +{ + if (this->Buffer->Reallocate(numTuples * this->GetNumberOfComponents())) + { + this->Size = this->Buffer->GetSize(); + return true; + } + return false; +} + +#endif // header guard diff --git a/Common/Core/vtkAbstractArray.cxx b/Common/Core/vtkAbstractArray.cxx index 256fdd8dbb4..af21ec8e699 100644 --- a/Common/Core/vtkAbstractArray.cxx +++ b/Common/Core/vtkAbstractArray.cxx @@ -184,6 +184,15 @@ int vtkAbstractArray::CopyComponentNames( vtkAbstractArray *da ) return 0; } +//---------------------------------------------------------------------------- +void vtkAbstractArray::SetNumberOfValues(vtkIdType numValues) +{ + if (this->Resize(std::ceil(numValues / + static_cast(this->NumberOfComponents)))) + { + this->MaxId = numValues - 1; + } +} //---------------------------------------------------------------------------- void vtkAbstractArray::SetInformation(vtkInformation *args) @@ -205,7 +214,7 @@ void vtkAbstractArray::SetInformation(vtkInformation *args) } //---------------------------------------------------------------------------- -void vtkAbstractArray::GetTuples(vtkIdList* ptIds, vtkAbstractArray* aa) +void vtkAbstractArray::GetTuples(vtkIdList* tupleIds, vtkAbstractArray* aa) { if (aa->GetNumberOfComponents() != this->GetNumberOfComponents()) { @@ -214,10 +223,10 @@ void vtkAbstractArray::GetTuples(vtkIdList* ptIds, vtkAbstractArray* aa) } // Here we give the slowest implementation. Subclasses can override // to use the knowledge about the data. - vtkIdType num = ptIds->GetNumberOfIds(); + vtkIdType num = tupleIds->GetNumberOfIds(); for (vtkIdType i = 0; i < num; i++) { - aa->SetTuple(i, ptIds->GetId(i), this); + aa->SetTuple(i, tupleIds->GetId(i), this); } } @@ -249,13 +258,35 @@ bool vtkAbstractArray::HasStandardMemoryLayout() //---------------------------------------------------------------------------- void vtkAbstractArray::DeepCopy( vtkAbstractArray* da ) { - if (da && da->HasInformation() && da!=this) + if (!da || da == this) + { + return; + } + + if (da->HasInformation()) { this->CopyInformation(da->GetInformation(),/*deep=*/1); } + else + { + this->SetInformation(NULL); + } + + this->SetName(da->Name); + this->CopyComponentNames( da ); } +//---------------------------------------------------------------------------- +void vtkAbstractArray::ExportToVoidPointer(void *dest) +{ + if (this->MaxId > 0 && this->GetDataTypeSize() > 0) + { + void *src = this->GetVoidPointer(0); + memcpy(dest, src, ((this->MaxId + 1) * this->GetDataTypeSize())); + } +} + //---------------------------------------------------------------------------- int vtkAbstractArray::CopyInformation(vtkInformation* infoFrom, int deep) { @@ -392,13 +423,13 @@ vtkVariant vtkAbstractArrayGetVariantValue(T* arr, vtkIdType index) } //---------------------------------------------------------------------------- -vtkVariant vtkAbstractArray::GetVariantValue(vtkIdType i) +vtkVariant vtkAbstractArray::GetVariantValue(vtkIdType valueIdx) { vtkVariant val; switch(this->GetDataType()) { vtkExtraExtendedTemplateMacro(val = vtkAbstractArrayGetVariantValue( - static_cast(this->GetVoidPointer(0)), i)); + static_cast(this->GetVoidPointer(0)), valueIdx)); } return val; } diff --git a/Common/Core/vtkAbstractArray.h b/Common/Core/vtkAbstractArray.h index 8c94735bcc1..b3c38d3a183 100644 --- a/Common/Core/vtkAbstractArray.h +++ b/Common/Core/vtkAbstractArray.h @@ -35,6 +35,19 @@ // change this name using the SetName() method. (The array name is // used for data manipulation.) // +// This class (and subclasses) use two forms of addressing elements: +// - Value Indexing: The index of an element assuming an array-of-structs +// memory layout. +// - Tuple/Component Indexing: Explicitly specify the tuple and component +// indices. +// +// It is also worth pointing out that the behavior of the "Insert*" methods +// of classes in this hierarchy may not behave as expected. They work exactly +// as the corresponding "Set*" methods, except that memory allocation will +// be performed if acting on a value past the end of the array. If the data +// already exists, "inserting" will overwrite existing values, rather than shift +// the array contents and insert the new data at the specified location. +// // .SECTION See Also // vtkDataArray vtkStringArray vtkCellArray @@ -59,15 +72,17 @@ class vtkVariantArray; class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject { public: - friend class vtkDataArrayTemplateHelper; - vtkTypeMacro(vtkAbstractArray,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Allocate memory for this array. Delete old storage only if necessary. // Note that ext is no longer used. - virtual int Allocate(vtkIdType sz, vtkIdType ext=1000) = 0; + // This method will reset MaxId to -1 and resize the array capacity such that + // this->Size >= numValues. + // If numValues is 0, all memory will be freed. + // Return 1 on success, 0 on failure. + virtual int Allocate(vtkIdType numValues, vtkIdType ext=1000) = 0; // Description: // Release storage and reset array to initial state. @@ -123,24 +138,43 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject // Also note that if allocation is performed no copy is performed so // existing data will be lost (if data conservation is sought, one may // use the Resize method instead). - virtual void SetNumberOfTuples(vtkIdType number) = 0; + virtual void SetNumberOfTuples(vtkIdType numTuples) = 0; // Description: - // Get the number of tuples (a component group) in the array. + // Specify the number of values (tuples * components) for this object to hold. + // Does an allocation as well as setting the MaxId ivar. Used in conjunction + // with SetValue() method for fast insertion. + virtual void SetNumberOfValues(vtkIdType numValues); + + // Description: + // Get the number of complete tuples (a component group) in the array. vtkIdType GetNumberOfTuples() {return (this->MaxId + 1)/this->NumberOfComponents;} // Description: - // Set the tuple at the ith location using the jth tuple in the source array. - // This method assumes that the two arrays have the same type - // and structure. Note that range checking and memory allocation is not + // Get the total number of values in the array. This is typically equivalent + // to (numTuples * numComponents). The exception is during incremental array + // construction for subclasses that support component insertion, which may + // result in an incomplete trailing tuple. + inline vtkIdType GetNumberOfValues() const + { + return (this->MaxId + 1); + } + + // Description: + // Set the tuple at dstTupleIdx in this array to the tuple at srcTupleIdx in + // the source array. This method assumes that the two arrays have the same + // type and structure. Note that range checking and memory allocation is not // performed; use in conjunction with SetNumberOfTuples() to allocate space. - virtual void SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) = 0; + virtual void SetTuple(vtkIdType dstTupleIdx, vtkIdType srcTupleIdx, + vtkAbstractArray *source) = 0; // Description: - // Insert the jth tuple in the source array, at ith location in this array. + // Insert the tuple at srcTupleIdx in the source array into this array at + // dstTupleIdx. // Note that memory allocation is performed as necessary to hold the data. - virtual void InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) = 0; + virtual void InsertTuple(vtkIdType dstTupleIdx, vtkIdType srcTupleIdx, + vtkAbstractArray* source) = 0; // Description: // Copy the tuples indexed in srcIds from the source array to the tuple @@ -157,19 +191,20 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject vtkAbstractArray* source) = 0; // Description: - // Insert the jth tuple in the source array, at the end in this array. - // Note that memory allocation is performed as necessary to hold the data. - // Returns the location at which the data was inserted. - virtual vtkIdType InsertNextTuple(vtkIdType j, vtkAbstractArray* source) = 0; + // Insert the tuple from srcTupleIdx in the source array at the end of this + // array. Note that memory allocation is performed as necessary to hold the + // data. Returns the tuple index at which the data was inserted. + virtual vtkIdType InsertNextTuple(vtkIdType srcTupleIdx, + vtkAbstractArray* source) = 0; // Description: - // Given a list of point ids, return an array of tuples. + // Given a list of tuple ids, return an array of tuples. // You must insure that the output array has been previously // allocated with enough space to hold the data. - virtual void GetTuples(vtkIdList *ptIds, vtkAbstractArray* output); + virtual void GetTuples(vtkIdList *tupleIds, vtkAbstractArray* output); // Description: - // Get the tuples for the range of points ids specified + // Get the tuples for the range of tuple ids specified // (i.e., p1->p2 inclusive). You must insure that the output array has // been previously allocated with enough space to hold the data. virtual void GetTuples(vtkIdType p1, vtkIdType p2, vtkAbstractArray *output); @@ -179,23 +214,15 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject // VTK user guide, e.g. a contiguous array: // {t1c1, t1c2, t1c3, ... t1cM, t2c1, ... tNcM} // where t1c2 is the second component of the first tuple. - // - // If the array does not have the standard memory layout GetVoidPointer should - // not be used, as a deep copy of the data must be made. Instead, use a - // vtkTypedDataArrayIterator to get pointer-like semantics that can safely - // access the data values. - // - // Subclasses that return false here must derive from vtkMappedDataArray - // to ensure that they will work safely with the rest of the pipeline. virtual bool HasStandardMemoryLayout(); // Description: // Return a void pointer. For image pipeline interface and other // special pointer manipulation. - // If the data is simply being iterated over, consider using - // vtkDataArrayIteratorMacro for safety and efficiency, rather than using this - // member directly. - virtual void *GetVoidPointer(vtkIdType id) = 0; + // Use of this method is discouraged, as newer arrays require a deep-copy of + // the array data in order to return a suitable pointer. See vtkArrayDispatch + // for a safer alternative for fast data access. + virtual void *GetVoidPointer(vtkIdType valueIdx) = 0; // Description: // Deep copy of data. Implementation left to subclasses, which @@ -207,24 +234,24 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject virtual void DeepCopy(vtkAbstractArray* da); // Description: - // Set the ith tuple in this array as the interpolated tuple value, - // given the ptIndices in the source array and associated - // interpolation weights. + // Set the tuple at dstTupleIdx in this array to the interpolated tuple value, + // given the ptIndices in the source array and associated interpolation + // weights. // This method assumes that the two arrays are of the same type // and strcuture. - virtual void InterpolateTuple(vtkIdType i, vtkIdList *ptIndices, - vtkAbstractArray* source, double* weights) = 0; + virtual void InterpolateTuple(vtkIdType dstTupleIdx, vtkIdList *ptIndices, + vtkAbstractArray* source, double* weights) = 0; // Description - // Insert the ith tuple in this array as interpolated from the two values, - // p1 and p2, and an interpolation factor, t. - // The interpolation factor ranges from (0,1), - // with t=0 located at p1. This method assumes that the three arrays are of - // the same type. p1 is value at index id1 in source1, while, p2 is - // value at index id2 in source2. - virtual void InterpolateTuple(vtkIdType i, - vtkIdType id1, vtkAbstractArray* source1, - vtkIdType id2, vtkAbstractArray* source2, double t) =0; + // Insert the tuple at dstTupleIdx in this array to the tuple interpolated + // from the two tuple indices, srcTupleIdx1 and srcTupleIdx2, and an + // interpolation factor, t. The interpolation factor ranges from (0,1), + // with t=0 located at the tuple described by srcTupleIdx1. This method + // assumes that the three arrays are of the same type, srcTupleIdx1 is an + // index to array source1, and srcTupleIdx2 is an index to array source2. + virtual void InterpolateTuple(vtkIdType dstTupleIdx, + vtkIdType srcTupleIdx1, vtkAbstractArray* source1, + vtkIdType srcTupleIdx2, vtkAbstractArray* source2, double t) =0; // Description: // Free any unnecessary memory. @@ -233,8 +260,13 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject virtual void Squeeze() = 0; // Description: - // Resize the array while conserving the data. Returns 1 if - // resizing succeeded and 0 otherwise. + // Resize the array to the requested number of tuples and preserve data. + // Increasing the array size may allocate extra memory beyond what was + // requested. MaxId will not be modified when increasing array size. + // Decreasing the array size will trim memory to the requested size and + // may update MaxId if the valid id range is truncated. + // Requesting an array size of 0 will free all memory. + // Returns 1 if resizing succeeded and 0 otherwise. virtual int Resize(vtkIdType numTuples) = 0; // Description: @@ -255,13 +287,11 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject vtkIdType GetMaxId() {return this->MaxId;} -//BTX enum DeleteMethod { VTK_DATA_ARRAY_FREE, VTK_DATA_ARRAY_DELETE }; -//ETX // Description: // This method lets the user specify data to be held by the array. The @@ -284,7 +314,7 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject // This method copies the array data to the void pointer specified // by the user. It is up to the user to allocate enough memory for // the void pointer. - virtual void ExportToVoidPointer(void *vtkNotUsed(out_ptr)) {} + virtual void ExportToVoidPointer(void *out_ptr); // Description: // Return the memory in kibibytes (1024 bytes) consumed by this data array. Used to @@ -313,6 +343,7 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject // VTK_STRING. // Note that the data array returned has to be deleted by the // user. + VTK_NEWINSTANCE static vtkAbstractArray* CreateArray(int dataType); // Description: @@ -323,6 +354,7 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject // Description: // Subclasses must override this method and provide the right kind // of templated vtkArrayIteratorTemplate. + VTK_NEWINSTANCE virtual vtkArrayIterator* NewIterator() = 0; // Description: @@ -336,23 +368,23 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject } // Description: - // Return the indices where a specific value appears. + // Return the value indices where a specific value appears. virtual vtkIdType LookupValue(vtkVariant value) = 0; - virtual void LookupValue(vtkVariant value, vtkIdList* ids) = 0; + virtual void LookupValue(vtkVariant value, vtkIdList* valueIds) = 0; // Description: // Retrieve value from the array as a variant. - virtual vtkVariant GetVariantValue(vtkIdType idx); + virtual vtkVariant GetVariantValue(vtkIdType valueIdx); // Description: // Insert a value into the array from a variant. This method does // bounds checking. - virtual void InsertVariantValue(vtkIdType idx, vtkVariant value) = 0; + virtual void InsertVariantValue(vtkIdType valueIdx, vtkVariant value) = 0; // Description: // Set a value in the array from a variant. This method does NOT do // bounds checking. - virtual void SetVariantValue(vtkIdType idx, vtkVariant value) = 0; + virtual void SetVariantValue(vtkIdType valueIdx, vtkVariant value) = 0; // Description: // Tell the array explicitly that the data has changed. @@ -438,7 +470,7 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject // Inquire if this array has an instance of vtkInformation // already associated with it. bool HasInformation(){ return this->Information!=0; } - //BTX + // Description: // Copy information instance. Arrays use information objects // in a variety of ways. It is important to have flexibility in @@ -450,7 +482,6 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject // keys they do not wish to be coppied. The subclass will not need to // explicilty copy the keys as it's handled here. virtual int CopyInformation(vtkInformation *infoFrom, int deep=1); - //ETX // Description: // This key is a hint to end user interface that this array @@ -500,13 +531,17 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject enum { AbstractArray = 0, DataArray, + AoSDataArrayTemplate, + SoADataArrayTemplate, TypedDataArray, - DataArrayTemplate, - MappedDataArray + MappedDataArray, + + DataArrayTemplate = AoSDataArrayTemplate //! Legacy }; // Description: - // Method for type-checking in FastDownCast implementations. + // Method for type-checking in FastDownCast implementations. See also + // vtkArrayDownCast. virtual int GetArrayType() { return AbstractArray; @@ -548,14 +583,75 @@ class VTKCOMMONCORE_EXPORT vtkAbstractArray : public vtkObject vtkInformation* Information; - //BTX class vtkInternalComponentNames; vtkInternalComponentNames* ComponentNames; //names for each component - //ETX private: vtkAbstractArray(const vtkAbstractArray&); // Not implemented. void operator=(const vtkAbstractArray&); // Not implemented. }; +// Description: +// Implementation of vtkArrayDownCast. The templating/etc is moved to this +// worker struct to get around limitations of template functions (no partial +// specialization, ambiguities, etc). +template +struct vtkArrayDownCast_impl +{ + inline ArrayT* operator()(vtkAbstractArray* array) + { + return ArrayT::SafeDownCast(array); + } +}; + +// Description: +// vtkArrayDownCast is to be used by generic (e.g. templated) code for quickly +// downcasting vtkAbstractArray pointers to more derived classes. +// The typical VTK downcast pattern (SafeDownCast) performs a string comparison +// on the class names in the object's inheritance hierarchy, which is quite +// expensive and can dominate computational resource usage when downcasting is +// needed in a worker function. +// To address this, certain arrays support a FastDownCast method, which replaces +// the chain of string comparisons with 1-2 integer comparisons and thus is +// significantly more efficient. +// However, not all arrays support the FastDownCast mechanism. vtkArrayDownCast +// exists to select between the two; Arrays that support FastDownCast will use +// it, while others will fallback to the slower SafeDownCast. +// +// A more detailed description of this class and related tools can be found +// \ref VTK-7-1-ArrayDispatch "here". +template +ArrayT* vtkArrayDownCast(vtkAbstractArray *array) +{ + // The default vtkArrayDownCast_impl struct uses SafeDownCast, but is + // specialized for arrays that support FastDownCast. + return vtkArrayDownCast_impl()(array); +} + +// Description: +// This macro is used to tell vtkArrayDownCast to use FastDownCast instead of +// SafeDownCast. +#define vtkArrayDownCast_FastCastMacro(ArrayT) \ + template <> struct vtkArrayDownCast_impl \ + { \ + inline ArrayT* operator()(vtkAbstractArray *array) \ + { \ + return ArrayT::FastDownCast(array); \ + } \ + }; + +// Description: +// Same as vtkArrayDownCast_FastCastMacro, but treats ArrayT as a +// single-parameter template (the parameter is the value type). Defines a +// vtkArrayDownCast implementation that uses the specified array template class +// with any value type. +#define vtkArrayDownCast_TemplateFastCastMacro(ArrayT) \ + template struct vtkArrayDownCast_impl > \ + { \ + inline ArrayT* operator()(vtkAbstractArray *array) \ + { \ + return ArrayT::FastDownCast(array); \ + } \ + }; + #endif diff --git a/Common/Core/vtkAngularPeriodicDataArray.h b/Common/Core/vtkAngularPeriodicDataArray.h index 4c4d5e99d71..a1ed18f93ca 100644 --- a/Common/Core/vtkAngularPeriodicDataArray.h +++ b/Common/Core/vtkAngularPeriodicDataArray.h @@ -38,10 +38,16 @@ template class vtkAngularPeriodicDataArray: public vtkPeriodicDataArray { public: - vtkMappedDataArrayNewInstanceMacro(vtkAngularPeriodicDataArray); + vtkAbstractTemplateTypeMacro(vtkAngularPeriodicDataArray, + vtkPeriodicDataArray) + vtkAOSArrayNewInstanceMacro(vtkAngularPeriodicDataArray) static vtkAngularPeriodicDataArray *New(); virtual void PrintSelf(ostream &os, vtkIndent indent); + // Description: + // Initialize the mapped array with the original input data array. + virtual void InitializeArray(vtkAOSDataArrayTemplate* inputData); + // Description: // Set/Get the rotation angle in degrees. Default is 0. void SetAngle(double angle); @@ -66,7 +72,7 @@ class vtkAngularPeriodicDataArray: public vtkPeriodicDataArray // Description: // Transform the provided tuple - virtual void Transform(Scalar* tuple); + virtual void Transform(Scalar* tuple) const; // Description: // Update rotation matrix from Axis, Angle and Center diff --git a/Common/Core/vtkAngularPeriodicDataArray.txx b/Common/Core/vtkAngularPeriodicDataArray.txx index c7e4069d556..d310fc8833b 100644 --- a/Common/Core/vtkAngularPeriodicDataArray.txx +++ b/Common/Core/vtkAngularPeriodicDataArray.txx @@ -38,6 +38,27 @@ template void vtkAngularPeriodicDataArray this->Center[0] << " " << this->Center[1] << " " << this->Center[2] << "\n"; } +//------------------------------------------------------------------------------ +template void vtkAngularPeriodicDataArray +::InitializeArray(vtkAOSDataArrayTemplate* data) +{ + this->Initialize(); + if (!data) + { + vtkErrorMacro(<< "No original data provided."); + return; + } + + if (data->GetNumberOfComponents() != 3 && data->GetNumberOfComponents() != 9) + { + vtkWarningMacro(<< "Original data has " << data->GetNumberOfComponents() << + " components, Expecting 3 or 9."); + return; + } + + this->Superclass::InitializeArray(data); +} + //------------------------------------------------------------------------------ template void vtkAngularPeriodicDataArray:: SetAngle(double angle) @@ -90,7 +111,7 @@ SetCenter(double* center) //------------------------------------------------------------------------------ template void vtkAngularPeriodicDataArray:: -Transform(Scalar* pos) +Transform(Scalar* pos) const { if (this->NumberOfComponents == 3) { diff --git a/Common/Core/vtkAnimationCue.h b/Common/Core/vtkAnimationCue.h index 57d29c78158..bd4207cc3a6 100644 --- a/Common/Core/vtkAnimationCue.h +++ b/Common/Core/vtkAnimationCue.h @@ -46,7 +46,6 @@ class VTKCOMMONCORE_EXPORT vtkAnimationCue: public vtkObject static vtkAnimationCue* New(); - //BTX // Structure passed on every event invocation. // Depending upon the cue time mode, these times are either // normalized [0,1] or relative to the scene that contains the cue. @@ -62,7 +61,6 @@ class VTKCOMMONCORE_EXPORT vtkAnimationCue: public vtkObject double DeltaTime; // valid only in AnimationCueTickEvent handler double ClockTime; // valid only in AnimationCueTickEvent handler }; - //ETX // Description: // Get/Set the time mode. In Normalized mode, the start and end @@ -149,23 +147,22 @@ class VTKCOMMONCORE_EXPORT vtkAnimationCue: public vtkObject // scene neither normalized nor offsetted to the start of the scene. vtkGetMacro(ClockTime, double); -//BTX enum TimeCodes { TIMEMODE_NORMALIZED=0, TIMEMODE_RELATIVE=1 }; -//ETX + protected: vtkAnimationCue(); ~vtkAnimationCue(); -//BTX + enum { UNINITIALIZED=0, INACTIVE, ACTIVE }; -//ETX + double StartTime; double EndTime; int TimeMode; diff --git a/Common/Core/vtkArray.h b/Common/Core/vtkArray.h index 1f7e39ccd37..ed943ef07ec 100644 --- a/Common/Core/vtkArray.h +++ b/Common/Core/vtkArray.h @@ -68,7 +68,6 @@ class VTKCOMMONCORE_EXPORT vtkArray : public vtkObject typedef vtkArrayExtents::DimensionT DimensionT; typedef vtkArrayExtents::SizeT SizeT; -//BTX enum { /// Used with CreateArray() to create dense arrays @@ -76,7 +75,6 @@ class VTKCOMMONCORE_EXPORT vtkArray : public vtkObject /// Used with CreateArray() to create sparse arrays SPARSE = 1 }; -//ETX // Description: // Creates a new array where StorageType is one of vtkArray::DENSE @@ -85,6 +83,7 @@ class VTKCOMMONCORE_EXPORT vtkArray : public vtkObject // VTK_UNSIGNED_INT, VTK_LONG, VTK_UNSIGNED_LONG, VTK_DOUBLE, // VTK_ID_TYPE, or VTK_STRING. The caller is responsible for the // lifetime of the returned object. + VTK_NEWINSTANCE static vtkArray* CreateArray(int StorageType, int ValueType); // Description: diff --git a/Common/Core/vtkArrayCoordinates.h b/Common/Core/vtkArrayCoordinates.h index 373eab66c33..e629b3ca64c 100644 --- a/Common/Core/vtkArrayCoordinates.h +++ b/Common/Core/vtkArrayCoordinates.h @@ -105,9 +105,9 @@ class VTKCOMMONCORE_EXPORT vtkArrayCoordinates ostream& stream, const vtkArrayCoordinates& rhs); private: - //BTX + std::vector Storage; - //ETX + }; #endif diff --git a/Common/Core/vtkArrayDispatch.h b/Common/Core/vtkArrayDispatch.h new file mode 100644 index 00000000000..7234181dabf --- /dev/null +++ b/Common/Core/vtkArrayDispatch.h @@ -0,0 +1,385 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkArrayDispatch.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkArrayDispatch - vtkDataArray code generator/dispatcher. +// +// vtkArrayDispatch implements a mechanism for generating optimized code for +// multiple subclasses of vtkDataArray at once. Using a TypeList based +// approach (see vtkTypeList), a templated worker implementation is generated +// for a restricted or unrestricted set of vtkDataArray subclasses. +// +// A more detailed description of this class and related tools can be found +// \ref VTK-7-1-ArrayDispatch "here". +// +// The primary goals of this class are to simplify multi-array dispatch +// implementations, and provide tools to lower compilation time and binary +// size (i.e. avoiding 'template explosions'). +// +// vtkArrayDispatch is also intended to replace code that currently relies on +// the encapsulation-breaking vtkDataArray::GetVoidPointer method. Not all +// subclasses of vtkDataArray use the memory layout assumed by GetVoidPointer; +// calling this method on, e.g. a vtkSOADataArrayTemplate will trigger a deep +// copy of the array data into an AOS buffer. This is very inefficient and +// should be avoided. +// +// The vtkDataArrayAccessor wrapper is worth mentioning here, as it allows +// vtkArrayDispatch workers to operate on selected concrete subclasses for +// 'fast paths', yet fallback to using the slower vtkDataArray API for uncommon +// array types. This helps mitigate the "template explosion" issues that can +// result from instantiating a large worker functions for many array types. +// +// These dispatchers extend the basic functionality of vtkTemplateMacro with +// the following features: +// - Multiarray dispatch: A single call can dispatch up to 3 arrays at once. +// - Array restriction: The set of valid arrays for a particular dispatch +// can be restricted. For example, if only vtkDoubleArray or vtkFloatArray +// will be passed into the call, the dispatcher will only generate code paths +// that use those arrays. +// - ValueType restriction: If both SoA and AoS arrays need to be supported, +// but only certain ValueTypes are expected, the dispatcher can restrict +// itself to only use arrays that match this critera. +// - Application-wide array restrictions: If a VTK application uses only a few +// arraytype / valuetype combinations, certain dispatchers will eliminate +// paths using unsupported arrays at compile time. +// +// The basic Dispatch implementation will generate code paths for all arrays +// in the application-wide array list, and operates on a single array. +// +// Dispatchers that start with Dispatch2 operate on 2 arrays simultaneously, +// while those that begin with Dispatch3 operate on 3 arrays. +// +// To reduce compile time and binary size, the following dispatchers can be +// used to restrict the set of arrays that will be used. There are versions of +// these that operate on 1, 2, or 3 arrays: +// +// - DispatchByArray: +// Accepts an explicit TypeList of arrays to consider. +// These dispatchers do NOT respect the application-wide array restrictions. +// Example usecase: A filter that creates either vtkFloatArray or +// vtkDoubleArray depending on configuration can use this to restrict itself +// to only these specific types. +// Note that these should not be used for operating on filter inputs, instead +// use DispatchByValueType, which also considers variations in vtkDataArray +// subclasses and respects the application-wide array restrictions. +// +// - DispatchByValueType: +// Accepts an explicit TypeList of ValueTypes to consider. +// These dispatchers respect the application-wide array restrictions. +// Example usecase: An image filter that operates on an input array that must +// have either a float or unsigned char ValueType. +// +// - DispatchNByArrayWithSameValueType: +// Multiarray dispatcher that accepts an explicit TypeList of arrays for +// consideration. Generated code paths are further restricted to enforce that +// all dispatched arrays will have the same ValueType. +// Example usecase: A filter that creates and operates on multiple arrays at +// the same time, where the arrays are guaranteed to have the same ValueType. +// Note that these should not be used for operating on filter inputs, instead +// use DispatchNBySameValueType, which also considers variations in +// vtkDataArray subclasses and respects the application-wide array +// restrictions. +// +// - DispatchNBySameValueType: +// Multiarray dispatcher that accepts an explicit TypeList of ValueTypes to +// consider. Generated code paths are further restricted to enforce that +// all dispatched arrays will have the same ValueType. +// Example usecase: A filter that creates a modified version of an input +// array using NewInstance(). Both arrays may be passed into the dispatcher +// using a worker function that produces the output from the input. +// +// Execution: +// There are three components to a dispatch: The dispatcher, the worker, and +// the array(s). They are combined like so: +// +// @code +// bool result = Dispatcher<...>::Execute(array, worker); +// @endcode +// +// The dispatcher can also be instantiated into an object, e.g.: +// +// @code +// vtkArrayDispatch::SomeDispatcher<...> myDispatcher; +// MyWorker worker; +// bool result = myDispatcher.Execute(array, worker); +// @endcode +// +// Return value: +// The Execute method of the dispatcher will return true if a code path matching +// the array arguments is found, or false if the arrays are not supported. If +// false is returned, the arrays will not be modified, and the worker will not +// be executed. +// +// Workers: +// The dispatch requires a Worker functor that performs the work. +// For single array, the functor must be callable with the array object as an +// argument. For 2-array dispatch, the arguments must be (array1, array2). +// For 3-array dispatch, the arguments must be (array1, array2, array3). +// Workers are passed by reference, so stateful functors are permitted if +// additional input/output data is needed. +// +// A simple worker implementation for triple dispatch: +// @code +// struct MyWorker +// { +// template +// void operator()(Array1T *array1, Array2T *array2, Array3T *array3) +// { +// // Do work using vtkGenericDataArray API... +// } +// }; +// @endcode +// +// Note that optimized implementations (e.g. for AoS arrays vs SoA arrays) can +// be supported by providing overloads of operator() that have more restrictive +// template parameters. +// +// Examples: +// See TestArrayDispatchers.cxx for examples of each dispatch type. +// +// .SECTION See Also +// vtkDataArrayAccessor + +#ifndef vtkArrayDispatch_h +#define vtkArrayDispatch_h + +#include "vtkArrayDispatchArrayList.h" +#include "vtkConfigure.h" +#include "vtkType.h" +#include "vtkTypeList.h" + +namespace vtkArrayDispatch { + +// Description: +// A TypeList containing all real ValueTypes. +typedef vtkTypeList_Create_2(double, float) Reals; + +// Description: +// A Typelist containing all integral ValueTypes. +typedef vtkTypeList::Unique< + vtkTypeList_Create_12(char, int, long, long long, short, signed char, + unsigned char, unsigned int, unsigned long, + unsigned long long, unsigned short, vtkIdType) + >::Result Integrals; + +// Description: +// A Typelist containing all standard VTK array ValueTypes. +typedef vtkTypeList::Append::Result AllTypes; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch a single array against all array types in the application-wide +// vtkArrayDispatch::Arrays list. +// The entry point is: +// bool Dispatch::Execute(vtkDataArray *array, Worker &worker). +struct Dispatch; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch a single array against all array types mentioned in the ArrayList +// template parameter. +// The entry point is: +// bool DispatchByArray<...>::Execute(vtkDataArray *array, Worker &worker). +template +struct DispatchByArray; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch a single array against all array types in the application-wide +// vtkArrayDispatch::Arrays list with the added restriction that the array +// must have a type that appears the ValueTypeList TypeList. +// The entry point is: +// bool DispatchByValueType<...>::Execute(vtkDataArray *array, Worker &worker). +template +struct DispatchByValueType; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch two arrays using all array types in the application-wide +// vtkArrayDispatch::Arrays list. +// The entry point is: +// bool Dispatch2::Execute(vtkDataArray *array, vtkDataArray *array2, +// Worker &worker). +struct Dispatch2; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch two arrays, restricting the valid code paths to use only arrays that +// have the same ValueType. +// All application-wide arrays in vtkArrayDispatch::Arrays are used. +// The entry point is: +// bool Dispatch2SameValueType::Execute( +// vtkDataArray *a1, vtkDataArray *a2, Worker &worker). +struct Dispatch2SameValueType; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch two arrays with the restriction that the type of the first array is +// in the ArrayList1 TypeList, and the second is in ArrayList2. +// If all application-wide arrays are desired, use vtkArrayDispatch::Arrays for +// the first two template parameters. +// The entry point is: +// bool Dispatch2ByArray<...>::Execute(vtkDataArray *a1, vtkDataArray *a2, +// Worker &worker). +template < + typename ArrayList1, + typename ArrayList2 + > +struct Dispatch2ByArray; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch two arrays, restricting the valid code paths to use +// ValueType-filtered versions of the application-wide vtkArrayDispatch::Arrays +// TypeList. The first array's ValueType must be in the ValueTypeList1 TypeList, +// and the second's must be in ValueTypeList2. +// If all types are to be considered, use vtkArrayDispatch::AllTypes for the +// first two template parameters. +// The entry point is: +// bool Dispatch2ByValueType<...>::Execute(vtkDataArray *a1, vtkDataArray *a2, +// Worker &worker). +template < + typename ValueTypeList1, + typename ValueTypeList2 + > +struct Dispatch2ByValueType; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch two arrays, restricting the valid code paths to use only array types +// specified in the ArrayList TypeList, additionally enforcing that all arrays +// must have the same ValueType. +// If all application-wide arrays are desired, use vtkArrayDispatch::Arrays for +// the first two template parameters. +// The entry point is: +// bool Dispatch2ByArrayWithSameValueType<...>::Execute( +// vtkDataArray *a1, vtkDataArray *a2, Worker &worker). +template < + typename ArrayList1, + typename ArrayList2 + > +struct Dispatch2ByArrayWithSameValueType; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch two arrays, restricting the valid code paths to use only array types +// found in application-wide vtkArrayDispatch::Arrays TypeList that have a +// ValueType contained in the ValueTypeList TypeList. This dispatcher also +// enforces that all arrays have the same ValueType. +// If all types are to be considered, use vtkArrayDispatch::AllTypes for the +// first two template parameters. +// The entry point is: +// bool Dispatch2BySameValueType<...>::Execute( +// vtkDataArray *a1, vtkDataArray *a2, Worker &worker). +template +struct Dispatch2BySameValueType; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch three arrays using all array types in the application-wide +// vtkArrayDispatch::Arrays list. +// The entry point is: +// bool Dispatch3::Execute(vtkDataArray *array1, vtkDataArray *array2, +// vtkDataArray *array3, Worker &worker). +struct Dispatch3; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch three arrays, restricting the valid code paths to use only arrays +// that have the same ValueType. +// All application-wide arrays in vtkArrayDispatch::Arrays are used. +// The entry point is: +// bool Dispatch3SameValueType::Execute( +// vtkDataArray *a1, vtkDataArray *a2, vtkDataArray *a3, Worker &worker). +struct Dispatch3SameValueType; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch three arrays with the restriction that the type of the first array +// is in the ArrayList1 TypeList, the second is in ArrayList2, and the third +// is in ArrayList3. +// If all application-wide arrays are desired, use vtkArrayDispatch::Arrays for +// the first three template parameters. +// The entry point is: +// bool Dispatch3ByArray::Execute<...>(vtkDataArray *a1, vtkDataArray *a2, +// vtkDataArray *a3, Worker &worker). +template < + typename ArrayList1, + typename ArrayList2, + typename ArrayList3 + > +struct Dispatch3ByArray; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch three arrays, restricting the valid code paths to use +// ValueType-filtered versions of the application-wide vtkArrayDispatch::Arrays +// TypeList. The first array's ValueType must be in the ValueTypeList1 TypeList, +// the second's must be in ValueTypeList2, and the third's must be in +// ValueTypeList3. +// If all types are to be considered, use vtkArrayDispatch::AllTypes for the +// first three template parameters. +// The entry point is: +// bool Dispatch3ByValueType<...>::Execute(vtkDataArray *a1, vtkDataArray *a2, +// vtkDataArray *a3, Worker &worker). +template < + typename ValueTypeList1, + typename ValueTypeList2, + typename ValueTypeList3 + > +struct Dispatch3ByValueType; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch three arrays, restricting the valid code paths to use only array +// types specified in the ArrayList TypeList, additionally enforcing that all +// arrays must have the same ValueType. +// If all application-wide arrays are desired, use vtkArrayDispatch::Arrays for +// the first three template parameters. +// The entry point is: +// bool Dispatch3ByArrayWithSameValueType<...>::Execute( +// vtkDataArray *a1, vtkDataArray *a2, vtkDataArray *a3, Worker &worker). +template < + typename ArrayList1, + typename ArrayList2, + typename ArrayList3 + > +struct Dispatch3ByArrayWithSameValueType; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch three arrays, restricting the valid code paths to use only array +// types found in application-wide vtkArrayDispatch::Arrays TypeList that have a +// ValueType contained in the ValueTypeList TypeList. This dispatcher also +// enforces that all arrays have the same ValueType. +// If all types are to be considered, use vtkArrayDispatch::AllTypes for the +// first three template parameters. +// The entry point is: +// bool Dispatch3BySameValueType<...>::Execute( +// vtkDataArray *a1, vtkDataArray *a2, vtkDataArray *a3, Worker &worker). +template +struct Dispatch3BySameValueType; + +//------------------------------------------------------------------------------ +// Description: +// Filter the ArrayList to contain only arrays with ArrayType::ValueType that +// exist in ValueList. The result TypeList is stored in Result. +template +struct FilterArraysByValueType; + +} // end namespace vtkArrayDispatch + +#include "vtkArrayDispatch.txx" + +#endif // vtkArrayDispatch_h +// VTK-HeaderTest-Exclude: vtkArrayDispatch.h diff --git a/Common/Core/vtkArrayDispatch.txx b/Common/Core/vtkArrayDispatch.txx new file mode 100644 index 00000000000..7d31a983b37 --- /dev/null +++ b/Common/Core/vtkArrayDispatch.txx @@ -0,0 +1,839 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkArrayDispatch.txx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#ifndef vtkArrayDispatch_txx +#define vtkArrayDispatch_txx + +#include "vtkArrayDispatch.h" + +#include "vtkConfigure.h" // For warning macro settings. +#include "vtkSetGet.h" // For warning macros. + +class vtkDataArray; + +namespace vtkArrayDispatch { +namespace impl { + +//------------------------------------------------------------------------------ +// Implementation of the single-array dispatch mechanism. +template +struct Dispatch; + +// Terminal case: +template<> +struct Dispatch +{ + template + static bool Execute(vtkDataArray *, Worker&) + { +#ifdef VTK_WARN_ON_DISPATCH_FAILURE + vtkGenericWarningMacro("Array dispatch failed."); +#endif + return false; + } +}; + +// Recursive case: +template < + typename ArrayHead, + typename ArrayTail + > +struct Dispatch > +{ + template + static bool Execute(vtkDataArray *inArray, Worker &worker) + { + if (ArrayHead *array = vtkArrayDownCast(inArray)) + { + worker(array); + return true; + } + else + { + return Dispatch::Execute(inArray, worker); + } + } +}; + +//------------------------------------------------------------------------------ +// Description: +// Implementation of the 2 array dispatch mechanism. +template < + typename ArrayList1, + typename ArrayList2 + > +struct Dispatch2; + +//----------------------------// +// First dispatch trampoline: // +//----------------------------// +template < + typename Array1T, + typename ArrayList2 + > +struct Dispatch2Trampoline; + +// Dispatch2 Terminal case: +template +struct Dispatch2 +{ + template + static bool Execute(vtkDataArray *, vtkDataArray *, Worker &) + { +#ifdef VTK_WARN_ON_DISPATCH_FAILURE + vtkGenericWarningMacro("Dual array dispatch failed."); +#endif + return false; + } +}; + +// Dispatch2 Recursive case: +template < + typename Array1Head, + typename Array1Tail, + typename ArrayList2 + > +struct Dispatch2, ArrayList2> +{ + typedef Dispatch2 NextDispatch; + typedef Dispatch2Trampoline Trampoline; + + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + Worker &worker) + { + if (Array1Head *array = vtkArrayDownCast(array1)) + { + return Trampoline::Execute(array, array2, worker); + } + else + { + return NextDispatch::Execute(array1, array2, worker); + } + } +}; + +// Dispatch2 Trampoline terminal case: +template +struct Dispatch2Trampoline +{ + template + static bool Execute(Array1T *, vtkDataArray *, Worker &) + { +#ifdef VTK_WARN_ON_DISPATCH_FAILURE + vtkGenericWarningMacro("Dual array dispatch failed."); +#endif + return false; + } +}; + +// Dispatch2 Trampoline recursive case: +template < + typename Array1T, + typename Array2Head, + typename Array2Tail + > +struct Dispatch2Trampoline< + Array1T, + vtkTypeList::TypeList + > +{ + typedef Dispatch2Trampoline NextDispatch; + + template + static bool Execute(Array1T *array1, vtkDataArray *array2, Worker &worker) + { + if (Array2Head *array = vtkArrayDownCast(array2)) + { + worker(array1, array); + return true; + } + else + { + return NextDispatch::Execute(array1, array2, worker); + } + } +}; + +//------------------------------------------------------------------------------ +// Description: +// Implementation of the 2 array same-type dispatch mechanism. +template < + typename ArrayList1, + typename ArrayList2 + > +struct Dispatch2Same; + +// Terminal case: +template +struct Dispatch2Same +{ + template + static bool Execute(vtkDataArray *, vtkDataArray *, Worker &) + { +#ifdef VTK_WARN_ON_DISPATCH_FAILURE + vtkGenericWarningMacro("Dual array dispatch failed."); +#endif + return false; + } +}; + +// Recursive case: +template < + typename ArrayHead, + typename ArrayTail, + typename ArrayList2 + > +struct Dispatch2Same< + vtkTypeList::TypeList, + ArrayList2 + > +{ + typedef Dispatch2Same NextDispatch; + typedef vtkTypeList_Create_1(typename ArrayHead::ValueType) ValueType; + typedef typename FilterArraysByValueType::Result ValueArrayList; + typedef Dispatch2Trampoline Trampoline; + + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + Worker &worker) + { + if (ArrayHead *array = vtkArrayDownCast(array1)) + { + return Trampoline::Execute(array, array2, worker); + } + else + { + return NextDispatch::Execute(array1, array2, worker); + } + } +}; + +//------------------------------------------------------------------------------ +// Description: +// Implementation of the 3 array dispatch mechanism. +template < + typename ArrayList1, + typename ArrayList2, + typename ArrayList3 + > +struct Dispatch3; + +//-----------------------------// +// First dispatch trampoline: // +//---------------------------// +template < + typename Array1T, + typename ArrayList2, + typename ArrayList3 + > +struct Dispatch3Trampoline1; + +//------------------------------// +// Second dispatch trampoline: // +//----------------------------// +template < + typename Array1T, + typename Array2T, + typename ArrayList3 + > +struct Dispatch3Trampoline2; + +// Dispatch3 Terminal case: +template < + typename ArrayList2, + typename ArrayList3 + > +struct Dispatch3 +{ + template + static bool Execute(vtkDataArray *, vtkDataArray*, vtkDataArray*, Worker&) + { +#ifdef VTK_WARN_ON_DISPATCH_FAILURE + vtkGenericWarningMacro("Triple array dispatch failed."); +#endif + return false; + } +}; + +// Dispatch3 Recursive case: +template < + typename ArrayHead, + typename ArrayTail, + typename ArrayList2, + typename ArrayList3 + > +struct Dispatch3, ArrayList2, + ArrayList3> +{ +private: + typedef Dispatch3Trampoline1 Trampoline; + typedef Dispatch3 NextDispatch; +public: + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + vtkDataArray *array3, Worker &worker) + { + if (ArrayHead *array = vtkArrayDownCast(array1)) + { + return Trampoline::Execute(array, array2, array3, worker); + } + else + { + return NextDispatch::Execute(array1, array2, array3, worker); + } + } +}; + +// Dispatch3 Trampoline1 terminal case: +template < + typename Array1T, + typename ArrayList3 + > +struct Dispatch3Trampoline1 +{ + template + static bool Execute(Array1T*, vtkDataArray*, vtkDataArray*, Worker&) + { +#ifdef VTK_WARN_ON_DISPATCH_FAILURE + vtkGenericWarningMacro("Triple array dispatch failed."); +#endif + return false; + } +}; + +// Dispatch3 Trampoline1 recursive case: +template < + typename Array1T, + typename ArrayHead, + typename ArrayTail, + typename ArrayList3 + > +struct Dispatch3Trampoline1, + ArrayList3> +{ +private: + typedef Dispatch3Trampoline2 Trampoline; + typedef Dispatch3Trampoline1 NextDispatch; +public: + template + static bool Execute(Array1T *array1, vtkDataArray *array2, + vtkDataArray *array3, Worker &worker) + { + if (ArrayHead *array = vtkArrayDownCast(array2)) + { + return Trampoline::Execute(array1, array, array3, worker); + } + else + { + return NextDispatch::Execute(array1, array2, array3, worker); + } + } +}; + + +// Dispatch3 Trampoline2 terminal case: +template < + typename Array1T, + typename Array2T + > +struct Dispatch3Trampoline2 +{ + template + static bool Execute(Array1T*, Array2T*, vtkDataArray*, Worker&) + { +#ifdef VTK_WARN_ON_DISPATCH_FAILURE + vtkGenericWarningMacro("Triple array dispatch failed."); +#endif + return false; + } +}; + +// Dispatch3 Trampoline2 recursive case: +template < + typename Array1T, + typename Array2T, + typename ArrayHead, + typename ArrayTail + > +struct Dispatch3Trampoline2 > +{ +private: + typedef Dispatch3Trampoline2 NextDispatch; +public: + template + static bool Execute(Array1T *array1, Array2T *array2, + vtkDataArray *array3, Worker &worker) + { + if (ArrayHead *array = vtkArrayDownCast(array3)) + { + worker(array1, array2, array); + return true; + } + else + { + return NextDispatch::Execute(array1, array2, array3, worker); + } + } +}; + +//------------------------------------------------------------------------------ +// Description: +// Dispatch three arrays, enforcing that all three have the same ValueType. +// Initially, set both ArraysToTest and ArrayList to the same TypeList. +// ArraysToTest is iterated through, while ArrayList is preserved for later +// dispatches. +template < + typename ArrayList1, + typename ArrayList2, + typename ArrayList3 + > +struct Dispatch3Same; + +// Dispatch3Same terminal case: +template +struct Dispatch3Same +{ + template + static bool Execute(vtkDataArray*, vtkDataArray*, + vtkDataArray*, Worker&) + { +#ifdef VTK_WARN_ON_DISPATCH_FAILURE + vtkGenericWarningMacro("Triple array dispatch failed."); +#endif + return false; + } +}; + +// Dispatch3Same recursive case: +template < + typename ArrayHead, + typename ArrayTail, + typename ArrayList2, + typename ArrayList3 + > +struct Dispatch3Same< + vtkTypeList::TypeList, + ArrayList2, + ArrayList3 + > +{ +private: + typedef vtkTypeList_Create_1(typename ArrayHead::ValueType) ValueType; + typedef typename FilterArraysByValueType::Result ValueArrays2; + typedef typename FilterArraysByValueType::Result ValueArrays3; + typedef Dispatch3Trampoline1 Trampoline; + typedef Dispatch3Same NextDispatch; +public: + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + vtkDataArray *array3, Worker &worker) + { + if (ArrayHead *array = vtkArrayDownCast(array1)) + { + return Trampoline::Execute(array, array2, array3, worker); + } + else + { + return NextDispatch::Execute(array1, array2, array3, worker); + } + } +}; + +} // end namespace impl + +//------------------------------------------------------------------------------ +// FilterArraysByValueType implementation: +//------------------------------------------------------------------------------ + +// Terminal case: +template +struct FilterArraysByValueType +{ + typedef vtkTypeList::NullType Result; +}; + +// Recursive case: +template +struct FilterArraysByValueType, + ValueList> +{ +private: + typedef typename ArrayHead::ValueType ValueType; + enum { ValueIsAllowed = + vtkTypeList::IndexOf::Result >= 0 }; + typedef typename FilterArraysByValueType::Result NewTail; +public: + typedef typename vtkTypeList::Select, + NewTail>::Result Result; +}; + +//------------------------------------------------------------------------------ +// DispatchByArray implementation: +//------------------------------------------------------------------------------ +// Preprocess and pass off to impl::Dispatch: +template < + typename ArrayHead, + typename ArrayTail + > +struct DispatchByArray > +{ +private: + typedef vtkTypeList::TypeList ArrayList; + typedef typename vtkTypeList::Unique::Result UniqueArrays; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArrays; + typedef impl::Dispatch ArrayDispatcher; +public: + DispatchByArray() {} + template + static bool Execute(vtkDataArray *inArray, Worker &worker) + { + return ArrayDispatcher::Execute(inArray, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch implementation: +// (defined after DispatchByArray to prevent 'incomplete type' errors) +//------------------------------------------------------------------------------ +struct Dispatch +{ +private: + typedef DispatchByArray Dispatcher; +public: + Dispatch() {} + template + static bool Execute(vtkDataArray *array, Worker &worker) + { + return Dispatcher::Execute(array, worker); + } +}; + +//------------------------------------------------------------------------------ +// DispatchByValueType implementation: +//------------------------------------------------------------------------------ +// Preprocess and pass off to impl::Dispatch +template < + typename ValueTypeHead, + typename ValueTypeTail + > +struct DispatchByValueType > +{ +private: + typedef vtkTypeList::TypeList ValueTypeList; + typedef typename FilterArraysByValueType::Result ArrayList; + typedef typename vtkTypeList::Unique::Result UniqueArrays; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArrays; + typedef impl::Dispatch ArrayDispatcher; +public: + DispatchByValueType() {} + template + static bool Execute(vtkDataArray *inArray, Worker &worker) + { + return ArrayDispatcher::Execute(inArray, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch2ByArray implementation: +//------------------------------------------------------------------------------ +// Preprocess and pass off to impl::Dispatch2: +template < + typename ArrayList1, + typename ArrayList2 + > +struct Dispatch2ByArray +{ +private: + typedef typename vtkTypeList::Unique::Result UniqueArray1; + typedef typename vtkTypeList::Unique::Result UniqueArray2; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray1; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray2; + typedef impl::Dispatch2 ArrayDispatcher; +public: + Dispatch2ByArray() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + Worker &worker) + { + return ArrayDispatcher::Execute(array1, array2, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch2 implementation: +//------------------------------------------------------------------------------ +struct Dispatch2 +{ +private: + typedef Dispatch2ByArray Dispatcher; +public: + Dispatch2() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + Worker &worker) + { + return Dispatcher::Execute(array1, array2, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch2ByValueType implementation: +//------------------------------------------------------------------------------ +// Preprocess and pass off to impl::Dispatch2 +template < + typename ValueTypeList1, + typename ValueTypeList2 + > +struct Dispatch2ByValueType +{ +private: + typedef typename FilterArraysByValueType::Result ArrayList1; + typedef typename FilterArraysByValueType::Result ArrayList2; + typedef typename vtkTypeList::Unique::Result UniqueArray1; + typedef typename vtkTypeList::Unique::Result UniqueArray2; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray1; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray2; + typedef impl::Dispatch2 ArrayDispatcher; +public: + Dispatch2ByValueType() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, Worker &worker) + { + return ArrayDispatcher::Execute(array1, array2, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch2BySameValueType implementation: +//------------------------------------------------------------------------------ +// Preprocess and pass off to impl::Dispatch2Same +template +struct Dispatch2BySameValueType +{ +private: + typedef typename FilterArraysByValueType::Result ArrayList; + typedef typename vtkTypeList::Unique::Result UniqueArray; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray; + typedef impl::Dispatch2Same Dispatcher; +public: + Dispatch2BySameValueType() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + Worker &worker) + { + return Dispatcher::Execute(array1, array2, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch2ByArrayWithSameValueType implementation: +//------------------------------------------------------------------------------ +// Preprocess and pass off to impl::Dispatch2Same +template < + typename ArrayList1, + typename ArrayList2 + > +struct Dispatch2ByArrayWithSameValueType +{ +private: + typedef typename vtkTypeList::Unique::Result UniqueArray1; + typedef typename vtkTypeList::Unique::Result UniqueArray2; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray1; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray2; + typedef impl::Dispatch2Same Dispatcher; +public: + Dispatch2ByArrayWithSameValueType() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + Worker &worker) + { + return Dispatcher::Execute(array1, array2, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch2SameValueType implementation: +//------------------------------------------------------------------------------ +struct Dispatch2SameValueType +{ +private: + typedef Dispatch2ByArrayWithSameValueType Dispatcher; +public: + Dispatch2SameValueType() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + Worker &worker) + { + return Dispatcher::Execute(array1, array2, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch3ByArray implementation: +//------------------------------------------------------------------------------ +// Preprocess and pass off to impl::Dispatch3: +template < + typename ArrayList1, + typename ArrayList2, + typename ArrayList3 + > +struct Dispatch3ByArray +{ +private: + typedef typename vtkTypeList::Unique::Result UniqueArray1; + typedef typename vtkTypeList::Unique::Result UniqueArray2; + typedef typename vtkTypeList::Unique::Result UniqueArray3; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray1; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray2; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray3; + typedef impl::Dispatch3 ArrayDispatcher; +public: + Dispatch3ByArray() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + vtkDataArray *array3, Worker &worker) + { + return ArrayDispatcher::Execute(array1, array2, array3, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch3 implementation: +//------------------------------------------------------------------------------ +struct Dispatch3 +{ +private: + typedef Dispatch3ByArray Dispatcher; +public: + Dispatch3() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + vtkDataArray *array3, Worker &worker) + { + return Dispatcher::Execute(array1, array2, array3, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch3ByValueType implementation: +//------------------------------------------------------------------------------ +// Preprocess and pass off to impl::Dispatch3 +template < + typename ValueTypeList1, + typename ValueTypeList2, + typename ValueTypeList3 + > +struct Dispatch3ByValueType +{ +private: + typedef typename FilterArraysByValueType::Result ArrayList1; + typedef typename FilterArraysByValueType::Result ArrayList2; + typedef typename FilterArraysByValueType::Result ArrayList3; + typedef typename vtkTypeList::Unique::Result UniqueArray1; + typedef typename vtkTypeList::Unique::Result UniqueArray2; + typedef typename vtkTypeList::Unique::Result UniqueArray3; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray1; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray2; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray3; + typedef impl::Dispatch3 ArrayDispatcher; +public: + Dispatch3ByValueType() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + vtkDataArray *array3, Worker &worker) + { + return ArrayDispatcher::Execute(array1, array2, array3, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch3BySameValueType implementation: +//------------------------------------------------------------------------------ +// Preprocess and pass off to impl::Dispatch3Same +template +struct Dispatch3BySameValueType +{ +private: + typedef typename FilterArraysByValueType::Result ArrayList; + typedef typename vtkTypeList::Unique::Result UniqueArray; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray; + typedef impl::Dispatch3Same Dispatcher; +public: + Dispatch3BySameValueType() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + vtkDataArray *array3, Worker &worker) + { + return Dispatcher::Execute(array1, array2, array3, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch3BySameValueType implementation: +//------------------------------------------------------------------------------ +// Preprocess and pass off to impl::Dispatch3Same +template < + typename ArrayList1, + typename ArrayList2, + typename ArrayList3 + > +struct Dispatch3ByArrayWithSameValueType +{ +private: + typedef typename vtkTypeList::Unique::Result UniqueArray1; + typedef typename vtkTypeList::Unique::Result UniqueArray2; + typedef typename vtkTypeList::Unique::Result UniqueArray3; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray1; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray2; + typedef typename vtkTypeList::DerivedToFront::Result SortedUniqueArray3; + typedef impl::Dispatch3Same Dispatcher; +public: + Dispatch3ByArrayWithSameValueType() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + vtkDataArray *array3, Worker &worker) + { + return Dispatcher::Execute(array1, array2, array3, worker); + } +}; + +//------------------------------------------------------------------------------ +// Dispatch3SameValueType implementation: +//------------------------------------------------------------------------------ +struct Dispatch3SameValueType +{ +private: + typedef Dispatch3ByArrayWithSameValueType Dispatcher; +public: + Dispatch3SameValueType() {} + template + static bool Execute(vtkDataArray *array1, vtkDataArray *array2, + vtkDataArray *array3, Worker &worker) + { + return Dispatcher::Execute(array1, array2, array3, worker); + } +}; + +} // end namespace vtkArrayDispatch + +#endif // vtkArrayDispatch_txx diff --git a/Common/Core/vtkArrayDispatchArrayList.h.in b/Common/Core/vtkArrayDispatchArrayList.h.in new file mode 100644 index 00000000000..7c2fb0172ba --- /dev/null +++ b/Common/Core/vtkArrayDispatchArrayList.h.in @@ -0,0 +1 @@ +${VTK_ARRAYDISPATCH_ARRAY_LIST} diff --git a/Common/Core/vtkArrayExtents.h b/Common/Core/vtkArrayExtents.h index 403eab34a2f..a4914e19320 100644 --- a/Common/Core/vtkArrayExtents.h +++ b/Common/Core/vtkArrayExtents.h @@ -202,9 +202,9 @@ class VTKCOMMONCORE_EXPORT vtkArrayExtents ostream& stream, const vtkArrayExtents& rhs); private: - //BTX + std::vector Storage; - //ETX + }; #endif diff --git a/Common/Core/vtkArrayExtentsList.h b/Common/Core/vtkArrayExtentsList.h index 582fe529b78..92fe885a3c1 100644 --- a/Common/Core/vtkArrayExtentsList.h +++ b/Common/Core/vtkArrayExtentsList.h @@ -88,9 +88,9 @@ class VTKCOMMONCORE_EXPORT vtkArrayExtentsList const vtkArrayExtents& operator[](vtkIdType i) const; private: - //BTX + std::vector Storage; - //ETX + }; #endif diff --git a/Common/Core/vtkArrayIteratorTemplate.h b/Common/Core/vtkArrayIteratorTemplate.h index 839b734401a..800ae3b227d 100644 --- a/Common/Core/vtkArrayIteratorTemplate.h +++ b/Common/Core/vtkArrayIteratorTemplate.h @@ -24,21 +24,14 @@ #define vtkArrayIteratorTemplate_h #include "vtkCommonCoreModule.h" // For export macro -#include "vtkTypeTemplate.h" // For templated vtkObject API #include "vtkArrayIterator.h" template -class VTKCOMMONCORE_EXPORT vtkArrayIteratorTemplate : - public vtkTypeTemplate, vtkArrayIterator> +class VTKCOMMONCORE_EXPORT vtkArrayIteratorTemplate : public vtkArrayIterator { public: static vtkArrayIteratorTemplate* New(); - typedef vtkArrayIterator Superclass; -private: - virtual const char* GetClassNameInternal() const - { return "vtkArrayIteratorTemplate"; } - -public: + vtkTemplateTypeMacro(vtkArrayIteratorTemplate, vtkArrayIterator) void PrintSelf(ostream& os, vtkIndent indent); // Description: diff --git a/Common/Core/vtkArrayIteratorTemplate.txx b/Common/Core/vtkArrayIteratorTemplate.txx index 2a77c59326c..469e485e581 100644 --- a/Common/Core/vtkArrayIteratorTemplate.txx +++ b/Common/Core/vtkArrayIteratorTemplate.txx @@ -20,19 +20,16 @@ #include "vtkAbstractArray.h" #include "vtkObjectFactory.h" +//----------------------------------------------------------------------------- template vtkArrayIteratorTemplate* vtkArrayIteratorTemplate::New() { - vtkObject* ret = vtkObjectFactory::CreateInstance("vtkArrayIteratorTemplate"); - if (ret) - { - return static_cast*> (ret); - } - return new vtkArrayIteratorTemplate; + VTK_STANDARD_NEW_BODY(vtkArrayIteratorTemplate); } template vtkCxxSetObjectMacro(vtkArrayIteratorTemplate, Array, vtkAbstractArray); + //----------------------------------------------------------------------------- template vtkArrayIteratorTemplate::vtkArrayIteratorTemplate() diff --git a/Common/Core/vtkArraySort.h b/Common/Core/vtkArraySort.h index b2f7b6ac94f..201003c9333 100644 --- a/Common/Core/vtkArraySort.h +++ b/Common/Core/vtkArraySort.h @@ -100,9 +100,9 @@ class VTKCOMMONCORE_EXPORT vtkArraySort ostream& stream, const vtkArraySort& rhs); private: - //BTX + std::vector Storage; - //ETX + }; #endif diff --git a/Common/Core/vtkAssume.h b/Common/Core/vtkAssume.h new file mode 100644 index 00000000000..c68857f8e49 --- /dev/null +++ b/Common/Core/vtkAssume.h @@ -0,0 +1,59 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkAssume.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME VTK_ASSUME - Provide compiler hints for non-obvious conditions. + +#ifndef vtkAssume_h +#define vtkAssume_h + +#include "vtkConfigure.h" + +#include + +// Description: +// VTK_ASSUME instructs the compiler that a certain non-obvious condition will +// *always* be true. Beware that if cond is false at runtime, the results are +// unpredictable (and likely catastrophic). A runtime assertion is added so +// that debugging builds may easily catch violations of the condition. +// +// A useful application of this macro is when a vtkGenericDataArray subclass has +// a known number of components at compile time. Adding, for example, +// VTK_ASSUME(array->GetNumberOfComponents() == 3); allows the compiler to +// provide faster access through the GetTypedComponent method, as the fixed data +// stride in AOS arrays allows advanced optimization of the accesses. +// +// A more detailed description of this class and related tools can be found +// \ref VTK-7-1-ArrayDispatch "here". +#define VTK_ASSUME(cond) \ + do { \ + const bool c = cond; \ + assert("Bad assumption in VTK_ASSUME: " #cond && c); \ + VTK_ASSUME_IMPL(c); \ + (void)c; /* Prevents unused var warnings */ \ + } while (false) /* do-while prevents extra semicolon warnings */ + +// VTK_ASSUME_IMPL is compiler-specific: +#if defined(VTK_COMPILER_MSVC) || defined(VTK_COMPILER_ICC) +# define VTK_ASSUME_IMPL(cond) __assume(cond) +#elif defined(VTK_COMPILER_GCC) && VTK_COMPILER_GCC_VERSION >= 40500 +// Added in 4.5.0: +# define VTK_ASSUME_IMPL(cond) if (!(cond)) __builtin_unreachable() +#elif defined(VTK_COMPILER_CLANG) +# define VTK_ASSUME_IMPL(cond) if (!(cond)) __builtin_unreachable() +#else +# define VTK_ASSUME_IMPL(cond) do {} while (false) /* no-op */ +#endif + +#endif // vtkAssume_h +// VTK-HeaderTest-Exclude: vtkAssume.h diff --git a/Common/Core/vtkBitArray.cxx b/Common/Core/vtkBitArray.cxx index 2dd4b6c09fe..1097cb0c0eb 100644 --- a/Common/Core/vtkBitArray.cxx +++ b/Common/Core/vtkBitArray.cxx @@ -341,7 +341,7 @@ void vtkBitArray::SetNumberOfTuples(vtkIdType number) // performed; use in conjunction with SetNumberOfTuples() to allocate space. void vtkBitArray::SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) { - vtkBitArray* ba = vtkBitArray::SafeDownCast(source); + vtkBitArray* ba = vtkArrayDownCast(source); if (!ba) { vtkWarningMacro("Input and output arrays types do not match."); @@ -364,7 +364,7 @@ void vtkBitArray::SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) // Note that memory allocation is performed as necessary to hold the data. void vtkBitArray::InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) { - vtkBitArray* ba = vtkBitArray::SafeDownCast(source); + vtkBitArray* ba = vtkArrayDownCast(source); if (!ba) { vtkWarningMacro("Input and output arrays types do not match."); @@ -384,7 +384,7 @@ void vtkBitArray::InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source void vtkBitArray::InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, vtkAbstractArray *source) { - vtkBitArray* ba = vtkBitArray::SafeDownCast(source); + vtkBitArray* ba = vtkArrayDownCast(source); if (!ba) { vtkWarningMacro("Input and output arrays types do not match."); @@ -421,7 +421,7 @@ void vtkBitArray::InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, void vtkBitArray::InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, vtkAbstractArray *source) { - vtkBitArray* sa = vtkBitArray::SafeDownCast(source); + vtkBitArray* sa = vtkArrayDownCast(source); if (!sa) { vtkWarningMacro("Input and outputs array data types do not match."); @@ -464,7 +464,7 @@ void vtkBitArray::InsertTuples(vtkIdType dstStart, vtkIdType n, // Returns the location at which the data was inserted. vtkIdType vtkBitArray::InsertNextTuple(vtkIdType j, vtkAbstractArray* source) { - vtkBitArray* ba = vtkBitArray::SafeDownCast(source); + vtkBitArray* ba = vtkArrayDownCast(source); if (!ba) { vtkWarningMacro("Input and output arrays types do not match."); diff --git a/Common/Core/vtkBitArray.h b/Common/Core/vtkBitArray.h index bedaae2dd5f..d4911585a73 100644 --- a/Common/Core/vtkBitArray.h +++ b/Common/Core/vtkBitArray.h @@ -197,7 +197,7 @@ class VTKCOMMONCORE_EXPORT vtkBitArray : public vtkDataArray // The class uses the actual array provided; it does not copy the data // from the supplied array. If save 0, the array must have been allocated // with new[] not malloc. -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ void SetArray(unsigned char* array, vtkIdType size, int save); #endif void SetVoidArray(void *array, vtkIdType size, int save) @@ -212,7 +212,7 @@ class VTKCOMMONCORE_EXPORT vtkBitArray : public vtkDataArray // Description: // Returns a new vtkBitArrayIterator instance. - vtkArrayIterator* NewIterator(); + VTK_NEWINSTANCE vtkArrayIterator* NewIterator(); // Description: // Return the indices where a specific value appears. @@ -257,10 +257,9 @@ class VTKCOMMONCORE_EXPORT vtkBitArray : public vtkDataArray vtkBitArray(const vtkBitArray&); // Not implemented. void operator=(const vtkBitArray&); // Not implemented. - //BTX vtkBitArrayLookup* Lookup; void UpdateLookup(); - //ETX + }; inline void vtkBitArray::SetNumberOfValues(vtkIdType number) diff --git a/Common/Core/vtkBitArrayIterator.cxx b/Common/Core/vtkBitArrayIterator.cxx index 0b29bd43e2f..946f86c8075 100644 --- a/Common/Core/vtkBitArrayIterator.cxx +++ b/Common/Core/vtkBitArrayIterator.cxx @@ -37,7 +37,7 @@ vtkBitArrayIterator::~vtkBitArrayIterator() //----------------------------------------------------------------------------- void vtkBitArrayIterator::Initialize(vtkAbstractArray* a) { - vtkBitArray* b = vtkBitArray::SafeDownCast(a); + vtkBitArray* b = vtkArrayDownCast(a); if (!b && a) { vtkErrorMacro("vtkBitArrayIterator can iterate only over vtkBitArray."); diff --git a/Common/Core/vtkBitArrayIterator.h b/Common/Core/vtkBitArrayIterator.h index 494b02eacb9..85cfcfd2e5a 100644 --- a/Common/Core/vtkBitArrayIterator.h +++ b/Common/Core/vtkBitArrayIterator.h @@ -75,11 +75,10 @@ class VTKCOMMONCORE_EXPORT vtkBitArrayIterator : public vtkArrayIterator // The caller must ensure that id is less than the maximum number of values. void SetValue(vtkIdType id, int value); - //BTX // Description: // Data type of a value. typedef int ValueType; - //ETX + protected: vtkBitArrayIterator(); ~vtkBitArrayIterator(); diff --git a/Common/Core/vtkBuffer.h b/Common/Core/vtkBuffer.h new file mode 100644 index 00000000000..90a2f8a7109 --- /dev/null +++ b/Common/Core/vtkBuffer.h @@ -0,0 +1,182 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkBuffer.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkBuffer - internal storage class used by vtkSOADataArrayTemplate, +// vtkAOSDataArrayTemplate, and others. +// .SECTION Description +// vtkBuffer makes it easier to keep data pointers in vtkDataArray subclasses. +// This is an internal class and not intended for direct use expect when writing +// new types of vtkDataArray subclasses. + +#ifndef vtkBuffer_h +#define vtkBuffer_h + +#include "vtkObject.h" +#include "vtkObjectFactory.h" // New() implementation + +template +class vtkBuffer : public vtkObject +{ +public: + vtkTypeMacro(vtkBuffer, vtkObject) + typedef ScalarTypeT ScalarType; + enum + { + VTK_DATA_ARRAY_FREE, + VTK_DATA_ARRAY_DELETE + }; + + static vtkBuffer* New(); + + // Description: + // Access the buffer as a scalar pointer. + inline ScalarType* GetBuffer() { return this->Pointer; } + inline const ScalarType* GetBuffer() const { return this->Pointer; } + + // Description: + // Set the memory buffer that this vtkBuffer object will manage. @a array + // is a pointer to the buffer data and @a size is the size of the bufffer (in + // number of elements). If @a save is true, the buffer will not be freed when + // this vtkBuffer object is deleted or resize -- otherwise, @a deleteMethod + // specifies how the buffer will be freed. + void SetBuffer(ScalarType* array, vtkIdType size, bool save=false, + int deleteMethod=VTK_DATA_ARRAY_FREE); + + // Description: + // Return the number of elements the current buffer can hold. + inline vtkIdType GetSize() const { return this->Size; } + + // Description: + // Allocate a new buffer that holds @a size elements. Old data is not saved. + bool Allocate(vtkIdType size); + + // Description: + // Allocate a new buffer that holds @a newsize elements. Old data is + // preserved. + bool Reallocate(vtkIdType newsize); + +protected: + vtkBuffer() + : Pointer(NULL), + Size(0), + Save(false), + DeleteMethod(VTK_DATA_ARRAY_FREE) + { + } + + ~vtkBuffer() + { + this->SetBuffer(NULL, 0); + } + + ScalarType *Pointer; + vtkIdType Size; + bool Save; + int DeleteMethod; + +private: + vtkBuffer(const vtkBuffer&); // Not implemented. + void operator=(const vtkBuffer&); // Not implemented. +}; + +template +inline vtkBuffer *vtkBuffer::New() +{ + VTK_STANDARD_NEW_BODY(vtkBuffer) +} + +//------------------------------------------------------------------------------ +template +void vtkBuffer::SetBuffer( + typename vtkBuffer::ScalarType *array, + vtkIdType size, bool save, int deleteMethod) +{ + if (this->Pointer != array) + { + if (!this->Save) + { + if (this->DeleteMethod == VTK_DATA_ARRAY_FREE) + { + free(this->Pointer); + } + else + { + delete [] this->Pointer; + } + } + this->Pointer = array; + } + this->Size = size; + this->Save = save; + this->DeleteMethod = deleteMethod; +} + +//------------------------------------------------------------------------------ +template +bool vtkBuffer::Allocate(vtkIdType size) +{ + // release old memory. + this->SetBuffer(NULL, 0); + if (size > 0) + { + ScalarType* newArray = + static_cast(malloc(size * sizeof(ScalarType))); + if (newArray) + { + this->SetBuffer(newArray, size, false, VTK_DATA_ARRAY_FREE); + return true; + } + return false; + } + return true; // size == 0 +} + +//------------------------------------------------------------------------------ +template +bool vtkBuffer::Reallocate(vtkIdType newsize) +{ + if (newsize == 0) { return this->Allocate(0); } + + if (this->Pointer && + (this->Save || this->DeleteMethod == VTK_DATA_ARRAY_DELETE)) + { + ScalarType* newArray = + static_cast(malloc(newsize * sizeof(ScalarType))); + if (!newArray) + { + return false; + } + std::copy(this->Pointer, this->Pointer + std::min(this->Size, newsize), + newArray); + // now save the new array and release the old one too. + this->SetBuffer(newArray, newsize, false, VTK_DATA_ARRAY_FREE); + } + else + { + // Try to reallocate with minimal memory usage and possibly avoid + // copying. + ScalarType* newArray = static_cast( + realloc(this->Pointer, newsize * sizeof(ScalarType))); + if (!newArray) + { + return false; + } + this->Pointer = newArray; + this->Size = newsize; + } + return true; +} + +#endif +// VTK-HeaderTest-Exclude: vtkBuffer.h diff --git a/Common/Core/vtkByteSwap.h b/Common/Core/vtkByteSwap.h index 2a3ad595bf9..d171dc1c63b 100644 --- a/Common/Core/vtkByteSwap.h +++ b/Common/Core/vtkByteSwap.h @@ -29,7 +29,6 @@ class VTKCOMMONCORE_EXPORT vtkByteSwap : public vtkObject static vtkByteSwap *New(); vtkTypeMacro(vtkByteSwap,vtkObject); - //BTX // Description: // Type-safe swap signatures to swap for storage in either Little // Endian or Big Endian format. Swapping is performed according to @@ -57,7 +56,6 @@ class VTKCOMMONCORE_EXPORT vtkByteSwap : public vtkObject VTK_BYTE_SWAP_DECL(unsigned long); VTK_BYTE_SWAP_DECL(unsigned long long); #undef VTK_BYTE_SWAP_DECL - //ETX // Description: // Swap 2, 4, or 8 bytes for storage as Little Endian. diff --git a/Common/Core/vtkCharArray.cxx b/Common/Core/vtkCharArray.cxx index aa1e5775c97..a9d66e1d4c4 100644 --- a/Common/Core/vtkCharArray.cxx +++ b/Common/Core/vtkCharArray.cxx @@ -13,13 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(char); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(char); #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(char); -#define vtkCharArray_cxx #include "vtkCharArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkCharArray.h b/Common/Core/vtkCharArray.h index 847fa204d50..0578bc93e4e 100644 --- a/Common/Core/vtkCharArray.h +++ b/Common/Core/vtkCharArray.h @@ -21,36 +21,38 @@ #ifndef vtkCharArray_h #define vtkCharArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkCharArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE char -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkCharArray : public vtkDataArray { public: vtkTypeMacro(vtkCharArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkCharArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(char); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkCharArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static char GetDataTypeValueMin() { return VTK_CHAR_MIN; } @@ -64,11 +66,14 @@ class VTKCOMMONCORE_EXPORT vtkCharArray : public vtkDataArray ~vtkCharArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkCharArray(const vtkCharArray&); // Not implemented. void operator=(const vtkCharArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkCharArray) + #endif diff --git a/Common/Core/vtkCollection.h b/Common/Core/vtkCollection.h index 72e6e513528..96990959191 100644 --- a/Common/Core/vtkCollection.h +++ b/Common/Core/vtkCollection.h @@ -31,7 +31,6 @@ #include "vtkCommonCoreModule.h" // For export macro #include "vtkObject.h" -//BTX - begin tcl exclude class vtkCollectionElement //;prevents pick-up by man page generator { public: @@ -40,7 +39,6 @@ class vtkCollectionElement //;prevents pick-up by man page generator vtkCollectionElement *Next; }; typedef void * vtkCollectionSimpleIterator; -//ETX end tcl exclude class vtkCollectionIterator; @@ -100,13 +98,11 @@ class VTKCOMMONCORE_EXPORT vtkCollection : public vtkObject // is set at the beginning of the list. void InitTraversal() { this->Current = this->Top;}; - //BTX // Description: // A reentrant safe way to iterate through a collection. // Just pass the same cookie value around each time void InitTraversal(vtkCollectionSimpleIterator &cookie) { cookie = static_cast(this->Top);}; - //ETX // Description: // Get the next item in the collection. NULL is returned if the collection @@ -118,21 +114,19 @@ class VTKCOMMONCORE_EXPORT vtkCollection : public vtkObject // of range vtkObject *GetItemAsObject(int i); - //BTX // Description: // A reentrant safe way to get the next object as a collection. Just pass the // same cookie back and forth. vtkObject *GetNextItemAsObject(vtkCollectionSimpleIterator &cookie); - //ETX // Description: // Get an iterator to traverse the objects in this collection. - vtkCollectionIterator* NewIterator(); + VTK_NEWINSTANCE vtkCollectionIterator* NewIterator(); // Description: // Participate in garbage collection. - virtual void Register(vtkObjectBase* o); - virtual void UnRegister(vtkObjectBase* o); + void Register(vtkObjectBase* o) VTK_OVERRIDE; + void UnRegister(vtkObjectBase* o) VTK_OVERRIDE; protected: vtkCollection(); ~vtkCollection(); @@ -145,9 +139,7 @@ class VTKCOMMONCORE_EXPORT vtkCollection : public vtkObject vtkCollectionElement *Bottom; vtkCollectionElement *Current; - //BTX friend class vtkCollectionIterator; - //ETX // See vtkGarbageCollector.h: virtual void ReportReferences(vtkGarbageCollector* collector); diff --git a/Common/Core/vtkCommand.h b/Common/Core/vtkCommand.h index 5692d890973..9ca284126ea 100644 --- a/Common/Core/vtkCommand.h +++ b/Common/Core/vtkCommand.h @@ -312,7 +312,19 @@ _vtk_add_event(WindowIsDirectEvent)\ _vtk_add_event(UncheckedPropertyModifiedEvent)\ _vtk_add_event(UpdateShaderEvent)\ - _vtk_add_event(MessageEvent) + _vtk_add_event(MessageEvent)\ + _vtk_add_event(StartPinchEvent)\ + _vtk_add_event(PinchEvent)\ + _vtk_add_event(EndPinchEvent)\ + _vtk_add_event(StartRotateEvent)\ + _vtk_add_event(RotateEvent)\ + _vtk_add_event(EndRotateEvent)\ + _vtk_add_event(StartPanEvent)\ + _vtk_add_event(PanEvent)\ + _vtk_add_event(EndPanEvent)\ + _vtk_add_event(TapEvent)\ + _vtk_add_event(LongTapEvent)\ + _vtk_add_event(SwipeEvent) #define vtkEventDeclarationMacro(_enum_name)\ enum _enum_name{\ @@ -382,7 +394,6 @@ class VTKCOMMONCORE_EXPORT vtkCommand : public vtkObjectBase void PassiveObserverOff() { this->SetPassiveObserver(0); } -//BTX // Description: // All the currently defined events are listed here. Developers can // use -- vtkCommand::UserEvent + int to specify their own event @@ -391,7 +402,6 @@ class VTKCOMMONCORE_EXPORT vtkCommand : public vtkObjectBase #define _vtk_add_event(Enum) Enum, vtkEventDeclarationMacro(EventIds) #undef _vtk_add_event -//ETX protected: int AbortFlag; @@ -401,10 +411,10 @@ class VTKCOMMONCORE_EXPORT vtkCommand : public vtkObjectBase virtual ~vtkCommand() {} friend class vtkSubjectHelper; -//BTX + vtkCommand(const vtkCommand& c) : vtkObjectBase(c) {} void operator=(const vtkCommand&) {} -//ETX + }; #endif /* vtkCommand_h */ diff --git a/Common/Core/vtkConditionVariable.h b/Common/Core/vtkConditionVariable.h index cc1374214ec..012e2787868 100644 --- a/Common/Core/vtkConditionVariable.h +++ b/Common/Core/vtkConditionVariable.h @@ -32,7 +32,6 @@ #include "vtkMutexLock.h" // Need for friend access to vtkSimpleMutexLock -//BTX #if defined(VTK_USE_PTHREADS) || defined(VTK_HP_PTHREADS) # include // Need POSIX thread implementation of mutex (even win32 provides mutexes) typedef pthread_cond_t vtkConditionType; @@ -140,8 +139,6 @@ class VTKCOMMONCORE_EXPORT vtkSimpleConditionVariable vtkSimpleConditionVariable& operator=(const vtkSimpleConditionVariable& rhs); // no copy assignment }; -//ETX - class VTKCOMMONCORE_EXPORT vtkConditionVariable : public vtkObject { public: @@ -170,16 +167,13 @@ class VTKCOMMONCORE_EXPORT vtkConditionVariable : public vtkObject protected: vtkConditionVariable() { } - //BTX vtkSimpleConditionVariable SimpleConditionVariable; - //ETX private: vtkConditionVariable( const vtkConditionVariable& ); // Not implemented. void operator = ( const vtkConditionVariable& ); // Not implemented. }; -//BTX inline void vtkConditionVariable::Signal() { this->SimpleConditionVariable.Signal(); @@ -194,6 +188,5 @@ inline int vtkConditionVariable::Wait( vtkMutexLock* lock ) { return this->SimpleConditionVariable.Wait( lock->SimpleMutexLock ); } -//ETX #endif // vtkConditionVariable_h diff --git a/Common/Core/vtkConfigure.h.in b/Common/Core/vtkConfigure.h.in index 266625cab52..41533daeb7f 100644 --- a/Common/Core/vtkConfigure.h.in +++ b/Common/Core/vtkConfigure.h.in @@ -17,6 +17,37 @@ /* This header is configured by VTK's build process. */ +/*--------------------------------------------------------------------------*/ +/* Compiler backend */ +/* Be careful modifying this -- order is important. */ +#if defined(_MSC_VER) +/* MSVC 2015+ can use a clang frontend, so we want to label it only as MSVC + * and not MSVC and clang. */ +#define VTK_COMPILER_MSVC + +#elif defined(__INTEL_COMPILER) +/* Intel 14+ on OSX uses a clang frontend, so again we want to label them as + * intel only, and not intel and clang. */ +#define VTK_COMPILER_ICC + +#elif defined(__PGI) +/* PGI reports as GNUC as it generates the same ABI, so we need to check for + * it before gcc. */ +#define VTK_COMPILER_PGI + +#elif defined(__clang__) +/* Check for clang before GCC, as clang says it is GNUC since it has ABI + * compliance. */ +#define VTK_COMPILER_CLANG + +#elif defined(__GNUC__) +/* Several compilers pretend to be GCC but have minor differences. Try to + * compensate for that, by checking for those compilers first. */ +#define VTK_COMPILER_GCC +#define VTK_COMPILER_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + \ + __GNUC_PATCHLEVEL__) +#endif + /*--------------------------------------------------------------------------*/ /* Platform Features */ @@ -42,7 +73,7 @@ /* Atomic operations */ #cmakedefine VTK_HAVE_SYNC_BUILTINS -#if defined(WIN32) +#if defined(_WIN32) #cmakedefine VTK_HAS_INTERLOCKEDADD #endif @@ -84,6 +115,9 @@ /* Debug leaks support. */ #cmakedefine VTK_DEBUG_LEAKS +/* Print warning on vtkArrayDispatch failure. */ +#cmakedefine VTK_WARN_ON_DISPATCH_FAILURE + /* Should all New methods use the object factory override. */ #cmakedefine VTK_ALL_NEW_OBJECT_FACTORY diff --git a/Common/Core/vtkDataArray.cxx b/Common/Core/vtkDataArray.cxx index a9cd8f44924..d6d0980fda5 100644 --- a/Common/Core/vtkDataArray.cxx +++ b/Common/Core/vtkDataArray.cxx @@ -12,13 +12,17 @@ PURPOSE. See the above copyright notice for more information. =========================================================================*/ + +#include "vtkArrayDispatch.h" +#include "vtkAOSDataArrayTemplate.h" // For fast paths #include "vtkDataArray.h" +#include "vtkDataArrayAccessor.h" #include "vtkDataArrayPrivate.txx" #include "vtkBitArray.h" #include "vtkCharArray.h" -#include "vtkDataArrayIteratorMacro.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" +#include "vtkGenericDataArray.h" #include "vtkInformation.h" #include "vtkInformationDoubleVectorKey.h" #include "vtkInformationInformationVectorKey.h" @@ -29,9 +33,9 @@ #include "vtkLookupTable.h" #include "vtkLongArray.h" #include "vtkMath.h" +#include "vtkSOADataArrayTemplate.h" // For fast paths #include "vtkShortArray.h" #include "vtkSignedCharArray.h" -#include "vtkTypedDataArrayIterator.h" #include "vtkTypeTraits.h" #include "vtkUnsignedCharArray.h" #include "vtkUnsignedIntArray.h" @@ -39,147 +43,299 @@ #include "vtkUnsignedShortArray.h" #include // for min(), max() + namespace { -//---------------------------------------------------------------------------- -template -void vtkDeepCopySwitchOnOutput(InputIterator begin, InputIterator end, - vtkDataArray *outputArray) -{ - switch (outputArray->GetDataType()) - { - vtkDataArrayIteratorMacro(outputArray, - std::copy(begin, end, vtkDABegin)); +//--------Copy tuples from src to dest------------------------------------------ +struct DeepCopyWorker +{ + // AoS --> AoS same-type specialization: + template + void operator()(vtkAOSDataArrayTemplate *src, + vtkAOSDataArrayTemplate *dst) + { + std::copy(src->Begin(), src->End(), dst->Begin()); + } + + // SoA --> SoA same-type specialization: + template + void operator()(vtkSOADataArrayTemplate *src, + vtkSOADataArrayTemplate *dst) + { + vtkIdType numTuples = src->GetNumberOfTuples(); + for (int comp; comp < src->GetNumberOfComponents(); ++comp) + { + ValueType *srcBegin = src->GetComponentArrayPointer(comp); + ValueType *srcEnd = srcBegin + numTuples; + ValueType *dstBegin = dst->GetComponentArrayPointer(comp); - default: - vtkGenericWarningMacro("Unsupported data type " - << outputArray->GetDataTypeAsString() << "!"); - } -} + std::copy(srcBegin, srcEnd, dstBegin); + } + } -//-------------------------------------------------------------------------- -template -inline void vtkDataArrayRoundIfNecessary(double val, T* retVal) -{ - val = std::max(val, static_cast(vtkTypeTraits::Min())); - val = std::min(val, static_cast(vtkTypeTraits::Max())); - *retVal = static_cast((val>=0.0)?(val + 0.5):(val - 0.5)); -} + // Generic implementation: + template + void operator()(Array1T *src, Array2T *dst) + { + vtkDataArrayAccessor s(src); + vtkDataArrayAccessor d(dst); -//-------------------------------------------------------------------------- -template<> -inline void vtkDataArrayRoundIfNecessary(double val, double* retVal) -{ - *retVal = val; -} + typedef typename vtkDataArrayAccessor::APIType DestType; + + vtkIdType tuples = src->GetNumberOfTuples(); + int comps = src->GetNumberOfComponents(); + + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + d.Set(t, c, static_cast(s.Get(t, c))); + } + } + } +}; -//-------------------------------------------------------------------------- -template<> -inline void vtkDataArrayRoundIfNecessary(double val, float* retVal) +//------------InterpolateTuple workers------------------------------------------ +struct InterpolateMultiTupleWorker { - *retVal = static_cast(val); -} + vtkIdType DestTuple; + vtkIdType *TupleIds; + vtkIdType NumTuples; + double *Weights; + + InterpolateMultiTupleWorker(vtkIdType destTuple, vtkIdType *tupleIds, + vtkIdType numTuples, double *weights) + : DestTuple(destTuple), TupleIds(tupleIds), NumTuples(numTuples), + Weights(weights) + {} + + + template + void operator()(Array1T *src, Array2T *dst) + { + vtkDataArrayAccessor s(src); + vtkDataArrayAccessor d(dst); + + typedef typename vtkDataArrayAccessor::APIType DestType; + + int numComp = src->GetNumberOfComponents(); + + for (int c = 0; c < numComp; ++c) + { + double val = 0.; + for (vtkIdType tupleId = 0; tupleId < this->NumTuples; ++tupleId) + { + vtkIdType t = this->TupleIds[tupleId]; + double weight = this->Weights[tupleId]; + val += weight * static_cast(s.Get(t, c)); + } + DestType valT; + vtkMath::RoundDoubleToIntegralIfNecessary(val, &valT); + d.Insert(this->DestTuple, c, valT); + } + } +}; -//-------------------------------------------------------------------------- -template -void vtkDataArrayInterpolateTuple(Iterator from, Scalar *to, int numComp, - vtkIdType* ids, vtkIdType numIds, double* weights) +struct InterpolateTupleWorker { - for(int i=0; i < numComp; ++i) - { - double c = 0; - for(vtkIdType j=0; j < numIds; ++j) + vtkIdType SrcTuple1; + vtkIdType SrcTuple2; + vtkIdType DstTuple; + double Weight; + + InterpolateTupleWorker(vtkIdType srcTuple1, vtkIdType srcTuple2, + vtkIdType dstTuple, double weight) + : SrcTuple1(srcTuple1), SrcTuple2(srcTuple2), DstTuple(dstTuple), + Weight(weight) + {} + + template + void operator()(Array1T *src1, Array2T *src2, Array3T *dst) + { + vtkDataArrayAccessor s1(src1); + vtkDataArrayAccessor s2(src2); + vtkDataArrayAccessor d(dst); + + typedef typename vtkDataArrayAccessor::APIType DestType; + + const int numComps = dst->GetNumberOfComponents(); + const double oneMinusT = 1. - this->Weight; + double val; + DestType valT; + + for (int c = 0; c < numComps; ++c) { - c += weights[j] * static_cast(from[ids[j]*numComp+i]); + val = s1.Get(this->SrcTuple1, c) * oneMinusT + + s2.Get(this->SrcTuple2, c) * this->Weight; + vtkMath::RoundDoubleToIntegralIfNecessary(val, &valT); + d.Insert(this->DstTuple, c, valT); } - // Round integer types. Don't round floating point types. - vtkDataArrayRoundIfNecessary(c, to); - ++to; - } -} + } +}; -//---------------------------------------------------------------------------- -template -void vtkDataArrayInterpolateTuple(Iterator from1, Iterator from2, Scalar* to, - int numComp, double t) +//-----------------GetTuples (id list)------------------------------------------ +struct GetTuplesFromListWorker { - const double oneMinusT = 1.0 - t; - while (numComp-- > 0) - { - double c = oneMinusT * (*(from1++)) + t * (*(from2++)); - // Round integer types. Don't round floating point types. - vtkDataArrayRoundIfNecessary(c, &(*(to++))); - } -} + vtkIdList *Ids; -//---------------------------------------------------------------------------- -template -void vtkDataArrayGetTuplesTemplate2(vtkIdType* ids, vtkIdType* idsEnd, - InputIterator inIter, - OutputIterator outIter, - int numComps) + GetTuplesFromListWorker(vtkIdList *ids) : Ids(ids) {} + + template + void operator()(Array1T *src, Array2T *dst) + { + vtkDataArrayAccessor s(src); + vtkDataArrayAccessor d(dst); + + typedef typename vtkDataArrayAccessor::APIType DestType; + + int numComps = src->GetNumberOfComponents(); + vtkIdType *srcTuple = this->Ids->GetPointer(0); + vtkIdType *srcTupleEnd = this->Ids->GetPointer(Ids->GetNumberOfIds()); + vtkIdType dstTuple = 0; + + while (srcTuple != srcTupleEnd) + { + for (int c = 0; c < numComps; ++c) + { + d.Set(dstTuple, c, static_cast(s.Get(*srcTuple, c))); + } + ++srcTuple; + ++dstTuple; + } + } +}; + +//-----------------GetTuples (tuple range)-------------------------------------- +struct GetTuplesRangeWorker { - InputIterator inPt; - while (ids != idsEnd) - { - inPt = inIter + (*(ids++) * numComps); - outIter = std::copy(inPt, inPt + numComps, outIter); - } -} + vtkIdType Start; + vtkIdType End; // Note that End is inclusive. -//---------------------------------------------------------------------------- -template -void vtkDataArrayGetTuplesTemplate1(vtkIdType* ids, vtkIdType* idsEnd, - InputIterator inIter, - vtkDataArray *outArray, - int numComps) -{ - switch (outArray->GetDataType()) - { - vtkDataArrayIteratorMacro(outArray, - vtkDataArrayGetTuplesTemplate2(ids, idsEnd, inIter, vtkDABegin, numComps) - ); - default: - vtkGenericWarningMacro("vtkDataArray::GetTuples: " - "Unsupported output type."); - return; - } -} + GetTuplesRangeWorker(vtkIdType start, vtkIdType end) + : Start(start), End(end) + {} -//---------------------------------------------------------------------------- -template -void vtkCopyTuples(IT* input, OT* output, int nComp, - vtkIdType p1, vtkIdType p2) + template + void operator()(Array1T *src, Array2T *dst) + { + vtkDataArrayAccessor s(src); + vtkDataArrayAccessor d(dst); + + typedef typename vtkDataArrayAccessor::APIType DestType; + + int numComps = src->GetNumberOfComponents(); + for (vtkIdType srcT = this->Start, dstT = 0; + srcT <= this->End; + ++srcT, ++dstT) + { + for (int c = 0; c < numComps; ++c) + { + d.Set(dstT, c, static_cast(s.Get(srcT, c))); + } + } + } +}; + +//----------------SetTuple (from array)----------------------------------------- +struct SetTupleArrayWorker { - vtkIdType i; - int j; - vtkIdType num=p2-p1+1; - for (i=0; i + void operator()(SrcArrayT *src, DstArrayT *dst) + { + vtkDataArrayAccessor s(src); + vtkDataArrayAccessor d(dst); + + typedef typename vtkDataArrayAccessor::APIType DestType; + + int numComps = src->GetNumberOfComponents(); + for (int c = 0; c < numComps; ++c) { - output[i*nComp+j] = static_cast(input[(p1+i)*nComp+j]); + d.Set(this->DstTuple, c, static_cast(s.Get(this->SrcTuple, c))); } - } -} + } +}; -//---------------------------------------------------------------------------- -template -void vtkCopyTuples1(IT* input, vtkDataArray* output, - vtkIdType p1, vtkIdType p2) +//----------------SetTuples (from array+vtkIdList)------------------------------ +struct SetTuplesIdListWorker { - switch (output->GetDataType()) - { - vtkTemplateMacro(vtkCopyTuples( input, - static_cast(output->GetVoidPointer(0)), - output->GetNumberOfComponents(), p1, p2) ); + vtkIdList *SrcTuples; + vtkIdList *DstTuples; - default: - vtkGenericWarningMacro("Sanity check failed: Unsupported data type " - << output->GetDataType() << "."); - return; - } -} + SetTuplesIdListWorker(vtkIdList *srcTuples, vtkIdList *dstTuples) + : SrcTuples(srcTuples), DstTuples(dstTuples) + {} + + template + void operator()(SrcArrayT *src, DstArrayT *dst) + { + vtkDataArrayAccessor s(src); + vtkDataArrayAccessor d(dst); + + typedef typename vtkDataArrayAccessor::APIType DestType; + + vtkIdType numTuples = this->SrcTuples->GetNumberOfIds(); + int numComps = src->GetNumberOfComponents(); + for (vtkIdType t = 0; t < numTuples; ++t) + { + vtkIdType srcT = this->SrcTuples->GetId(t); + vtkIdType dstT = this->DstTuples->GetId(t); + for (int c = 0; c < numComps; ++c) + { + d.Set(dstT, c, static_cast(s.Get(srcT, c))); + } + } + } +}; + +//----------------SetTuples (from array+range)---------------------------------- +struct SetTuplesRangeWorker +{ + vtkIdType SrcStartTuple; + vtkIdType DstStartTuple; + vtkIdType NumTuples; + + SetTuplesRangeWorker(vtkIdType srcStartTuple, vtkIdType dstStartTuple, + vtkIdType numTuples) + : SrcStartTuple(srcStartTuple), DstStartTuple(dstStartTuple), + NumTuples(numTuples) + {} + + // Generic implementation. We perform the obvious optimizations for AOS/SOA + // in the derived class implementations. + template + void operator()(SrcArrayT *src, DstArrayT *dst) + { + vtkDataArrayAccessor s(src); + vtkDataArrayAccessor d(dst); + + typedef typename vtkDataArrayAccessor::APIType DestType; + + int numComps = src->GetNumberOfComponents(); + vtkIdType srcT = this->SrcStartTuple; + vtkIdType srcTEnd = srcT + this->NumTuples; + vtkIdType dstT = this->DstStartTuple; + + while (srcT < srcTEnd) + { + for (vtkIdType t = 0; t < this->NumTuples; ++t) + { + for (int c = 0; c < numComps; ++c) + { + d.Set(dstT, c, static_cast(s.Get(srcT, c))); + } + } + ++srcT; + ++dstT; + } + } +}; template bool hasValidKey(InfoType info, KeyType key, @@ -271,29 +427,16 @@ void vtkDataArray::DeepCopy(vtkDataArray *da) this->Superclass::DeepCopy( da ); // copy Information object vtkIdType numTuples = da->GetNumberOfTuples(); - this->NumberOfComponents = da->NumberOfComponents; + int numComps = da->NumberOfComponents; + + this->SetNumberOfComponents(numComps); this->SetNumberOfTuples(numTuples); - if (numTuples > 0) + DeepCopyWorker worker; + if (!vtkArrayDispatch::Dispatch2::Execute(da, this, worker)) { - switch (da->GetDataType()) - { - vtkDataArrayIteratorMacro( - da, vtkDeepCopySwitchOnOutput(vtkDABegin, vtkDAEnd, this) - ); - - case VTK_BIT: - {//bit not supported, using generic double API - for (vtkIdType i=0; i < numTuples; i++) - { - this->SetTuple(i, da->GetTuple(i)); - } - break; - } - - default: - vtkErrorMacro("Unsupported data type " << da->GetDataType() << "!"); - } + // If dispatch fails, use fallback: + worker(da, this); } this->SetLookupTable(0); @@ -307,27 +450,244 @@ void vtkDataArray::DeepCopy(vtkDataArray *da) this->Squeeze(); } +//------------------------------------------------------------------------------ +void vtkDataArray::ShallowCopy(vtkDataArray *other) +{ + // Deep copy by default. Subclasses may override this behavior. + this->DeepCopy(other); +} + +//------------------------------------------------------------------------------ +void vtkDataArray::SetTuple(vtkIdType dstTupleIdx, vtkIdType srcTupleIdx, + vtkAbstractArray *source) +{ + vtkDataArray *srcDA = vtkDataArray::FastDownCast(source); + if (!srcDA) + { + vtkErrorMacro("Source array must be a vtkDataArray subclass (got " + << source->GetClassName() << ")."); + return; + } + + if (!vtkDataTypesCompare(source->GetDataType(), this->GetDataType())) + { + vtkErrorMacro("Type mismatch: Source: " << source->GetDataTypeAsString() + << " Dest: " << this->GetDataTypeAsString()); + return; + } + + if (source->GetNumberOfComponents() != this->GetNumberOfComponents()) + { + vtkErrorMacro("Number of components do not match: Source: " + << source->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + + SetTupleArrayWorker worker(srcTupleIdx, dstTupleIdx); + if (!vtkArrayDispatch::Dispatch2SameValueType::Execute(srcDA, this, worker)) + { + worker(srcDA, this); + } +} + +//---------------------------------------------------------------------------- +void vtkDataArray::SetTuple(vtkIdType i, const float *source) +{ + for (int c = 0; c < this->NumberOfComponents; ++c) + { + this->SetComponent(i, c, static_cast(source[c])); + } +} + +//---------------------------------------------------------------------------- +void vtkDataArray::SetTuple(vtkIdType i, const double *source) +{ + for (int c = 0; c < this->NumberOfComponents; ++c) + { + this->SetComponent(i, c, source[c]); + } +} + +//---------------------------------------------------------------------------- +void vtkDataArray::InsertTuple(vtkIdType dstTupleIdx, vtkIdType srcTupleIdx, + vtkAbstractArray *source) +{ + vtkIdType newSize = (dstTupleIdx + 1) * this->NumberOfComponents; + if (this->Size < newSize) + { + if (!this->Resize(dstTupleIdx + 1)) + { + vtkErrorMacro("Resize failed."); + return; + } + } + + this->MaxId = std::max(this->MaxId, newSize - 1); + + this->SetTuple(dstTupleIdx, srcTupleIdx, source); +} + +//---------------------------------------------------------------------------- +vtkIdType vtkDataArray::InsertNextTuple(vtkIdType srcTupleIdx, + vtkAbstractArray *source) +{ + vtkIdType tupleIdx = this->GetNumberOfTuples(); + this->InsertTuple(tupleIdx, srcTupleIdx, source); + return tupleIdx; +} + +//---------------------------------------------------------------------------- +void vtkDataArray::InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, + vtkAbstractArray *src) +{ + if (dstIds->GetNumberOfIds() == 0) + { + return; + } + if (dstIds->GetNumberOfIds() != srcIds->GetNumberOfIds()) + { + vtkErrorMacro("Mismatched number of tuples ids. Source: " + << srcIds->GetNumberOfIds() << " Dest: " + << dstIds->GetNumberOfIds()); + return; + } + if (!vtkDataTypesCompare(src->GetDataType(), this->GetDataType())) + { + vtkErrorMacro("Data type mismatch: Source: " << src->GetDataTypeAsString() + << " Dest: " << this->GetDataTypeAsString()); + return; + } + if (src->GetNumberOfComponents() != this->GetNumberOfComponents()) + { + vtkErrorMacro("Number of components do not match: Source: " + << src->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + vtkDataArray *srcDA = vtkDataArray::FastDownCast(src); + if (!srcDA) + { + vtkErrorMacro("Source array must be a subclass of vtkDataArray. Got: " + << src->GetClassName()); + return; + } + + vtkIdType maxSrcTupleId = srcIds->GetId(0); + vtkIdType maxDstTupleId = dstIds->GetId(0); + for (int i = 0; i < dstIds->GetNumberOfIds(); ++i) + { + maxSrcTupleId = std::max(maxSrcTupleId, srcIds->GetId(i)); + maxDstTupleId = std::max(maxDstTupleId, dstIds->GetId(i)); + } + + if (maxSrcTupleId >= src->GetNumberOfTuples()) + { + vtkErrorMacro("Source array too small, requested tuple at index " + << maxSrcTupleId << ", but there are only " + << src->GetNumberOfTuples() << " tuples in the array."); + return; + } + + vtkIdType newSize = (maxDstTupleId + 1) * this->NumberOfComponents; + if (this->Size < newSize) + { + if (!this->Resize(maxDstTupleId + 1)) + { + vtkErrorMacro("Resize failed."); + return; + } + } + + this->MaxId = std::max(this->MaxId, newSize - 1); + + SetTuplesIdListWorker worker(srcIds, dstIds); + if (!vtkArrayDispatch::Dispatch2SameValueType::Execute(srcDA, this, worker)) + { + worker(srcDA, this); + } +} + +//---------------------------------------------------------------------------- +void vtkDataArray::InsertTuples(vtkIdType dstStart, vtkIdType n, + vtkIdType srcStart, vtkAbstractArray *src) +{ + if (n == 0) + { + return; + } + if (!vtkDataTypesCompare(src->GetDataType(), this->GetDataType())) + { + vtkErrorMacro("Data type mismatch: Source: " << src->GetDataTypeAsString() + << " Dest: " << this->GetDataTypeAsString()); + return; + } + if (src->GetNumberOfComponents() != this->GetNumberOfComponents()) + { + vtkErrorMacro("Number of components do not match: Source: " + << src->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + vtkDataArray *srcDA = vtkDataArray::FastDownCast(src); + if (!srcDA) + { + vtkErrorMacro("Source array must be a subclass of vtkDataArray. Got: " + << src->GetClassName()); + return; + } + + vtkIdType maxSrcTupleId = srcStart + n - 1; + vtkIdType maxDstTupleId = dstStart + n - 1; + + if (maxSrcTupleId >= src->GetNumberOfTuples()) + { + vtkErrorMacro("Source array too small, requested tuple at index " + << maxSrcTupleId << ", but there are only " + << src->GetNumberOfTuples() << " tuples in the array."); + return; + } + + vtkIdType newSize = (maxDstTupleId + 1) * this->NumberOfComponents; + if (this->Size < newSize) + { + if (!this->Resize(maxDstTupleId + 1)) + { + vtkErrorMacro("Resize failed."); + return; + } + } + + this->MaxId = std::max(this->MaxId, newSize - 1); + + SetTuplesRangeWorker worker(srcStart, dstStart, n); + if (!vtkArrayDispatch::Dispatch2SameValueType::Execute(srcDA, this, worker)) + { + worker(srcDA, this); + } +} + //---------------------------------------------------------------------------- // These can be overridden for more efficiency -double vtkDataArray::GetComponent(vtkIdType i, int j) +double vtkDataArray::GetComponent(vtkIdType tupleIdx, int compIdx) { double *tuple=new double[this->NumberOfComponents], c; - this->GetTuple(i,tuple); - c = tuple[j]; + this->GetTuple(tupleIdx,tuple); + c = tuple[compIdx]; delete [] tuple; return c; } //---------------------------------------------------------------------------- -void vtkDataArray::SetComponent(vtkIdType i, int j, double c) +void vtkDataArray::SetComponent(vtkIdType tupleIdx, int compIdx, double value) { double *tuple=new double[this->NumberOfComponents]; - if ( i < this->GetNumberOfTuples() ) + if ( tupleIdx < this->GetNumberOfTuples() ) { - this->GetTuple(i,tuple); + this->GetTuple(tupleIdx,tuple); } else { @@ -337,20 +697,21 @@ void vtkDataArray::SetComponent(vtkIdType i, int j, double c) } } - tuple[j] = c; - this->SetTuple(i,tuple); + tuple[compIdx] = value; + this->SetTuple(tupleIdx,tuple); delete [] tuple; } //---------------------------------------------------------------------------- -void vtkDataArray::InsertComponent(vtkIdType i, int j, double c) +void vtkDataArray::InsertComponent(vtkIdType tupleIdx, int compIdx, + double value) { double *tuple=new double[this->NumberOfComponents]; - if ( i < this->GetNumberOfTuples() ) + if ( tupleIdx < this->GetNumberOfTuples() ) { - this->GetTuple(i,tuple); + this->GetTuple(tupleIdx,tuple); } else { @@ -360,8 +721,8 @@ void vtkDataArray::InsertComponent(vtkIdType i, int j, double c) } } - tuple[j] = c; - this->InsertTuple(i,tuple); + tuple[compIdx] = value; + this->InsertTuple(tupleIdx,tuple); delete [] tuple; } @@ -391,57 +752,74 @@ void vtkDataArray::GetData(vtkIdType tupleMin, vtkIdType tupleMax, int compMin, // Interpolate array value from other array value given the // indices and associated interpolation weights. // This method assumes that the two arrays are of the same time. -void vtkDataArray::InterpolateTuple(vtkIdType i, vtkIdList *ptIndices, - vtkAbstractArray* source, double* weights) +void vtkDataArray::InterpolateTuple(vtkIdType dstTupleIdx, vtkIdList *tupleIds, + vtkAbstractArray* source, double* weights) { if (!vtkDataTypesCompare(this->GetDataType(), source->GetDataType())) { - vtkErrorMacro("Cannot InterpolateValue from array of type " - << source->GetDataTypeAsString()); + vtkErrorMacro("Cannot interpolate arrays of different type."); + return; + } + + vtkDataArray *da = vtkDataArray::FastDownCast(source); + if (!da) + { + vtkErrorMacro(<<"Source array is not a vtkDataArray."); return; } - vtkDataArray* fromData = vtkDataArray::FastDownCast(source); - if (fromData) + int numComps = this->GetNumberOfComponents(); + if (da->GetNumberOfComponents() != numComps) + { + vtkErrorMacro("Number of components do not match: Source: " + << source->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + + vtkIdType numIds=tupleIds->GetNumberOfIds(); + vtkIdType *ids=tupleIds->GetPointer(0); + + bool fallback = da->GetDataType() == VTK_BIT || + this->GetDataType() == VTK_BIT; + + if (!fallback) { - int numComp = fromData->GetNumberOfComponents(); - vtkIdType j, numIds=ptIndices->GetNumberOfIds(); - vtkIdType *ids=ptIndices->GetPointer(0); - vtkIdType idx= i*numComp; - double c; + InterpolateMultiTupleWorker worker(dstTupleIdx, ids, numIds, weights); + // Use fallback if dispatch fails. + fallback = !vtkArrayDispatch::Dispatch2SameValueType::Execute(da, this, + worker); + } - // Note that we must call WriteVoidPointer before GetVoidPointer - // in case WriteVoidPointer reallocates memory and fromData == - // this. The vtkBitArray implementation doesn't use pointers, so skip - // the resizing in this case. - int dataType = fromData->GetDataType(); - void* vto = dataType != VTK_BIT ? - this->WriteVoidPointer(idx, numComp) : 0; + // Fallback to a separate implementation that checks vtkDataArray::GetDataType + // rather than relying on API types, since we'll need to round differently + // depending on type, and the API type for vtkDataArray is always double. + if (fallback) + { + bool doRound = !(this->GetDataType() == VTK_FLOAT || + this->GetDataType() == VTK_DOUBLE); + double typeMin = this->GetDataTypeMin(); + double typeMax = this->GetDataTypeMax(); - switch (dataType) + for (int c = 0; c < numComps; ++c) { - case VTK_BIT: + double val = 0.; + for (vtkIdType j = 0; j < numIds; ++j) { - vtkBitArray *from=static_cast(fromData); - vtkBitArray *to=static_cast(this); - for (int k=0; kGetValue(ids[j]*numComp+k); - } - to->InsertValue(idx+k, static_cast(c)); - } + val += weights[j] * da->GetComponent(ids[j], c); } - break; - vtkDataArrayIteratorMacro(fromData, - vtkDataArrayInterpolateTuple(vtkDABegin, - static_cast(vto), - numComp, ids, numIds, weights) - ); - default: - vtkErrorMacro("Unsupported data type " << fromData->GetDataType() - << " during interpolation!"); + + // Clamp to data type range: + val = std::max(val, typeMin); + val = std::min(val, typeMax); + + // Round for floating point types: + if (doRound) + { + val = std::floor((val >= 0.) ? (val + 0.5) : (val - 0.5)); + } + + this->InsertComponent(dstTupleIdx, c, val); } } } @@ -452,9 +830,9 @@ void vtkDataArray::InterpolateTuple(vtkIdType i, vtkIdList *ptIndices, // with t=0 located at p1. This method assumes that the three arrays are of // the same type. p1 is value at index id1 in fromArray1, while, p2 is // value at index id2 in fromArray2. -void vtkDataArray::InterpolateTuple(vtkIdType i, - vtkIdType id1, vtkAbstractArray* source1, - vtkIdType id2, vtkAbstractArray* source2, double t) +void vtkDataArray::InterpolateTuple(vtkIdType dstTuple, + vtkIdType srcTuple1, vtkAbstractArray* source1, + vtkIdType srcTuple2, vtkAbstractArray* source2, double t) { int type = this->GetDataType(); @@ -465,83 +843,69 @@ void vtkDataArray::InterpolateTuple(vtkIdType i, return; } - if (id1 >= source1->GetNumberOfTuples()) + if (srcTuple1 >= source1->GetNumberOfTuples()) { vtkErrorMacro("Tuple 1 out of range for provided array. " - "Requested tuple: " << id1 << " " + "Requested tuple: " << srcTuple1 << " " "Tuples: " << source1->GetNumberOfTuples()); return; } - if (id2 >= source2->GetNumberOfTuples()) + if (srcTuple2 >= source2->GetNumberOfTuples()) { vtkErrorMacro("Tuple 2 out of range for provided array. " - "Requested tuple: " << id2 << " " + "Requested tuple: " << srcTuple2 << " " "Tuples: " << source2->GetNumberOfTuples()); return; } - int k, numComp = source1->GetNumberOfComponents(); - double c; - vtkIdType loc = i * numComp; + vtkDataArray *src1DA = vtkDataArray::FastDownCast(source1); + vtkDataArray *src2DA = vtkDataArray::FastDownCast(source2); + if (!src1DA || !src2DA) + { + vtkErrorMacro("Both arrays must be vtkDataArray subclasses."); + return; + } - switch (type) + bool fallback = type == VTK_BIT; + + if (!fallback) { - case VTK_BIT: + InterpolateTupleWorker worker(srcTuple1, srcTuple2, dstTuple, t); + // Use fallback if dispatch fails: + fallback = !vtkArrayDispatch::Dispatch3SameValueType::Execute( + src1DA, src2DA, this, worker); + } + + // Fallback to a separate implementation that checks vtkDataArray::GetDataType + // rather than relying on API types, since we'll need to round differently + // depending on type, and the API type for vtkDataArray is always double. + if (fallback) + { + bool doRound = !(this->GetDataType() == VTK_FLOAT || + this->GetDataType() == VTK_DOUBLE); + double typeMin = this->GetDataTypeMin(); + double typeMax = this->GetDataTypeMax(); + int numComp = source1->GetNumberOfComponents(); + double in1; + double in2; + double out; + for (int c = 0; c < numComp; c++) { - vtkBitArray *from1 = static_cast(source1); - vtkBitArray *from2 = static_cast(source2); - vtkBitArray *to = static_cast(this); - for (k=0; kGetComponent(srcTuple1, c); + in2 = src2DA->GetComponent(srcTuple2, c); + out = in1 + t * (in2 - in1); + // Clamp to datatype range: + out = std::max(out, typeMin); + out = std::min(out, typeMax); + // Round if needed: + if (doRound) { - c = from1->GetValue(id1) + t * (from2->GetValue(id2) - from1->GetValue(id1)); - to->InsertValue(loc + k, static_cast(c)); + out = std::floor((out >= 0.) ? (out + 0.5) : (out - 0.5)); } + this->InsertComponent(dstTuple, c, out); } - break; - // Note that we must call WriteVoidPointer before GetVoidPointer/creating - // iterators in case WriteVoidPointer reallocates memory and - // fromData1==this or fromData2==this. - vtkTemplateMacro( - // If either of the source arrays are mapped, use iterators. Otherwise, - // void pointers are safe. - if (source1->HasStandardMemoryLayout() && - source2->HasStandardMemoryLayout()) - { - // Use pointers: - void *vto = this->WriteVoidPointer(loc, numComp); - void *vfrom1 = source1->GetVoidPointer(id1 * numComp); - void *vfrom2 = source2->GetVoidPointer(id2 * numComp); - vtkDataArrayInterpolateTuple(static_cast(vfrom1), - static_cast(vfrom2), - static_cast(vto), - numComp, t); - } - else - { - vtkTypedDataArray *tfrom1 = - vtkTypedDataArray::FastDownCast(source1); - vtkTypedDataArray *tfrom2 = - vtkTypedDataArray::FastDownCast(source2); - if (!tfrom1 || !tfrom2) - { - vtkErrorMacro(<<"Cannot call this function with non-standard arrays " - "unless all arrays are vtkTypedDataArray subclasses."); - return; - } - VTK_TT *vto = static_cast( - this->WriteVoidPointer(loc, numComp)); - vtkDataArrayInterpolateTuple( - vtkTypedDataArrayIterator(tfrom1, id1 * numComp), - vtkTypedDataArrayIterator(tfrom2, id2 * numComp), - vto, numComp, t); - } - ); - default: - vtkErrorMacro("Unsupported data type " << type - << " during interpolation!"); } - } //---------------------------------------------------------------------------- @@ -943,7 +1307,7 @@ unsigned long vtkDataArray::GetActualMemorySize() vtkDataArray* vtkDataArray::CreateDataArray(int dataType) { vtkAbstractArray* aa = vtkAbstractArray::CreateArray(dataType); - vtkDataArray* da = vtkDataArray::SafeDownCast(aa); + vtkDataArray* da = vtkDataArray::FastDownCast(aa); if (!da && aa) { // Requested array is not a vtkDataArray. Delete the allocated array. @@ -953,44 +1317,35 @@ vtkDataArray* vtkDataArray::CreateDataArray(int dataType) } //---------------------------------------------------------------------------- -void vtkDataArray::GetTuples(vtkIdList *ptIds, vtkAbstractArray *aa) +void vtkDataArray::GetTuples(vtkIdList *tupleIds, vtkAbstractArray *aa) { - vtkDataArray *outArray = vtkDataArray::FastDownCast(aa); - if (!outArray) + vtkDataArray *da = vtkDataArray::FastDownCast(aa); + if (!da) { - vtkWarningMacro("Input is not a vtkDataArray."); + vtkErrorMacro("Input is not a vtkDataArray, but " << aa->GetClassName()); return; } - if ((outArray->GetNumberOfComponents() != this->GetNumberOfComponents())) + if ((da->GetNumberOfComponents() != this->GetNumberOfComponents())) { - vtkWarningMacro("Number of components for input and output do not match"); + vtkErrorMacro("Number of components for input and output do not match.\n" + "Source: " << this->GetNumberOfComponents() << "\n" + "Destination: " << da->GetNumberOfComponents()); return; } - vtkIdType* ids = ptIds->GetPointer(0); - vtkIdType* idsEnd = ptIds->GetPointer(ptIds->GetNumberOfIds()); - - switch (this->GetDataType()) + GetTuplesFromListWorker worker(tupleIds); + if (!vtkArrayDispatch::Dispatch2::Execute(this, da, worker)) { - vtkDataArrayIteratorMacro(this, - vtkDataArrayGetTuplesTemplate1(ids, idsEnd, vtkDABegin, outArray, - this->NumberOfComponents) - ); - default: // Fallback to the double interface - vtkIdType num=ptIds->GetNumberOfIds(); - for (vtkIdType i=0; iSetTuple(i, this->GetTuple(ptIds->GetId(i))); - } - break; + // Use fallback if dispatch fails. + worker(this, da); } } //---------------------------------------------------------------------------- void vtkDataArray::GetTuples(vtkIdType p1, vtkIdType p2, vtkAbstractArray *aa) { - vtkDataArray* da = vtkDataArray::SafeDownCast(aa); + vtkDataArray* da = vtkDataArray::FastDownCast(aa); if (!da) { vtkWarningMacro("Input is not a vtkDataArray."); @@ -999,38 +1354,26 @@ void vtkDataArray::GetTuples(vtkIdType p1, vtkIdType p2, vtkAbstractArray *aa) if ((da->GetNumberOfComponents() != this->GetNumberOfComponents())) { - vtkWarningMacro("Number of components for input and output do not match"); + vtkErrorMacro("Number of components for input and output do not match.\n" + "Source: " << this->GetNumberOfComponents() << "\n" + "Destination: " << da->GetNumberOfComponents()); return; } - switch (this->GetDataType()) + GetTuplesRangeWorker worker(p1, p2); + if (!vtkArrayDispatch::Dispatch2::Execute(this, da, worker)) { - vtkTemplateMacro(vtkCopyTuples1( static_cast(this->GetVoidPointer(0)), da, - p1, p2 ) ); - // This is not supported by the template macro. - // Switch to using the double interface. - case VTK_BIT: - { - vtkIdType num=p2-p1+1; - for (vtkIdType i=0; iSetTuple(i,this->GetTuple(p1+i)); - } - } - break; - default: - vtkErrorMacro("Sanity check failed: Unsupported data type " - << this->GetDataType() << "."); - return; + // Use fallback if dispatch fails. + worker(this, da); } } //---------------------------------------------------------------------------- -void vtkDataArray::FillComponent(int j, double c) +void vtkDataArray::FillComponent(int compIdx, double value) { - if (j < 0 || j >= this->GetNumberOfComponents()) + if (compIdx < 0 || compIdx >= this->GetNumberOfComponents()) { - vtkErrorMacro(<< "Specified component " << j << " is not in [0, " + vtkErrorMacro(<< "Specified component " << compIdx << " is not in [0, " << this->GetNumberOfComponents() << ")" ); return; } @@ -1039,41 +1382,43 @@ void vtkDataArray::FillComponent(int j, double c) for (i = 0; i < this->GetNumberOfTuples(); i++) { - this->SetComponent(i, j, c); + this->SetComponent(i, compIdx, value); } } //---------------------------------------------------------------------------- -void vtkDataArray::CopyComponent(int j, vtkDataArray *from, - int fromComponent) +void vtkDataArray::CopyComponent(int dstComponent, vtkDataArray *src, + int srcComponent) { - if (this->GetNumberOfTuples() != from->GetNumberOfTuples()) + if (this->GetNumberOfTuples() != src->GetNumberOfTuples()) { vtkErrorMacro(<< "Number of tuples in 'from' (" - << from->GetNumberOfTuples() << ") and 'to' (" + << src->GetNumberOfTuples() << ") and 'to' (" << this->GetNumberOfTuples() << ") do not match."); return; } - if (j < 0 || j >= this->GetNumberOfComponents()) + if (dstComponent < 0 || dstComponent >= this->GetNumberOfComponents()) { - vtkErrorMacro(<< "Specified component " << j << " in 'to' array is not in [0, " - << this->GetNumberOfComponents() << ")" ); + vtkErrorMacro(<< "Specified component " << dstComponent + << " in 'to' array is not in [0, " + << this->GetNumberOfComponents() << ")" ); return; } - if (fromComponent < 0 || fromComponent >= from->GetNumberOfComponents()) + if (srcComponent < 0 || srcComponent >= src->GetNumberOfComponents()) { - vtkErrorMacro(<< "Specified component " << fromComponent << " in 'from' array is not in [0, " - << from->GetNumberOfComponents() << ")" ); + vtkErrorMacro(<< "Specified component " << srcComponent + << " in 'from' array is not in [0, " + << src->GetNumberOfComponents() << ")" ); return; } vtkIdType i; for (i = 0; i < this->GetNumberOfTuples(); i++) { - this->SetComponent(i, j, from->GetComponent(i, fromComponent)); + this->SetComponent(i, dstComponent, src->GetComponent(i, srcComponent)); } } @@ -1181,41 +1526,64 @@ void vtkDataArray::ComputeRange(double range[2], int comp) } } +namespace +{ + +// Wrap the DoCompute[Scalar|Vector]Range calls for vtkArrayDispatch: +struct ScalarRangeDispatchWrapper +{ + bool Success; + double *Range; + + ScalarRangeDispatchWrapper(double *range) : Success(false), Range(range) {} + + template + void operator()(ArrayT *array) + { + this->Success = vtkDataArrayPrivate::DoComputeScalarRange(array, + this->Range); + } + +}; + +struct VectorRangeDispatchWrapper +{ + bool Success; + double *Range; + + VectorRangeDispatchWrapper(double *range) : Success(false), Range(range) {} + + template + void operator()(ArrayT *array) + { + this->Success = vtkDataArrayPrivate::DoComputeVectorRange(array, + this->Range); + } + +}; + +} // end anon namespace + //---------------------------------------------------------------------------- bool vtkDataArray::ComputeScalarRange(double* ranges) { - bool computed = false; - switch (this->GetDataType()) - { - vtkDataArrayIteratorMacro(this, - computed = vtkDataArrayPrivate::DoComputeScalarRange( - vtkDABegin, vtkDAEnd, - this->GetNumberOfComponents(), - ranges) - ); - default: - break; - } - return computed; + ScalarRangeDispatchWrapper worker(ranges); + if (!vtkArrayDispatch::Dispatch::Execute(this, worker)) + { + worker(this); + } + return worker.Success; } //----------------------------------------------------------------------------- bool vtkDataArray::ComputeVectorRange(double range[2]) { - bool computed = false; - switch (this->GetDataType()) + VectorRangeDispatchWrapper worker(range); + if (!vtkArrayDispatch::Dispatch::Execute(this, worker)) { - vtkDataArrayIteratorMacro(this, - computed = vtkDataArrayPrivate::DoComputeVectorRange( - vtkDABegin, vtkDAEnd, - this->GetNumberOfComponents(), - range) - ); - default: - break; + worker(this); } - - return computed; + return worker.Success; } //---------------------------------------------------------------------------- @@ -1291,6 +1659,15 @@ double vtkDataArray::GetDataTypeMax(int type) } } +//---------------------------------------------------------------------------- +void vtkDataArray::RemoveLastTuple() +{ + if (this->GetNumberOfTuples() > 0) + { + this->Resize(this->GetNumberOfTuples() - 1); + } +} + //---------------------------------------------------------------------------- void vtkDataArray::PrintSelf(ostream& os, vtkIndent indent) { diff --git a/Common/Core/vtkDataArray.h b/Common/Core/vtkDataArray.h index 74bdc9bed44..c6b4b29aa48 100644 --- a/Common/Core/vtkDataArray.h +++ b/Common/Core/vtkDataArray.h @@ -27,9 +27,7 @@ // data whose components are meaningful when cast to and from double. // // .SECTION See Also -// vtkBitArray vtkCharArray vtkUnsignedCharArray vtkShortArray -// vtkUnsignedShortArray vtkIntArray vtkUnsignedIntArray vtkLongArray -// vtkUnsignedLongArray vtkDoubleArray vtkDoubleArray +// vtkBitArray vtkGenericDataArray #ifndef vtkDataArray_h #define vtkDataArray_h @@ -51,7 +49,7 @@ class VTKCOMMONCORE_EXPORT vtkDataArray : public vtkAbstractArray // Description: // Perform a fast, safe cast from a vtkAbstractArray to a vtkDataArray. - // This method checks if source->GetArrayType() returns DataArrayFastCast + // This method checks if source->GetArrayType() returns DataArray // or a more derived type, and performs a static_cast to return // source as a vtkDataArray pointer. Otherwise, NULL is returned. static vtkDataArray* FastDownCast(vtkAbstractArray *source); @@ -71,129 +69,94 @@ class VTKCOMMONCORE_EXPORT vtkDataArray : public vtkAbstractArray virtual int GetElementComponentSize() { return this->GetDataTypeSize(); } - // Description: - // Set the tuple at the ith location using the jth tuple in the source array. - // This method assumes that the two arrays have the same type - // and structure. Note that range checking and memory allocation is not - // performed; use in conjunction with SetNumberOfTuples() to allocate space. - virtual void SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) = 0; - - // Description: - // Insert the jth tuple in the source array, at ith location in this array. - // Note that memory allocation is performed as necessary to hold the data. - // This pure virtual function is redeclared here to avoid - // declaration hidden warnings. - virtual void InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) = 0; - - // Description: - // Insert the jth tuple in the source array, at the end in this array. - // Note that memory allocation is performed as necessary to hold the data. - // Returns the location at which the data was inserted. - // This pure virtual function is redeclared here to avoid - // declaration hidden warnings. - virtual vtkIdType InsertNextTuple(vtkIdType j, vtkAbstractArray* source) = 0; - - // Description: - // Given a list of point ids, return an array of tuples. - // You must insure that the output array has been previously - // allocated with enough space to hold the data. - virtual void GetTuples(vtkIdList *ptIds, vtkAbstractArray *output); - - // Description: - // Get the tuples for the range of points ids specified - // (i.e., p1->p2 inclusive). You must insure that the output array has - // been previously allocated with enough space to hold the data. + // Reimplemented virtuals (doc strings are inherited from superclass): + virtual void InsertTuple(vtkIdType dstTupleIdx, vtkIdType srcTupleIdx, + vtkAbstractArray* source); + virtual vtkIdType InsertNextTuple(vtkIdType srcTupleIdx, + vtkAbstractArray* source); + virtual void InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, + vtkAbstractArray *source); + virtual void InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, + vtkAbstractArray* source); + virtual void GetTuples(vtkIdList *tupleIds, vtkAbstractArray *output); virtual void GetTuples(vtkIdType p1, vtkIdType p2, vtkAbstractArray *output); - - - // Description: - // Set the ith tuple in this array as the interpolated tuple value, - // given the ptIndices in the source array and associated - // interpolation weights. - // This method assumes that the two arrays are of the same type - // and strcuture. - virtual void InterpolateTuple(vtkIdType i, vtkIdList *ptIndices, - vtkAbstractArray* source, double* weights); - - // Description - // Insert the ith tuple in this array as interpolated from the two values, - // p1 and p2, and an interpolation factor, t. - // The interpolation factor ranges from (0,1), - // with t=0 located at p1. This method assumes that the three arrays are of - // the same type. p1 is value at index id1 in source1, while, p2 is - // value at index id2 in source2. - virtual void InterpolateTuple(vtkIdType i, - vtkIdType id1, vtkAbstractArray* source1, - vtkIdType id2, vtkAbstractArray* source2, double t); + virtual void InterpolateTuple(vtkIdType dstTupleIdx, vtkIdList *ptIndices, + vtkAbstractArray* source, double* weights); + virtual void InterpolateTuple(vtkIdType dstTupleIdx, + vtkIdType srcTupleIdx1, vtkAbstractArray* source1, + vtkIdType srcTupleIdx2, vtkAbstractArray* source2, double t); // Description: - // Get the data tuple at ith location. Return it as a pointer to an array. + // Get the data tuple at tupleIdx. Return it as a pointer to an array. // Note: this method is not thread-safe, and the pointer is only valid // as long as another method invocation to a vtk object is not performed. - virtual double *GetTuple(vtkIdType i) = 0; + virtual double *GetTuple(vtkIdType tupleIdx) = 0; // Description: - // Get the data tuple at ith location by filling in a user-provided array, + // Get the data tuple at tupleIdx by filling in a user-provided array, // Make sure that your array is large enough to hold the NumberOfComponents // amount of data being returned. - virtual void GetTuple(vtkIdType i, double * tuple) = 0; + virtual void GetTuple(vtkIdType tupleIdx, double * tuple) = 0; // Description: // These methods are included as convenience for the wrappers. // GetTuple() and SetTuple() which return/take arrays can not be // used from wrapped languages. These methods can be used instead. - double GetTuple1(vtkIdType i); - double* GetTuple2(vtkIdType i); - double* GetTuple3(vtkIdType i); - double* GetTuple4(vtkIdType i); - double* GetTuple6(vtkIdType i); - double* GetTuple9(vtkIdType i); + double GetTuple1(vtkIdType tupleIdx); + double* GetTuple2(vtkIdType tupleIdx); + double* GetTuple3(vtkIdType tupleIdx); + double* GetTuple4(vtkIdType tupleIdx); + double* GetTuple6(vtkIdType tupleIdx); + double* GetTuple9(vtkIdType tupleIdx); + + virtual void SetTuple(vtkIdType dstTupleIdx, vtkIdType srcTupleIdx, + vtkAbstractArray* source); // Description: - // Set the data tuple at ith location. Note that range checking or + // Set the data tuple at tupleIdx. Note that range checking or // memory allocation is not performed; use this method in conjunction // with SetNumberOfTuples() to allocate space. - virtual void SetTuple(vtkIdType i, const float * tuple) = 0; - virtual void SetTuple(vtkIdType i, const double * tuple) = 0; + virtual void SetTuple(vtkIdType tupleIdx, const float * tuple); + virtual void SetTuple(vtkIdType tupleIdx, const double * tuple); // Description: // These methods are included as convenience for the wrappers. // GetTuple() and SetTuple() which return/take arrays can not be // used from wrapped languages. These methods can be used instead. - void SetTuple1(vtkIdType i, double value); - void SetTuple2(vtkIdType i, double val0, double val1); - void SetTuple3(vtkIdType i, double val0, double val1, double val2); - void SetTuple4(vtkIdType i, double val0, double val1, double val2, + void SetTuple1(vtkIdType tupleIdx, double value); + void SetTuple2(vtkIdType tupleIdx, double val0, double val1); + void SetTuple3(vtkIdType tupleIdx, double val0, double val1, double val2); + void SetTuple4(vtkIdType tupleIdx, double val0, double val1, double val2, double val3); - void SetTuple6(vtkIdType i, double val0, double val1, double val2, + void SetTuple6(vtkIdType tupleIdx, double val0, double val1, double val2, double val3, double val4, double val5); - void SetTuple9(vtkIdType i, double val0, double val1, double val2, + void SetTuple9(vtkIdType tupleIdx, double val0, double val1, double val2, double val3, double val4, double val5, double val6, double val7, double val8); // Description: - // Insert the data tuple at ith location. Note that memory allocation + // Insert the data tuple at tupleIdx. Note that memory allocation // is performed as necessary to hold the data. - virtual void InsertTuple(vtkIdType i, const float * tuple) = 0; - virtual void InsertTuple(vtkIdType i, const double * tuple) = 0; + virtual void InsertTuple(vtkIdType tupleIdx, const float * tuple) = 0; + virtual void InsertTuple(vtkIdType tupleIdx, const double * tuple) = 0; // Description: // These methods are included as convenience for the wrappers. // InsertTuple() which takes arrays can not be // used from wrapped languages. These methods can be used instead. - void InsertTuple1(vtkIdType i, double value); - void InsertTuple2(vtkIdType i, double val0, double val1); - void InsertTuple3(vtkIdType i, double val0, double val1, double val2); - void InsertTuple4(vtkIdType i, double val0, double val1, double val2, + void InsertTuple1(vtkIdType tupleIdx, double value); + void InsertTuple2(vtkIdType tupleIdx, double val0, double val1); + void InsertTuple3(vtkIdType tupleIdx, double val0, double val1, double val2); + void InsertTuple4(vtkIdType tupleIdx, double val0, double val1, double val2, double val3); - void InsertTuple6(vtkIdType i, double val0, double val1, double val2, + void InsertTuple6(vtkIdType tupleIdx, double val0, double val1, double val2, double val3, double val4, double val5); - void InsertTuple9(vtkIdType i, double val0, double val1, double val2, + void InsertTuple9(vtkIdType tupleIdx, double val0, double val1, double val2, double val3, double val4, double val5, double val6, double val7, double val8); // Description: - // Insert the data tuple at the end of the array and return the location at + // Insert the data tuple at the end of the array and return the tuple index at // which the data was inserted. Memory is allocated as necessary to hold // the data. virtual vtkIdType InsertNextTuple(const float * tuple) = 0; @@ -218,27 +181,27 @@ class VTKCOMMONCORE_EXPORT vtkDataArray : public vtkAbstractArray // These methods remove tuples from the data array. They shift data and // resize array, so the data array is still valid after this operation. Note, // this operation is fairly slow. - virtual void RemoveTuple(vtkIdType id) = 0; - virtual void RemoveFirstTuple() = 0; - virtual void RemoveLastTuple() = 0; + virtual void RemoveTuple(vtkIdType tupleIdx) = 0; + virtual void RemoveFirstTuple() { this->RemoveTuple(0); } + virtual void RemoveLastTuple(); // Description: - // Return the data component at the ith tuple and jth component location. - // Note that i is less than NumberOfTuples and j is less than - // NumberOfComponents. - virtual double GetComponent(vtkIdType i, int j); + // Return the data component at the location specified by tupleIdx and + // compIdx. + virtual double GetComponent(vtkIdType tupleIdx, int compIdx); // Description: - // Set the data component at the ith tuple and jth component location. + // Set the data component at the location specified by tupleIdx and compIdx + // to value. // Note that i is less than NumberOfTuples and j is less than // NumberOfComponents. Make sure enough memory has been allocated // (use SetNumberOfTuples() and SetNumberOfComponents()). - virtual void SetComponent(vtkIdType i, int j, double c); + virtual void SetComponent(vtkIdType tupleIdx, int compIdx, double value); // Description: - // Insert the data component at ith tuple and jth component location. + // Insert value at the location specified by tupleIdx and compIdx. // Note that memory allocation is performed as necessary to hold the data. - virtual void InsertComponent(vtkIdType i, int j, double c); + virtual void InsertComponent(vtkIdType tupleIdx, int compIdx, double value); // Description: // Get the data as a double array in the range (tupleMin,tupleMax) and @@ -256,28 +219,38 @@ class VTKCOMMONCORE_EXPORT vtkDataArray : public vtkAbstractArray virtual void DeepCopy(vtkAbstractArray *aa); virtual void DeepCopy(vtkDataArray *da); + // Description: + // Create a shallow copy of other into this, if possible. Shallow copies are + // only possible: + // (a) if both arrays are the same data type + // (b) if both arrays are the same array type (e.g. AOS vs. SOA) + // (c) if both arrays support shallow copies (e.g. vtkBitArray currently + // does not.) + // If a shallow copy is not possible, a deep copy will be performed instead. + virtual void ShallowCopy(vtkDataArray *other); + // Description: // Fill a component of a data array with a specified value. This method // sets the specified component to specified value for all tuples in the // data array. This methods can be used to initialize or reinitialize a // single component of a multi-component array. - virtual void FillComponent(int j, double c); + virtual void FillComponent(int compIdx, double value); // Description: // Copy a component from one data array into a component on this data array. - // This method copies the specified component ("fromComponent") from the - // specified data array ("from") to the specified component ("j") over all - // the tuples in this data array. This method can be used to extract + // This method copies the specified component ("srcComponent") from the + // specified data array ("src") to the specified component ("dstComponent") + // over all the tuples in this data array. This method can be used to extract // a component (column) from one data array and paste that data into // a component on this data array. - virtual void CopyComponent(int j, vtkDataArray *from, - int fromComponent); + virtual void CopyComponent(int dstComponent, vtkDataArray *src, + int srcComponent); // Description: // Get the address of a particular data index. Make sure data is allocated // for the number of items requested. If needed, increase MaxId to mark any // new value ranges as in-use. - virtual void* WriteVoidPointer(vtkIdType id, vtkIdType number) = 0; + virtual void* WriteVoidPointer(vtkIdType valueIdx, vtkIdType numValues) = 0; // Description: // Return the memory in kibibytes (1024 bytes) consumed by this data array. Used to @@ -370,6 +343,7 @@ class VTKCOMMONCORE_EXPORT vtkDataArray : public vtkAbstractArray // VTK_UNSIGNED_LONG, VTK_DOUBLE, VTK_DOUBLE, VTK_ID_TYPE. // Note that the data array returned has be deleted by the // user. + VTK_NEWINSTANCE static vtkDataArray* CreateDataArray(int dataType); // Description: @@ -440,16 +414,23 @@ class VTKCOMMONCORE_EXPORT vtkDataArray : public vtkAbstractArray //------------------------------------------------------------------------------ inline vtkDataArray* vtkDataArray::FastDownCast(vtkAbstractArray *source) { - switch (source->GetArrayType()) + if (source) { - case DataArrayTemplate: - case TypedDataArray: - case DataArray: - case MappedDataArray: - return static_cast(source); - default: - return NULL; + switch (source->GetArrayType()) + { + case AoSDataArrayTemplate: + case SoADataArrayTemplate: + case TypedDataArray: + case DataArray: + case MappedDataArray: + return static_cast(source); + default: + break; + } } + return NULL; } +vtkArrayDownCast_FastCastMacro(vtkDataArray) + #endif diff --git a/Common/Core/vtkDataArrayAccessor.h b/Common/Core/vtkDataArrayAccessor.h new file mode 100644 index 00000000000..191613c6943 --- /dev/null +++ b/Common/Core/vtkDataArrayAccessor.h @@ -0,0 +1,178 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkDataArrayAccessor.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +// .NAME vtkDataArrayAccessor - Efficient templated access to vtkDataArray. +// +// .SECTION Description +// vtkDataArrayAccessor provides access to data stored in a vtkDataArray. It +// is intended to be used in conjunction with vtkArrayDispatcher. +// +// A more detailed description of this class and related tools can be found +// \ref VTK-7-1-ArrayDispatch "here". +// +// The goal of this helper template is to allow developers to write a single +// templated worker function that will generates code to use the efficient typed +// APIs provided by vtkGenericDataArray when the array type is known, but +// fallback to the slower vtkDataArray virtual double API if needed. +// +// This can be used to reduce template-explosion issues by restricting the +// vtkArrayDispatch call to only dispatch a few common cases/array types, and +// route all other arrays through a slower implementation using vtkDataArray's +// API. With vtkDataArrayAccessor, a single templated worker function can be +// used to generate both. +// +// Note that while this interface provides both component-wise and tuple access, +// the tuple methods are discouraged as they are significantly slower due to +// copying, and prevent many advanced compiler optimizations that are possible +// when using the component accessors. +// +// A standard usage pattern of this class would be: +// +// @code +// // vtkArrayDispatch worker struct: +// struct Worker +// { +// // Templated worker function: +// template +// void operator()(ArrayT *array) +// { +// // The accessor: +// vtkDataArrayAccessor accessor(array); +// // The data type used by ArrayT's API, use this for +// // temporary/intermediate results: +// typedef typename vtkDataArrayAccessor::APIType APIType; +// +// // Do work using accessor to set/get values.... +// } +// }; +// +// // Usage: +// Worker worker; +// vtkDataArray *array = ...; +// if (!vtkArrayDispatch::Dispatch::Execute(array, worker)) +// { +// // Dispatch failed: unknown array type. Fallback to vtkDataArray API: +// worker(array); +// } +// @endcode +// +// We define Worker::operator() as the templated worker function, restricting +// all data accesses to go through the 'accessor' object (methods like +// GetNumberOfTuples, GetNumberOfComponents, etc should be called on the array +// itself). +// +// This worker is passed into an array dispatcher, which tests 'array' to see +// if it can figure out the array subclass. If it does, Worker is instantiated +// with ArrayT set to the array's subclass, resulting in efficient code. If +// Dispatch::Execute returns false (meaning the array type is not recognized), +// the worker is executed using the vtkDataArray pointer. While slower, this +// ensures that less-common cases will still be handled -- all from one worker +// function template. +// +// .SEE ALSO +// vtkArrayDispatch + +#include "vtkDataArray.h" +#include "vtkGenericDataArray.h" + +#ifndef vtkDataArrayAccessor_h +#define vtkDataArrayAccessor_h + +// Generic form for all (non-bit) vtkDataArray subclasses. +template +struct vtkDataArrayAccessor +{ + typedef ArrayT ArrayType; + typedef typename ArrayType::ValueType APIType; + + ArrayType *Array; + + vtkDataArrayAccessor(ArrayType *array) : Array(array) {} + + inline APIType Get(vtkIdType tupleIdx, int compIdx) const + { + return this->Array->GetTypedComponent(tupleIdx, compIdx); + } + + inline void Set(vtkIdType tupleIdx, int compIdx, APIType val) const + { + this->Array->SetTypedComponent(tupleIdx, compIdx, val); + } + + inline void Insert(vtkIdType tupleIdx, int compIdx, APIType val) const + { + this->Array->InsertTypedComponent(tupleIdx, compIdx, val); + } + + inline void Get(vtkIdType tupleIdx, APIType *tuple) const + { + this->Array->GetTypedTuple(tupleIdx, tuple); + } + + inline void Set(vtkIdType tupleIdx, const APIType *tuple) const + { + this->Array->SetTypedTuple(tupleIdx, tuple); + } + + inline void Insert(vtkIdType tupleIdx, const APIType *tuple) const + { + this->Array->InsertTypedTuple(tupleIdx, tuple); + } +}; + +// Specialization for vtkDataArray. +template <> +struct vtkDataArrayAccessor +{ + typedef vtkDataArray ArrayType; + typedef double APIType; + + ArrayType *Array; + + vtkDataArrayAccessor(ArrayType *array) : Array(array) {} + + inline APIType Get(vtkIdType tupleIdx, int compIdx) const + { + return this->Array->GetComponent(tupleIdx, compIdx); + } + + inline void Set(vtkIdType tupleIdx, int compIdx, APIType val) const + { + this->Array->SetComponent(tupleIdx, compIdx, val); + } + + inline void Insert(vtkIdType tupleIdx, int compIdx, APIType val) const + { + this->Array->InsertComponent(tupleIdx, compIdx, val); + } + + inline void Get(vtkIdType tupleIdx, APIType *tuple) const + { + this->Array->GetTuple(tupleIdx, tuple); + } + + inline void Set(vtkIdType tupleIdx, const APIType *tuple) const + { + this->Array->SetTuple(tupleIdx, tuple); + } + + inline void Insert(vtkIdType tupleIdx, const APIType *tuple) const + { + this->Array->InsertTuple(tupleIdx, tuple); + } +}; + +#endif // vtkDataArrayAccessor_h +// VTK-HeaderTest-Exclude: vtkDataArrayAccessor.h diff --git a/Common/Core/vtkDataArrayCollection.h b/Common/Core/vtkDataArrayCollection.h index 6d9b141b2c4..4cee3808aac 100644 --- a/Common/Core/vtkDataArrayCollection.h +++ b/Common/Core/vtkDataArrayCollection.h @@ -48,13 +48,11 @@ class VTKCOMMONCORE_EXPORT vtkDataArrayCollection : public vtkCollection vtkDataArray *GetItem(int i) { return static_cast(this->GetItemAsObject(i));}; - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkDataArray *GetNextDataArray(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkDataArrayCollection() {} diff --git a/Common/Core/vtkDataArrayIteratorMacro.h b/Common/Core/vtkDataArrayIteratorMacro.h index 58b1946276e..7c4638bf93f 100644 --- a/Common/Core/vtkDataArrayIteratorMacro.h +++ b/Common/Core/vtkDataArrayIteratorMacro.h @@ -16,6 +16,11 @@ // vtkDataArray data when the array implementation and type are unknown. // // .SECTION Description +// +// NOTE: This macro is deprecated and should not be used any longer. Use +// vtkArrayDispatch and the vtkGenericDataArray API instead of +// vtkDataArrayIteratorMacro and vtkTypedDataArrayIterator. +// // See vtkTemplateMacro. // This macro is similar, but defines several additional typedefs and variables // for safely iterating through data in a vtkAbstractArray container: @@ -36,14 +41,14 @@ // as vtkFloatArray. // // For the standard vtkDataArray implementations (which are subclasses of -// vtkDataArrayTemplate), the iterators will simply be pointers to the raw +// vtkAOSDataArrayTemplate), the iterators will simply be pointers to the raw // memory of the array. // This allows very fast iteration when possible, and permits compiler // optimizations in the standard template library to occur (such as reducing // std::copy to memmove). // -// For arrays that are subclasses of vtkTypedDataArray (but not -// vtkDataArrayTemplate), a vtkTypedDataArrayIterator is used. +// For arrays that are subclasses of vtkTypedDataArray, a +// vtkTypedDataArrayIterator is used. // Such iterators safely traverse the array using API calls and have // pointer-like semantics, but add about a 35% performance overhead compared // with iterating over the raw memory (measured by summing a vtkFloatArray @@ -71,13 +76,15 @@ // } // // .SECTION See Also +// vtkArrayDispatch vtkGenericDataArray // vtkTemplateMacro vtkTypedDataArrayIterator #ifndef vtkDataArrayIteratorMacro_h #define vtkDataArrayIteratorMacro_h -#include "vtkDataArrayTemplate.h" // For all classes referred to in the macro +#include "vtkAOSDataArrayTemplate.h" // For classes referred to in the macro #include "vtkSetGet.h" // For vtkTemplateMacro +#include "vtkTypedDataArray.h" // For classes referred to in the macro // Silence 'unused typedef' warnings on GCC. // use of the typedef in question depends on the macro @@ -91,11 +98,11 @@ #define vtkDataArrayIteratorMacro(_array, _call) \ vtkTemplateMacro( \ vtkAbstractArray *_aa(_array); \ - if (vtkDataArrayTemplate *_dat = \ - vtkDataArrayTemplate::FastDownCast(_aa)) \ + if (vtkAOSDataArrayTemplate *_dat = \ + vtkAOSDataArrayTemplate::FastDownCast(_aa)) \ { \ typedef VTK_TT vtkDAValueType; \ - typedef vtkDataArrayTemplate vtkDAContainerType; \ + typedef vtkAOSDataArrayTemplate vtkDAContainerType; \ typedef vtkDAContainerType::Iterator vtkDAIteratorType; \ vtkDAIteratorType vtkDABegin(_dat->Begin()); \ vtkDAIteratorType vtkDAEnd(_dat->End()); \ diff --git a/Common/Core/vtkDataArrayPrivate.txx b/Common/Core/vtkDataArrayPrivate.txx index 283ae475e70..f72860e1106 100644 --- a/Common/Core/vtkDataArrayPrivate.txx +++ b/Common/Core/vtkDataArrayPrivate.txx @@ -15,14 +15,16 @@ #ifndef vtkDataArrayPrivate_txx #define vtkDataArrayPrivate_txx - +#include "vtkAssume.h" +#include "vtkDataArray.h" +#include "vtkDataArrayAccessor.h" #include "vtkTypeTraits.h" #include #include // for assert() namespace vtkDataArrayPrivate { -#if defined(_MSC_VER) && ( _MSC_VER < 1900 ) +#if defined(_MSC_VER) && ( _MSC_VER < 2000 ) namespace msvc { //---------------------------------------------------------------------------- @@ -34,6 +36,9 @@ namespace msvc // and also handles the cases where the right value may be a NaN properly. // All code using these methods should ensure that the "left" value is never // NaN. +// We use _MSC_VER < 2000 instead of 1900 not due to performance issues, but +// because MSVC 2015 (_MSC_VER=1900) doesn't handle NaNs properly in optimized +// builds. template ValueType max(const ValueType& left, const ValueType& right) { @@ -50,7 +55,7 @@ ValueType min(const ValueType& left, const ValueType& right) namespace detail { -#if defined(_MSC_VER) && ( _MSC_VER < 1900 ) +#if defined(_MSC_VER) && ( _MSC_VER < 2000 ) using msvc::min; using msvc::max; #else @@ -60,27 +65,33 @@ using std::max; } //---------------------------------------------------------------------------- -template +template struct ComputeScalarRange { - template - bool operator()(InputIteratorType begin, InputIteratorType end, - double* ranges) + template + bool operator()(ArrayT *array, double *ranges) { - ValueType tempRange[RangeSize]; + VTK_ASSUME(array->GetNumberOfComponents() == NumComps); + + vtkDataArrayAccessor access(array); + APIType tempRange[RangeSize]; + for(int i = 0, j = 0; i < NumComps; ++i, j+=2) { - tempRange[j] = vtkTypeTraits::Max(); - tempRange[j+1] = vtkTypeTraits::Min(); + tempRange[j] = vtkTypeTraits::Max(); + tempRange[j+1] = vtkTypeTraits::Min(); } //compute the range for each component of the data array at the same time - for(InputIteratorType value = begin; value != end; value+=NumComps) + const int numTuples = array->GetNumberOfTuples(); + for(vtkIdType tupleIdx = 0; tupleIdx < numTuples; ++tupleIdx) { - for(int i = 0, j = 0; i < NumComps; ++i, j+=2) + for(int compIdx = 0, j = 0; compIdx < NumComps; ++compIdx, j+=2) { - tempRange[j] = detail::min(tempRange[j], value[i]); - tempRange[j+1] = detail::max(tempRange[j+1], value[i]); + tempRange[j] = detail::min(tempRange[j], + access.Get(tupleIdx, compIdx)); + tempRange[j+1] = detail::max(tempRange[j+1], + access.Get(tupleIdx, compIdx)); } } @@ -95,10 +106,15 @@ struct ComputeScalarRange }; //---------------------------------------------------------------------------- -template -bool DoComputeScalarRange(InputIteratorType begin, InputIteratorType end, - const int numComp, double* ranges) +template +bool DoComputeScalarRange(ArrayT *array, double *ranges) { + vtkDataArrayAccessor access(array); + typedef typename vtkDataArrayAccessor::APIType APIType; + + const int numTuples = array->GetNumberOfTuples(); + const int numComp = array->GetNumberOfComponents(); + //setup the initial ranges to be the max,min for double for (int i = 0, j = 0; i < numComp; ++i, j+=2) { @@ -107,70 +123,68 @@ bool DoComputeScalarRange(InputIteratorType begin, InputIteratorType end, } //do this after we make sure range is max to min - if (begin == end) + if (numTuples == 0) { return false; } - //verify that length of the array is divisible by the number of components - //this will make sure we don't walk off the end - assert((end-begin) % numComp == 0); - //Special case for single value scalar range. This is done to help the //compiler detect it can perform loop optimizations. if (numComp == 1) { - return ComputeScalarRange()(begin, end, ranges); + return ComputeScalarRange()(array, ranges); } else if (numComp == 2) { - return ComputeScalarRange()(begin, end, ranges); + return ComputeScalarRange()(array, ranges); } else if (numComp == 3) { - return ComputeScalarRange()(begin, end, ranges); + return ComputeScalarRange()(array, ranges); } else if (numComp == 4) { - return ComputeScalarRange()(begin, end, ranges); + return ComputeScalarRange()(array, ranges); } else if (numComp == 5) { - return ComputeScalarRange()(begin, end, ranges); + return ComputeScalarRange()(array, ranges); } else if (numComp == 6) { - return ComputeScalarRange()(begin, end, ranges); + return ComputeScalarRange()(array, ranges); } else if (numComp == 7) { - return ComputeScalarRange()(begin, end, ranges); + return ComputeScalarRange()(array, ranges); } else if (numComp == 8) { - return ComputeScalarRange()(begin, end, ranges); + return ComputeScalarRange()(array, ranges); } else if (numComp == 9) { - return ComputeScalarRange()(begin, end, ranges); + return ComputeScalarRange()(array, ranges); } else { //initialize the temp range storage to min/max pairs - ValueType* tempRange = new ValueType[numComp*2]; + APIType* tempRange = new APIType[numComp*2]; for (int i = 0, j = 0; i < numComp; ++i, j+=2) { - tempRange[j] = vtkTypeTraits::Max(); - tempRange[j+1] = vtkTypeTraits::Min(); + tempRange[j] = vtkTypeTraits::Max(); + tempRange[j+1] = vtkTypeTraits::Min(); } //compute the range for each component of the data array at the same time - for (InputIteratorType value = begin; value != end; value+=numComp) + for (vtkIdType tupleIdx = 0; tupleIdx < numTuples; ++tupleIdx) { - for(int i = 0, j = 0; i < numComp; ++i, j+=2) + for(int compIdx = 0, j = 0; compIdx < numComp; ++compIdx, j+=2) { - tempRange[j] = detail::min(tempRange[j], value[i]); - tempRange[j+1] = detail::max(tempRange[j+1], value[i]); + tempRange[j] = detail::min(tempRange[j], + access.Get(tupleIdx, compIdx)); + tempRange[j+1] = detail::max(tempRange[j+1], + access.Get(tupleIdx, compIdx)); } } @@ -189,30 +203,30 @@ bool DoComputeScalarRange(InputIteratorType begin, InputIteratorType end, } //---------------------------------------------------------------------------- -template -bool DoComputeVectorRange(InputIteratorType begin, InputIteratorType end, - int numComp, double range[2]) +template +bool DoComputeVectorRange(ArrayT *array, double range[2]) { + vtkDataArrayAccessor access(array); + + const int numTuples = array->GetNumberOfTuples(); + const int numComps = array->GetNumberOfComponents(); + range[0] = vtkTypeTraits::Max(); range[1] = vtkTypeTraits::Min(); //do this after we make sure range is max to min - if (begin == end) + if (numTuples == 0) { return false; } - //verify that length of the array is divisible by the number of components - //this will make sure we don't walk off the end - assert((end-begin) % numComp == 0); - //iterate over all the tuples - for (InputIteratorType value = begin; value != end; value+=numComp) + for (vtkIdType tupleIdx = 0; tupleIdx < numTuples; ++tupleIdx) { double squaredSum = 0.0; - for (int i = 0; i < numComp; ++i) + for (int compIdx = 0; compIdx < numComps; ++compIdx) { - const double t = static_cast(value[i]); + const double t = static_cast(access.Get(tupleIdx, compIdx)); squaredSum += t * t; } range[0] = detail::min(range[0], squaredSum); @@ -227,6 +241,6 @@ bool DoComputeVectorRange(InputIteratorType begin, InputIteratorType end, return true; } -} +} // end namespace vtkDataArrayPrivate #endif // VTK-HeaderTest-Exclude: vtkDataArrayPrivate.txx diff --git a/Common/Core/vtkDataArraySelection.h b/Common/Core/vtkDataArraySelection.h index 71d3987401b..216504e5d34 100644 --- a/Common/Core/vtkDataArraySelection.h +++ b/Common/Core/vtkDataArraySelection.h @@ -95,7 +95,6 @@ class VTKCOMMONCORE_EXPORT vtkDataArraySelection : public vtkObject // Remove all array entries. void RemoveAllArrays(); - //BTX // Description: // Add to the list of arrays that have entries. For arrays that // already have entries, the settings are untouched. For arrays @@ -124,7 +123,6 @@ class VTKCOMMONCORE_EXPORT vtkDataArraySelection : public vtkObject void SetArrays(const char* const* names, int numArrays); void SetArraysWithDefault(const char* const* names, int numArrays, int defaultStatus); - //ETX // Description: // Copy the selections from the given vtkDataArraySelection instance. diff --git a/Common/Core/vtkDataArrayTemplate.h b/Common/Core/vtkDataArrayTemplate.h index 664b7bca875..1c52db74fc3 100644 --- a/Common/Core/vtkDataArrayTemplate.h +++ b/Common/Core/vtkDataArrayTemplate.h @@ -12,415 +12,40 @@ PURPOSE. See the above copyright notice for more information. =========================================================================*/ -// .NAME vtkDataArrayTemplate - Implementation template for vtkDataArray. +// .NAME vtkDataArrayTemplate // .SECTION Description -// There is a vtkDataArray subclass for each native type supported by -// VTK. This template is used to implement all the subclasses in the -// same way while avoiding code duplication. +// vtkDataArrayTemplate is deprecated, use vtkAOSDataArrayTemplate instead. #ifndef vtkDataArrayTemplate_h #define vtkDataArrayTemplate_h -#include "vtkCommonCoreModule.h" // For export macro -#include "vtkAbstractArray.h" // For delete method enums -#include "vtkTypedDataArray.h" -#include "vtkTypeTemplate.h" // For templated vtkObject API -#include // for assert() +#include "vtkAOSDataArrayTemplate.h" -template -class vtkDataArrayTemplateLookup; +#ifndef VTK_LEGACY_REMOVE -template -class VTKCOMMONCORE_EXPORT vtkDataArrayTemplate: - public vtkTypeTemplate, vtkTypedDataArray > +template +class vtkDataArrayTemplate : public vtkAOSDataArrayTemplate { public: - typedef vtkTypedDataArray Superclass; - typedef typename Superclass::ValueType ValueType; - friend class vtkDataArrayTemplateHelper; + vtkTemplateTypeMacro(vtkDataArrayTemplate, + vtkAOSDataArrayTemplate) - void PrintSelf(ostream& os, vtkIndent indent); - - // Description: - // Typedef to a suitable iterator class. - // Rather than using this member directly, consider using - // vtkDataArrayIteratorMacro for safety and efficiency. - typedef ValueType* Iterator; - - // Description: - // Return an iterator initialized to the first element of the data. - // Rather than using this member directly, consider using - // vtkDataArrayIteratorMacro for safety and efficiency. - Iterator Begin() { return Iterator(this->GetVoidPointer(0)); } - - // Description: - // Return an iterator initialized to first element past the end of the data. - // Rather than using this member directly, consider using - // vtkDataArrayIteratorMacro for safety and efficiency. - Iterator End() { return Iterator(this->GetVoidPointer(this->MaxId + 1)); } - - // Description: - // Perform a fast, safe cast from a vtkAbstractArray to a - // vtkDataArrayTemplate. - // This method checks if: - // - source->GetArrayType() is appropriate, and - // - source->GetDataType() matches vtkTypeTraits::VTK_TYPE_ID - // if these conditions are met, the method performs a static_cast to return - // source as a vtkTypedDataArray pointer. Otherwise, NULL is returned. - static vtkDataArrayTemplate* FastDownCast(vtkAbstractArray *src); - - // Description: - // Allocate memory for this array. Delete old storage only if necessary. - // Note that ext is no longer used. - int Allocate(vtkIdType sz, vtkIdType ext=1000); - - // Description: - // Release storage and reset array to initial state. - void Initialize(); - - // Description: - // Return the size of the data type. - int GetDataTypeSize() { return static_cast(sizeof(T)); } - - // Description: - // Set the number of n-tuples in the array. - void SetNumberOfTuples(vtkIdType number); - - // Description: - // Set the tuple at the ith location using the jth tuple in the source array. - // This method assumes that the two arrays have the same type - // and structure. Note that range checking and memory allocation is not - // performed; use in conjunction with SetNumberOfTuples() to allocate space. - virtual void SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source); - - // Description: - // Insert the jth tuple in the source array, at ith location in this array. - // Note that memory allocation is performed as necessary to hold the data. - virtual void InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source); - - // Description: - // Copy the tuples indexed in srcIds from the source array to the tuple - // locations indexed by dstIds in this array. - // Note that memory allocation is performed as necessary to hold the data. - virtual void InsertTuples(vtkIdList *destIds, vtkIdList *srcIds, - vtkAbstractArray *source); - - // Description: - // Copy n consecutive tuples starting at srcStart from the source array to - // this array, starting at the dstStart location. - // Note that memory allocation is performed as necessary to hold the data. - virtual void InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, - vtkAbstractArray* source); - - // Description: - // Insert the jth tuple in the source array, at the end in this array. - // Note that memory allocation is performed as necessary to hold the data. - // Returns the location at which the data was inserted. - virtual vtkIdType InsertNextTuple(vtkIdType j, vtkAbstractArray* source); - - // Description: - // Get a pointer to a tuple at the ith location. This is a dangerous method - // (it is not thread safe since a pointer is returned). - double* GetTuple(vtkIdType i); - - // Description: - // Copy the tuple value into a user-provided array. - void GetTuple(vtkIdType i, double* tuple); - void GetTupleValue(vtkIdType i, T* tuple); - - // Description: - // Set the tuple value at the ith location in the array. - void SetTuple(vtkIdType i, const float* tuple); - void SetTuple(vtkIdType i, const double* tuple); - void SetTupleValue(vtkIdType i, const T* tuple); - - // Description: - // Insert (memory allocation performed) the tuple into the ith location - // in the array. - void InsertTuple(vtkIdType i, const float* tuple); - void InsertTuple(vtkIdType i, const double* tuple); - void InsertTupleValue(vtkIdType i, const T* tuple); - - // Description: - // Insert (memory allocation performed) the tuple onto the end of the array. - vtkIdType InsertNextTuple(const float* tuple); - vtkIdType InsertNextTuple(const double* tuple); - vtkIdType InsertNextTupleValue(const T* tuple); - - // Description: - // Get the range of array values for the given component in the - // native data type. - void GetValueRange(T range[2], int comp) - { - double doubleRange[2]; - this->ComputeRange(doubleRange, comp); - range[0] = static_cast(doubleRange[0]); - range[1] = static_cast(doubleRange[1]); - } - T *GetValueRange(int comp) - { - this->GetValueRange(this->ValueRange, comp); - return this->ValueRange; - } - - // Description: - // Get the range of array values for the 0th component in the - // native data type. - T *GetValueRange() - { return this->GetValueRange(0); } - void GetValueRange(T range[2]) - { this->GetValueRange(range, 0); } - - // Description: - // Resize object to just fit data requirement. Reclaims extra memory. - void Squeeze() { this->ResizeAndExtend (this->MaxId+1); } - - // Description: - // Return the capacity in typeof T units of the current array. - vtkIdType Capacity() { return this->Size; } - - // Description: - // Resize the array while conserving the data. - // Caution: No assumption can be made on the resulting size of the DataArray, - // meaning that the provided argument won't necessary be equal to - // the data array size, but at least the size will be bigger. - virtual int Resize(vtkIdType numTuples); - - // Description: - // Get the data at a particular index. - T GetValue(vtkIdType id) - { assert(id >= 0 && id < this->Size); return this->Array[id]; } - T& GetValueReference(vtkIdType id) - { assert(id >= 0 && id < this->Size); return this->Array[id]; } - - // Description: - // Set the data at a particular index. Does not do range checking. Make sure - // you use the method SetNumberOfValues() before inserting data. - void SetValue(vtkIdType id, T value) - { assert(id >= 0 && id < this->Size); this->Array[id] = value;}; - - // Description: - // Specify the number of values for this object to hold. Does an - // allocation as well as setting the MaxId ivar. Used in conjunction with - // SetValue() method for fast insertion. - void SetNumberOfValues(vtkIdType number); - - // Description: - // Insert data at a specified position in the array. - void InsertValue(vtkIdType id, T f); - - // Description: - // Set a value in the array from a vtkVariant. - void SetVariantValue(vtkIdType id, vtkVariant value); - - // Description: - // Insert a value in the array from a vtkVariant. - void InsertVariantValue(vtkIdType id, vtkVariant value); - - // Description: - // Insert data at the end of the array. Return its location in the array. - vtkIdType InsertNextValue(T f); - - // Description: - // These methods remove tuples from the data array. They shift data and - // resize array, so the data array is still valid after this operation. Note, - // this operation is fairly slow. - virtual void RemoveTuple(vtkIdType id); - virtual void RemoveFirstTuple(); - virtual void RemoveLastTuple(); - - // Description: - // Return the data component at the ith tuple and jth component location. - // Note that i is less then NumberOfTuples and j is less then - // NumberOfComponents. - double GetComponent(vtkIdType i, int j); - - // Description: - // Set the data component at the ith tuple and jth component location. - // Note that i is less then NumberOfTuples and j is less then - // NumberOfComponents. Make sure enough memory has been allocated - // (use SetNumberOfTuples() and SetNumberOfComponents()). - void SetComponent(vtkIdType i, int j, double c); - - // Description: - // Insert the data component at ith tuple and jth component location. - // Note that memory allocation is performed as necessary to hold the data. - virtual void InsertComponent(vtkIdType i, int j, double c); - - // Description: - // Get the address of a particular data index. Make sure data is allocated - // for the number of items requested. Set MaxId according to the number of - // data values requested. - T* WritePointer(vtkIdType id, vtkIdType number); - virtual void* WriteVoidPointer(vtkIdType id, vtkIdType number) - { return this->WritePointer(id, number); } - - // Description: - // Get the address of a particular data index. Performs no checks - // to verify that the memory has been allocated etc. - // If the data is simply being iterated over, consider using - // vtkDataArrayIteratorMacro for safety and efficiency, rather than using this - // member directly. - T* GetPointer(vtkIdType id) { return this->Array + id; } - virtual void* GetVoidPointer(vtkIdType id) { return this->GetPointer(id); } - - // Description: - // This method lets the user specify data to be held by the array. The - // array argument is a pointer to the data. size is the size of the - // array supplied by the user. Set save to 1 to keep the class from - // deleting the array when it cleans up or reallocates memory. The class - // uses the actual array provided; it does not copy the data from the - // suppled array. If specified, the delete method determines how the data - // array will be deallocated. If the delete method is - // VTK_DATA_ARRAY_FREE, free() will be used. If the delete method is - // DELETE, delete[] will be used. The default is FREE. - void SetArray(T* array, vtkIdType size, int save, int deleteMethod); - void SetArray(T* array, vtkIdType size, int save) - { this->SetArray(array, size, save, vtkAbstractArray::VTK_DATA_ARRAY_FREE); } - virtual void SetVoidArray(void* array, vtkIdType size, int save) - { this->SetArray(static_cast(array), size, save); } - virtual void SetVoidArray(void* array, vtkIdType size, int save, - int deleteMethod) - { - this->SetArray(static_cast(array), size, save, deleteMethod); - } - - // Description: - // This method copies the array data to the void pointer specified - // by the user. It is up to the user to allocate enough memory for - // the void pointer. - virtual void ExportToVoidPointer(void *out_ptr); - - // Description: - // Returns a vtkArrayIteratorTemplate. - virtual vtkArrayIterator* NewIterator(); - - // Description: - // Return the indices where a specific value appears. - virtual vtkIdType LookupValue(vtkVariant value); - virtual void LookupValue(vtkVariant value, vtkIdList* ids); - vtkIdType LookupValue(T value); - void LookupValue(T value, vtkIdList* ids); - vtkIdType LookupTypedValue(T value) - { return this->LookupValue(value); } - void LookupTypedValue(T value, vtkIdList* ids) - { this->LookupValue(value, ids); } - - // Description: - // Tell the array explicitly that the data has changed. - // This is only necessary to call when you modify the array contents - // without using the array's API (i.e. you retrieve a pointer to the - // data and modify the array contents). You need to call this so that - // the fast lookup will know to rebuild itself. Otherwise, the lookup - // functions will give incorrect results. - virtual void DataChanged(); - - // Description: - // Tell the array explicitly that a single data element has - // changed. Like DataChanged(), then is only necessary when you - // modify the array contents without using the array's API. - virtual void DataElementChanged(vtkIdType id); - - // Description: - // Delete the associated fast lookup data structure on this array, - // if it exists. The lookup will be rebuilt on the next call to a lookup - // function. - virtual void ClearLookup(); - - // Description: - // Method for type-checking in FastDownCast implementations. - virtual int GetArrayType() { return vtkAbstractArray::DataArrayTemplate; } + static vtkDataArrayTemplate* New() + { + VTK_STANDARD_NEW_BODY(vtkDataArrayTemplate); + } protected: - vtkDataArrayTemplate(); - ~vtkDataArrayTemplate(); - - T* Array; // pointer to data - T ValueRange[2]; // range of the data - T* ResizeAndExtend(vtkIdType sz); // function to resize data - T* Realloc(vtkIdType sz); + vtkDataArrayTemplate() {} + ~vtkDataArrayTemplate() {} - int TupleSize; //used for data conversion - double* Tuple; - - int SaveUserArray; - int DeleteMethod; - - virtual bool ComputeScalarRange(double* ranges); - virtual bool ComputeVectorRange(double range[2]); private: - vtkDataArrayTemplate(const vtkDataArrayTemplate&); // Not implemented. - void operator=(const vtkDataArrayTemplate&); // Not implemented. - - vtkDataArrayTemplateLookup* Lookup; - bool RebuildLookup; - void UpdateLookup(); - - void DeleteArray(); + vtkDataArrayTemplate(const vtkDataArrayTemplate&); // Not implemented. + void operator=(const vtkDataArrayTemplate&); // Not implemented. }; -#define VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(T) \ - template class VTKCOMMONCORE_EXPORT vtkDataArrayTemplate< T > - -// This macro is used by the subclasses to create dummy -// declarations for these functions such that the wrapper -// can see them. The wrappers ignore vtkDataArrayTemplate. -#define vtkCreateWrappedArrayInterface(T) \ - int GetDataType(); \ - void GetTupleValue(vtkIdType i, T* tuple); \ - void SetTupleValue(vtkIdType i, const T* tuple); \ - void InsertTupleValue(vtkIdType i, const T* tuple); \ - vtkIdType InsertNextTupleValue(const T* tuple); \ - T GetValue(vtkIdType id); \ - void SetValue(vtkIdType id, T value); \ - void SetNumberOfValues(vtkIdType number); \ - void InsertValue(vtkIdType id, T f); \ - vtkIdType InsertNextValue(T f); \ - T *GetValueRange(int comp); \ - T *GetValueRange(); \ - T* WritePointer(vtkIdType id, vtkIdType number); \ - T* GetPointer(vtkIdType id)/*; \ - - * These methods are not wrapped to avoid wrappers exposing these - * easy-to-get-wrong methods because passing in the wrong value for 'save' is - * guaranteed to cause a memory issue down the line. Either the wrappers - * didn't use malloc to allocate the memory or the memory isn't actually - * persisted because a temporary array is used that doesn't persist like this - * method expects. - - void SetArray(T* array, vtkIdType size, int save); \ - void SetArray(T* array, vtkIdType size, int save, int deleteMethod) */ - -#endif // !defined(vtkDataArrayTemplate_h) - -// This portion must be OUTSIDE the include blockers. Each -// vtkDataArray subclass uses this to give its instantiation of this -// template a DLL interface. -#if defined(VTK_DATA_ARRAY_TEMPLATE_TYPE) -# if defined(VTK_BUILD_SHARED_LIBS) && defined(_MSC_VER) -# pragma warning (push) -# pragma warning (disable: 4091) // warning C4091: 'extern ' : - // ignored on left of 'int' when no variable is declared -# pragma warning (disable: 4231) // Compiler-specific extension warning. +#endif // VTK_LEGACY_REMOVE - // We need to disable warning 4910 and do an extern dllexport - // anyway. When deriving vtkCharArray and other types from an - // instantiation of this template the compiler does an explicit - // instantiation of the base class. From outside the vtkCommon - // library we block this using an extern dllimport instantiation. - // For classes inside vtkCommon we should be able to just do an - // extern instantiation, but VS 2008 complains about missing - // definitions. We cannot do an extern dllimport inside vtkCommon - // since the symbols are local to the dll. An extern dllexport - // seems to be the only way to convince VS 2008 to do the right - // thing, so we just disable the warning. -# pragma warning (disable: 4910) // extern and dllexport incompatible +#endif // vtkDataArrayTemplate_h - // Use an "extern explicit instantiation" to give the class a DLL - // interface. This is a compiler-specific extension. - extern VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(VTK_DATA_ARRAY_TEMPLATE_TYPE); -# pragma warning (pop) -# endif -# undef VTK_DATA_ARRAY_TEMPLATE_TYPE -#endif // VTK-HeaderTest-Exclude: vtkDataArrayTemplate.h diff --git a/Common/Core/vtkDataArrayTemplate.txx b/Common/Core/vtkDataArrayTemplate.txx deleted file mode 100644 index 73f4d534348..00000000000 --- a/Common/Core/vtkDataArrayTemplate.txx +++ /dev/null @@ -1,1278 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkDataArrayTemplate.txx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#ifndef vtkDataArrayTemplate_txx -#define vtkDataArrayTemplate_txx - -#include "vtkDataArrayTemplate.h" -#include "vtkDataArrayPrivate.txx" - -#include "vtkArrayIteratorTemplate.h" -#include "vtkDataArrayTemplateHelper.h" -#include "vtkIdList.h" -#include "vtkInformation.h" -#include "vtkInformationDoubleVectorKey.h" -#include "vtkInformationInformationVectorKey.h" -#include "vtkInformationVector.h" -#include "vtkMappedDataArray.h" -#include "vtkSortDataArray.h" -#include "vtkTypeTraits.h" -#include "vtkVariantCast.h" - -#include -#include -#include -#include -#include - -// We do not provide a definition for the copy constructor or -// operator=. Block the warning. -#ifdef _MSC_VER -# pragma warning (disable: 4661) -#endif - -//---------------------------------------------------------------------------- -template -class vtkDataArrayTemplateLookup -{ -public: - vtkDataArrayTemplateLookup() - { - this->SortedArray = NULL; - this->IndexArray = NULL; - } - ~vtkDataArrayTemplateLookup() - { - if (this->SortedArray) - { - this->SortedArray->Delete(); - this->SortedArray = NULL; - } - if (this->IndexArray) - { - this->IndexArray->Delete(); - this->IndexArray = NULL; - } - } - vtkAbstractArray* SortedArray; - vtkIdList* IndexArray; - std::multimap CachedUpdates; -}; - -//---------------------------------------------------------------------------- -template -vtkDataArrayTemplate::vtkDataArrayTemplate() -{ - this->Array = 0; - this->ValueRange[0] = 0; - this->ValueRange[1] = 1; - this->TupleSize = 0; - this->Tuple = 0; - this->SaveUserArray = 0; - this->DeleteMethod = vtkAbstractArray::VTK_DATA_ARRAY_FREE; - this->Lookup = 0; - this->RebuildLookup = true; -} - -//---------------------------------------------------------------------------- -template -vtkDataArrayTemplate::~vtkDataArrayTemplate() -{ - this->DeleteArray(); - free(this->Tuple); - delete this->Lookup; -} - -//---------------------------------------------------------------------------- -// This method lets the user specify data to be held by the array. The -// array argument is a pointer to the data. size is the size of -// the array supplied by the user. Set save to 1 to keep the class -// from deleting the array when it cleans up or reallocates memory. -// The class uses the actual array provided; it does not copy the data -// from the suppled array. -template -void vtkDataArrayTemplate::SetArray(T* array, - vtkIdType size, - int save, - int deleteMethod) -{ - this->DeleteArray(); - - vtkDebugMacro(<<"Setting array to: " << static_cast(array)); - - this->Array = array; - this->Size = size; - this->MaxId = size-1; - this->SaveUserArray = save; - this->DeleteMethod = deleteMethod; - this->DataChanged(); -} - -//---------------------------------------------------------------------------- -// Allocate memory for this array. Delete old storage only if necessary. -template -int vtkDataArrayTemplate::Allocate(vtkIdType sz, vtkIdType) -{ - this->MaxId = -1; - - if(sz > this->Size) - { - this->DeleteArray(); - - this->Size = 0; - - vtkIdType newSize = (sz > 0 ? sz : 1); - this->Array = static_cast(malloc(static_cast(newSize) - * sizeof(T))); - if(this->Array==0) - { - vtkErrorMacro("Unable to allocate " << newSize - << " elements of size " << sizeof(T) - << " bytes. "); - #if !defined NDEBUG - // We're debugging, crash here preserving the stack - abort(); - #elif !defined VTK_DONT_THROW_BAD_ALLOC - // We can throw something that has universal meaning - throw std::bad_alloc(); - #else - // We indicate that malloc failed by return - return 0; - #endif - } - this->Size = newSize; - } - this->DataChanged(); - - return 1; -} - -//---------------------------------------------------------------------------- -// Release storage and reset array to initial state. -template -void vtkDataArrayTemplate::Initialize() -{ - this->DeleteArray(); - this->Array = 0; - this->Size = 0; - this->MaxId = -1; - this->DataChanged(); -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os,indent); - vtkOStreamWrapper osw(os); - if(this->Array) - { - osw << indent << "Array: " << static_cast(this->Array) << "\n"; - } - else - { - osw << indent << "Array: (null)\n"; - } -} - -//---------------------------------------------------------------------------- -template vtkDataArrayTemplate * -vtkDataArrayTemplate::FastDownCast(vtkAbstractArray *src) -{ - if ((src->GetArrayType() == vtkAbstractArray::DataArrayTemplate) && - (src->GetDataType() == vtkTypeTraits::VTK_TYPE_ID)) - { - return static_cast*>(src); - } - else - { - return NULL; - } -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::DeleteArray() -{ - if ((this->Array) && (!this->SaveUserArray)) - { - if (this->DeleteMethod == vtkAbstractArray::VTK_DATA_ARRAY_FREE) - { - free(this->Array); - } - else - { - delete[] this->Array; - } - } - this->SaveUserArray = 0; - this->DeleteMethod = vtkAbstractArray::VTK_DATA_ARRAY_FREE; - this->Array = 0; -} - -//---------------------------------------------------------------------------- -template -T* vtkDataArrayTemplate::ResizeAndExtend(vtkIdType sz) -{ - T* newArray; - vtkIdType newSize; - - if(sz > this->Size) - { - // Requested size is bigger than current size. Allocate enough - // memory to fit the requested size and be more than double the - // currently allocated memory. - newSize = this->Size + sz; - } - else if (sz == this->Size) - { - // Requested size is equal to current size. Do nothing. - return this->Array; - } - else - { - // Requested size is smaller than current size. Squeeze the - // memory. - newSize = sz; - this->DataChanged(); - } - - // Wipe out the array completely if new size is zero. - if(newSize <= 0) - { - this->Initialize(); - return 0; - } - - // OS X's realloc does not free memory if the new block is smaller. This - // is a very serious problem and causes huge amount of memory to be - // wasted. Do not use realloc on the Mac. - bool dontUseRealloc=false; - #if defined __APPLE__ - dontUseRealloc=true; - #endif - - // Allocate the new array or reallocate the old. - if (this->Array - && - (this->SaveUserArray - || this->DeleteMethod==vtkAbstractArray::VTK_DATA_ARRAY_DELETE - || dontUseRealloc )) - { - newArray = static_cast(malloc(static_cast(newSize)*sizeof(T))); - if(!newArray) - { - vtkErrorMacro("Unable to allocate " << newSize - << " elements of size " << sizeof(T) - << " bytes. "); - #if !defined NDEBUG - // We're debugging, crash here preserving the stack - abort(); - #elif !defined VTK_DONT_THROW_BAD_ALLOC - // We can throw something that has universal meaning - throw std::bad_alloc(); - #else - // We indicate that malloc failed by return - return 0; - #endif - } - // Copy the data from the old array. - memcpy(newArray, this->Array, - static_cast(newSize < this->Size ? newSize : this->Size) - * sizeof(T)); - - // Realease old array if we own - this->DeleteArray(); - } - else - { - // Try to reallocate with minimal memory usage and possibly avoid - // copying. - newArray = static_cast( - realloc(this->Array,static_cast(newSize)*sizeof(T))); - if(!newArray) - { - vtkErrorMacro("Unable to allocate " << newSize - << " elements of size " << sizeof(T) - << " bytes. "); - #if !defined NDEBUG - // We're debugging, crash here preserving the stack - abort(); - #elif !defined VTK_DONT_THROW_BAD_ALLOC - // We can throw something that has universal meaning - throw std::bad_alloc(); - #else - // We indicate that malloc failed by return - return 0; - #endif - } - } - - // Allocation was successful. Save it. - if((newSize-1) < this->MaxId) - { - this->MaxId = newSize-1; - } - this->Size = newSize; - this->Array = newArray; - - return this->Array; -} - -//---------------------------------------------------------------------------- -template -int vtkDataArrayTemplate::Resize(vtkIdType sz) -{ - this->DataChanged(); - T *newArray = this->ResizeAndExtend(sz*this->NumberOfComponents); - if( newArray!=0 || sz <= 0) - { - return 1; - } - else - { - return 0; - } -} - -//---------------------------------------------------------------------------- -// Set the number of n-tuples in the array. -template -void vtkDataArrayTemplate::SetNumberOfTuples(vtkIdType number) -{ - this->SetNumberOfValues(number*this->NumberOfComponents); -} - -//---------------------------------------------------------------------------- -// Set the tuple at the ith location using the jth tuple in the source array. -// This method assumes that the two arrays have the same type -// and structure. Note that range checking and memory allocation is not -// performed; use in conjunction with SetNumberOfTuples() to allocate space. -template -void vtkDataArrayTemplate::SetTuple(vtkIdType i, vtkIdType j, - vtkAbstractArray* source) -{ - if (!vtkDataTypesCompare(source->GetDataType(), this->GetDataType())) - { - vtkWarningMacro("Input and output array data types do not match."); - return; - } - if (this->NumberOfComponents != source->GetNumberOfComponents()) - { - vtkWarningMacro("Input and output component sizes do not match."); - return; - } - - vtkIdType loci = i * this->NumberOfComponents; - vtkIdType locj = j * source->GetNumberOfComponents(); - - T* data = static_cast(source->GetVoidPointer(0)); - - for (vtkIdType cur = 0; cur < this->NumberOfComponents; cur++) - { - this->Array[loci + cur] = data[locj + cur]; - } - this->DataChanged(); -} - -//---------------------------------------------------------------------------- -// Insert the jth tuple in the source array, at ith location in this array. -// Note that memory allocation is performed as necessary to hold the data. -template -void vtkDataArrayTemplate::InsertTuple(vtkIdType i, vtkIdType j, - vtkAbstractArray* source) -{ - if (!vtkDataTypesCompare(source->GetDataType(), this->GetDataType())) - { - vtkWarningMacro("Input and output array data types do not match."); - return; - } - int inNumComp = source->GetNumberOfComponents(); - if (this->NumberOfComponents != inNumComp) - { - vtkWarningMacro("Input and output component sizes do not match."); - return; - } - - vtkIdType locOut = i * inNumComp; - vtkIdType maxSize = locOut + inNumComp; - if (maxSize > this->Size) - { - if (this->ResizeAndExtend(maxSize)==0) - { - return; - } - } - - // Copy directly into our array if the source has supporting API: - if (vtkTypedDataArray *typedSource = - vtkTypedDataArray::FastDownCast(source)) - { - typedSource->GetTupleValue(j, this->GetPointer(locOut)); - } - else if (vtkDataArray *dataSource = vtkDataArray::FastDownCast(source)) - { - // Otherwise use the double interface - this->SetTuple(i, dataSource->GetTuple(j)); - } - else - { - vtkWarningMacro("Input array is not a vtkDataArray subclass!"); - return; - } - - vtkIdType maxId = maxSize-1; - if ( maxId > this->MaxId ) - { - this->MaxId = maxId; - } - - this->DataChanged(); -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, - vtkAbstractArray *source) -{ - if (!vtkDataTypesCompare(source->GetDataType(), this->GetDataType())) - { - vtkWarningMacro("Input and output array data types do not match."); - return; - } - - if (this->NumberOfComponents != source->GetNumberOfComponents()) - { - vtkWarningMacro("Input and output component sizes do not match."); - return; - } - - vtkIdType numIds = dstIds->GetNumberOfIds(); - if (srcIds->GetNumberOfIds() != numIds) - { - vtkWarningMacro("Input and output id array sizes do not match."); - return; - } - - // Find maximum destination id and resize if needed - vtkIdType maxDstId = 0; - for (vtkIdType idIndex = 0; idIndex < numIds; ++idIndex) - { - maxDstId = std::max(maxDstId, dstIds->GetId(idIndex)); - } - - vtkIdType maxSize = (maxDstId + 1) * this->NumberOfComponents; - if (maxSize > this->Size) - { - if (this->ResizeAndExtend(maxSize) == 0) - { - vtkWarningMacro("Failed to allocate memory."); - return; - } - } - - // Copy directly into our array if the source has supporting API: - if (vtkTypedDataArray *typedSource = - vtkTypedDataArray::FastDownCast(source)) - { - for (vtkIdType idIndex = 0; idIndex < numIds; ++idIndex) - { - typedSource->GetTupleValue(srcIds->GetId(idIndex), - this->GetPointer(dstIds->GetId(idIndex) - * this->NumberOfComponents)); - } - } - else if (vtkDataArray *dataSource = vtkDataArray::FastDownCast(source)) - { - // Otherwise use the double interface - for (vtkIdType idIndex = 0; idIndex < numIds; ++idIndex) - { - this->SetTuple(dstIds->GetId(idIndex), - dataSource->GetTuple(srcIds->GetId(idIndex))); - } - } - else - { - vtkWarningMacro("Input array is not a vtkDataArray subclass!"); - return; - } - - vtkIdType maxId = maxSize - 1; - if (maxId > this->MaxId) - { - this->MaxId = maxId; - } - - this->DataChanged(); -} - -//------------------------------------------------------------------------------ -template -void vtkDataArrayTemplate::InsertTuples(vtkIdType dstStart, vtkIdType n, - vtkIdType srcStart, - vtkAbstractArray *source) -{ - if (n == 0) - { - return; - } - - if (!vtkDataTypesCompare(source->GetDataType(), this->GetDataType())) - { - vtkWarningMacro("Input and output array data types do not match."); - return; - } - - if (this->NumberOfComponents != source->GetNumberOfComponents()) - { - vtkWarningMacro("Input and output component sizes do not match."); - return; - } - - vtkDataArrayTemplateHelper::InsertTuples(this, dstStart, n, srcStart, source); -} - -//---------------------------------------------------------------------------- -// Insert the jth tuple in the source array, at the end in this array. -// Note that memory allocation is performed as necessary to hold the data. -// Returns the location at which the data was inserted. -template -vtkIdType vtkDataArrayTemplate::InsertNextTuple(vtkIdType j, - vtkAbstractArray* source) -{ - if (!vtkDataTypesCompare(source->GetDataType(), this->GetDataType())) - { - vtkWarningMacro("Input and output array data types do not match."); - return -1; - } - vtkIdType numComps = source->GetNumberOfComponents(); - if (this->NumberOfComponents != numComps) - { - vtkWarningMacro("Input and output component sizes do not match."); - return -1; - } - - // If this and source are the same, we need to make sure that - // the array grows before we get the pointer. Growing the array - // after getting the pointer may make it invalid. - - // Copy directly into our array if the source has supporting API: - if (vtkTypedDataArray *typedSource = - vtkTypedDataArray::FastDownCast(source)) - { - typedSource->GetTupleValue(j, - this->WritePointer(this->MaxId + 1, numComps)); - } - else if (vtkDataArray *dataSource = vtkDataArray::FastDownCast(source)) - { - // Otherwise use the double interface - T *out = this->WritePointer(this->MaxId + 1, numComps); - double *in = dataSource->GetTuple(j); - - while (numComps-- > 0) - { - *(out++) = static_cast(*(in++)); - } - } - else - { - vtkWarningMacro("Input array is not a vtkDataArray subclass!"); - return -1; - } - - return this->GetNumberOfTuples() - 1; -} - -//---------------------------------------------------------------------------- -// Get a pointer to a tuple at the ith location. This is a dangerous method -// (it is not thread safe since a pointer is returned). -template -double* vtkDataArrayTemplate::GetTuple(vtkIdType i) -{ -#if 1 - // Allocate a larger tuple buffer if needed. - if(this->TupleSize < this->NumberOfComponents) - { - this->TupleSize = this->NumberOfComponents; - free(this->Tuple); - size_t s=static_cast(this->TupleSize); - this->Tuple = static_cast(malloc(s*sizeof(double))); - } - - // Make sure tuple allocation succeeded. - if(!this->Tuple) - { - vtkErrorMacro("Unable to allocate " << this->TupleSize - << " elements of size " << sizeof(double) - << " bytes. "); - #if !defined NDEBUG - // We're debugging, crash here preserving the stack - abort(); - #elif !defined VTK_DONT_THROW_BAD_ALLOC - // We can throw something that has universal meaning - throw std::bad_alloc(); - #else - // We indicate that malloc failed by return - return 0; - #endif - } - - // Copy the data into the tuple. - T* t = this->Array + this->NumberOfComponents*i; - for(int j=0; j < this->NumberOfComponents; ++j) - { - this->Tuple[j] = static_cast(t[j]); - } - return this->Tuple; -#else - // Use this version along with purify or valgrind to detect code - // that saves the pointer returned by GetTuple. By always - // allocating a new tuple and freeing the old one code that keeps - // the pointer will do invalid reads or writes. - double* newTuple; - newTuple = (double*)malloc(this->NumberOfComponents * sizeof(double)); - if(!newTuple) - { - vtkErrorMacro("Unable to allocate " << this->NumberOfComponents - << " elements of size " << sizeof(double) - << " bytes. "); - #if !defined NDEBUG - // We're debugging, crash here preserving the stack - abort(); - #elif !defined VTK_DONT_THROW_BAD_ALLOC - // We can throw something that has universal meaning - throw std::bad_alloc(); - #else - // We indicate that malloc failed by return - return 0; - #endif - } - - // Copy the data into the new tuple. - T* t = this->Array + this->NumberOfComponents*i; - for(int j=0; j < this->NumberOfComponents; ++j) - { - newTuple[j] = static_cast(t[j]); - } - - // Replace the old tuple with the new one. - free(this->Tuple); - this->Tuple = newTuple; - return this->Tuple; -#endif -} - -//---------------------------------------------------------------------------- -// Copy the tuple value into a user-provided array. -template -void vtkDataArrayTemplate::GetTuple(vtkIdType i, double* tuple) -{ - T* t = this->Array + this->NumberOfComponents*i; - for(int j=0; j < this->NumberOfComponents; ++j) - { - tuple[j] = static_cast(t[j]); - } -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::GetTupleValue(vtkIdType i, T* tuple) -{ - T* t = this->Array + this->NumberOfComponents*i; - for(int j=0; j < this->NumberOfComponents; ++j) - { - tuple[j] = t[j]; - } -} - -//---------------------------------------------------------------------------- -// Set the tuple value at the ith location in the array. -template -void vtkDataArrayTemplate::SetTuple(vtkIdType i, const float* tuple) -{ - vtkIdType loc = i * this->NumberOfComponents; - for(int j=0; j < this->NumberOfComponents; ++j) - { - this->Array[loc+j] = static_cast(tuple[j]); - } - this->DataChanged(); -} - -template -void vtkDataArrayTemplate::SetTuple(vtkIdType i, const double* tuple) -{ - vtkIdType loc = i * this->NumberOfComponents; - for(int j=0; j < this->NumberOfComponents; ++j) - { - this->Array[loc+j] = static_cast(tuple[j]); - } - this->DataChanged(); -} - -template -void vtkDataArrayTemplate::SetTupleValue(vtkIdType i, const T* tuple) -{ - vtkIdType loc = i * this->NumberOfComponents; - for(int j=0; j < this->NumberOfComponents; ++j) - { - this->Array[loc+j] = tuple[j]; - } - this->DataChanged(); -} - -//---------------------------------------------------------------------------- -// Insert (memory allocation performed) the tuple into the ith location -// in the array. -template -void vtkDataArrayTemplate::InsertTuple(vtkIdType i, const float* tuple) -{ - T* t = this->WritePointer(i*this->NumberOfComponents, - this->NumberOfComponents); - if (t==0) - { - return; - } - - for(int j=0; j < this->NumberOfComponents; ++j) - { - *t++ = static_cast(*tuple++); - } - this->DataChanged(); -} - -template -void vtkDataArrayTemplate::InsertTuple(vtkIdType i, const double* tuple) -{ - T* t = this->WritePointer(i*this->NumberOfComponents, - this->NumberOfComponents); - if (t==0) - { - return; - } - - for(int j=0; j < this->NumberOfComponents; ++j) - { - *t++ = static_cast(*tuple++); - } - this->DataChanged(); -} - -template -void vtkDataArrayTemplate::InsertTupleValue(vtkIdType i, const T* tuple) -{ - T* t = this->WritePointer(i*this->NumberOfComponents, - this->NumberOfComponents); - if (t==0) - { - return; - } - - for(int j=0; j < this->NumberOfComponents; ++j) - { - *t++ = *tuple++; - } - this->DataChanged(); -} - -//---------------------------------------------------------------------------- -// Insert (memory allocation performed) the tuple onto the end of the array. -template -vtkIdType vtkDataArrayTemplate::InsertNextTuple(const float* tuple) -{ - T* t = this->WritePointer(this->MaxId + 1, this->NumberOfComponents); - if (t==0) - { - return -1; - } - - for(int j=0; j < this->NumberOfComponents; ++j) - { - *t++ = static_cast(*tuple++); - } - - this->DataChanged(); - return this->MaxId / this->NumberOfComponents; -} - -template -vtkIdType vtkDataArrayTemplate::InsertNextTuple(const double* tuple) -{ - T* t = this->WritePointer(this->MaxId + 1,this->NumberOfComponents); - if (t==0) - { - return -1; - } - - for(int j=0; j < this->NumberOfComponents; ++j) - { - *t++ = static_cast(*tuple++); - } - - this->DataChanged(); - return this->MaxId / this->NumberOfComponents; -} - -template -vtkIdType vtkDataArrayTemplate::InsertNextTupleValue(const T* tuple) -{ - T* t = this->WritePointer(this->MaxId + 1,this->NumberOfComponents); - if (t==0) - { - return -1; - } - - for(int j=0; j < this->NumberOfComponents; ++j) - { - *t++ = *tuple++; - } - - this->DataChanged(); - return this->MaxId / this->NumberOfComponents; -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::RemoveTuple(vtkIdType id) -{ - if ( id < 0 || id >= this->GetNumberOfTuples()) - { - // Nothing to be done - return; - } - if ( id == this->GetNumberOfTuples() - 1 ) - { - // To remove last item, just decrease the size by one - this->RemoveLastTuple(); - return; - } - // Remove the element by moving those after it over by one. We must - // use memmove instead of memcpy because the memory areas overlap. - vtkIdType len = (this->GetNumberOfTuples() - id) - 1; - len *= this->GetNumberOfComponents(); - vtkIdType from = (id+1) * this->GetNumberOfComponents(); - vtkIdType to = id * this->GetNumberOfComponents(); - memmove(this->Array + to, this->Array + from, - static_cast(len) * sizeof(T)); - this->Resize(this->GetNumberOfTuples() - 1); - this->DataChanged(); -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::RemoveFirstTuple() -{ - this->RemoveTuple(0); - this->DataChanged(); -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::RemoveLastTuple() -{ - this->Resize(this->GetNumberOfTuples()- 1); - this->DataChanged(); -} - -//---------------------------------------------------------------------------- -// Return the data component at the ith tuple and jth component location. -// Note that i -double vtkDataArrayTemplate::GetComponent(vtkIdType i, int j) -{ - return static_cast(this->GetValue(i*this->NumberOfComponents + j)); -} - -//---------------------------------------------------------------------------- -// Set the data component at the ith tuple and jth component location. -// Note that i -void vtkDataArrayTemplate::SetComponent(vtkIdType i, int j, - double c) -{ - this->SetValue(i*this->NumberOfComponents + j, static_cast(c)); -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::InsertComponent(vtkIdType i, int j, - double c) -{ - this->InsertValue(i*this->NumberOfComponents + j, static_cast(c)); -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::SetNumberOfValues(vtkIdType number) -{ - if (this->Allocate(number)) - { - this->MaxId = number - 1; - } -} - -//---------------------------------------------------------------------------- -template -T* vtkDataArrayTemplate::WritePointer(vtkIdType id, - vtkIdType number) -{ - vtkIdType newSize=id+number; - if ( newSize > this->Size ) - { - if (this->ResizeAndExtend(newSize)==0) - { - return 0; - } - } - if ( (--newSize) > this->MaxId ) - { - this->MaxId = newSize; - } - this->DataChanged(); - return this->Array + id; -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::InsertValue(vtkIdType id, T f) -{ - if ( id >= this->Size ) - { - if (this->ResizeAndExtend(id+1)==0) - { - return; - } - } - this->Array[id] = f; - if ( id > this->MaxId ) - { - this->MaxId = id; - } - this->DataElementChanged(id); -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::SetVariantValue(vtkIdType id, vtkVariant value) -{ - bool valid; - T toInsert = vtkVariantCast(value, &valid); - if (valid) - { - this->SetValue(id, toInsert); - } - else - { - vtkErrorMacro("unable to set value of type " << value.GetType()); - } -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::InsertVariantValue(vtkIdType id, vtkVariant value) -{ - bool valid; - T toInsert = vtkVariantCast(value, &valid); - if (valid) - { - this->InsertValue(id, toInsert); - } - else - { - vtkErrorMacro("unable to set value of type " << value.GetType()); - } -} - -//---------------------------------------------------------------------------- -template -vtkIdType vtkDataArrayTemplate::InsertNextValue(T f) -{ - this->InsertValue (++this->MaxId,f); - return this->MaxId; -} - -//---------------------------------------------------------------------------- -template -bool vtkDataArrayTemplate::ComputeScalarRange(double* ranges) -{ - const T* begin = this->Array; - const T* end = this->Array+this->MaxId+1; - const int numComp = this->NumberOfComponents; - - return vtkDataArrayPrivate::DoComputeScalarRange(begin,end, - numComp,ranges); -} - -//---------------------------------------------------------------------------- -template -bool vtkDataArrayTemplate::ComputeVectorRange(double range[2]) -{ - const T* begin = this->Array; - const T* end = this->Array+this->MaxId+1; - const int numComp = this->NumberOfComponents; - - return vtkDataArrayPrivate::DoComputeVectorRange(begin,end, - numComp,range); -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::ExportToVoidPointer(void *out_ptr) -{ - if(out_ptr && this->Array) - { - memcpy(static_cast(out_ptr), this->Array, - static_cast(this->MaxId + 1)*sizeof(T)); - } -} - -//---------------------------------------------------------------------------- -template -vtkArrayIterator* vtkDataArrayTemplate::NewIterator() -{ - vtkArrayIteratorTemplate* iter = vtkArrayIteratorTemplate::New(); - iter->Initialize(this); - return iter; -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::UpdateLookup() -{ - if (!this->Lookup) - { - this->Lookup = new vtkDataArrayTemplateLookup(); - this->Lookup->SortedArray = vtkAbstractArray::CreateArray(this->GetDataType()); - this->Lookup->IndexArray = vtkIdList::New(); - this->RebuildLookup = true; - } - if (this->RebuildLookup) - { - int numComps = this->GetNumberOfComponents(); - vtkIdType numTuples = this->GetNumberOfTuples(); - this->Lookup->SortedArray->DeepCopy(this); - this->Lookup->IndexArray->SetNumberOfIds(numComps*numTuples); - for (vtkIdType i = 0; i < numComps*numTuples; i++) - { - this->Lookup->IndexArray->SetId(i, i); - } - vtkSortDataArray::Sort(this->Lookup->SortedArray, this->Lookup->IndexArray); - this->Lookup->CachedUpdates.clear(); - this->RebuildLookup = false; - } -} - -//---------------------------------------------------------------------------- -template -vtkIdType vtkDataArrayTemplate::LookupValue(vtkVariant var) -{ - bool valid = true; - T value = vtkVariantCast(var, &valid); - if (valid) - { - return this->LookupValue(value); - } - return -1; -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::LookupValue(vtkVariant var, vtkIdList* ids) -{ - bool valid = true; - T value = vtkVariantCast(var, &valid); - ids->Reset(); - if (valid) - { - this->LookupValue(value, ids); - } -} - -//---------------------------------------------------------------------------- -template -vtkIdType vtkDataArrayTemplate::LookupValue(T value) -{ - this->UpdateLookup(); - - // First look into the cached updates, to see if there were any - // cached changes. Find an equivalent element in the set of cached - // indices for this value. Some of the indices may have changed - // values since the cache was built, so we need to do this equality - // check. - typedef typename std::multimap::iterator CacheIterator; - CacheIterator cached = this->Lookup->CachedUpdates.lower_bound(value), - cachedEnd = this->Lookup->CachedUpdates.end(); - while (cached != cachedEnd) - { - // Check that we are still in the same equivalence class as the - // value. - if (value == cached->first) - { - // Check that the value in the original array hasn't changed. - T currentValue = this->GetValue(cached->second); - if (value == currentValue) - { - return cached->second; - } - } - else - { - break; - } - - ++cached; - } - - // The index array can have size zero even when the - // sorted array is of size 1, due to vtkDataArrayTemplate::DeepCopy's - // refusal to allocate a 0-length array. - if (this->Lookup->IndexArray->GetNumberOfIds() == 0) - { - return -1; - } - - int numComps = this->Lookup->SortedArray->GetNumberOfComponents(); - vtkIdType numTuples = this->Lookup->SortedArray->GetNumberOfTuples(); - T* ptr = static_cast(this->Lookup->SortedArray->GetVoidPointer(0)); - T* ptrEnd = ptr + numComps*numTuples; - T* found = std::lower_bound(ptr, ptrEnd, value); - - // Find an index with a matching value. Non-matching values might - // show up here when the underlying value at that index has been - // changed (so the sorted array is out-of-date). - vtkIdType offset = static_cast(found - ptr); - while (found != ptrEnd) - { - // Check whether we still have a value equivalent to what we're - // looking for. - if (value == *found) - { - // Check that the value in the original array hasn't changed. - vtkIdType index = this->Lookup->IndexArray->GetId(offset); - T currentValue = this->GetValue(index); - if (value == currentValue) - { - return index; - } - } - else - { - break; - } - - ++found; - ++offset; - } - - return -1; -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::LookupValue(T value, vtkIdList* ids) -{ - this->UpdateLookup(); - ids->Reset(); - - // First look into the cached updates, to see if there were any - // cached changes. Find an equivalent element in the set of cached - // indices for this value. Some of the indices may have changed - // values since the cache was built, so we need to do this equality - // check. - typedef typename std::multimap::iterator CacheIterator; - std::pair cached - = this->Lookup->CachedUpdates.equal_range(value); - while (cached.first != cached.second) - { - // Check that the value in the original array hasn't changed. - T currentValue = this->GetValue(cached.first->second); - if (cached.first->first == currentValue) - { - ids->InsertNextId(cached.first->second); - } - - ++cached.first; - } - - // The index array can have size zero even when the - // sorted array is of size 1, due to vtkDataArrayTemplate::DeepCopy's - // refusal to allocate a 0-length array. - if (this->Lookup->IndexArray->GetNumberOfIds() == 0) - { - return; - } - - // Perform a binary search of the sorted array using STL equal_range. - int numComps = this->GetNumberOfComponents(); - vtkIdType numTuples = this->GetNumberOfTuples(); - T* ptr = static_cast(this->Lookup->SortedArray->GetVoidPointer(0)); - std::pair found = - std::equal_range(ptr, ptr + numComps*numTuples, value); - - // Add the indices of the found items to the ID list. - vtkIdType offset = static_cast(found.first - ptr); - while (found.first != found.second) - { - // Check that the value in the original array hasn't changed. - vtkIdType index = this->Lookup->IndexArray->GetId(offset); - T currentValue = this->GetValue(index); - if (*found.first == currentValue) - { - ids->InsertNextId(index); - } - - ++found.first; - ++offset; - } -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::DataChanged() -{ - this->RebuildLookup = true; -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::DataElementChanged(vtkIdType id) -{ - if (!this->RebuildLookup && this->Lookup) - { - if (this->Lookup->CachedUpdates.size() > - static_cast(this->GetNumberOfTuples()/10)) - { - // At this point, just rebuild the full table. - this->RebuildLookup = true; - } - else - { - // Insert this change into the set of cached updates - std::pair - value(this->GetValue(id), id); - this->Lookup->CachedUpdates.insert(value); - } - } -} - -//---------------------------------------------------------------------------- -template -void vtkDataArrayTemplate::ClearLookup() -{ - delete this->Lookup; - this->Lookup = NULL; -} - -#endif diff --git a/Common/Core/vtkDataArrayTemplateHelper.cxx b/Common/Core/vtkDataArrayTemplateHelper.cxx deleted file mode 100644 index 9b3cd5a5abd..00000000000 --- a/Common/Core/vtkDataArrayTemplateHelper.cxx +++ /dev/null @@ -1,90 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkDataArrayTemplateHelper.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#include "vtkDataArrayTemplateHelper.h" - -#include "vtkDataArrayIteratorMacro.h" -#include "vtkDataArrayTemplate.h" - -//------------------------------------------------------------------------------ -void vtkDataArrayTemplateHelper::InsertTuples( - vtkDataArray *dst, vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, - vtkAbstractArray *source) -{ - vtkIdType srcEnd = srcStart + n; - if (srcEnd > source->GetNumberOfTuples()) - { - vtkWarningWithObjectMacro(dst, - "Source range exceeds array size (srcStart=" - << srcStart << ", n=" << n << ", numTuples=" - << source->GetNumberOfTuples() << ")."); - return; - } - - // Find maximum destination id and resize if needed - vtkIdType dstEnd = dstStart + n; - vtkIdType maxSize = dstEnd * dst->GetNumberOfComponents(); - if (maxSize > dst->GetSize()) - { - void *resizeResult(NULL); - switch (dst->GetDataType()) - { - vtkTemplateMacro(resizeResult = - static_cast*>(dst)->ResizeAndExtend(maxSize); - ); - } - if (resizeResult == NULL) - { - vtkWarningWithObjectMacro(dst, "Failed to allocate memory."); - return; - } - } - - // TypedDataArrays and their subclasses have iterator interfaces: - if (source->GetArrayType() == vtkAbstractArray::TypedDataArray) - { - switch (source->GetDataType()) - { - vtkDataArrayIteratorMacro( - source, - std::copy(vtkDABegin + srcStart, vtkDABegin + srcEnd, - static_cast*>(dst) - ->Begin() + dstStart) - ); - } - } - else if (vtkDataArray *dataSource = vtkDataArray::FastDownCast(source)) - { - // Otherwise use the double interface - for (vtkIdType i = 0; i < n; ++i) - { - dst->SetTuple(dstStart + i, dataSource->GetTuple(srcStart + i)); - } - } - else - { - vtkWarningWithObjectMacro(dst, - "Input array is not a vtkDataArray subclass!"); - return; - } - - vtkIdType maxId = maxSize - 1; - if (maxId > dst->MaxId) - { - dst->MaxId = maxId; - } - - dst->DataChanged(); -} diff --git a/Common/Core/vtkDataArrayTemplateHelper.h b/Common/Core/vtkDataArrayTemplateHelper.h deleted file mode 100644 index c6477b6405d..00000000000 --- a/Common/Core/vtkDataArrayTemplateHelper.h +++ /dev/null @@ -1,44 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkDataArrayTemplateHelper.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -// .NAME vtkDataArrayTemplateHelpers - Non-templated implementations for -// vtkDataArrayTemplate. -// .SECTION Description -// This namespace contains algorithms for internal use by vtkDataArrayTemplate. -// Its purpose is it to work around template instantiation issues caused by -// referring to concrete vtkDataArrayTemplate in vtkDataArrayTemplate's -// inlined implementations. -// Methods that cause compiler warnings such as: -// "type attributes ignored after type is already defined [-Wattributes]" -// when declaring DLL interfaces in vtkIntArray.cxx, vtkFloatArray.cxx, etc. -// should go here. - -#include "vtkDataArrayTemplate.h" - -#ifndef vtkDataArrayTemplateHelper_h -#define vtkDataArrayTemplateHelper_h - -class vtkDataArrayTemplateHelper -{ -public: - // Description: - // Helper implementation for vtkDataArrayTemplate::InsertTuples - static void InsertTuples(vtkDataArray *dst, vtkIdType dstStart, vtkIdType n, - vtkIdType srcStart, vtkAbstractArray *source); - -}; - -#endif // vtkDataArrayTemplateHelper_h - -// VTK-HeaderTest-Exclude: vtkDataArrayTemplateHelper.h diff --git a/Common/Core/vtkDebugLeaks.cxx b/Common/Core/vtkDebugLeaks.cxx index 96bd8d753c8..dfabcf53537 100644 --- a/Common/Core/vtkDebugLeaks.cxx +++ b/Common/Core/vtkDebugLeaks.cxx @@ -20,6 +20,10 @@ #include +#if defined(_MSC_VER) && (_MSC_VER < 1900) +#define snprintf _snprintf +#endif + static const char *vtkDebugLeaksIgnoreClasses[] = { 0 }; @@ -28,7 +32,7 @@ static const char *vtkDebugLeaksIgnoreClasses[] = { // return 1 if the class should be ignored static int vtkDebugLeaksIgnoreClassesCheck(const char* s) { - int i =0; + int i = 0; while(vtkDebugLeaksIgnoreClasses[i]) { if(strcmp(s, vtkDebugLeaksIgnoreClasses[i]) == 0) @@ -51,7 +55,7 @@ static inline size_t vtkHashString(const char* s) { h = 5*h + *s; } - return size_t(h); + return static_cast(h); } //---------------------------------------------------------------------------- @@ -60,17 +64,17 @@ class vtkDebugLeaksHashNode public: vtkDebugLeaksHashNode() { - this->Count =1; // if it goes in, then there is one of them + this->Count = 1; // if it goes in, then there is one of them this->Key = 0; - this->Next =0; + this->Next = 0; } void Print(std::string& os) { if(this->Count) { char tmp[256]; - sprintf(tmp,"\" has %i %s still around.\n",this->Count, - (this->Count == 1) ? "instance" : "instances"); + snprintf(tmp, 256, "\" has %i %s still around.\n",this->Count, + (this->Count == 1) ? "instance" : "instances"); os += "Class \""; os += this->Key; os += tmp; @@ -114,8 +118,7 @@ class vtkDebugLeaksHashTable //---------------------------------------------------------------------------- vtkDebugLeaksHashTable::vtkDebugLeaksHashTable() { - int i; - for (i = 0; i < 64; i++) + for (int i = 0; i < 64; i++) { this->Nodes[i] = NULL; } @@ -124,21 +127,17 @@ vtkDebugLeaksHashTable::vtkDebugLeaksHashTable() //---------------------------------------------------------------------------- void vtkDebugLeaksHashTable::IncrementCount(const char * name) { - vtkDebugLeaksHashNode *pos; - vtkDebugLeaksHashNode *newpos; - int loc; - - pos = this->GetNode(name); + vtkDebugLeaksHashNode *pos = this->GetNode(name); if(pos) { pos->Count++; return; } - newpos = new vtkDebugLeaksHashNode; + vtkDebugLeaksHashNode *newpos = new vtkDebugLeaksHashNode; newpos->Key = strcpy(new char[strlen(name)+1], name); - loc = (static_cast(vtkHashString(name)) & 0x03f0) / 16; + unsigned long loc = (static_cast(vtkHashString(name)) & 0x03f0) / 16; pos = this->Nodes[loc]; if (!pos) @@ -156,10 +155,9 @@ void vtkDebugLeaksHashTable::IncrementCount(const char * name) //---------------------------------------------------------------------------- vtkDebugLeaksHashNode* vtkDebugLeaksHashTable::GetNode(const char* key) { - vtkDebugLeaksHashNode *pos; - int loc = (static_cast(vtkHashString(key)) & 0x03f0) / 16; + unsigned long loc = (static_cast(vtkHashString(key)) & 0x03f0) / 16; - pos = this->Nodes[loc]; + vtkDebugLeaksHashNode *pos = this->Nodes[loc]; if (!pos) { @@ -175,10 +173,9 @@ vtkDebugLeaksHashNode* vtkDebugLeaksHashTable::GetNode(const char* key) //---------------------------------------------------------------------------- unsigned int vtkDebugLeaksHashTable::GetCount(const char* key) { - vtkDebugLeaksHashNode *pos; - int loc = (static_cast(vtkHashString(key)) & 0x03f0) / 16; + unsigned long loc = (static_cast(vtkHashString(key)) & 0x03f0) / 16; - pos = this->Nodes[loc]; + vtkDebugLeaksHashNode *pos = this->Nodes[loc]; if (!pos) { @@ -224,7 +221,6 @@ int vtkDebugLeaksHashTable::IsEmpty() //---------------------------------------------------------------------------- int vtkDebugLeaksHashTable::DecrementCount(const char *key) { - vtkDebugLeaksHashNode *pos = this->GetNode(key); if(pos) { @@ -335,6 +331,8 @@ int vtkDebugLeaks::PrintCurrentLeaks() #ifdef VTK_DEBUG_LEAKS if(vtkDebugLeaks::MemoryTable->IsEmpty()) { + // Log something anyway, so users know vtkDebugLeaks is active/working. + cout << "vtkDebugLeaks has found no leaks.\n"; return 0; } diff --git a/Common/Core/vtkDebugLeaks.h b/Common/Core/vtkDebugLeaks.h index 6cf6d2be9c0..9ca55201585 100644 --- a/Common/Core/vtkDebugLeaks.h +++ b/Common/Core/vtkDebugLeaks.h @@ -60,10 +60,9 @@ class VTKCOMMONCORE_EXPORT vtkDebugLeaks : public vtkObject // Default is on when VTK_DEBUG_LEAKS is on and off otherwise. static int GetExitError(); static void SetExitError(int); - //BTX + static void SetDebugLeaksObserver(vtkDebugLeaksObserver* observer); static vtkDebugLeaksObserver* GetDebugLeaksObserver(); - //ETX protected: vtkDebugLeaks(){} @@ -77,10 +76,8 @@ class VTKCOMMONCORE_EXPORT vtkDebugLeaks : public vtkObject static void ConstructingObject(vtkObjectBase* object); static void DestructingObject(vtkObjectBase* object); - //BTX friend class vtkDebugLeaksManager; friend class vtkObjectBase; - //ETX private: static vtkDebugLeaksHashTable* MemoryTable; @@ -92,7 +89,6 @@ class VTKCOMMONCORE_EXPORT vtkDebugLeaks : public vtkObject void operator=(const vtkDebugLeaks&); // Not implemented. }; -//BTX // This class defines callbacks for debugging tools. The callbacks are not for general use. // The objects passed as arguments to the callbacks are in partially constructed or destructed // state and accessing them may cause undefined behavior. @@ -102,7 +98,6 @@ class VTKCOMMONCORE_EXPORT vtkDebugLeaksObserver { virtual void ConstructingObject(vtkObjectBase*) = 0; virtual void DestructingObject(vtkObjectBase*) = 0; }; -//ETX #endif // vtkDebugLeaks_h // VTK-HeaderTest-Exclude: vtkDebugLeaks.h diff --git a/Common/Core/vtkDenseArray.h b/Common/Core/vtkDenseArray.h index 5d8e6e2aacc..fb1081beee4 100644 --- a/Common/Core/vtkDenseArray.h +++ b/Common/Core/vtkDenseArray.h @@ -46,14 +46,13 @@ #include "vtkArrayCoordinates.h" #include "vtkObjectFactory.h" #include "vtkTypedArray.h" -#include "vtkTypeTemplate.h" template -class vtkDenseArray : - public vtkTypeTemplate, vtkTypedArray > +class vtkDenseArray : public vtkTypedArray { public: static vtkDenseArray* New(); + vtkTemplateTypeMacro(vtkDenseArray, vtkTypedArray) void PrintSelf(ostream &os, vtkIndent indent); typedef typename vtkArray::CoordinateT CoordinateT; diff --git a/Common/Core/vtkDoubleArray.cxx b/Common/Core/vtkDoubleArray.cxx index 7bb3db72177..ef91876a4bd 100644 --- a/Common/Core/vtkDoubleArray.cxx +++ b/Common/Core/vtkDoubleArray.cxx @@ -13,13 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(double); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(double); #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(double); -#define vtkDoubleArray_cxx #include "vtkDoubleArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkDoubleArray.h b/Common/Core/vtkDoubleArray.h index a6fab0b6443..342d4e308b7 100644 --- a/Common/Core/vtkDoubleArray.h +++ b/Common/Core/vtkDoubleArray.h @@ -21,36 +21,38 @@ #ifndef vtkDoubleArray_h #define vtkDoubleArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkDoubleArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE double -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkDoubleArray : public vtkDataArray { public: vtkTypeMacro(vtkDoubleArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkDoubleArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(double); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkDoubleArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static double GetDataTypeValueMin() { return VTK_DOUBLE_MIN; } @@ -64,11 +66,15 @@ class VTKCOMMONCORE_EXPORT vtkDoubleArray : public vtkDataArray ~vtkDoubleArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkDoubleArray(const vtkDoubleArray&); // Not implemented. void operator=(const vtkDoubleArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkDoubleArray) + + #endif diff --git a/Common/Core/vtkDynamicLoader.h b/Common/Core/vtkDynamicLoader.h index 26e94d85c15..3ec09747e9b 100644 --- a/Common/Core/vtkDynamicLoader.h +++ b/Common/Core/vtkDynamicLoader.h @@ -26,11 +26,9 @@ #include "vtkObject.h" #include -//BTX typedef vtksys::DynamicLoader::LibraryHandle vtkLibHandle; // Cannot use this as this is a void (*)() but VTK old API used to be void* typedef vtksys::DynamicLoader::SymbolPointer vtkSymbolPointer; -//ETX class VTKCOMMONCORE_EXPORT vtkDynamicLoader : public vtkObject { @@ -38,7 +36,6 @@ class VTKCOMMONCORE_EXPORT vtkDynamicLoader : public vtkObject static vtkDynamicLoader* New(); vtkTypeMacro(vtkDynamicLoader,vtkObject); - //BTX // Description: // Load a dynamic library into the current process. // The returned vtkLibHandle can be used to access the symbols in the @@ -54,7 +51,6 @@ class VTKCOMMONCORE_EXPORT vtkDynamicLoader : public vtkObject // Find the address of the symbol in the given library //static vtkSymbolPointer GetSymbolAddress(vtkLibHandle, const char*); static void* GetSymbolAddress(vtkLibHandle, const char*); - //ETX // Description: // Return the library prefix for the given architecture diff --git a/Common/Core/vtkFloatArray.cxx b/Common/Core/vtkFloatArray.cxx index 90d24e27139..083606609fb 100644 --- a/Common/Core/vtkFloatArray.cxx +++ b/Common/Core/vtkFloatArray.cxx @@ -13,13 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(float); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(float); #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(float); -#define vtkFloatArray_cxx #include "vtkFloatArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkFloatArray.h b/Common/Core/vtkFloatArray.h index 24806692e60..1b876b8c7e6 100644 --- a/Common/Core/vtkFloatArray.h +++ b/Common/Core/vtkFloatArray.h @@ -21,24 +21,19 @@ #ifndef vtkFloatArray_h #define vtkFloatArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkFloatArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE float -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkFloatArray : public vtkDataArray { public: vtkTypeMacro(vtkFloatArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif @@ -46,12 +41,19 @@ class VTKCOMMONCORE_EXPORT vtkFloatArray : public vtkDataArray void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(float); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkFloatArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static float GetDataTypeValueMin() { return VTK_FLOAT_MIN; } @@ -66,11 +68,14 @@ class VTKCOMMONCORE_EXPORT vtkFloatArray : public vtkDataArray ~vtkFloatArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkFloatArray(const vtkFloatArray&); // Not implemented. void operator=(const vtkFloatArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkFloatArray) + #endif diff --git a/Common/Core/vtkGarbageCollector.h b/Common/Core/vtkGarbageCollector.h index 225ebc1d6cd..63528835419 100644 --- a/Common/Core/vtkGarbageCollector.h +++ b/Common/Core/vtkGarbageCollector.h @@ -166,10 +166,8 @@ class VTKCOMMONCORE_EXPORT vtkGarbageCollector : public vtkObject static void ClassInitialize(); static void ClassFinalize(); - //BTX friend class vtkGarbageCollectorManager; friend class vtkObjectBaseToGarbageCollectorFriendship; - //ETX // Internal report callback and friend function that calls it. virtual void Report(vtkObjectBase* obj, void* ptr, const char* desc); @@ -183,7 +181,6 @@ class VTKCOMMONCORE_EXPORT vtkGarbageCollector : public vtkObject void operator=(const vtkGarbageCollector&); // Not implemented. }; -//BTX class vtkSmartPointerBase; // Description: @@ -201,7 +198,6 @@ void vtkGarbageCollectorReport(vtkGarbageCollector* collector, T*& ptr, { vtkGarbageCollectorReportInternal(collector, ptr, &ptr, desc); } -//ETX #endif // VTK-HeaderTest-Exclude: vtkGarbageCollector.h diff --git a/Common/Core/vtkGenericDataArray.h b/Common/Core/vtkGenericDataArray.h new file mode 100644 index 00000000000..e30f81fa506 --- /dev/null +++ b/Common/Core/vtkGenericDataArray.h @@ -0,0 +1,325 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkGenericDataArray.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkGenericDataArray - Base interface for all typed vtkDataArray +// subclasses. +// +// .SECTION Description +// +// A more detailed description of this class and related tools can be found +// \ref VTK-7-1-ArrayDispatch "here". +// +// The vtkGenericDataArray class provides a generic implementation of the +// vtkDataArray API. It relies on subclasses providing access to data +// via 8 "concept methods", which should be implemented as non-virtual +// methods of the subclass. These methods are: +// +// - ValueType GetValue(vtkIdType valueIdx) const +// - [public] void SetValue(vtkIdType valueIdx, ValueType value) +// - [public] void GetTypedTuple(vtkIdType tupleIdx, ValueType* tuple) const +// - [public] void SetTypedTuple(vtkIdType tupleIdx, const ValueType* tuple) +// - [public] ValueType GetTypedComponent(vtkIdType tupleIdx, int compIdx) const +// - [public] void SetTypedComponent(vtkIdType tupleIdx, int compIdx, +// ValueType value) +// - [protected] bool AllocateTuples(vtkIdType numTuples) +// - [protected] bool ReallocateTuples(vtkIdType numTuples) +// +// Note that these methods use the CRTP idiom, which provides static binding to +// avoid virtual calls. This allows the compiler to optimize away layers of +// indirection when these methods are used. Well-designed implementations +// of these methods will reduce to raw memory accesses, providing efficient +// performance comparable to working with the pointer data. +// +// See vtkAOSDataArrayTemplate and vtkSOADataArrayTemplate for example +// implementations. +// +// In practice, code should not be written to use vtkGenericDataArray objects. +// Doing so is rather unweildy due to the CRTP pattern requiring the derived +// class be provided as a template argument. Instead, the vtkArrayDispatch +// framework can be used to detect a vtkDataArray's implementation type and +// instantiate appropriate templated worker code. +// +// vtkArrayDispatch is also intended to replace code that currently relies on +// the encapsulation-breaking GetVoidPointer method. Not all subclasses of +// vtkDataArray use the memory layout assumed by GetVoidPointer; calling this +// method on, e.g. a vtkSOADataArrayTemplate will trigger a deep copy of the +// array data into an AOS buffer. This is very inefficient and should be +// avoided. +// +// .SECTION See Also +// vtkArrayDispatcher vtkDataArrayAccessor + +#ifndef vtkGenericDataArray_h +#define vtkGenericDataArray_h + +#include "vtkDataArray.h" +#include "vtkSmartPointer.h" +#include "vtkTypeTraits.h" +#include "vtkGenericDataArrayLookupHelper.h" + +#include + +template +class vtkGenericDataArray : public vtkDataArray +{ + typedef vtkGenericDataArray SelfType; +public: + typedef ValueTypeT ValueType; + vtkTemplateTypeMacro(SelfType, vtkDataArray) + + // Description: + // Compile time access to the VTK type identifier. + enum { VTK_DATA_TYPE = vtkTypeTraits::VTK_TYPE_ID }; + + /// @defgroup vtkGDAConceptMethods vtkGenericDataArray Concept Methods + /// These signatures must be reimplemented in subclasses as public, + /// non-virtual methods. Ideally, they should be inlined and as efficient as + /// possible to ensure the best performance possible. + + // Description: + // Get the value at @a valueIdx. @a valueIdx assumes AOS ordering. + // @note GetTypedComponent is preferred over this method. It is faster for + // SOA arrays, and shows equivalent performance for AOS arrays when + // NumberOfComponents is known to the compiler (See vtkAssume.h). + // @ingroup vtkGDAConceptMethods + inline ValueType GetValue(vtkIdType valueIdx) const + { + return static_cast(this)->GetValue(valueIdx); + } + + // Description: + // Set the value at @a valueIdx to @a value. @a valueIdx assumes AOS ordering. + // @note SetTypedComponent is preferred over this method. It is faster for + // SOA arrays, and shows equivalent performance for AOS arrays when + // NumberOfComponents is known to the compiler (See vtkAssume.h). + // @ingroup vtkGDAConceptMethods + inline void SetValue(vtkIdType valueIdx, ValueType value) + { + static_cast(this)->SetValue(valueIdx, value); + } + + // Description: + // Copy the tuple at @a tupleIdx into @a tuple. + // @note GetTypedComponent is preferred over this method. The overhead of + // copying the tuple is significant compared to the more performant + // component-wise access methods, which typically optimize to raw memory + // access. + // @ingroup vtkGDAConceptMethods + inline void GetTypedTuple(vtkIdType tupleIdx, ValueType* tuple) const + { + static_cast(this)->GetTypedTuple(tupleIdx, tuple); + } + + // Description: + // Set this array's tuple at @a tupleIdx to the values in @a tuple. + // @note SetTypedComponent is preferred over this method. The overhead of + // copying the tuple is significant compared to the more performant + // component-wise access methods, which typically optimize to raw memory + // access. + // @ingroup vtkGDAConceptMethods + inline void SetTypedTuple(vtkIdType tupleIdx, const ValueType* tuple) + { + static_cast(this)->SetTypedTuple(tupleIdx, tuple); + } + + // Description: + // Get component @a compIdx of the tuple at @a tupleIdx. This is typically + // the fastest way to access array data. + // @ingroup vtkGDAConceptMethods + inline ValueType GetTypedComponent(vtkIdType tupleIdx, int compIdx) const + { + return static_cast(this)->GetTypedComponent(tupleIdx, + compIdx); + } + + // Description: + // Set component @a compIdx of the tuple at @a tupleIdx to @a value. This is + // typically the fastest way to set array data. + // @ingroup vtkGDAConceptMethods + inline void SetTypedComponent(vtkIdType tupleIdx, int compIdx, + ValueType value) + { + static_cast(this)->SetTypedComponent(tupleIdx, compIdx, value); + } + + // Description: + // Default implementation raises a runtime error. If subclasses keep on + // supporting this API, they should override this method. + virtual void *GetVoidPointer(vtkIdType valueIdx); + ValueType* GetPointer(vtkIdType valueIdx); + virtual void SetVoidArray(void*, vtkIdType, int); + virtual void SetVoidArray(void*, vtkIdType, int, int); + virtual void* WriteVoidPointer(vtkIdType valueIdx, vtkIdType numValues); + ValueType* WritePointer(vtkIdType valueIdx, vtkIdType numValues); + + // Description: + // Removes a tuple at the given index. Default implementation + // iterates over tuples to move elements. Subclasses are + // encouraged to reimplemented this method to support faster implementations, + // if needed. + virtual void RemoveTuple(vtkIdType tupleIdx); + + // Description: + // Insert data at the end of the array. Return its location in the array. + vtkIdType InsertNextValue(ValueType value); + + // Description: + // Insert data at a specified position in the array. + void InsertValue(vtkIdType valueIdx, ValueType value); + + // Description: + // Insert (memory allocation performed) the tuple t at tupleIdx. + void InsertTypedTuple(vtkIdType tupleIdx, const ValueType *t); + + // Description: + // Insert (memory allocation performed) the tuple onto the end of the array. + vtkIdType InsertNextTypedTuple(const ValueType *t); + + // Description: + // Insert (memory allocation performed) the value at the specified tuple and + // component location. + void InsertTypedComponent(vtkIdType tupleIdx, int compIdx, ValueType val); + + // Description: + // Get the range of array values for the given component in the + // native data type. + void GetValueRange(ValueType range[2], int comp); + ValueType *GetValueRange(int comp); + + // Description: + // Get the range of array values for the 0th component in the + // native data type. + ValueType *GetValueRange() { return this->GetValueRange(0); } + void GetValueRange(ValueType range[2]) { this->GetValueRange(range, 0); } + + // Description: + // Return the capacity in typeof T units of the current array. + // TODO Leftover from vtkDataArrayTemplate, redundant with GetSize. Deprecate? + vtkIdType Capacity() { return this->Size; } + + virtual int GetDataType(); + virtual int GetDataTypeSize(); + virtual bool HasStandardMemoryLayout(); + virtual int Allocate(vtkIdType size, vtkIdType ext = 1000); + virtual int Resize(vtkIdType numTuples); + virtual void SetNumberOfComponents(int num); + virtual void SetNumberOfTuples(vtkIdType number); + virtual void Initialize(); + virtual void Squeeze(); + virtual void SetTuple(vtkIdType dstTupleIdx, vtkIdType srcTupleIdx, + vtkAbstractArray* source); + // MSVC doesn't like 'using' here (error C2487). Just forward instead: +// using Superclass::SetTuple; + virtual void SetTuple(vtkIdType tupleIdx, const float *tuple) + { this->Superclass::SetTuple(tupleIdx, tuple); } + virtual void SetTuple(vtkIdType tupleIdx, const double *tuple) + { this->Superclass::SetTuple(tupleIdx, tuple); } + + virtual void InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, + vtkAbstractArray *source); + // MSVC doesn't like 'using' here (error C2487). Just forward instead: +// using Superclass::InsertTuples; + virtual void InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, + vtkAbstractArray* source) + { this->Superclass::InsertTuples(dstStart, n, srcStart, source); } + + virtual void InsertTuple(vtkIdType dstTupleIdx, vtkIdType srcTupleIdx, + vtkAbstractArray *source); + virtual void InsertTuple(vtkIdType tupleIdx, const float *source); + virtual void InsertTuple(vtkIdType tupleIdx, const double *source); + virtual void InsertComponent(vtkIdType tupleIdx, int compIdx, double value); + virtual vtkIdType InsertNextTuple(vtkIdType srcTupleIdx, + vtkAbstractArray *source); + virtual vtkIdType InsertNextTuple(const float *tuple); + virtual vtkIdType InsertNextTuple(const double *tuple); + virtual void GetTuples(vtkIdList *tupleIds, vtkAbstractArray *output); + virtual void GetTuples(vtkIdType p1, vtkIdType p2, vtkAbstractArray *output); + virtual double *GetTuple(vtkIdType tupleIdx); + virtual void GetTuple(vtkIdType tupleIdx, double * tuple); + virtual void InterpolateTuple(vtkIdType dstTupleIdx, vtkIdList *ptIndices, + vtkAbstractArray* source, double* weights); + virtual void InterpolateTuple(vtkIdType dstTupleIdx, + vtkIdType srcTupleIdx1, vtkAbstractArray* source1, + vtkIdType srcTupleIdx2, vtkAbstractArray* source2, double t); + virtual void SetComponent(vtkIdType tupleIdx, int compIdx, double value); + virtual double GetComponent(vtkIdType tupleIdx, int compIdx); + virtual void SetVariantValue(vtkIdType valueIdx, vtkVariant value); + virtual vtkVariant GetVariantValue(vtkIdType valueIdx); + virtual void InsertVariantValue(vtkIdType valueIdx, vtkVariant value); + virtual vtkIdType LookupValue(vtkVariant value); + virtual vtkIdType LookupTypedValue(ValueType value); + virtual void LookupValue(vtkVariant value, vtkIdList* valueIds); + virtual void LookupTypedValue(ValueType value, vtkIdList* valueIds); + virtual void ClearLookup(); + virtual void DataChanged(); + virtual VTK_NEWINSTANCE vtkArrayIterator* NewIterator(); + +protected: + vtkGenericDataArray(); + virtual ~vtkGenericDataArray(); + + // Description: + // Allocate space for numTuples. Old data is not preserved. If numTuples == 0, + // all data is freed. + // @ingroup vtkGDAConceptMethods + inline bool AllocateTuples(vtkIdType numTuples) + { + return static_cast(this)->AllocateTuples(numTuples); + } + + // Description: + // Allocate space for numTuples. Old data is preserved. If numTuples == 0, + // all data is freed. + // @ingroup vtkGDAConceptMethods + inline bool ReallocateTuples(vtkIdType numTuples) + { + return static_cast(this)->ReallocateTuples(numTuples); + } + + // This method resizes the array if needed so that the given tuple index is + // valid/accessible. + bool EnsureAccessToTuple(vtkIdType tupleIdx); + + vtkGenericDataArrayLookupHelper Lookup; +private: + vtkGenericDataArray(const vtkGenericDataArray&); // Not implemented. + void operator=(const vtkGenericDataArray&); // Not implemented. + + std::vector LegacyTuple; + std::vector LegacyValueRange; +}; + +#include "vtkGenericDataArray.txx" + +// Adds an implementation of NewInstanceInternal() that returns an AoS +// (unmapped) VTK array, if possible. This allows the pipeline to copy and +// propagate the array when the array data is not modifiable. Use this in +// combination with vtkAbstractTypeMacro or vtkAbstractTemplateTypeMacro +// (instead of vtkTypeMacro) to avoid adding the default NewInstance +// implementation. +#define vtkAOSArrayNewInstanceMacro(thisClass) \ + protected: \ + vtkObjectBase *NewInstanceInternal() const \ + { \ + if (vtkDataArray *da = \ + vtkDataArray::CreateDataArray(thisClass::VTK_DATA_TYPE)) \ + { \ + return da; \ + } \ + return thisClass::New(); \ + } \ + public: + +#endif +// VTK-HeaderTest-Exclude: vtkGenericDataArray.h diff --git a/Common/Core/vtkGenericDataArray.txx b/Common/Core/vtkGenericDataArray.txx new file mode 100644 index 00000000000..1b54b670dfe --- /dev/null +++ b/Common/Core/vtkGenericDataArray.txx @@ -0,0 +1,924 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkGenericDataArray.txx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#ifndef vtkGenericDataArray_txx +#define vtkGenericDataArray_txx + +#include "vtkGenericDataArray.h" + +#include "vtkIdList.h" +#include "vtkMath.h" +#include "vtkVariantCast.h" + +//----------------------------------------------------------------------------- +template +double* vtkGenericDataArray::GetTuple(vtkIdType tupleIdx) +{ + assert(!this->LegacyTuple.empty() && "Number of components is nonzero."); + this->GetTuple(tupleIdx, &this->LegacyTuple[0]); + return &this->LegacyTuple[0]; +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::GetTuple(vtkIdType tupleIdx, double *tuple) +{ + for (int c = 0; c < this->NumberOfComponents; ++c) + { + tuple[c] = static_cast(this->GetTypedComponent(tupleIdx, c)); + } +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::InterpolateTuple( + vtkIdType dstTupleIdx, vtkIdList *ptIndices, vtkAbstractArray *source, + double *weights) +{ + // First, check for the common case of typeid(source) == typeid(this). This + // way we don't waste time redoing the other checks in the superclass, and + // can avoid doing a dispatch for the most common usage of this method. + DerivedT *other = vtkArrayDownCast(source); + if (!other) + { + // Let the superclass handle dispatch/fallback. + this->Superclass::InterpolateTuple(dstTupleIdx, ptIndices, source, weights); + return; + } + + int numComps = this->GetNumberOfComponents(); + if (other->GetNumberOfComponents() != numComps) + { + vtkErrorMacro("Number of components do not match: Source: " + << other->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + + vtkIdType numIds = ptIndices->GetNumberOfIds(); + vtkIdType *ids = ptIndices->GetPointer(0); + + for (int c = 0; c < numComps; ++c) + { + double val = 0.; + for (vtkIdType tupleId = 0; tupleId < numIds; ++tupleId) + { + vtkIdType t = ids[tupleId]; + double weight = weights[tupleId]; + val += weight * static_cast(other->GetTypedComponent(t, c)); + } + ValueType valT; + vtkMath::RoundDoubleToIntegralIfNecessary(val, &valT); + this->InsertTypedComponent(dstTupleIdx, c, valT); + } +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::InterpolateTuple( + vtkIdType dstTupleIdx, vtkIdType srcTupleIdx1, vtkAbstractArray *source1, + vtkIdType srcTupleIdx2, vtkAbstractArray *source2, double t) +{ + // First, check for the common case of typeid(source) == typeid(this). This + // way we don't waste time redoing the other checks in the superclass, and + // can avoid doing a dispatch for the most common usage of this method. + DerivedT *other1 = vtkArrayDownCast(source1); + DerivedT *other2 = other1 ? vtkArrayDownCast(source2) : NULL; + if (!other1 || !other2) + { + // Let the superclass handle dispatch/fallback. + this->Superclass::InterpolateTuple(dstTupleIdx, + srcTupleIdx1, source1, + srcTupleIdx2, source2, t); + return; + } + + if (srcTupleIdx1 >= source1->GetNumberOfTuples()) + { + vtkErrorMacro("Tuple 1 out of range for provided array. " + "Requested tuple: " << srcTupleIdx1 << " " + "Tuples: " << source1->GetNumberOfTuples()); + return; + } + + if (srcTupleIdx2 >= source2->GetNumberOfTuples()) + { + vtkErrorMacro("Tuple 2 out of range for provided array. " + "Requested tuple: " << srcTupleIdx2 << " " + "Tuples: " << source2->GetNumberOfTuples()); + return; + } + + int numComps = this->GetNumberOfComponents(); + if (other1->GetNumberOfComponents() != numComps) + { + vtkErrorMacro("Number of components do not match: Source: " + << other1->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + if (other2->GetNumberOfComponents() != numComps) + { + vtkErrorMacro("Number of components do not match: Source: " + << other2->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + + const double oneMinusT = 1. - t; + double val; + ValueType valT; + + for (int c = 0; c < numComps; ++c) + { + val = other1->GetTypedComponent(srcTupleIdx1, c) * oneMinusT + + other2->GetTypedComponent(srcTupleIdx2, c) * t; + vtkMath::RoundDoubleToIntegralIfNecessary(val, &valT); + this->InsertTypedComponent(dstTupleIdx, c, valT); + } +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::SetComponent(vtkIdType tupleIdx, int compIdx, double value) +{ + // Reimplemented for efficiency (base impl allocates heap memory) + this->SetTypedComponent(tupleIdx, compIdx, static_cast(value)); +} + +//----------------------------------------------------------------------------- +template +double vtkGenericDataArray +::GetComponent(vtkIdType tupleIdx, int compIdx) +{ + // Reimplemented for efficiency (base impl allocates heap memory) + return static_cast(this->GetTypedComponent(tupleIdx, compIdx)); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::RemoveTuple(vtkIdType id) +{ + if (id < 0 || id >= this->GetNumberOfTuples()) + { + // Nothing to be done + return; + } + if (id == (this->GetNumberOfTuples() - 1)) + { + // To remove last item, just decrease the size by one + this->RemoveLastTuple(); + return; + } + + // This is a very slow implementation since it uses generic API. Subclasses + // are encouraged to provide a faster implementation. + assert(((this->GetNumberOfTuples() - id) - 1) /* (length) */ > 0); + + int numComps = this->GetNumberOfComponents(); + vtkIdType fromTuple = id + 1; + vtkIdType toTuple = id; + vtkIdType endTuple = this->GetNumberOfTuples(); + for (; fromTuple != endTuple; ++toTuple, ++fromTuple) + { + for (int comp=0; comp < numComps; ++comp) + { + this->SetTypedComponent(toTuple, comp, + this->GetTypedComponent(fromTuple, comp)); + } + } + this->SetNumberOfTuples(this->GetNumberOfTuples() - 1); + this->DataChanged(); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::SetVoidArray(void*, vtkIdType, int) +{ + vtkErrorMacro("SetVoidArray is not supported by this class."); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::SetVoidArray(void*, vtkIdType, int, int) +{ + vtkErrorMacro("SetVoidArray is not supported by this class."); +} + +//----------------------------------------------------------------------------- +template +void* vtkGenericDataArray +::WriteVoidPointer(vtkIdType, vtkIdType) +{ + vtkErrorMacro("WriteVoidPointer is not supported by this class."); + return NULL; +} + +//----------------------------------------------------------------------------- +template +typename vtkGenericDataArray::ValueType * +vtkGenericDataArray +::WritePointer(vtkIdType id, vtkIdType number) +{ + return static_cast(this->WriteVoidPointer(id, number)); +} + +//----------------------------------------------------------------------------- +template +int vtkGenericDataArray::GetDataType() +{ + return vtkTypeTraits::VTK_TYPE_ID; +} + +//----------------------------------------------------------------------------- +template +int vtkGenericDataArray::GetDataTypeSize() +{ + return static_cast(sizeof(ValueType)); +} + +//----------------------------------------------------------------------------- +template +bool vtkGenericDataArray::HasStandardMemoryLayout() +{ + // False by default, AoS should set true. + return false; +} + +//----------------------------------------------------------------------------- +template +void* vtkGenericDataArray::GetVoidPointer(vtkIdType) +{ + vtkErrorMacro("GetVoidPointer is not supported by this class."); + return NULL; +} + +//----------------------------------------------------------------------------- +template +typename vtkGenericDataArray::ValueType * +vtkGenericDataArray::GetPointer(vtkIdType id) +{ + return static_cast(this->GetVoidPointer(id)); +} + +//----------------------------------------------------------------------------- +template +vtkIdType vtkGenericDataArray +::LookupValue(vtkVariant valueVariant) +{ + bool valid = true; + ValueType value = vtkVariantCast(valueVariant, &valid); + if (valid) + { + return this->LookupTypedValue(value); + } + return -1; +} + +//----------------------------------------------------------------------------- +template +vtkIdType vtkGenericDataArray +::LookupTypedValue(ValueType value) +{ + return this->Lookup.LookupValue(value); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::LookupValue(vtkVariant valueVariant, vtkIdList* ids) +{ + ids->Reset(); + bool valid = true; + ValueType value = vtkVariantCast(valueVariant, &valid); + if (valid) + { + this->LookupTypedValue(value, ids); + } +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::LookupTypedValue(ValueType value, vtkIdList* ids) +{ + ids->Reset(); + this->Lookup.LookupValue(value, ids); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::ClearLookup() +{ + this->Lookup.ClearLookup(); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::DataChanged() +{ + this->Lookup.ClearLookup(); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::SetVariantValue(vtkIdType valueIdx, vtkVariant valueVariant) +{ + bool valid = true; + ValueType value = vtkVariantCast(valueVariant, &valid); + if (valid) + { + this->SetValue(valueIdx, value); + } +} + +//----------------------------------------------------------------------------- +template +vtkVariant vtkGenericDataArray +::GetVariantValue(vtkIdType valueIdx) +{ + return vtkVariant(this->GetValue(valueIdx)); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::InsertVariantValue(vtkIdType valueIdx, vtkVariant valueVariant) +{ + bool valid = true; + ValueType value = vtkVariantCast(valueVariant, &valid); + if (valid) + { + this->InsertValue(valueIdx, value); + } +} + +//----------------------------------------------------------------------------- +template +int vtkGenericDataArray +::Allocate(vtkIdType size, vtkIdType vtkNotUsed(ext)) +{ + // Allocator must updated this->Size and this->MaxId properly. + this->MaxId = -1; + if (size > this->Size || size == 0) + { + this->Size = 0; + + // let's keep the size an integral multiple of the number of components. + size = size < 0 ? 0 : size; + int numComps = this->GetNumberOfComponents() > 0 + ? this->GetNumberOfComponents() : 1; + vtkIdType numTuples = ceil(size / static_cast(numComps)); + // NOTE: if numTuples is 0, AllocateTuples is expected to release the + // memory. + if (this->AllocateTuples(numTuples) == false) + { + vtkErrorMacro("Unable to allocate " << size + << " elements of size " << sizeof(ValueType) + << " bytes. "); +#if !defined NDEBUG + // We're debugging, crash here preserving the stack + abort(); +#elif !defined VTK_DONT_THROW_BAD_ALLOC + // We can throw something that has universal meaning + throw std::bad_alloc(); +#else + // We indicate that alloc failed by return + return 0; +#endif + } + this->Size = numTuples * numComps; + } + this->DataChanged(); + return 1; +} + +//----------------------------------------------------------------------------- +template +int vtkGenericDataArray::Resize(vtkIdType numTuples) +{ + int numComps = this->GetNumberOfComponents(); + vtkIdType curNumTuples = this->Size / (numComps> 0? numComps : 1); + if (numTuples > curNumTuples) + { + // Requested size is bigger than current size. Allocate enough + // memory to fit the requested size and be more than double the + // currently allocated memory. + numTuples = curNumTuples + numTuples; + } + else if (numTuples == curNumTuples) + { + return 1; + } + else + { + // Requested size is smaller than current size. Squeeze the + // memory. + this->DataChanged(); + } + + assert(numTuples >= 0); + + if (!this->ReallocateTuples(numTuples)) + { + vtkErrorMacro("Unable to allocate " << numTuples * numComps + << " elements of size " << sizeof(ValueType) + << " bytes. "); +#if !defined NDEBUG + // We're debugging, crash here preserving the stack + abort(); +#elif !defined VTK_DONT_THROW_BAD_ALLOC + // We can throw something that has universal meaning + throw std::bad_alloc(); +#else + // We indicate that malloc failed by return + return 0; +#endif + } + + // Allocation was successful. Save it. + this->Size = numTuples * numComps; + + // Update MaxId if we truncated: + if ((this->Size - 1) < this->MaxId) + { + this->MaxId = (this->Size - 1); + } + + return 1; +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::SetNumberOfComponents(int num) +{ + this->vtkDataArray::SetNumberOfComponents(num); + this->LegacyTuple.resize(num); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray:: +SetNumberOfTuples(vtkIdType number) +{ + vtkIdType newSize = number * this->NumberOfComponents; + if (this->Allocate(newSize, 0)) + { + this->MaxId = newSize - 1; + } +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::Initialize() +{ + this->Resize(0); + this->DataChanged(); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::Squeeze() +{ + this->Resize(this->GetNumberOfTuples()); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::SetTuple( + vtkIdType dstTupleIdx, vtkIdType srcTupleIdx, vtkAbstractArray *source) +{ + // First, check for the common case of typeid(source) == typeid(this). This + // way we don't waste time redoing the other checks in the superclass, and + // can avoid doing a dispatch for the most common usage of this method. + DerivedT *other = vtkArrayDownCast(source); + if (!other) + { + // Let the superclass handle dispatch/fallback. + this->Superclass::SetTuple(dstTupleIdx, srcTupleIdx, source); + return; + } + + int numComps = this->GetNumberOfComponents(); + if (source->GetNumberOfComponents() != numComps) + { + vtkErrorMacro("Number of components do not match: Source: " + << source->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + + for (int c = 0; c < numComps; ++c) + { + this->SetTypedComponent(dstTupleIdx, c, + other->GetTypedComponent(srcTupleIdx, c)); + } +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::InsertTuples( + vtkIdList *dstIds, vtkIdList *srcIds, vtkAbstractArray *source) +{ + // First, check for the common case of typeid(source) == typeid(this). This + // way we don't waste time redoing the other checks in the superclass, and + // can avoid doing a dispatch for the most common usage of this method. + DerivedT *other = vtkArrayDownCast(source); + if (!other) + { + // Let the superclass handle dispatch/fallback. + this->Superclass::InsertTuples(dstIds, srcIds, source); + return; + } + + if (dstIds->GetNumberOfIds() == 0) + { + return; + } + + if (dstIds->GetNumberOfIds() != srcIds->GetNumberOfIds()) + { + vtkErrorMacro("Mismatched number of tuples ids. Source: " + << srcIds->GetNumberOfIds() << " Dest: " + << dstIds->GetNumberOfIds()); + return; + } + + int numComps = this->GetNumberOfComponents(); + if (other->GetNumberOfComponents() != numComps) + { + vtkErrorMacro("Number of components do not match: Source: " + << other->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + + vtkIdType maxSrcTupleId = srcIds->GetId(0); + vtkIdType maxDstTupleId = dstIds->GetId(0); + for (int i = 0; i < dstIds->GetNumberOfIds(); ++i) + { + // parenthesis around std::max prevent MSVC macro replacement when + // inlined: + maxSrcTupleId = (std::max)(maxSrcTupleId, srcIds->GetId(i)); + maxDstTupleId = (std::max)(maxDstTupleId, dstIds->GetId(i)); + } + + if (maxSrcTupleId >= other->GetNumberOfTuples()) + { + vtkErrorMacro("Source array too small, requested tuple at index " + << maxSrcTupleId << ", but there are only " + << other->GetNumberOfTuples() << " tuples in the array."); + return; + } + + vtkIdType newSize = (maxDstTupleId + 1) * this->NumberOfComponents; + if (this->Size < newSize) + { + if (!this->Resize(maxDstTupleId + 1)) + { + vtkErrorMacro("Resize failed."); + return; + } + } + + // parenthesis around std::max prevent MSVC macro replacement when + // inlined: + this->MaxId = (std::max)(this->MaxId, newSize - 1); + + vtkIdType numTuples = srcIds->GetNumberOfIds(); + for (vtkIdType t = 0; t < numTuples; ++t) + { + vtkIdType srcT = srcIds->GetId(t); + vtkIdType dstT = dstIds->GetId(t); + for (int c = 0; c < numComps; ++c) + { + this->SetTypedComponent(dstT, c, other->GetTypedComponent(srcT, c)); + } + } +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray *source) +{ + this->EnsureAccessToTuple(i); + this->SetTuple(i, j, source); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::InsertTuple(vtkIdType i, const float *source) +{ + this->EnsureAccessToTuple(i); + this->SetTuple(i, source); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::InsertTuple(vtkIdType i, const double *source) +{ + this->EnsureAccessToTuple(i); + this->SetTuple(i, source); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::InsertComponent(vtkIdType tupleIdx, int compIdx, double value) +{ + // Update MaxId to the inserted component (not the complete tuple) for + // compatibility with InsertNextValue. + vtkIdType newMaxId = tupleIdx * this->NumberOfComponents + compIdx; + if (newMaxId < this->MaxId) + { + newMaxId = this->MaxId; + } + this->EnsureAccessToTuple(tupleIdx); + assert("Sufficient space allocated." && this->MaxId >= newMaxId); + this->MaxId = newMaxId; + this->SetComponent(tupleIdx, compIdx, value); +} + +//----------------------------------------------------------------------------- +template +vtkIdType vtkGenericDataArray +::InsertNextTuple(vtkIdType srcTupleIdx, vtkAbstractArray *source) +{ + vtkIdType nextTuple = this->GetNumberOfTuples(); + this->InsertTuple(nextTuple, srcTupleIdx, source); + return nextTuple; +} + +//----------------------------------------------------------------------------- +template +vtkIdType vtkGenericDataArray +::InsertNextTuple(const float *tuple) +{ + vtkIdType nextTuple = this->GetNumberOfTuples(); + this->InsertTuple(nextTuple, tuple); + return nextTuple; +} + +//----------------------------------------------------------------------------- +template +vtkIdType vtkGenericDataArray +::InsertNextTuple(const double *tuple) +{ + vtkIdType nextTuple = this->GetNumberOfTuples(); + this->InsertTuple(nextTuple, tuple); + return nextTuple; +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::GetTuples( + vtkIdList *tupleIds, vtkAbstractArray *output) +{ + // First, check for the common case of typeid(source) == typeid(this). This + // way we don't waste time redoing the other checks in the superclass, and + // can avoid doing a dispatch for the most common usage of this method. + DerivedT *other = vtkArrayDownCast(output); + if (!other) + { + // Let the superclass handle dispatch/fallback. + this->Superclass::GetTuples(tupleIds, output); + return; + } + + int numComps = this->GetNumberOfComponents(); + if (other->GetNumberOfComponents() != numComps) + { + vtkErrorMacro("Number of components for input and output do not match.\n" + "Source: " << this->GetNumberOfComponents() << "\n" + "Destination: " << other->GetNumberOfComponents()); + return; + } + + vtkIdType *srcTuple = tupleIds->GetPointer(0); + vtkIdType *srcTupleEnd = tupleIds->GetPointer(tupleIds->GetNumberOfIds()); + vtkIdType dstTuple = 0; + + while (srcTuple != srcTupleEnd) + { + for (int c = 0; c < numComps; ++c) + { + other->SetTypedComponent(dstTuple, c, + this->GetTypedComponent(*srcTuple, c)); + } + ++srcTuple; + ++dstTuple; + } +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray::GetTuples( + vtkIdType p1, vtkIdType p2, vtkAbstractArray *output) +{ + // First, check for the common case of typeid(source) == typeid(this). This + // way we don't waste time redoing the other checks in the superclass, and + // can avoid doing a dispatch for the most common usage of this method. + DerivedT *other = vtkArrayDownCast(output); + if (!other) + { + // Let the superclass handle dispatch/fallback. + this->Superclass::GetTuples(p1, p2, output); + return; + } + + int numComps = this->GetNumberOfComponents(); + if (other->GetNumberOfComponents() != numComps) + { + vtkErrorMacro("Number of components for input and output do not match.\n" + "Source: " << this->GetNumberOfComponents() << "\n" + "Destination: " << other->GetNumberOfComponents()); + return; + } + + // p1-p2 are inclusive + for (vtkIdType srcT = p1, dstT = 0; srcT <= p2; ++srcT, ++dstT) + { + for (int c = 0; c < numComps; ++c) + { + other->SetTypedComponent(dstT, c, + this->GetTypedComponent(srcT, c)); + } + } +} + +//----------------------------------------------------------------------------- +template +vtkArrayIterator* vtkGenericDataArray::NewIterator() +{ + vtkWarningMacro(<< "No vtkArrayIterator defined for " << this->GetClassName() + << " arrays."); + return NULL; +} + +//----------------------------------------------------------------------------- +template +vtkIdType vtkGenericDataArray +::InsertNextValue(ValueType value) +{ + vtkIdType nextValueIdx = this->MaxId + 1; + if (nextValueIdx >= this->Size) + { + vtkIdType tuple = nextValueIdx / this->NumberOfComponents; + this->EnsureAccessToTuple(tuple); + // Since EnsureAccessToTuple will update the MaxId to point to the last + // component in the last tuple, we move it back to support this method on + // multi-component arrays. + this->MaxId = nextValueIdx; + } + + // Extending array without needing to reallocate: + if (this->MaxId < nextValueIdx) + { + this->MaxId = nextValueIdx; + } + + this->SetValue(nextValueIdx, value); + return nextValueIdx; +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::InsertValue(vtkIdType valueIdx, ValueType value) +{ + vtkIdType tuple = valueIdx / this->NumberOfComponents; + // Update MaxId to the inserted component (not the complete tuple) for + // compatibility with InsertNextValue. + vtkIdType newMaxId = valueIdx > this->MaxId ? valueIdx : this->MaxId; + if (this->EnsureAccessToTuple(tuple)) + { + assert("Sufficient space allocated." && this->MaxId >= newMaxId); + this->MaxId = newMaxId; + this->SetValue(valueIdx, value); + } +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::InsertTypedTuple(vtkIdType tupleIdx, const ValueType *t) +{ + if (this->EnsureAccessToTuple(tupleIdx)) + { + this->SetTypedTuple(tupleIdx, t); + } +} + +//----------------------------------------------------------------------------- +template +vtkIdType vtkGenericDataArray +::InsertNextTypedTuple(const ValueType *t) +{ + vtkIdType nextTuple = this->GetNumberOfTuples(); + this->InsertTypedTuple(nextTuple, t); + return nextTuple; +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::InsertTypedComponent(vtkIdType tupleIdx, int compIdx, ValueType val) +{ + // Update MaxId to the inserted component (not the complete tuple) for + // compatibility with InsertNextValue. + vtkIdType newMaxId = tupleIdx * this->NumberOfComponents + compIdx; + if (this->MaxId > newMaxId) + { + newMaxId = this->MaxId; + } + this->EnsureAccessToTuple(tupleIdx); + assert("Sufficient space allocated." && this->MaxId >= newMaxId); + this->MaxId = newMaxId; + this->SetTypedComponent(tupleIdx, compIdx, val); +} + +//----------------------------------------------------------------------------- +template +void vtkGenericDataArray +::GetValueRange(ValueType range[2], int comp) +{ + // TODO This is how vtkDataArrayTemplate implemented this. It should be + // reimplemented to avoid truncation of e.g. longer integers. + double doubleRange[2]; + this->ComputeRange(doubleRange, comp); + range[0] = static_cast(doubleRange[0]); + range[1] = static_cast(doubleRange[1]); +} + +//----------------------------------------------------------------------------- +template +typename vtkGenericDataArray::ValueType * +vtkGenericDataArray::GetValueRange(int comp) +{ + this->LegacyValueRange.resize(2); + this->GetValueRange(&this->LegacyValueRange[0], comp); + return &this->LegacyValueRange[0]; +} + +//----------------------------------------------------------------------------- +template +vtkGenericDataArray::vtkGenericDataArray() +{ + // Initialize internal data structures: + this->Lookup.SetArray(this); + this->SetNumberOfComponents(this->NumberOfComponents); +} + +//----------------------------------------------------------------------------- +template +vtkGenericDataArray::~vtkGenericDataArray() +{ +} + +//----------------------------------------------------------------------------- +template +bool vtkGenericDataArray +::EnsureAccessToTuple(vtkIdType tupleIdx) +{ + if (tupleIdx < 0) + { + return false; + } + vtkIdType minSize = (1 + tupleIdx) * this->NumberOfComponents; + vtkIdType expectedMaxId = minSize - 1; + if (this->MaxId < expectedMaxId) + { + if (this->Size < minSize) + { + if (!this->Resize(tupleIdx + 1)) + { + return false; + } + } + this->MaxId = expectedMaxId; + } + return true; +} + +#undef vtkGenericDataArrayT + +#endif // header guard diff --git a/Common/Core/vtkGenericDataArrayLookupHelper.h b/Common/Core/vtkGenericDataArrayLookupHelper.h new file mode 100644 index 00000000000..2ff5a5dfc35 --- /dev/null +++ b/Common/Core/vtkGenericDataArrayLookupHelper.h @@ -0,0 +1,151 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkGenericDataArrayLookupHelper.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkGenericDataArrayLookupHelper - internal class used by +// vtkGenericDataArray to support LookupValue. +// .SECTION Description + +#ifndef vtkGenericDataArrayLookupHelper_h +#define vtkGenericDataArrayLookupHelper_h + +#include +#include "vtkIdList.h" + +namespace detail +{ + // this can be removed when C++11 is required. + template< class T > struct remove_const { typedef T type; }; + template< class T > struct remove_const { typedef T type; }; +} + +template +class vtkGenericDataArrayLookupHelper +{ +public: + typedef ArrayTypeT ArrayType; + typedef typename ArrayType::ValueType ValueType; + + // Constructor. + vtkGenericDataArrayLookupHelper() + : AssociatedArray(NULL), + SortedArray(NULL) + { + } + ~vtkGenericDataArrayLookupHelper() + { + this->ClearLookup(); + } + + void SetArray(ArrayTypeT *array) + { + if (this->AssociatedArray != array) + { + this->ClearLookup(); + this->AssociatedArray = array; + } + } + + vtkIdType LookupValue(ValueType elem) + { + this->UpdateLookup(); + ValueWithIndex temp; + temp.Value = elem; + ValueWithIndex* pos = + std::lower_bound(this->SortedArray, + this->SortedArray + this->SortedArraySize, temp); + if (pos == (this->SortedArray + this->SortedArraySize)) + { + return -1; + } + if (pos->Value != elem) + { + return -1; + } + return pos->Index; + } + + void LookupValue(ValueType elem, vtkIdList* ids) + { + this->UpdateLookup(); + ValueWithIndex temp; + temp.Value = elem; + std::pair range = + std::equal_range(this->SortedArray, + this->SortedArray + this->SortedArraySize, temp); + while (range.first != range.second) + { + // assert(range.first->Value == elem); + ids->InsertNextId(range.first->Index); + ++range.first; + } + } + + // Description: + // Release any allocated memory for internal data-structures. + void ClearLookup() + { + free(this->SortedArray); + this->SortedArray = NULL; + this->SortedArraySize = 0; + } + +private: + vtkGenericDataArrayLookupHelper(const vtkGenericDataArrayLookupHelper&); // Not implemented. + void operator=(const vtkGenericDataArrayLookupHelper&); // Not implemented. + + struct ValueWithIndex + { + typename ::detail::remove_const::type Value; + vtkIdType Index; + inline bool operator<(const ValueWithIndex& other) const + { + return this->Value < other.Value; + } + }; + + void UpdateLookup() + { + if (!this->AssociatedArray || this->SortedArray) + { + return; + } + + int numComps = this->AssociatedArray->GetNumberOfComponents(); + this->SortedArraySize = + this->AssociatedArray->GetNumberOfTuples() * numComps; + + if (this->SortedArraySize == 0) + { + return; + } + + this->SortedArray = reinterpret_cast( + malloc(this->SortedArraySize * sizeof(ValueWithIndex))); + for (vtkIdType cc = 0, max = this->AssociatedArray->GetNumberOfValues(); + cc < max; ++cc) + { + ValueWithIndex& item = this->SortedArray[cc]; + item.Value = this->AssociatedArray->GetValue(cc); + item.Index = cc; + } + std::sort(this->SortedArray, this->SortedArray + this->SortedArraySize); + } + + ArrayTypeT *AssociatedArray; + ValueWithIndex* SortedArray; + vtkIdType SortedArraySize; +}; + +#endif +// VTK-HeaderTest-Exclude: vtkGenericDataArrayLookupHelper.h diff --git a/Common/Core/vtkIdList.h b/Common/Core/vtkIdList.h index c920ba6c3b7..e4c9f409dbb 100644 --- a/Common/Core/vtkIdList.h +++ b/Common/Core/vtkIdList.h @@ -120,11 +120,9 @@ class VTKCOMMONCORE_EXPORT vtkIdList : public vtkObject // when being truncated). vtkIdType *Resize(const vtkIdType sz); - //BTX // This method should become legacy void IntersectWith(vtkIdList& otherIds) { this->IntersectWith(&otherIds); }; - //ETX protected: vtkIdList(); @@ -158,7 +156,7 @@ inline vtkIdType vtkIdList::InsertNextId(const vtkIdType vtkid) { if ( this->NumberOfIds >= this->Size ) { - if (!this->Resize(this->NumberOfIds+1)) + if (!this->Resize(2*this->NumberOfIds+1)) //grow by factor of 2 { return this->NumberOfIds-1; } diff --git a/Common/Core/vtkIdListCollection.h b/Common/Core/vtkIdListCollection.h index 359db4c30e6..ae1d2ada9ea 100644 --- a/Common/Core/vtkIdListCollection.h +++ b/Common/Core/vtkIdListCollection.h @@ -48,13 +48,11 @@ class VTKCOMMONCORE_EXPORT vtkIdListCollection : public vtkCollection vtkIdList *GetItem(int i) { return static_cast(this->GetItemAsObject(i));}; - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkIdList *GetNextIdList(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkIdListCollection() {} diff --git a/Common/Core/vtkIdTypeArray.cxx b/Common/Core/vtkIdTypeArray.cxx index 9e4dfa73d7c..83ec03e1794 100644 --- a/Common/Core/vtkIdTypeArray.cxx +++ b/Common/Core/vtkIdTypeArray.cxx @@ -12,16 +12,16 @@ PURPOSE. See the above copyright notice for more information. =========================================================================*/ -// We never need to instantiate vtkDataArrayTemplate or +// We never need to instantiate vtkAOSDataArrayTemplate or // vtkArrayIteratorTemplate because they are instantiated // by the corresponding array for its native type. Therefore this // code should not be uncommented and is here for reference: -// #include "vtkDataArrayTemplate.txx" -// VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(vtkIdType); +// #define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +// #include "vtkAOSDataArrayTemplate.txx" +// VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(vtkIdType); // #include "vtkArrayIteratorTemplate.txx" // VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(vtkIdType); -#define vtkIdTypeArray_cxx #include "vtkIdTypeArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkIdTypeArray.h b/Common/Core/vtkIdTypeArray.h index b054a5836a4..966260f7e78 100644 --- a/Common/Core/vtkIdTypeArray.h +++ b/Common/Core/vtkIdTypeArray.h @@ -21,33 +21,28 @@ #ifndef vtkIdTypeArray_h #define vtkIdTypeArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !(defined(vtkIdTypeArray_cxx) && defined(VTK_USE_64BIT_IDS)) && (defined(VTK_USE_64BIT_IDS) || !defined(vtkIntArray_h)) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE vtkIdType -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkIdTypeArray : public vtkDataArray { public: vtkTypeMacro(vtkIdTypeArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkIdTypeArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(vtkIdType); #else @@ -59,11 +54,18 @@ class VTKCOMMONCORE_EXPORT vtkIdTypeArray : public vtkDataArray // the templated superclass is not able to differentiate // vtkIdType from a long long or an int since vtkIdType // is simply a typedef. This means that - // vtkDataArrayTemplate != vtkIdTypeArray. + // vtkAOSDataArrayTemplate != vtkIdTypeArray. return VTK_ID_TYPE; } #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkIdTypeArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static vtkIdType GetDataTypeValueMin() { return VTK_ID_MIN; } @@ -77,11 +79,14 @@ class VTKCOMMONCORE_EXPORT vtkIdTypeArray : public vtkDataArray ~vtkIdTypeArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkIdTypeArray(const vtkIdTypeArray&); // Not implemented. void operator=(const vtkIdTypeArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkIdTypeArray) + #endif diff --git a/Common/Core/vtkIndent.h b/Common/Core/vtkIndent.h index 08294bc999b..33572e5c2e7 100644 --- a/Common/Core/vtkIndent.h +++ b/Common/Core/vtkIndent.h @@ -39,11 +39,9 @@ class VTKCOMMONCORE_EXPORT vtkIndent // max of forty. vtkIndent GetNextIndent(); - //BTX // Description: // Print out the indentation. Basically output a bunch of spaces. friend VTKCOMMONCORE_EXPORT ostream& operator<<(ostream& os, const vtkIndent& o); - //ETX protected: int Indent; diff --git a/Common/Core/vtkInformation.cxx b/Common/Core/vtkInformation.cxx index ff6cb4d1cdd..f418bbae15c 100644 --- a/Common/Core/vtkInformation.cxx +++ b/Common/Core/vtkInformation.cxx @@ -28,6 +28,7 @@ #include "vtkInformationIterator.h" #include "vtkInformationKeyVectorKey.h" #include "vtkInformationObjectBaseKey.h" +#include "vtkInformationObjectBaseVectorKey.h" #include "vtkInformationRequestKey.h" #include "vtkInformationStringKey.h" #include "vtkInformationStringVectorKey.h" @@ -327,6 +328,21 @@ void vtkInformation::CopyEntry(vtkInformation* from, } } +//---------------------------------------------------------------------------- +void vtkInformation::CopyEntry(vtkInformation *from, + vtkInformationObjectBaseVectorKey *key, + int deep) +{ + if (!deep) + { + key->ShallowCopy(from, this); + } + else + { + key->DeepCopy(from, this); + } +} + //---------------------------------------------------------------------------- void vtkInformation::CopyEntry(vtkInformation* from, vtkInformationDoubleVectorKey* key, int deep) @@ -587,6 +603,60 @@ int vtkInformation::Has(vtkInformationStringVectorKey* key) return key->vtkInformationStringVectorKey::Has(this); } + +//------------------------------------------------------------------------------ +void vtkInformation::Append(vtkInformationObjectBaseVectorKey *key, + vtkObjectBase *data) +{ + key->Append(this, data); +} + +//------------------------------------------------------------------------------ +void vtkInformation::Set(vtkInformationObjectBaseVectorKey *key, + vtkObjectBase *value, int idx) +{ + key->Set(this, value, idx); +} + +//------------------------------------------------------------------------------ +vtkObjectBase *vtkInformation::Get(vtkInformationObjectBaseVectorKey *key, + int idx) +{ + return key->Get(this, idx); +} + +//------------------------------------------------------------------------------ +int vtkInformation::Length(vtkInformationObjectBaseVectorKey *key) +{ + return key->Length(this); +} + +//------------------------------------------------------------------------------ +void vtkInformation::Remove(vtkInformationObjectBaseVectorKey *key) +{ + key->Remove(this); +} + +//------------------------------------------------------------------------------ +void vtkInformation::Remove(vtkInformationObjectBaseVectorKey *key, + vtkObjectBase *objectToRemove) +{ + key->Remove(this, objectToRemove); +} + +//------------------------------------------------------------------------------ +void vtkInformation::Remove(vtkInformationObjectBaseVectorKey *key, + int indexToRemove) +{ + key->Remove(this, indexToRemove); +} + +//------------------------------------------------------------------------------ +int vtkInformation::Has(vtkInformationObjectBaseVectorKey *key) +{ + return key->Has(this); +} + VTK_INFORMATION_DEFINE_VECTOR_PROPERTY(Key, vtkInformationKey*); #define VTK_INFORMATION_DEFINE_VECTOR_VALUE2_PROPERTY(name, type, atype) \ void vtkInformation::Set(vtkInformation##name##VectorKey* key, \ diff --git a/Common/Core/vtkInformation.h b/Common/Core/vtkInformation.h index 84dc8fd0031..1b25f22019f 100644 --- a/Common/Core/vtkInformation.h +++ b/Common/Core/vtkInformation.h @@ -55,6 +55,7 @@ class vtkInformationKey; class vtkInformationKeyToInformationFriendship; class vtkInformationKeyVectorKey; class vtkInformationObjectBaseKey; +class vtkInformationObjectBaseVectorKey; class vtkInformationRequestKey; class vtkInformationStringKey; class vtkInformationStringVectorKey; @@ -128,6 +129,7 @@ class VTK_INFORMATION_EXPORT vtkInformation : public vtkObject VTKCOMMONCORE_EXPORT void CopyEntry(vtkInformation* from, vtkInformationInformationVectorKey* key, int deep=0); VTKCOMMONCORE_EXPORT void CopyEntry(vtkInformation* from, vtkInformationIntegerKey* key, int deep=0); VTKCOMMONCORE_EXPORT void CopyEntry(vtkInformation* from, vtkInformationIntegerVectorKey* key, int deep=0); + VTKCOMMONCORE_EXPORT void CopyEntry(vtkInformation* from, vtkInformationObjectBaseVectorKey* key, int deep=0); VTKCOMMONCORE_EXPORT void CopyEntry(vtkInformation* from, vtkInformationRequestKey* key, int deep=0); VTKCOMMONCORE_EXPORT void CopyEntry(vtkInformation* from, vtkInformationStringKey* key, int deep=0); VTKCOMMONCORE_EXPORT void CopyEntry(vtkInformation* from, vtkInformationStringVectorKey* key, int deep=0); @@ -272,7 +274,7 @@ class VTK_INFORMATION_EXPORT vtkInformation : public vtkObject // code to include the headers for these key types. Avoid wrapping // them because the original method can be called from the wrappers // anyway and this causes a python help string to be too long. - //BTX + VTKCOMMONCORE_EXPORT void Append(vtkInformationKeyVectorKey* key, vtkInformationDataObjectKey* value); VTKCOMMONCORE_EXPORT void Append(vtkInformationKeyVectorKey* key, vtkInformationDoubleKey* value); @@ -316,7 +318,6 @@ class VTK_INFORMATION_EXPORT vtkInformation : public vtkObject vtkInformationObjectBaseKey* value); VTKCOMMONCORE_EXPORT void AppendUnique(vtkInformationKeyVectorKey* key, vtkInformationUnsignedLongKey* value); - //ETX // Description: // Get/Set a string-valued entry. @@ -346,6 +347,22 @@ class VTK_INFORMATION_EXPORT vtkInformation : public vtkObject VTKCOMMONCORE_EXPORT void Remove(vtkInformationObjectBaseKey* key); VTKCOMMONCORE_EXPORT int Has(vtkInformationObjectBaseKey* key); + // Description: + // Manipulate a ObjectBaseVector entry. + VTKCOMMONCORE_EXPORT void Append(vtkInformationObjectBaseVectorKey* key, + vtkObjectBase *data); + VTKCOMMONCORE_EXPORT void Set(vtkInformationObjectBaseVectorKey *key, + vtkObjectBase* value, int idx = 0); + VTKCOMMONCORE_EXPORT vtkObjectBase* Get(vtkInformationObjectBaseVectorKey *key, + int idx = 0); + VTKCOMMONCORE_EXPORT int Length(vtkInformationObjectBaseVectorKey *key); + VTKCOMMONCORE_EXPORT void Remove(vtkInformationObjectBaseVectorKey *key); + VTKCOMMONCORE_EXPORT void Remove(vtkInformationObjectBaseVectorKey *key, + vtkObjectBase *objectToRemove); + VTKCOMMONCORE_EXPORT void Remove(vtkInformationObjectBaseVectorKey *key, + int indexToRemove); + VTKCOMMONCORE_EXPORT int Has(vtkInformationObjectBaseVectorKey *key); + // Description: // Get/Set an entry storing a vtkDataObject instance. VTKCOMMONCORE_EXPORT void Set(vtkInformationDataObjectKey* key, @@ -373,8 +390,8 @@ class VTK_INFORMATION_EXPORT vtkInformation : public vtkObject // Description: // Initiate garbage collection when a reference is removed. - VTKCOMMONCORE_EXPORT virtual void Register(vtkObjectBase* o); - VTKCOMMONCORE_EXPORT virtual void UnRegister(vtkObjectBase* o); + VTKCOMMONCORE_EXPORT void Register(vtkObjectBase* o) VTK_OVERRIDE; + VTKCOMMONCORE_EXPORT void UnRegister(vtkObjectBase* o) VTK_OVERRIDE; // Description: // Get/Set the Request ivar @@ -397,17 +414,17 @@ class VTK_INFORMATION_EXPORT vtkInformation : public vtkObject vtkInformationInternals* Internal; // Garbage collection support. - VTKCOMMONCORE_EXPORT virtual void ReportReferences(vtkGarbageCollector*); + VTKCOMMONCORE_EXPORT void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; // Report the object associated with the given key to the collector. VTKCOMMONCORE_EXPORT void ReportAsObjectBase(vtkInformationKey* key, vtkGarbageCollector* collector); private: - //BTX + friend class vtkInformationKeyToInformationFriendship; friend class vtkInformationIterator; - //ETX + private: VTKCOMMONCORE_EXPORT vtkInformation(const vtkInformation&); // Not implemented. VTKCOMMONCORE_EXPORT void operator=(const vtkInformation&); // Not implemented. diff --git a/Common/Core/vtkInformationDataObjectKey.h b/Common/Core/vtkInformationDataObjectKey.h index 935d66b57b2..c080e1839a3 100644 --- a/Common/Core/vtkInformationDataObjectKey.h +++ b/Common/Core/vtkInformationDataObjectKey.h @@ -45,13 +45,11 @@ class VTKCOMMONCORE_EXPORT vtkInformationDataObjectKey : public vtkInformationKe return new vtkInformationDataObjectKey(name, location); } - //BTX // Description: // Get/Set the value associated with this key in the given // information object. void Set(vtkInformation* info, vtkDataObject*); vtkDataObject* Get(vtkInformation* info); - //ETX // Description: // Copy the entry associated with this key from one information diff --git a/Common/Core/vtkInformationKey.cxx b/Common/Core/vtkInformationKey.cxx index 0f9f3519ce6..ecacd50e479 100644 --- a/Common/Core/vtkInformationKey.cxx +++ b/Common/Core/vtkInformationKey.cxx @@ -13,6 +13,7 @@ =========================================================================*/ #include "vtkInformationKey.h" +#include "vtkInformationKeyLookup.h" #include "vtkDebugLeaks.h" #include "vtkInformation.h" @@ -52,6 +53,8 @@ vtkInformationKey::vtkInformationKey(const char* name, const char* location) this->Location = 0; this->SetLocation(location); + + vtkInformationKeyLookup::RegisterKey(this, name, location); } //---------------------------------------------------------------------------- diff --git a/Common/Core/vtkInformationKeyLookup.cxx b/Common/Core/vtkInformationKeyLookup.cxx new file mode 100644 index 00000000000..176c138fd2f --- /dev/null +++ b/Common/Core/vtkInformationKeyLookup.cxx @@ -0,0 +1,72 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkInformationKeyLookup.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkInformationKeyLookup.h" + +#include "vtkObjectFactory.h" + +vtkStandardNewMacro(vtkInformationKeyLookup) + +//------------------------------------------------------------------------------ +void vtkInformationKeyLookup::PrintSelf(std::ostream &os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "Registered Keys:\n"; + indent = indent.GetNextIndent(); + KeyMap &keys = Keys(); + for (KeyMap::iterator i = keys.begin(), iEnd = keys.end(); i != iEnd; ++i) + { + os << indent << i->first.first << "::" << i->first.second + << " @" << i->second << "\n"; + } +} + +//------------------------------------------------------------------------------ +vtkInformationKey *vtkInformationKeyLookup::Find(const std::string &name, + const std::string &location) +{ + KeyMap &keys = Keys(); + KeyMap::iterator it = keys.find(std::make_pair(location, name)); + return it != keys.end() ? it->second : NULL; +} + +//------------------------------------------------------------------------------ +vtkInformationKeyLookup::vtkInformationKeyLookup() +{ +} + +//------------------------------------------------------------------------------ +vtkInformationKeyLookup::~vtkInformationKeyLookup() +{ + // Keys are owned / cleaned up by the vtk*InformationKeyManagers. +} + +//------------------------------------------------------------------------------ +void vtkInformationKeyLookup::RegisterKey(vtkInformationKey *key, + const std::string &name, + const std::string &location) +{ + vtkInformationKeyLookup::Keys().insert( + std::make_pair(std::make_pair(location, name), key)); +} + +//------------------------------------------------------------------------------ +vtkInformationKeyLookup::KeyMap &vtkInformationKeyLookup::Keys() +{ + // Ensure that the map is initialized before using from other static + // initializations: + static vtkInformationKeyLookup::KeyMap keys; + return keys; +} diff --git a/Common/Core/vtkInformationKeyLookup.h b/Common/Core/vtkInformationKeyLookup.h new file mode 100644 index 00000000000..5cd8d502ece --- /dev/null +++ b/Common/Core/vtkInformationKeyLookup.h @@ -0,0 +1,74 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkInformationKeyLookup.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +// .NAME vtkInformationKeyLookup - Find vtkInformationKeys from name and +// location strings. + +#ifndef vtkInformationKeyLookup_h +#define vtkInformationKeyLookup_h + +#include "vtkCommonCoreModule.h" // For export macro +#include "vtkObject.h" + +#include // For std::map +#include // For std::pair +#include // For std::string + +class vtkInformationKey; + +class VTKCOMMONCORE_EXPORT vtkInformationKeyLookup: public vtkObject +{ +public: + static vtkInformationKeyLookup* New(); + vtkTypeMacro(vtkInformationKeyLookup, vtkObject) + + // Description: + // Lists all known keys. + virtual void PrintSelf(ostream &os, vtkIndent indent); + + // Description: + // Find an information key from name and location strings. For example, + // Find("GUI_HIDE", "vtkAbstractArray") returns vtkAbstractArray::GUI_HIDE. + // Note that this class only knows about keys in modules that are currently + // linked to the running executable. + static vtkInformationKey* Find(const std::string &name, + const std::string &location); + +protected: + vtkInformationKeyLookup(); + ~vtkInformationKeyLookup(); + + friend class vtkInformationKey; + + // Description: + // Add a key to the KeyMap. This is done automatically in the + // vtkInformationKey constructor. + static void RegisterKey(vtkInformationKey *key, + const std::string &name, + const std::string &location); + +private: + vtkInformationKeyLookup(const vtkInformationKeyLookup&); // Not implemented + void operator=(const vtkInformationKeyLookup&); // Not implemented + + typedef std::pair Identifier; // Location, Name + typedef std::map KeyMap; + + // Using a static function / variable here to ensure static initialization + // works as intended, since key objects are static, too. + static KeyMap& Keys(); +}; + +#endif // vtkInformationKeyLookup_h diff --git a/Common/Core/vtkInformationObjectBaseVectorKey.cxx b/Common/Core/vtkInformationObjectBaseVectorKey.cxx index 93cd7bc6feb..efc26584754 100644 --- a/Common/Core/vtkInformationObjectBaseVectorKey.cxx +++ b/Common/Core/vtkInformationObjectBaseVectorKey.cxx @@ -15,6 +15,7 @@ #include "vtkInformationObjectBaseVectorKey.h" #include "vtkInformation.h" // For vtkErrorWithObjectMacro #include "vtkSmartPointer.h" +#include #include @@ -22,6 +23,8 @@ class vtkInformationObjectBaseVectorValue: public vtkObjectBase { public: + typedef std::vector > VectorType; + vtkTypeMacro(vtkInformationObjectBaseVectorValue, vtkObjectBase); std::vector > &GetVector() { @@ -144,6 +147,49 @@ void vtkInformationObjectBaseVectorKey::Set( base->GetVector()[i]=aValue; } +//---------------------------------------------------------------------------- +void vtkInformationObjectBaseVectorKey::Remove(vtkInformation *info, + vtkObjectBase *val) +{ + if (!this->ValidateDerivedType(info, val)) + { + return; + } + vtkInformationObjectBaseVectorValue *base = this->GetObjectBaseVector(info); + + typedef vtkInformationObjectBaseVectorValue::VectorType Vector; + Vector &vector = base->GetVector(); + Vector::iterator end = std::remove(vector.begin(), vector.end(), val); + if (end != vector.end()) + { + vector.resize(std::distance(vector.begin(), end)); + if (val) + { + val->UnRegister(base); + } + } +} + +//---------------------------------------------------------------------------- +void vtkInformationObjectBaseVectorKey::Remove(vtkInformation *info, int idx) +{ + typedef vtkInformationObjectBaseVectorValue::VectorType Vector; + vtkInformationObjectBaseVectorValue *base = this->GetObjectBaseVector(info); + Vector &vector = base->GetVector(); + if (idx >= static_cast(vector.size())) + { + return; + } + + vtkObjectBase *val = vector[idx]; + if (val) + { + val->UnRegister(base); + } + + vector.erase(vector.begin() + idx); +} + //---------------------------------------------------------------------------- void vtkInformationObjectBaseVectorKey::SetRange( vtkInformation* info, diff --git a/Common/Core/vtkInformationObjectBaseVectorKey.h b/Common/Core/vtkInformationObjectBaseVectorKey.h index 0783aa6f62e..437a1bb5373 100644 --- a/Common/Core/vtkInformationObjectBaseVectorKey.h +++ b/Common/Core/vtkInformationObjectBaseVectorKey.h @@ -60,21 +60,33 @@ class VTKCOMMONCORE_EXPORT vtkInformationObjectBaseVectorKey : public vtkInforma // Description: // Clear the vector. void Clear(vtkInformation* info); + // Description: // Resize (extend) the vector to hold n objects. Any new elements // created will be null initialized. void Resize(vtkInformation* info, int n); + // Description: // Get the vector's length. int Size(vtkInformation* info); int Length(vtkInformation* info){ return this->Size(info); } + // Description: // Put the value on the back of the vector, with ref counting. void Append(vtkInformation* info, vtkObjectBase *value); + // Description: // Set element i of the vector to value. Resizes the vector // if needed. void Set(vtkInformation* info, vtkObjectBase *value, int i); + + // Description: + // Remove all instances of val from the list. If using the indexed overload, + // the object at the specified position is removed. + void Remove(vtkInformation *info, vtkObjectBase *val); + void Remove(vtkInformation *info, int idx); + using Superclass::Remove; // Don't hide base class methods + // Description: // Copy n values from the range in source defined by [from from+n-1] // into the range in this vector defined by [to to+n-1]. Resizes diff --git a/Common/Core/vtkInformationVector.h b/Common/Core/vtkInformationVector.h index 78847c2b8e0..a45dec9c9a4 100644 --- a/Common/Core/vtkInformationVector.h +++ b/Common/Core/vtkInformationVector.h @@ -60,8 +60,8 @@ class VTKCOMMONCORE_EXPORT vtkInformationVector : public vtkObject // Description: // Initiate garbage collection when a reference is removed. - virtual void Register(vtkObjectBase* o); - virtual void UnRegister(vtkObjectBase* o); + void Register(vtkObjectBase* o) VTK_OVERRIDE; + void UnRegister(vtkObjectBase* o) VTK_OVERRIDE; // Description: // Copy all information entries from the given vtkInformation @@ -81,7 +81,7 @@ class VTKCOMMONCORE_EXPORT vtkInformationVector : public vtkObject int NumberOfInformationObjects; // Garbage collection support. - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; private: vtkInformationVector(const vtkInformationVector&); // Not implemented. void operator=(const vtkInformationVector&); // Not implemented. diff --git a/Common/Core/vtkInstantiator.h b/Common/Core/vtkInstantiator.h index da50fca4f0f..2a625826a2c 100644 --- a/Common/Core/vtkInstantiator.h +++ b/Common/Core/vtkInstantiator.h @@ -73,9 +73,9 @@ class VTKCOMMONCORE_EXPORT vtkInstantiator : public vtkObject // Description: // Create an instance of the class whose name is given. If creation // fails, a NULL pointer is returned. + VTK_NEWINSTANCE static vtkObject* CreateInstance(const char* className); - //BTX typedef vtkObject* (*CreateFunction)(); // Description: @@ -92,7 +92,6 @@ class VTKCOMMONCORE_EXPORT vtkInstantiator : public vtkObject // function registered for the same class will be left untouched. static void UnRegisterInstantiator(const char* className, CreateFunction createFunction); - //ETX protected: vtkInstantiator(); @@ -104,16 +103,13 @@ class VTKCOMMONCORE_EXPORT vtkInstantiator : public vtkObject static void ClassInitialize(); static void ClassFinalize(); - //BTX friend class vtkInstantiatorInitialize; - //ETX private: vtkInstantiator(const vtkInstantiator&); // Not implemented. void operator=(const vtkInstantiator&); // Not implemented. }; -//BTX // Utility class to make sure vtkInstantiator is initialized before it // is used. class VTKCOMMONCORE_EXPORT vtkInstantiatorInitialize @@ -132,6 +128,5 @@ class VTKCOMMONCORE_EXPORT vtkInstantiatorInitialize // vtkInstantiator. It will make sure vtkInstantiator is initialized // before it is used. static vtkInstantiatorInitialize vtkInstantiatorInitializer; -//ETX #endif diff --git a/Common/Core/vtkIntArray.cxx b/Common/Core/vtkIntArray.cxx index e41a5c9dce2..8d73d9aea7b 100644 --- a/Common/Core/vtkIntArray.cxx +++ b/Common/Core/vtkIntArray.cxx @@ -13,13 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(int); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(int); #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(int); -#define vtkIntArray_cxx #include "vtkIntArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkIntArray.h b/Common/Core/vtkIntArray.h index 3c4772b9f25..8be3630c2fa 100644 --- a/Common/Core/vtkIntArray.h +++ b/Common/Core/vtkIntArray.h @@ -25,36 +25,38 @@ #ifndef vtkIntArray_h #define vtkIntArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkIntArray_cxx) && (defined(VTK_USE_64BIT_IDS) || !defined(vtkIdTypeArray_h)) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE int -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkIntArray : public vtkDataArray { public: vtkTypeMacro(vtkIntArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkIntArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(int); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkIntArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static int GetDataTypeValueMin() { return VTK_INT_MIN; } @@ -68,11 +70,14 @@ class VTKCOMMONCORE_EXPORT vtkIntArray : public vtkDataArray ~vtkIntArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkIntArray(const vtkIntArray&); // Not implemented. void operator=(const vtkIntArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkIntArray) + #endif diff --git a/Common/Core/vtkLargeInteger.cxx b/Common/Core/vtkLargeInteger.cxx index a02c6b7c301..c28de7cc2fa 100644 --- a/Common/Core/vtkLargeInteger.cxx +++ b/Common/Core/vtkLargeInteger.cxx @@ -270,109 +270,109 @@ void vtkLargeInteger::Complement(void) } } -int vtkLargeInteger::operator==(const vtkLargeInteger& n) const +bool vtkLargeInteger::operator==(const vtkLargeInteger& n) const { if (this->Sig != n.Sig) // check size { - return 0; + return false; } if (this->Negative != n.Negative) // check sign { - return 0; + return false; } for (int i = this->Sig; i >= 0; i--) { if (this->Number[i] != n.Number[i]) // check bits { - return 0; + return false; } } - return 1; + return true; } -int vtkLargeInteger::operator!=(const vtkLargeInteger& n) const +bool vtkLargeInteger::operator!=(const vtkLargeInteger& n) const { return !(*this == n); } -int vtkLargeInteger::IsSmaller(const vtkLargeInteger& n) const +bool vtkLargeInteger::IsSmaller(const vtkLargeInteger& n) const { if (this->Sig < n.Sig) // check size { - return 1; + return true; } if (this->Sig > n.Sig) // check size { - return 0; + return false; } for (int i = this->Sig; i >= 0; i--) { if (this->Number[i] < n.Number[i]) // check bits { - return 1; + return true; } if (this->Number[i] > n.Number[i]) { - return 0; + return false; } } - return 0; + return false; } -int vtkLargeInteger::IsGreater(const vtkLargeInteger& n) const +bool vtkLargeInteger::IsGreater(const vtkLargeInteger& n) const { if (this->Sig > n.Sig) // check size { - return 1; + return true; } if (this->Sig < n.Sig) // check sign { - return 0; + return false; } for (int i = this->Sig; i >= 0; i--) { if (this->Number[i] > n.Number[i]) // check bits { - return 1; + return true; } if (this->Number[i] < n.Number[i]) { - return 0; + return false; } } - return 0; + return false; } -int vtkLargeInteger::operator<(const vtkLargeInteger& n) const +bool vtkLargeInteger::operator<(const vtkLargeInteger& n) const { if (this->Negative & !n.Negative) // try to make judgement using signs - return 1; + return true; else if ((!this->Negative) & n.Negative) - return 0; + return false; else if (this->Negative) return !this->IsSmaller(n); else return this->IsSmaller(n); } -int vtkLargeInteger::operator<=(const vtkLargeInteger& n) const +bool vtkLargeInteger::operator<=(const vtkLargeInteger& n) const { return *this < n || *this == n; } -int vtkLargeInteger::operator>(const vtkLargeInteger& n) const +bool vtkLargeInteger::operator>(const vtkLargeInteger& n) const { return !(*this <= n); } -int vtkLargeInteger::operator>=(const vtkLargeInteger& n) const +bool vtkLargeInteger::operator>=(const vtkLargeInteger& n) const { return !(*this < n); } diff --git a/Common/Core/vtkLargeInteger.h b/Common/Core/vtkLargeInteger.h index e46f93ab293..cb8219bbb63 100644 --- a/Common/Core/vtkLargeInteger.h +++ b/Common/Core/vtkLargeInteger.h @@ -50,12 +50,12 @@ class VTKCOMMONCORE_EXPORT vtkLargeInteger void Truncate(unsigned int n); // reduce to lower n bits void Complement(void); // * -1 - int operator==(const vtkLargeInteger& n) const; - int operator!=(const vtkLargeInteger& n) const; - int operator<(const vtkLargeInteger& n) const; - int operator<=(const vtkLargeInteger& n) const; - int operator>(const vtkLargeInteger& n) const; - int operator>=(const vtkLargeInteger& n) const; + bool operator==(const vtkLargeInteger& n) const; + bool operator!=(const vtkLargeInteger& n) const; + bool operator<(const vtkLargeInteger& n) const; + bool operator<=(const vtkLargeInteger& n) const; + bool operator>(const vtkLargeInteger& n) const; + bool operator>=(const vtkLargeInteger& n) const; vtkLargeInteger& operator=(const vtkLargeInteger& n); vtkLargeInteger& operator+=(const vtkLargeInteger& n); @@ -96,8 +96,8 @@ class VTKCOMMONCORE_EXPORT vtkLargeInteger unsigned int Max; // unsigned operators - int IsSmaller(const vtkLargeInteger& n) const; // unsigned - int IsGreater(const vtkLargeInteger& n) const; // unsigned + bool IsSmaller(const vtkLargeInteger& n) const; // unsigned + bool IsGreater(const vtkLargeInteger& n) const; // unsigned void Expand(unsigned int n); // ensure n'th bit exits void Contract(); // remove leading 0s void Plus(const vtkLargeInteger& n); // unsigned diff --git a/Common/Core/vtkLongArray.cxx b/Common/Core/vtkLongArray.cxx index 1f1c1003653..1585fc576f4 100644 --- a/Common/Core/vtkLongArray.cxx +++ b/Common/Core/vtkLongArray.cxx @@ -13,13 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(long); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(long); #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(long); -#define vtkLongArray_cxx #include "vtkLongArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkLongArray.h b/Common/Core/vtkLongArray.h index 296b321772c..d3169f6ee68 100644 --- a/Common/Core/vtkLongArray.h +++ b/Common/Core/vtkLongArray.h @@ -26,36 +26,38 @@ #ifndef vtkLongArray_h #define vtkLongArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkLongArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE long -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkLongArray : public vtkDataArray { public: vtkTypeMacro(vtkLongArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkLongArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(long); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkLongArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static long GetDataTypeValueMin() { return VTK_LONG_MIN; } @@ -69,11 +71,14 @@ class VTKCOMMONCORE_EXPORT vtkLongArray : public vtkDataArray ~vtkLongArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkLongArray(const vtkLongArray&); // Not implemented. void operator=(const vtkLongArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkLongArray) + #endif diff --git a/Common/Core/vtkLongLongArray.cxx b/Common/Core/vtkLongLongArray.cxx index 86ae59aa02c..8179b8199fc 100644 --- a/Common/Core/vtkLongLongArray.cxx +++ b/Common/Core/vtkLongLongArray.cxx @@ -13,12 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(long long); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(long long); + #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(long long); -#define vtkLongLongArray_cxx #include "vtkLongLongArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkLongLongArray.h b/Common/Core/vtkLongLongArray.h index 2488fbb1427..9259d72a4a5 100644 --- a/Common/Core/vtkLongLongArray.h +++ b/Common/Core/vtkLongLongArray.h @@ -25,35 +25,38 @@ #ifndef vtkLongLongArray_h #define vtkLongLongArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkLongLongArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE long long -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkLongLongArray : public vtkDataArray { public: vtkTypeMacro(vtkLongLongArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkLongLongArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(long long); #endif + + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkLongLongArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static long long GetDataTypeValueMin() { return VTK_LONG_LONG_MIN; } @@ -67,11 +70,14 @@ class VTKCOMMONCORE_EXPORT vtkLongLongArray : public vtkDataArray ~vtkLongLongArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkLongLongArray(const vtkLongLongArray&); // Not implemented. void operator=(const vtkLongLongArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkLongLongArray) + #endif diff --git a/Common/Core/vtkLookupTable.h b/Common/Core/vtkLookupTable.h index 1f962e9ec8f..3cd24cf20b5 100644 --- a/Common/Core/vtkLookupTable.h +++ b/Common/Core/vtkLookupTable.h @@ -282,7 +282,6 @@ class VTKCOMMONCORE_EXPORT vtkLookupTable : public vtkScalarsToColors void SetRange(double min, double max) { this->SetTableRange(min, max); }; void SetRange(double rng[2]) { this->SetRange(rng[0], rng[1]); }; - //BTX // Description: // Returns the log of \c range in \c log_range. // There is a little more to this than simply taking the log10 of the @@ -294,7 +293,6 @@ class VTKCOMMONCORE_EXPORT vtkLookupTable : public vtkScalarsToColors // Apply log to value, with appropriate constraints. static double ApplyLogScale(double v, const double range[2], const double log_range[2]); - //ETX // Description: // Set the number of colors in the lookup table. Use diff --git a/Common/Core/vtkMappedDataArray.h b/Common/Core/vtkMappedDataArray.h index d713e830089..cba31a467af 100644 --- a/Common/Core/vtkMappedDataArray.h +++ b/Common/Core/vtkMappedDataArray.h @@ -34,14 +34,11 @@ #include "vtkTypedDataArray.h" -#include "vtkTypeTemplate.h" // for vtkTypeTemplate - template -class vtkMappedDataArray : public vtkTypeTemplate, - vtkTypedDataArray > +class vtkMappedDataArray : public vtkTypedDataArray { public: - typedef vtkTypedDataArray Superclass; + vtkTemplateTypeMacro(vtkMappedDataArray, vtkTypedDataArray) typedef typename Superclass::ValueType ValueType; // Description: @@ -73,7 +70,7 @@ class vtkMappedDataArray : public vtkTypeTemplate, // Description: // Print an error and create an internal, long-lived temporary array. This // method should not be used on vtkMappedDataArray subclasses. See - // vtkTypedDataArrayIterator and/or vtkDataArrayIteratorMacro instead. + // vtkArrayDispatch for a better way. void * GetVoidPointer(vtkIdType id); // Description: @@ -130,11 +127,15 @@ class vtkMappedDataArray : public vtkTypeTemplate, size_t TemporaryScalarPointerSize; }; +// Declare vtkArrayDownCast implementations for mapped containers: +vtkArrayDownCast_TemplateFastCastMacro(vtkMappedDataArray) + #include "vtkMappedDataArray.txx" -// Adds an implementation of NewInstanceInternal() that returns a standard -// (unmapped) VTK array, if possible. Use this with classes that derive from -// vtkTypeTemplate, otherwise, use vtkMappedDataArrayTypeMacro. +// Adds an implementation of NewInstanceInternal() that returns an AoS +// (unmapped) VTK array, if possible. Use this in combination with +// vtkAbstractTemplateTypeMacro when your subclass is a template class. +// Otherwise, use vtkMappedDataArrayTypeMacro. #define vtkMappedDataArrayNewInstanceMacro(thisClass) \ protected: \ vtkObjectBase *NewInstanceInternal() const \ diff --git a/Common/Core/vtkMappedDataArray.txx b/Common/Core/vtkMappedDataArray.txx index 5d59c87cb07..857c19980eb 100644 --- a/Common/Core/vtkMappedDataArray.txx +++ b/Common/Core/vtkMappedDataArray.txx @@ -132,16 +132,21 @@ void vtkMappedDataArray::DataChanged() template inline vtkMappedDataArray* vtkMappedDataArray::FastDownCast(vtkAbstractArray *source) { - switch (source->GetArrayType()) + if (source) { - case vtkAbstractArray::MappedDataArray: - if (source->GetDataType() == vtkTypeTraits::VTK_TYPE_ID) - { - return static_cast*>(source); - } - default: - return NULL; + switch (source->GetArrayType()) + { + case vtkAbstractArray::MappedDataArray: + if (vtkDataTypesCompare(source->GetDataType(), + vtkTypeTraits::VTK_TYPE_ID)) + { + return static_cast*>(source); + } + default: + break; + } } + return NULL; } //------------------------------------------------------------------------------ diff --git a/Common/Core/vtkMath.h b/Common/Core/vtkMath.h index d84e0eb8517..07d6ed1eed6 100644 --- a/Common/Core/vtkMath.h +++ b/Common/Core/vtkMath.h @@ -38,6 +38,7 @@ #include "vtkCommonCoreModule.h" // For export macro #include "vtkObject.h" +#include "vtkTypeTraits.h" // For type traits #include "vtkMathConfigure.h" // For and VTK_HAS_ISNAN etc. @@ -69,6 +70,13 @@ class vtkMathInternal; class vtkMinimalStandardRandomSequence; class vtkBoxMuellerRandomSequence; +namespace vtk_detail +{ +// forward declaration +template +void RoundDoubleToIntegralIfNecessary(double val, OutT* ret); +} // end namespace vtk_detail + class VTKCOMMONCORE_EXPORT vtkMath : public vtkObject { public: @@ -97,6 +105,17 @@ class VTKCOMMONCORE_EXPORT vtkMath : public vtkObject static int Round(double f) { return static_cast( f + ( f >= 0.0 ? 0.5 : -0.5 ) ); } + // Description: + // Round a double to type OutT if OutT is integral, otherwise simply clamp + // the value to the output range. + template + static void RoundDoubleToIntegralIfNecessary(double val, OutT* ret) + { + // Can't specialize template methods in a template class, so we move the + // implementations to a external namespace. + vtk_detail::RoundDoubleToIntegralIfNecessary(val, ret); + } + // Description: // Rounds a double to the nearest integer not greater than itself. // This is faster than floor() but provides undefined output on @@ -1173,7 +1192,6 @@ inline void vtkMath::Cross(const double x[3], const double y[3], double z[3]) z[0] = Zx; z[1] = Zy; z[2] = Zz; } -//BTX //---------------------------------------------------------------------------- template inline double vtkDeterminant3x3(T A[3][3]) @@ -1182,7 +1200,6 @@ inline double vtkDeterminant3x3(T A[3][3]) A[2][0] * A[0][1] * A[1][2] - A[0][0] * A[2][1] * A[1][2] - A[1][0] * A[0][1] * A[2][2] - A[2][0] * A[1][1] * A[0][2]; } -//ETX //---------------------------------------------------------------------------- inline double vtkMath::Determinant3x3(float A[3][3]) @@ -1295,6 +1312,30 @@ inline double vtkMath::ClampAndNormalizeValue(double value, return result; } +namespace vtk_detail +{ +// Can't specialize templates inside a template class, so we move the impl here. +template +void RoundDoubleToIntegralIfNecessary(double val, OutT* ret) +{ // OutT is integral -- clamp and round + val = vtkMath::Max(val, static_cast(vtkTypeTraits::Min())); + val = vtkMath::Min(val, static_cast(vtkTypeTraits::Max())); + *ret = static_cast((val >= 0.0) ? (val + 0.5) : (val - 0.5)); +} +template <> +inline void RoundDoubleToIntegralIfNecessary(double val, double* retVal) +{ // OutT is double: passthrough + *retVal = val; +} +template <> +inline void RoundDoubleToIntegralIfNecessary(double val, float* retVal) +{ // OutT is float -- just clamp + val = vtkMath::Max(val, static_cast(vtkTypeTraits::Min())); + val = vtkMath::Min(val, static_cast(vtkTypeTraits::Max())); + *retVal = static_cast(val); +} +} // end namespace vtk_detail + //----------------------------------------------------------------------------- #if defined(VTK_HAS_ISINF) || defined(VTK_HAS_STD_ISINF) #define VTK_MATH_ISINF_IS_INLINE diff --git a/Common/Core/vtkMultiThreader.h b/Common/Core/vtkMultiThreader.h index d79cde709ad..b371a19daed 100644 --- a/Common/Core/vtkMultiThreader.h +++ b/Common/Core/vtkMultiThreader.h @@ -48,7 +48,7 @@ // function is of type void *, and returns NULL // Otherwise the type is void which is correct for WIN32 // and SPROC -//BTX + #ifdef VTK_USE_SPROC typedef int vtkThreadProcessIDType; typedef int vtkMultiThreaderIDType; @@ -81,7 +81,6 @@ typedef int vtkThreadProcessIDType; // #define VTK_THREAD_RETURN_TYPE void typedef int vtkMultiThreaderIDType; #endif -//ETX class vtkMutexLock; @@ -105,7 +104,6 @@ class VTKCOMMONCORE_EXPORT vtkMultiThreader : public vtkObject // The UserData is the (void *)arg passed into the SetSingleMethod, // SetMultipleMethod, or SpawnThread method. - //BTX #define ThreadInfoStruct vtkMultiThreader::ThreadInfo class ThreadInfo { @@ -116,7 +114,6 @@ class VTKCOMMONCORE_EXPORT vtkMultiThreader : public vtkObject vtkMutexLock *ActiveFlagLock; void *UserData; }; - //ETX // Description: // Get/Set the number of threads to create. It will be clamped to the range @@ -142,7 +139,6 @@ class VTKCOMMONCORE_EXPORT vtkMultiThreader : public vtkObject // These methods are excluded from Tcl wrapping 1) because the // wrapper gives up on them and 2) because they really shouldn't be // called from a script anyway. - //BTX // Description: // Execute the SingleMethod (as define by SetSingleMethod) using @@ -214,8 +210,6 @@ class VTKCOMMONCORE_EXPORT vtkMultiThreader : public vtkObject vtkThreadProcessIDType SpawnedThreadProcessID[VTK_MAX_THREADS]; ThreadInfo SpawnedThreadInfoArray[VTK_MAX_THREADS]; -//ETX - // Internal storage of the data void *SingleData; void *MultipleData[VTK_MAX_THREADS]; diff --git a/Common/Core/vtkMutexLock.h b/Common/Core/vtkMutexLock.h index 78583d4192b..d630337dbf2 100644 --- a/Common/Core/vtkMutexLock.h +++ b/Common/Core/vtkMutexLock.h @@ -25,8 +25,6 @@ #include "vtkCommonCoreModule.h" // For export macro #include "vtkObject.h" -//BTX - #ifdef VTK_USE_SPROC #include // Needed for SPROC implementation of mutex typedef abilock_t vtkMutexType; @@ -78,8 +76,6 @@ class VTKCOMMONCORE_EXPORT vtkSimpleMutexLock vtkSimpleMutexLock& operator=(const vtkSimpleMutexLock& rhs); // no copy assignment }; -//ETX - class VTKCOMMONCORE_EXPORT vtkMutexLock : public vtkObject { public: @@ -97,9 +93,8 @@ class VTKCOMMONCORE_EXPORT vtkMutexLock : public vtkObject void Unlock( void ); protected: - //BTX + friend class vtkConditionVariable; // needs to get at SimpleMutexLock. - //ETX vtkSimpleMutexLock SimpleMutexLock; vtkMutexLock() {} diff --git a/Common/Core/vtkObject.h b/Common/Core/vtkObject.h index eb46b54eebe..b5d47812d1b 100644 --- a/Common/Core/vtkObject.h +++ b/Common/Core/vtkObject.h @@ -111,7 +111,6 @@ class VTKCOMMONCORE_EXPORT vtkObject : public vtkObjectBase {vtkObject::SetGlobalWarningDisplay(0);}; static int GetGlobalWarningDisplay(); -//BTX // Description: // Allow people to add/remove/invoke observers (callbacks) to any VTK // object. This is an implementation of the subject/observer design @@ -133,7 +132,7 @@ class VTKCOMMONCORE_EXPORT vtkObject : public vtkObjectBase void RemoveObservers(const char *event, vtkCommand *); int HasObserver(unsigned long event, vtkCommand *); int HasObserver(const char *event, vtkCommand *); -//ETX + void RemoveObserver(unsigned long tag); void RemoveObservers(unsigned long event); void RemoveObservers(const char *event); @@ -141,7 +140,6 @@ class VTKCOMMONCORE_EXPORT vtkObject : public vtkObjectBase int HasObserver(unsigned long event); int HasObserver(const char *event); -//BTX // Description: // Overloads to AddObserver that allow developers to add class member // functions as callbacks for events. The callback function can @@ -202,16 +200,14 @@ class VTKCOMMONCORE_EXPORT vtkObject : public vtkObjectBase // vtkObjectCommandInternal) return this->AddTemplatedObserver(event, callable, priority); } -//ETX -//BTX // Description: // This method invokes an event and return whether the event was // aborted or not. If the event was aborted, the return value is 1, // otherwise it is 0. int InvokeEvent(unsigned long event, void *callData); int InvokeEvent(const char *event, void *callData); -//ETX + int InvokeEvent(unsigned long event) { return this->InvokeEvent(event, NULL); }; int InvokeEvent(const char *event) { return this->InvokeEvent(event, NULL); }; @@ -220,14 +216,13 @@ class VTKCOMMONCORE_EXPORT vtkObject : public vtkObjectBase virtual ~vtkObject(); // See vtkObjectBase.h. - virtual void RegisterInternal(vtkObjectBase*, int check); - virtual void UnRegisterInternal(vtkObjectBase*, int check); + void RegisterInternal(vtkObjectBase*, int check) VTK_OVERRIDE; + void UnRegisterInternal(vtkObjectBase*, int check) VTK_OVERRIDE; bool Debug; // Enable debug messages vtkTimeStamp MTime; // Keep track of modification time vtkSubjectHelper *SubjectHelper; // List of observers on this object -//BTX // Description: // These methods allow a command to exclusively grab all events. (This // method is typically used by widgets to grab events once an event @@ -237,8 +232,7 @@ class VTKCOMMONCORE_EXPORT vtkObject : public vtkObjectBase // they use two separate vtkCommands to watch for mouse and keypress events. void InternalGrabFocus(vtkCommand *mouseEvents, vtkCommand *keypressEvents=NULL); void InternalReleaseFocus(); -//ETX -//BTX + private: vtkObject(const vtkObject&); // Not implemented. void operator=(const vtkObject&); // Not implemented. @@ -365,7 +359,7 @@ class VTKCOMMONCORE_EXPORT vtkObject : public vtkObjectBase unsigned long event, vtkClassMemberCallbackBase* callable, float priority); // Friend to access AddTemplatedObserver(). friend class vtkObjectCommandInternal; -//ETX + }; #endif diff --git a/Common/Core/vtkObjectBase.h b/Common/Core/vtkObjectBase.h index 75725cde549..83a4683e872 100644 --- a/Common/Core/vtkObjectBase.h +++ b/Common/Core/vtkObjectBase.h @@ -73,11 +73,11 @@ class VTKCOMMONCORE_EXPORT vtkObjectBase #ifdef VTK_WORKAROUND_WINDOWS_MANGLE # undef GetClassNameW # undef GetClassNameA - //BTX + // Define possible mangled names. const char* GetClassNameA() const; const char* GetClassNameW() const; - //ETX + #endif // Description: @@ -176,16 +176,16 @@ class VTKCOMMONCORE_EXPORT vtkObjectBase virtual void ReportReferences(vtkGarbageCollector*); private: - //BTX + friend VTKCOMMONCORE_EXPORT ostream& operator<<(ostream& os, vtkObjectBase& o); friend class vtkGarbageCollectorToObjectBaseFriendship; friend class vtkWeakPointerBaseToObjectBaseFriendship; - //ETX + protected: -//BTX + vtkObjectBase(const vtkObjectBase&) {} void operator=(const vtkObjectBase&) {} -//ETX + }; #endif diff --git a/Common/Core/vtkObjectFactory.h b/Common/Core/vtkObjectFactory.h index b6590a2bfdc..39aed11fed2 100644 --- a/Common/Core/vtkObjectFactory.h +++ b/Common/Core/vtkObjectFactory.h @@ -55,6 +55,7 @@ class VTKCOMMONCORE_EXPORT vtkObjectFactory : public vtkObject // If the requested class is abstract, set isAbstract to true. Otherwise // it is assumed that an instance of 'vtkclassname' will be instantiated // by the caller when no override is found. + VTK_NEWINSTANCE static vtkObject* CreateInstance(const char* vtkclassname, bool isAbstract = false); @@ -180,11 +181,9 @@ class VTKCOMMONCORE_EXPORT vtkObjectFactory : public vtkObject // This returns the path to a dynamically loaded factory. vtkGetStringMacro(LibraryPath); - //BTX typedef vtkObject* (*CreateFunction)(); - //ETX + protected: - //BTX // Description: // Register object creation information with the factory. @@ -194,9 +193,6 @@ class VTKCOMMONCORE_EXPORT vtkObjectFactory : public vtkObject int enableFlag, CreateFunction createFunction); - //ETX - - // Description: // This method is provided by sub-classes of vtkObjectFactory. // It should create the named vtk object or return 0 if that object @@ -205,7 +201,7 @@ class VTKCOMMONCORE_EXPORT vtkObjectFactory : public vtkObject vtkObjectFactory(); ~vtkObjectFactory(); - //BTX + struct OverrideInformation { char* Description; @@ -213,7 +209,7 @@ class VTKCOMMONCORE_EXPORT vtkObjectFactory : public vtkObject int EnabledFlag; CreateFunction CreateCallback; }; - //ETX + OverrideInformation* OverrideArray; char** OverrideClassNames; int SizeOverrideArray; diff --git a/Common/Core/vtkObjectFactoryCollection.h b/Common/Core/vtkObjectFactoryCollection.h index 3e6bcd0af41..ec00958f298 100644 --- a/Common/Core/vtkObjectFactoryCollection.h +++ b/Common/Core/vtkObjectFactoryCollection.h @@ -47,14 +47,12 @@ class VTKCOMMONCORE_EXPORT vtkObjectFactoryCollection : public vtkCollection vtkObjectFactory *GetNextItem() { return static_cast(this->GetNextItemAsObject());} - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkObjectFactory *GetNextObjectFactory(vtkCollectionSimpleIterator &cookie) { return static_cast( this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkObjectFactoryCollection() {} diff --git a/Common/Core/vtkOutputWindow.h b/Common/Core/vtkOutputWindow.h index f5ee8b2811f..88ce50c7325 100644 --- a/Common/Core/vtkOutputWindow.h +++ b/Common/Core/vtkOutputWindow.h @@ -25,7 +25,6 @@ #include "vtkCommonCoreModule.h" // For export macro #include "vtkObject.h" -//BTX class VTKCOMMONCORE_EXPORT vtkOutputWindowCleanup { public: @@ -36,7 +35,6 @@ class VTKCOMMONCORE_EXPORT vtkOutputWindowCleanup vtkOutputWindowCleanup(const vtkOutputWindowCleanup& other); // no copy constructor vtkOutputWindowCleanup& operator=(const vtkOutputWindowCleanup& rhs); // no copy assignment }; -//ETX class VTKCOMMONCORE_EXPORT vtkOutputWindow : public vtkObject { @@ -77,12 +75,12 @@ class VTKCOMMONCORE_EXPORT vtkOutputWindow : public vtkObject // messages. vtkBooleanMacro(PromptUser,int); vtkSetMacro(PromptUser, int); -//BTX + // use this as a way of memory management when the // program exits the SmartPointer will be deleted which // will delete the Instance singleton static vtkOutputWindowCleanup Cleanup; -//ETX + protected: vtkOutputWindow(); virtual ~vtkOutputWindow(); diff --git a/Common/Core/vtkOverrideInformation.h b/Common/Core/vtkOverrideInformation.h index c0fbc467586..cf921fe0dbe 100644 --- a/Common/Core/vtkOverrideInformation.h +++ b/Common/Core/vtkOverrideInformation.h @@ -82,9 +82,8 @@ class VTKCOMMONCORE_EXPORT vtkOverrideInformation : public vtkObject ~vtkOverrideInformation(); // allow the object factory to set the values in this // class, but only the object factory -//BTX + friend class vtkObjectFactory; -//ETX char* ClassOverrideName; char* ClassOverrideWithName; diff --git a/Common/Core/vtkOverrideInformationCollection.h b/Common/Core/vtkOverrideInformationCollection.h index 3e11dc0b15f..4cba8a8e7db 100644 --- a/Common/Core/vtkOverrideInformationCollection.h +++ b/Common/Core/vtkOverrideInformationCollection.h @@ -41,7 +41,6 @@ class VTKCOMMONCORE_EXPORT vtkOverrideInformationCollection : public vtkCollecti // Get the next OverrideInformation in the list. vtkOverrideInformation *GetNextItem(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. @@ -49,7 +48,6 @@ class VTKCOMMONCORE_EXPORT vtkOverrideInformationCollection : public vtkCollecti vtkCollectionSimpleIterator &cookie) { return static_cast( this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkOverrideInformationCollection() {} diff --git a/Common/Core/vtkPeriodicDataArray.h b/Common/Core/vtkPeriodicDataArray.h index f1c34ff44ec..917e492dd73 100644 --- a/Common/Core/vtkPeriodicDataArray.h +++ b/Common/Core/vtkPeriodicDataArray.h @@ -26,19 +26,23 @@ #ifndef vtkPeriodicDataArray_h #define vtkPeriodicDataArray_h -#include "vtkMappedDataArray.h" // Parent -#include "vtkDataArrayTemplate.h" // Template +#include "vtkGenericDataArray.h" // Parent +#include "vtkAOSDataArrayTemplate.h" // Template template class vtkPeriodicDataArray: -public vtkTypeTemplate , vtkMappedDataArray > + public vtkGenericDataArray, Scalar> { + typedef vtkGenericDataArray, Scalar> GenericBase; public: + vtkTemplateTypeMacro(vtkPeriodicDataArray, GenericBase) + typedef typename Superclass::ValueType ValueType; + virtual void PrintSelf(ostream &os, vtkIndent indent); // Description: // Initialize the mapped array with the original input data array. - void InitializeArray(vtkDataArrayTemplate* inputData); + virtual void InitializeArray(vtkAOSDataArrayTemplate* inputData); // Description: // Initialize array with zero values @@ -58,7 +62,7 @@ public vtkTypeTemplate , vtkMappedDataArray , vtkMappedDataArray , vtkMappedDataArray , vtkMappedDataArray , vtkMappedDataArray , Scalar>; + + Scalar* TempScalarArray; // Temporary array used by GetTypedTuple methods double* TempDoubleArray; // Temporary array used by GetTuple vethods vtkIdType TempTupleIdx; // Location of currently stored Temp Tuple to use as cache - vtkDataArrayTemplate* Data; // Original data + vtkAOSDataArrayTemplate* Data; // Original data bool InvalidRange; double PeriodicRange[6]; // Transformed periodic range diff --git a/Common/Core/vtkPeriodicDataArray.txx b/Common/Core/vtkPeriodicDataArray.txx index 8dbf31cf575..4e2487bdb3a 100644 --- a/Common/Core/vtkPeriodicDataArray.txx +++ b/Common/Core/vtkPeriodicDataArray.txx @@ -52,7 +52,7 @@ template void vtkPeriodicDataArray //------------------------------------------------------------------------------ template void vtkPeriodicDataArray -::InitializeArray(vtkDataArrayTemplate* data) +::InitializeArray(vtkAOSDataArrayTemplate* data) { this->Initialize(); if (!data) @@ -61,13 +61,6 @@ template void vtkPeriodicDataArray return; } - if (data->GetNumberOfComponents() != 3 && data->GetNumberOfComponents() != 9) - { - vtkWarningMacro(<< "Original data has " << data->GetNumberOfComponents() << - " components, Expecting 3 or 9."); - return; - } - this->NumberOfComponents = data->GetNumberOfComponents(); this->Size = data->GetSize(); this->MaxId = data->GetMaxId(); @@ -112,21 +105,9 @@ ComputeScalarRange(double* range) template bool vtkPeriodicDataArray:: ComputeVectorRange(double range[2]) { - if (this->NumberOfComponents == 3) + if (this->NumberOfComponents == 3 && this->Data) { - if (this->InvalidRange) - { - this->ComputePeriodicRange(); - } - - range[0] = vtkTypeTraits::Max(); - range[1] = vtkTypeTraits::Min(); - - for (int i = 0; i < 3; i++) - { - range[0] = std::min(this->PeriodicRange[i * 2], range[0]); - range[1] = std::max(this->PeriodicRange[i * 2 + 1], range[1]); - } + this->Data->GetRange(range, -1); } else { @@ -310,7 +291,7 @@ template double* vtkPeriodicDataArray { if (this->TempTupleIdx != i) { - this->GetTupleValue(i, this->TempScalarArray); + this->GetTypedTuple(i, this->TempScalarArray); this->TempTupleIdx = i; } for (int j = 0; j < this->NumberOfComponents; j++) @@ -326,7 +307,7 @@ template void vtkPeriodicDataArray { if (this->TempTupleIdx != i) { - this->GetTupleValue(i, this->TempScalarArray); + this->GetTypedTuple(i, this->TempScalarArray); this->TempTupleIdx = i; } for (int j = 0; j < this->NumberOfComponents; j++) @@ -351,20 +332,22 @@ template void vtkPeriodicDataArray } //------------------------------------------------------------------------------ -template Scalar vtkPeriodicDataArray -::GetValue(vtkIdType idx) +template +typename vtkPeriodicDataArray::ValueType +vtkPeriodicDataArray::GetValue(vtkIdType idx) const { - return this->GetValueReference(idx); + return const_cast*>(this)->GetValueReference(idx); } //------------------------------------------------------------------------------ -template Scalar& vtkPeriodicDataArray -::GetValueReference(vtkIdType idx) +template +typename vtkPeriodicDataArray::ValueType& +vtkPeriodicDataArray::GetValueReference(vtkIdType idx) { vtkIdType tupleIdx = idx / this->NumberOfComponents; if (tupleIdx != this->TempTupleIdx) { - this->GetTupleValue(tupleIdx, this->TempScalarArray); + this->GetTypedTuple(tupleIdx, this->TempScalarArray); this->TempTupleIdx = tupleIdx; } return this->TempScalarArray[idx % this->NumberOfComponents]; @@ -372,12 +355,28 @@ template Scalar& vtkPeriodicDataArray //------------------------------------------------------------------------------ template void vtkPeriodicDataArray -::GetTupleValue(vtkIdType tupleId, Scalar *tuple) +::GetTypedTuple(vtkIdType tupleId, Scalar *tuple) const { - this->Data->GetTupleValue(tupleId, tuple); + this->Data->GetTypedTuple(tupleId, tuple); this->Transform(tuple); } +//------------------------------------------------------------------------------ +template +typename vtkPeriodicDataArray::ValueType +vtkPeriodicDataArray::GetTypedComponent(vtkIdType tupleId, + int compId) const +{ + if (tupleId != this->TempTupleIdx) + { + this->Data->GetTypedTuple(tupleId, this->TempScalarArray); + this->Transform(const_cast(this->TempScalarArray)); + *const_cast(&this->TempTupleIdx) = tupleId; + } + + return this->TempScalarArray[compId]; +} + //------------------------------------------------------------------------------ template unsigned long int vtkPeriodicDataArray ::GetActualMemorySize() @@ -556,21 +555,28 @@ template void vtkPeriodicDataArray //------------------------------------------------------------------------------ template void vtkPeriodicDataArray -::SetTupleValue(vtkIdType, const Scalar*) +::SetTypedTuple(vtkIdType, const Scalar*) { vtkErrorMacro("Read only container."); } //------------------------------------------------------------------------------ template void vtkPeriodicDataArray -::InsertTupleValue(vtkIdType, const Scalar*) +::SetTypedComponent(vtkIdType, int, Scalar) +{ + vtkErrorMacro("Read only container."); +} + +//------------------------------------------------------------------------------ +template void vtkPeriodicDataArray +::InsertTypedTuple(vtkIdType, const Scalar*) { vtkErrorMacro("Read only container."); } //------------------------------------------------------------------------------ template vtkIdType vtkPeriodicDataArray -::InsertNextTupleValue(const Scalar *) +::InsertNextTypedTuple(const Scalar *) { vtkErrorMacro("Read only container."); return -1; @@ -598,6 +604,22 @@ template void vtkPeriodicDataArray vtkErrorMacro("Read only container."); } +//------------------------------------------------------------------------------ +template bool vtkPeriodicDataArray +::AllocateTuples(vtkIdType) +{ + vtkErrorMacro("Read only container."); + return false; +} + +//------------------------------------------------------------------------------ +template bool vtkPeriodicDataArray +::ReallocateTuples(vtkIdType) +{ + vtkErrorMacro("Read only container."); + return false; +} + //------------------------------------------------------------------------------ template void vtkPeriodicDataArray ::InvalidateRange() diff --git a/Common/Core/vtkPoints.h b/Common/Core/vtkPoints.h index 898b5a16ab4..8aacde67a47 100644 --- a/Common/Core/vtkPoints.h +++ b/Common/Core/vtkPoints.h @@ -30,9 +30,9 @@ class vtkIdList; class VTKCOMMONCORE_EXPORT vtkPoints : public vtkObject { public: -//BTX + static vtkPoints *New(int dataType); -//ETX + static vtkPoints *New(); vtkTypeMacro(vtkPoints,vtkObject); diff --git a/Common/Core/vtkPoints2D.h b/Common/Core/vtkPoints2D.h index 569b4332453..f67be026f29 100644 --- a/Common/Core/vtkPoints2D.h +++ b/Common/Core/vtkPoints2D.h @@ -30,9 +30,9 @@ class vtkIdList; class VTKCOMMONCORE_EXPORT vtkPoints2D : public vtkObject { public: -//BTX + static vtkPoints2D *New(int dataType); -//ETX + static vtkPoints2D *New(); vtkTypeMacro(vtkPoints2D, vtkObject); diff --git a/Common/Core/vtkPriorityQueue.h b/Common/Core/vtkPriorityQueue.h index cbbaec43f04..a3f30ca1fcd 100644 --- a/Common/Core/vtkPriorityQueue.h +++ b/Common/Core/vtkPriorityQueue.h @@ -43,14 +43,13 @@ class VTKCOMMONCORE_EXPORT vtkPriorityQueue : public vtkObject { public: - //BTX + class Item { public: double priority; vtkIdType id; }; - //ETX // Description: // Instantiate priority queue with default size and extension size of 1000. @@ -68,26 +67,22 @@ class VTKCOMMONCORE_EXPORT vtkPriorityQueue : public vtkObject // index like a point id or cell id. void Insert(double priority, vtkIdType id); -//BTX // Description: // Removes item at specified location from tree; then reorders and // balances tree. The location == 0 is the root of the tree. If queue // is exhausted, then a value < 0 is returned. (Note: the location // is not the same as deleting an id; id is mapped to location.) vtkIdType Pop(vtkIdType location, double &priority); -//ETX // Description: // Same as above but simplified for easier wrapping into interpreted // languages. vtkIdType Pop(vtkIdType location=0); -//BTX // Description: // Peek into the queue without actually removing anything. Returns the // id and the priority. vtkIdType Peek(vtkIdType location, double &priority); -//ETX // Description: // Peek into the queue without actually removing anything. Returns the diff --git a/Common/Core/vtkSMPTools.h b/Common/Core/vtkSMPTools.h index df474b9e3b4..9c9d46dd424 100644 --- a/Common/Core/vtkSMPTools.h +++ b/Common/Core/vtkSMPTools.h @@ -31,7 +31,7 @@ #ifndef DOXYGEN_SHOULD_SKIP_THIS -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ namespace vtk { namespace detail @@ -129,7 +129,7 @@ class vtkSMPTools_Lookup_For } // namespace smp } // namespace detail } // namespace vtk -#endif // __WRAP__ +#endif // __VTK_WRAP__ #endif // DOXYGEN_SHOULD_SKIP_THIS class VTKCOMMONCORE_EXPORT vtkSMPTools diff --git a/Common/Core/vtkSOADataArrayTemplate.h b/Common/Core/vtkSOADataArrayTemplate.h new file mode 100644 index 00000000000..35c53840582 --- /dev/null +++ b/Common/Core/vtkSOADataArrayTemplate.h @@ -0,0 +1,267 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSOADataArrayTemplate.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkSOADataArrayTemplate - Struct-Of-Arrays implementation of +// vtkGenericDataArray. +// +// .SECTION Description +// vtkSOADataArrayTemplate is the counterpart of vtkAOSDataArrayTemplate. Each +// component is stored in a separate array. +// +// .SECTION See Also +// vtkGenericDataArray vtkAOSDataArrayTemplate + +#ifndef vtkSOADataArrayTemplate_h +#define vtkSOADataArrayTemplate_h + +#include "vtkCommonCoreModule.h" // For export macro +#include "vtkGenericDataArray.h" +#include "vtkBuffer.h" + +// The export macro below makes no sense, but is necessary for older compilers +// when we export instantiations of this class from vtkCommonCore. +template +class VTKCOMMONCORE_EXPORT vtkSOADataArrayTemplate : + public vtkGenericDataArray, ValueTypeT> +{ + typedef vtkGenericDataArray, ValueTypeT> + GenericDataArrayType; +public: + typedef vtkSOADataArrayTemplate SelfType; + vtkTemplateTypeMacro(SelfType, GenericDataArrayType) + typedef typename Superclass::ValueType ValueType; + + enum DeleteMethod + { + VTK_DATA_ARRAY_FREE=vtkBuffer::VTK_DATA_ARRAY_FREE, + VTK_DATA_ARRAY_DELETE=vtkBuffer::VTK_DATA_ARRAY_DELETE + }; + + static vtkSOADataArrayTemplate* New(); + + // Description: + // Get the value at @a valueIdx. @a valueIdx assumes AOS ordering. + inline ValueType GetValue(vtkIdType valueIdx) const + { + vtkIdType tupleIdx; + int comp; + this->GetTupleIndexFromValueIndex(valueIdx, tupleIdx, comp); + return this->GetTypedComponent(tupleIdx, comp); + } + + // Description: + // Set the value at @a valueIdx to @a value. @a valueIdx assumes AOS ordering. + inline void SetValue(vtkIdType valueIdx, ValueType value) + { + vtkIdType tupleIdx; + int comp; + this->GetTupleIndexFromValueIndex(valueIdx, tupleIdx, comp); + this->SetTypedComponent(tupleIdx, comp, value); + } + + // Description: + // Copy the tuple at @a tupleIdx into @a tuple. + inline void GetTypedTuple(vtkIdType tupleIdx, ValueType* tuple) const + { + for (size_t cc=0; cc < this->Data.size(); cc++) + { + tuple[cc] = this->Data[cc]->GetBuffer()[tupleIdx]; + } + } + + // Description: + // Set this array's tuple at @a tupleIdx to the values in @a tuple. + inline void SetTypedTuple(vtkIdType tupleIdx, const ValueType* tuple) + { + for (size_t cc=0; cc < this->Data.size(); ++cc) + { + this->Data[cc]->GetBuffer()[tupleIdx] = tuple[cc]; + } + } + + // Description: + // Get component @a comp of the tuple at @a tupleIdx. + inline ValueType GetTypedComponent(vtkIdType tupleIdx, int comp) const + { + return this->Data[comp]->GetBuffer()[tupleIdx]; + } + + // Description: + // Set component @a comp of the tuple at @a tupleIdx to @a value. + inline void SetTypedComponent(vtkIdType tupleIdx, int comp, ValueType value) + { + this->Data[comp]->GetBuffer()[tupleIdx] = value; + } + + // Description: + // Use this API to pass externally allocated memory to this instance. Since + // vtkSOADataArrayTemplate uses separate contiguous regions for each + // component, use this API to add arrays for each of the component. + // \c save: When set to true, vtkSOADataArrayTemplate will not release or + // realloc the memory even when the AllocatorType is set to RESIZABLE. If + // needed it will simply allow new memory buffers and "forget" the supplied + // pointers. When save is set to false, this will be the \c deleteMethod + // specified to release the array. + // If updateMaxId is true, the array's MaxId will be updated, and assumes + // that size is the number of tuples in the array. + // \c size is specified in number of elements of ScalarType. + void SetArray(int comp, ValueType* array, vtkIdType size, + bool updateMaxId = false, bool save=false, + int deleteMethod=VTK_DATA_ARRAY_FREE); + + // Description: + // Return a pointer to a contiguous block of memory containing all values for + // a particular components (ie. a single array of the struct-of-arrays). + ValueType* GetComponentArrayPointer(int comp); + + // Description: + // Use of this method is discouraged, it creates a deep copy of the data into + // a contiguous AoS-ordered buffer and prints a warning. + virtual void *GetVoidPointer(vtkIdType valueIdx); + + // Description: + // Export a copy of the data in AoS ordering to the preallocated memory + // buffer. + void ExportToVoidPointer(void *ptr); + + // Description: + // Perform a fast, safe cast from a vtkAbstractArray to a vtkDataArray. + // This method checks if source->GetArrayType() returns DataArray + // or a more derived type, and performs a static_cast to return + // source as a vtkDataArray pointer. Otherwise, NULL is returned. + static vtkSOADataArrayTemplate* + FastDownCast(vtkAbstractArray *source) + { + if (source) + { + switch (source->GetArrayType()) + { + case vtkAbstractArray::SoADataArrayTemplate: + if (vtkDataTypesCompare(source->GetDataType(), + vtkTypeTraits::VTK_TYPE_ID)) + { + return static_cast*>(source); + } + break; + } + } + return NULL; + } + + virtual int GetArrayType() { return vtkAbstractArray::SoADataArrayTemplate; } + virtual VTK_NEWINSTANCE vtkArrayIterator *NewIterator(); + virtual void SetNumberOfComponents(int numComps); + virtual void ShallowCopy(vtkDataArray *other); + + // Reimplemented for efficiency: + virtual void InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, + vtkAbstractArray* source); + // MSVC doesn't like 'using' here (error C2487). Just forward instead: + // using Superclass::InsertTuples; + virtual void InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, + vtkAbstractArray *source) + { this->Superclass::InsertTuples(dstIds, srcIds, source); } + +protected: + vtkSOADataArrayTemplate(); + ~vtkSOADataArrayTemplate(); + + // Description: + // Allocate space for numTuples. Old data is not preserved. If numTuples == 0, + // all data is freed. + bool AllocateTuples(vtkIdType numTuples); + + // Description: + // Allocate space for numTuples. Old data is preserved. If numTuples == 0, + // all data is freed. + bool ReallocateTuples(vtkIdType numTuples); + + std::vector*> Data; + vtkBuffer *AoSCopy; + + double NumberOfComponentsReciprocal; + +private: + vtkSOADataArrayTemplate(const vtkSOADataArrayTemplate&); // Not implemented. + void operator=(const vtkSOADataArrayTemplate&); // Not implemented. + + inline void GetTupleIndexFromValueIndex(vtkIdType valueIdx, + vtkIdType& tupleIdx, int& comp) const + { + tupleIdx = static_cast(valueIdx * + this->NumberOfComponentsReciprocal); + comp = valueIdx - (tupleIdx * this->NumberOfComponents); + } + + friend class vtkGenericDataArray, + ValueTypeT>; +}; + +// Declare vtkArrayDownCast implementations for SoA containers: +vtkArrayDownCast_TemplateFastCastMacro(vtkSOADataArrayTemplate) + +# define VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(T) \ + template class VTKCOMMONCORE_EXPORT vtkSOADataArrayTemplate< T > + +#endif // header guard + +// This portion must be OUTSIDE the include blockers. This is used to tell +// libraries other than vtkCommonCore that instantiations of +// vtkSOADataArrayTemplate can be found externally. This prevents each library +// from instantiating these on their own. +#ifndef VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATING +#if defined(VTK_BUILD_SHARED_LIBS) && defined(_MSC_VER) +#pragma warning (push) + +// C4091: 'extern ' : ignored on left of 'int' when no variable is declared +#pragma warning (disable: 4091) + +// Compiler-specific extension warning. +#pragma warning (disable: 4231) + +// We need to disable warning 4910 and do an extern dllexport +// anyway. When deriving new arrays from an +// instantiation of this template the compiler does an explicit +// instantiation of the base class. From outside the vtkCommon +// library we block this using an extern dllimport instantiation. +// For classes inside vtkCommon we should be able to just do an +// extern instantiation, but VS 2008 complains about missing +// definitions. We cannot do an extern dllimport inside vtkCommon +// since the symbols are local to the dll. An extern dllexport +// seems to be the only way to convince VS 2008 to do the right +// thing, so we just disable the warning. +#pragma warning (disable: 4910) // extern and dllexport incompatible + +// Use an "extern explicit instantiation" to give the class a DLL +// interface. This is a compiler-specific extension. +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(char); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(double); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(float); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(int); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(long); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(long long); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(short); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(signed char); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned char); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned int); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned long); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned long long); +extern VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned short); + +#pragma warning (pop) + +#endif // VTK_BUILD_SHARED_LIBS && _MSC_VER +#endif // VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATING + +// VTK-HeaderTest-Exclude: vtkSOADataArrayTemplate.h diff --git a/Common/Core/vtkSOADataArrayTemplate.txx b/Common/Core/vtkSOADataArrayTemplate.txx new file mode 100644 index 00000000000..cef1e1b93c8 --- /dev/null +++ b/Common/Core/vtkSOADataArrayTemplate.txx @@ -0,0 +1,311 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSOADataArrayTemplate.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#ifndef vtkSOADataArrayTemplate_txx +#define vtkSOADataArrayTemplate_txx + +#include "vtkSOADataArrayTemplate.h" + +#include "vtkArrayIteratorTemplate.h" +#include "vtkBuffer.h" + +#include + +//----------------------------------------------------------------------------- +template +vtkSOADataArrayTemplate* +vtkSOADataArrayTemplate::New() +{ + VTK_STANDARD_NEW_BODY(vtkSOADataArrayTemplate); +} + +//----------------------------------------------------------------------------- +template +vtkSOADataArrayTemplate::vtkSOADataArrayTemplate() + : AoSCopy(NULL), + NumberOfComponentsReciprocal(1.0) +{ +} + +//----------------------------------------------------------------------------- +template +vtkSOADataArrayTemplate::~vtkSOADataArrayTemplate() +{ + for (size_t cc = 0; cc < this->Data.size(); ++cc) + { + this->Data[cc]->Delete(); + } + this->Data.clear(); + if (this->AoSCopy) + { + this->AoSCopy->Delete(); + this->AoSCopy = NULL; + } +} + +//----------------------------------------------------------------------------- +template +void vtkSOADataArrayTemplate::SetNumberOfComponents(int val) +{ + this->GenericDataArrayType::SetNumberOfComponents(val); + size_t numComps = static_cast(this->GetNumberOfComponents()); + assert(numComps >= 1); + while (this->Data.size() > numComps) + { + this->Data.back()->Delete(); + this->Data.pop_back(); + } + while (this->Data.size() < numComps) + { + this->Data.push_back(vtkBuffer::New()); + } + this->NumberOfComponentsReciprocal = 1.0 / this->NumberOfComponents; +} + +//----------------------------------------------------------------------------- +template +vtkArrayIterator* vtkSOADataArrayTemplate::NewIterator() +{ + vtkArrayIterator *iter = vtkArrayIteratorTemplate::New(); + iter->Initialize(this); + return iter; +} + +//----------------------------------------------------------------------------- +template +void vtkSOADataArrayTemplate::ShallowCopy(vtkDataArray *other) +{ + SelfType *o = SelfType::FastDownCast(other); + if (o) + { + this->Size = o->Size; + this->MaxId = o->MaxId; + this->SetName(o->Name); + this->SetNumberOfComponents(o->NumberOfComponents); + this->CopyComponentNames(o); + assert(this->Data.size() == o->Data.size()); + for (size_t cc = 0; cc < this->Data.size(); ++cc) + { + vtkBuffer *thisBuffer = this->Data[cc]; + vtkBuffer *otherBuffer = o->Data[cc]; + if (thisBuffer != otherBuffer) + { + thisBuffer->Delete(); + this->Data[cc] = otherBuffer; + otherBuffer->Register(NULL); + } + } + this->DataChanged(); + } + else + { + this->Superclass::ShallowCopy(other); + } +} + +//----------------------------------------------------------------------------- +template +void vtkSOADataArrayTemplate::InsertTuples( + vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, + vtkAbstractArray *source) +{ + // First, check for the common case of typeid(source) == typeid(this). This + // way we don't waste time redoing the other checks in the superclass, and + // can avoid doing a dispatch for the most common usage of this method. + SelfType *other = vtkArrayDownCast(source); + if (!other) + { + // Let the superclass handle dispatch/fallback. + this->Superclass::InsertTuples(dstStart, n, srcStart, source); + return; + } + + if (n == 0) + { + return; + } + + int numComps = this->GetNumberOfComponents(); + if (other->GetNumberOfComponents() != numComps) + { + vtkErrorMacro("Number of components do not match: Source: " + << other->GetNumberOfComponents() << " Dest: " + << this->GetNumberOfComponents()); + return; + } + + vtkIdType maxSrcTupleId = srcStart + n - 1; + vtkIdType maxDstTupleId = dstStart + n - 1; + + if (maxSrcTupleId >= other->GetNumberOfTuples()) + { + vtkErrorMacro("Source array too small, requested tuple at index " + << maxSrcTupleId << ", but there are only " + << other->GetNumberOfTuples() << " tuples in the array."); + return; + } + + vtkIdType newSize = (maxDstTupleId + 1) * this->NumberOfComponents; + if (this->Size < newSize) + { + if (!this->Resize(maxDstTupleId + 1)) + { + vtkErrorMacro("Resize failed."); + return; + } + } + + this->MaxId = std::max(this->MaxId, newSize - 1); + + for (int c = 0; c < numComps; ++c) + { + ValueType *srcBegin = other->GetComponentArrayPointer(c) + srcStart; + ValueType *srcEnd = srcBegin + n; + ValueType *dstBegin = this->GetComponentArrayPointer(c) + dstStart; + std::copy(srcBegin, srcEnd, dstBegin); + } +} + +//----------------------------------------------------------------------------- +template +void vtkSOADataArrayTemplate::SetArray(int comp, ValueType* array, + vtkIdType size, + bool updateMaxId, + bool save, int deleteMethod) +{ + const int numComps = this->GetNumberOfComponents(); + if (comp >= numComps || comp < 0) + { + vtkErrorMacro("Invalid component number '" << comp << "' specified. " + "Use `SetNumberOfComponents` first to set the number of components."); + return; + } + + this->Data[comp]->SetBuffer(array, size, save, deleteMethod); + if (updateMaxId) + { + this->Size = numComps * size; + this->MaxId = this->Size - 1; + } + this->DataChanged(); +} + +//----------------------------------------------------------------------------- +template +typename vtkSOADataArrayTemplate::ValueType* +vtkSOADataArrayTemplate::GetComponentArrayPointer(int comp) +{ + const int numComps = this->GetNumberOfComponents(); + if (comp >= numComps || comp < 0) + { + vtkErrorMacro("Invalid component number '" << comp << "' specified."); + return NULL; + } + + return this->Data[comp]->GetBuffer(); +} + +//----------------------------------------------------------------------------- +template +bool vtkSOADataArrayTemplate::AllocateTuples(vtkIdType numTuples) +{ + for (size_t cc = 0, max = this->Data.size(); cc < max; ++cc) + { + if (!this->Data[cc]->Allocate(numTuples)) + { + return false; + } + } + return true; +} + +//----------------------------------------------------------------------------- +template +bool vtkSOADataArrayTemplate::ReallocateTuples(vtkIdType numTuples) +{ + for (size_t cc = 0, max = this->Data.size(); cc < max; ++cc) + { + if (!this->Data[cc]->Reallocate(numTuples)) + { + return false; + } + } + return true; +} + +//----------------------------------------------------------------------------- +template +void *vtkSOADataArrayTemplate::GetVoidPointer(vtkIdType valueIdx) +{ + // Allow warnings to be silenced: + const char *silence = getenv("VTK_SILENCE_GET_VOID_POINTER_WARNINGS"); + if (!silence) + { + vtkWarningMacro(<<"GetVoidPointer called. This is very expensive for " + "non-array-of-structs subclasses, as the scalar array " + "must be generated for each call. Using the " + "vtkGenericDataArray API with vtkArrayDispatch are " + "preferred. Define the environment variable " + "VTK_SILENCE_GET_VOID_POINTER_WARNINGS to silence " + "this warning."); + } + + size_t numValues = this->GetNumberOfValues(); + + if (!this->AoSCopy) + { + this->AoSCopy = vtkBuffer::New(); + } + + if (!this->AoSCopy->Allocate(numValues)) + { + vtkErrorMacro(<<"Error allocating a buffer of " << numValues << " '" + << this->GetDataTypeAsString() << "' elements."); + return NULL; + } + + this->ExportToVoidPointer(static_cast(this->AoSCopy->GetBuffer())); + + return static_cast(this->AoSCopy->GetBuffer() + valueIdx); +} + +//----------------------------------------------------------------------------- +template +void vtkSOADataArrayTemplate::ExportToVoidPointer(void *voidPtr) +{ + vtkIdType numTuples = this->GetNumberOfTuples(); + if (this->NumberOfComponents * numTuples == 0) + { + // Nothing to do. + return; + } + + if (!voidPtr) + { + vtkErrorMacro(<< "Buffer is NULL."); + return; + } + + ValueType *ptr = static_cast(voidPtr); + for (vtkIdType t = 0; t < numTuples; ++t) + { + for (int c = 0; c < this->NumberOfComponents; ++c) + { + *ptr++ = this->Data[c]->GetBuffer()[t]; + } + } +} + +#endif diff --git a/Common/Core/vtkSOADataArrayTemplateInstantiate.cxx b/Common/Core/vtkSOADataArrayTemplateInstantiate.cxx new file mode 100644 index 00000000000..609fafba631 --- /dev/null +++ b/Common/Core/vtkSOADataArrayTemplateInstantiate.cxx @@ -0,0 +1,37 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSOADataArrayTemplateInstantiate.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +// This file generates instantiations of vtkSOADataArrayTemplate for the +// common data types. For AoS arrays, this is done in the more derived classes +// (e.g. vtkFloatArray.cxx.o contains the instantiation of +// vtkAOSDataArrayTemplate), but since these aren't derived from in VTK +// (yet), we instantiate them here. + +#define VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkSOADataArrayTemplate.txx" + +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(char); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(double); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(float); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(int); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(long); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(long long); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(short); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(signed char); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned char); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned int); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned long); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned long long); +VTK_SOA_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned short); diff --git a/Common/Core/vtkScalarsToColors.cxx b/Common/Core/vtkScalarsToColors.cxx index 02a09e66eaa..1ac24acfb27 100644 --- a/Common/Core/vtkScalarsToColors.cxx +++ b/Common/Core/vtkScalarsToColors.cxx @@ -234,11 +234,11 @@ vtkUnsignedCharArray *vtkScalarsToColors::MapScalars(vtkAbstractArray *scalars, int numberOfComponents = scalars->GetNumberOfComponents(); vtkUnsignedCharArray *newColors; - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(scalars); + vtkDataArray *dataArray = vtkArrayDownCast(scalars); // map scalars through lookup table only if needed if ((colorMode == VTK_COLOR_MODE_DEFAULT && - vtkUnsignedCharArray::SafeDownCast(dataArray) != NULL) || + vtkArrayDownCast(dataArray) != NULL) || (colorMode == VTK_COLOR_MODE_DIRECT_SCALARS && dataArray)) { newColors = this-> @@ -1542,16 +1542,16 @@ void vtkScalarsToColors::MapScalarsThroughTable2( vtkUnsignedCharArray *vtkScalarsToColors::ConvertToRGBA( vtkDataArray *colors, int numComp, int numTuples) { - if (vtkCharArray::SafeDownCast(colors) != NULL) + if (vtkArrayDownCast(colors) != NULL) { vtkErrorMacro(<<"char type does not have enough values to hold a color"); return NULL; } if (numComp == 4 && this->Alpha >= 1.0 && - vtkUnsignedCharArray::SafeDownCast(colors) != NULL) + vtkArrayDownCast(colors) != NULL) { - vtkUnsignedCharArray* c = vtkUnsignedCharArray::SafeDownCast(colors); + vtkUnsignedCharArray* c = vtkArrayDownCast(colors); c->Register(this); return c; } diff --git a/Common/Core/vtkScalarsToColors.h b/Common/Core/vtkScalarsToColors.h index 32e05fe7be2..025784398f7 100644 --- a/Common/Core/vtkScalarsToColors.h +++ b/Common/Core/vtkScalarsToColors.h @@ -147,14 +147,11 @@ class VTKCOMMONCORE_EXPORT vtkScalarsToColors : public vtkObject void SetVectorModeToComponent(); void SetVectorModeToRGBColors(); -//BTX enum VectorModes { MAGNITUDE=0, COMPONENT=1, RGBCOLORS=2 }; -//ETX - // Description: // If the mapper does not select which component of a vector diff --git a/Common/Core/vtkSetGet.h b/Common/Core/vtkSetGet.h index 6ce507dd0ed..78115bc3aab 100644 --- a/Common/Core/vtkSetGet.h +++ b/Common/Core/vtkSetGet.h @@ -28,6 +28,7 @@ #include "vtkCommonCoreModule.h" // For export macro #include "vtkSystemIncludes.h" #include +#include //---------------------------------------------------------------------------- // Check for unsupported old compilers. @@ -602,14 +603,17 @@ virtual double *Get##name() \ // Allows definition of vtkObject API such that NewInstance may return a // superclass of thisClass. -#define vtkAbstractTypeMacroWithNewInstanceType(thisClass,superclass,instanceType) \ - typedef superclass Superclass; \ - private: \ - virtual const char* GetClassNameInternal() const { return #thisClass; } \ +#define vtkAbstractTypeMacroWithNewInstanceType(thisClass,superclass,instanceType,thisClassName) \ + protected: \ + virtual const char* GetClassNameInternal() const \ + { \ + return thisClassName; \ + } \ public: \ + typedef superclass Superclass; \ static int IsTypeOf(const char *type) \ { \ - if ( !strcmp(#thisClass,type) ) \ + if ( !strcmp(thisClassName,type) ) \ { \ return 1; \ } \ @@ -621,20 +625,21 @@ virtual double *Get##name() \ } \ static thisClass* SafeDownCast(vtkObjectBase *o) \ { \ - if ( o && o->IsA(#thisClass) ) \ + if ( o && o->IsA(thisClassName) ) \ { \ return static_cast(o); \ } \ return NULL;\ } \ - instanceType *NewInstance() const \ + VTK_NEWINSTANCE instanceType *NewInstance() const \ { \ return instanceType::SafeDownCast(this->NewInstanceInternal()); \ } -// Same as vtkTypeMacro, but adapted for cases where thisClass is abstact. +// Same as vtkTypeMacro, but adapted for cases where thisClass is abstract. #define vtkAbstractTypeMacro(thisClass,superclass) \ - vtkAbstractTypeMacroWithNewInstanceType(thisClass, superclass, thisClass) + vtkAbstractTypeMacroWithNewInstanceType(thisClass, superclass, thisClass, #thisClass) \ + public: // Macro used to determine whether a class is the same class or // a subclass of the named class. @@ -647,6 +652,32 @@ virtual double *Get##name() \ } \ public: +// Version of vtkAbstractTypeMacro for when thisClass is templated. +// For templates, we use the compiler generated typeid(...).name() identifier +// to distinguish classes. Otherwise, the template parameter names would appear +// in the class name, rather than the actual parameters. The resulting name may +// not be human readable on some platforms, but it will at least be unique. On +// GCC 4.9.2 release builds, this ends up being the same performance-wise as +// returning a string literal as the name() string is resolved at compile time. +// +// If either class has multiple template parameters, the commas will interfere +// with the macro call. In this case, create a typedef to the multi-parameter +// template class and pass that into the macro instead. +#define vtkAbstractTemplateTypeMacro(thisClass,superclass) \ + vtkAbstractTypeMacroWithNewInstanceType(thisClass, superclass, thisClass, typeid(thisClass).name()) \ + public: + +// Version of vtkTypeMacro for when thisClass is templated. +// See vtkAbstractTemplateTypeMacro for more info. +#define vtkTemplateTypeMacro(thisClass,superclass) \ + vtkAbstractTemplateTypeMacro(thisClass, superclass) \ + protected: \ + virtual vtkObjectBase *NewInstanceInternal() const \ + { \ + return thisClass::New(); \ + } \ + public: + // Macro to implement the instantiator's wrapper around the New() // method. Use this macro if and only if vtkStandardNewMacro or // vtkObjectFactoryNewMacro is not used by the class. @@ -657,6 +688,9 @@ virtual double *Get##name() \ return thisClass::New(); \ } +// NOTE: This is no longer the prefer method for dispatching an array to a +// worker template. See vtkArrayDispatch for the new approach. +// // The vtkTemplateMacro is used to centralize the set of types // supported by Execute methods. It also avoids duplication of long // switch statement case lists. diff --git a/Common/Core/vtkShortArray.cxx b/Common/Core/vtkShortArray.cxx index 08f4760cd4d..e0225a627a5 100644 --- a/Common/Core/vtkShortArray.cxx +++ b/Common/Core/vtkShortArray.cxx @@ -13,12 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(short); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(short); + #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(short); -#define vtkShortArray_cxx #include "vtkShortArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkShortArray.h b/Common/Core/vtkShortArray.h index 3595fcf93b1..964a1b41367 100644 --- a/Common/Core/vtkShortArray.h +++ b/Common/Core/vtkShortArray.h @@ -25,36 +25,38 @@ #ifndef vtkShortArray_h #define vtkShortArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkShortArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE short -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkShortArray : public vtkDataArray { public: vtkTypeMacro(vtkShortArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkShortArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(short); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkShortArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static short GetDataTypeValueMin() { return VTK_SHORT_MIN; } @@ -68,11 +70,14 @@ class VTKCOMMONCORE_EXPORT vtkShortArray : public vtkDataArray ~vtkShortArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkShortArray(const vtkShortArray&); // Not implemented. void operator=(const vtkShortArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkShortArray) + #endif diff --git a/Common/Core/vtkSignedCharArray.cxx b/Common/Core/vtkSignedCharArray.cxx index 699adce431e..e7a047a29a3 100644 --- a/Common/Core/vtkSignedCharArray.cxx +++ b/Common/Core/vtkSignedCharArray.cxx @@ -13,12 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(signed char); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(signed char); + #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(signed char); -#define vtkSignedCharArray_cxx #include "vtkSignedCharArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkSignedCharArray.h b/Common/Core/vtkSignedCharArray.h index d9968557c11..b75be1d32cb 100644 --- a/Common/Core/vtkSignedCharArray.h +++ b/Common/Core/vtkSignedCharArray.h @@ -21,36 +21,38 @@ #ifndef vtkSignedCharArray_h #define vtkSignedCharArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkSignedCharArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE signed char -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkSignedCharArray : public vtkDataArray { public: vtkTypeMacro(vtkSignedCharArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkSignedCharArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(signed char); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkSignedCharArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static signed char GetDataTypeValueMin() { return VTK_SIGNED_CHAR_MIN; } @@ -64,11 +66,14 @@ class VTKCOMMONCORE_EXPORT vtkSignedCharArray : public vtkDataArray ~vtkSignedCharArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkSignedCharArray(const vtkSignedCharArray&); // Not implemented. void operator=(const vtkSignedCharArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkSignedCharArray) + #endif diff --git a/Common/Core/vtkSimpleCriticalSection.h b/Common/Core/vtkSimpleCriticalSection.h index aa7656e37e3..246eb927526 100644 --- a/Common/Core/vtkSimpleCriticalSection.h +++ b/Common/Core/vtkSimpleCriticalSection.h @@ -36,8 +36,6 @@ #include "vtkCommonCoreModule.h" // For export macro #include "vtkSystemIncludes.h" -//BTX - #ifdef VTK_USE_SPROC #include // Needed for sproc implementation of mutex typedef abilock_t vtkCritSecType; @@ -99,7 +97,6 @@ class VTKCOMMONCORE_EXPORT vtkSimpleCriticalSection vtkSimpleCriticalSection(const vtkSimpleCriticalSection& other); // no copy constructor vtkSimpleCriticalSection& operator=(const vtkSimpleCriticalSection& rhs); // no copy assignment }; -//ETX #endif // VTK-HeaderTest-Exclude: vtkSimpleCriticalSection.h diff --git a/Common/Core/vtkSparseArray.h b/Common/Core/vtkSparseArray.h index 0cf6b6fe152..3211faa464d 100644 --- a/Common/Core/vtkSparseArray.h +++ b/Common/Core/vtkSparseArray.h @@ -66,14 +66,13 @@ #include "vtkArrayCoordinates.h" #include "vtkArraySort.h" #include "vtkObjectFactory.h" -#include "vtkTypeTemplate.h" #include "vtkTypedArray.h" template -class vtkSparseArray : - public vtkTypeTemplate, vtkTypedArray > +class vtkSparseArray : public vtkTypedArray { public: + vtkTemplateTypeMacro(vtkSparseArray, vtkTypedArray) static vtkSparseArray* New(); void PrintSelf(ostream &os, vtkIndent indent); diff --git a/Common/Core/vtkStringArray.cxx b/Common/Core/vtkStringArray.cxx index 72d4363408c..da783fa36a4 100644 --- a/Common/Core/vtkStringArray.cxx +++ b/Common/Core/vtkStringArray.cxx @@ -201,7 +201,7 @@ void vtkStringArray::DeepCopy(vtkAbstractArray* aa) return; } - vtkStringArray *fa = vtkStringArray::SafeDownCast( aa ); + vtkStringArray *fa = vtkArrayDownCast( aa ); if ( fa == NULL ) { vtkErrorMacro(<< "Shouldn't Happen: Couldn't downcast array into a vtkStringArray." ); @@ -518,7 +518,7 @@ vtkIdType vtkStringArray::GetDataSize() void vtkStringArray::SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) { - vtkStringArray* sa = vtkStringArray::SafeDownCast(source); + vtkStringArray* sa = vtkArrayDownCast(source); if (!sa) { vtkWarningMacro("Input and outputs array data types do not match."); @@ -540,7 +540,7 @@ void vtkStringArray::SetTuple(vtkIdType i, vtkIdType j, void vtkStringArray::InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) { - vtkStringArray* sa = vtkStringArray::SafeDownCast(source); + vtkStringArray* sa = vtkArrayDownCast(source); if (!sa) { vtkWarningMacro("Input and outputs array data types do not match."); @@ -560,7 +560,7 @@ void vtkStringArray::InsertTuple(vtkIdType i, vtkIdType j, void vtkStringArray::InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, vtkAbstractArray *source) { - vtkStringArray* sa = vtkStringArray::SafeDownCast(source); + vtkStringArray* sa = vtkArrayDownCast(source); if (!sa) { vtkWarningMacro("Input and outputs array data types do not match."); @@ -598,7 +598,7 @@ void vtkStringArray::InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, void vtkStringArray::InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, vtkAbstractArray *source) { - vtkStringArray* sa = vtkStringArray::SafeDownCast(source); + vtkStringArray* sa = vtkArrayDownCast(source); if (!sa) { vtkWarningMacro("Input and outputs array data types do not match."); @@ -641,7 +641,7 @@ void vtkStringArray::InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType vtkStringArray::InsertNextTuple(vtkIdType j, vtkAbstractArray* source) { - vtkStringArray* sa = vtkStringArray::SafeDownCast(source); + vtkStringArray* sa = vtkArrayDownCast(source); if (!sa) { vtkWarningMacro("Input and outputs array data types do not match."); @@ -672,7 +672,7 @@ void vtkStringArray::GetTuples(vtkIdList *indices, vtkAbstractArray *aa) return; } - vtkStringArray *output = vtkStringArray::SafeDownCast(aa); + vtkStringArray *output = vtkArrayDownCast(aa); if (output == NULL) { @@ -699,7 +699,7 @@ void vtkStringArray::GetTuples(vtkIdType startIndex, return; } - vtkStringArray *output = vtkStringArray::SafeDownCast(aa); + vtkStringArray *output = vtkArrayDownCast(aa); if (output == NULL) { diff --git a/Common/Core/vtkStringArray.h b/Common/Core/vtkStringArray.h index 66d07d51ee8..0f451d3ab46 100644 --- a/Common/Core/vtkStringArray.h +++ b/Common/Core/vtkStringArray.h @@ -146,13 +146,12 @@ class VTKCOMMONCORE_EXPORT vtkStringArray : public vtkAbstractArray // Get the data at a particular index. vtkStdString &GetValue(vtkIdType id); -//BTX // Description: // Set the data at a particular index. Does not do range checking. Make sure // you use the method SetNumberOfValues() before inserting data. void SetValue(vtkIdType id, vtkStdString value) { this->Array[id] = value; this->DataChanged(); } -//ETX + void SetValue(vtkIdType id, const char *value); // Description: @@ -172,11 +171,10 @@ class VTKCOMMONCORE_EXPORT vtkStringArray : public vtkAbstractArray int GetNumberOfElementComponents() { return 0; } int GetElementComponentSize() { return static_cast(sizeof(vtkStdString::value_type)); } -//BTX // Description: // Insert data at a specified position in the array. void InsertValue(vtkIdType id, vtkStdString f); -//ETX + void InsertValue(vtkIdType id, const char *val); // Description: @@ -189,36 +187,29 @@ class VTKCOMMONCORE_EXPORT vtkStringArray : public vtkAbstractArray // Safely insert a value into the array from a variant. void InsertVariantValue(vtkIdType idx, vtkVariant value); -//BTX // Description: // Insert data at the end of the array. Return its location in the array. vtkIdType InsertNextValue(vtkStdString f); -//ETX + vtkIdType InsertNextValue(const char *f); -//BTX // Description: // Get the address of a particular data index. Make sure data is allocated // for the number of items requested. Set MaxId according to the number of // data values requested. vtkStdString* WritePointer(vtkIdType id, vtkIdType number); -//ETX -//BTX // Description: // Get the address of a particular data index. Performs no checks // to verify that the memory has been allocated etc. vtkStdString* GetPointer(vtkIdType id) { return this->Array + id; } void* GetVoidPointer(vtkIdType id) { return this->GetPointer(id); } -//ETX // Description: // Deep copy of another string array. Will complain and change nothing // if the array passed in is not a vtkStringArray. void DeepCopy( vtkAbstractArray* aa ); - -//BTX // Description: // This method lets the user specify data to be held by the array. The // array argument is a pointer to the data. size is the size of @@ -234,7 +225,6 @@ class VTKCOMMONCORE_EXPORT vtkStringArray : public vtkAbstractArray virtual void SetVoidArray(void* array, vtkIdType size, int save, int vtkNotUsed(deleteMethod)) { this->SetArray(static_cast(array), size, save); } -//ETX // Description: // Return the memory in kibibytes (1024 bytes) consumed by this data array. Used to @@ -250,7 +240,7 @@ class VTKCOMMONCORE_EXPORT vtkStringArray : public vtkAbstractArray // Description: // Returns a vtkArrayIteratorTemplate. - virtual vtkArrayIterator* NewIterator(); + virtual VTK_NEWINSTANCE vtkArrayIterator* NewIterator(); // Description: // Returns the size of the data in DataTypeSize units. Thus, the number of bytes @@ -262,10 +252,10 @@ class VTKCOMMONCORE_EXPORT vtkStringArray : public vtkAbstractArray // Return the indices where a specific value appears. virtual vtkIdType LookupValue(vtkVariant value); virtual void LookupValue(vtkVariant value, vtkIdList* ids); -//BTX + vtkIdType LookupValue(vtkStdString value); void LookupValue(vtkStdString value, vtkIdList* ids); -//ETX + vtkIdType LookupValue(const char* value); void LookupValue(const char* value, vtkIdList* ids); @@ -303,10 +293,9 @@ class VTKCOMMONCORE_EXPORT vtkStringArray : public vtkAbstractArray vtkStringArray(const vtkStringArray&); // Not implemented. void operator=(const vtkStringArray&); // Not implemented. - //BTX vtkStringArrayLookup* Lookup; void UpdateLookup(); - //ETX + }; diff --git a/Common/Core/vtkSystemIncludes.h b/Common/Core/vtkSystemIncludes.h index f959a908e0b..190d5ae1173 100644 --- a/Common/Core/vtkSystemIncludes.h +++ b/Common/Core/vtkSystemIncludes.h @@ -39,6 +39,9 @@ // Setup the basic types to be used by VTK. #include "vtkType.h" +// Define some macros to provide wrapping hints +#include "vtkWrappingHints.h" + // this should be removed at some point #define VTK_USE_EXECUTIVES diff --git a/Common/Core/vtkTestDataArray.h b/Common/Core/vtkTestDataArray.h new file mode 100644 index 00000000000..989f234fd77 --- /dev/null +++ b/Common/Core/vtkTestDataArray.h @@ -0,0 +1,89 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSOADataArrayTemplate.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkTestDataArray - An implementation of vtkGenericDataArray for testing +// fallback algorithms. +// +// .SECTION Description +// vtkTestDataArray is derived from vtkGenericDataArray, and is deliberately +// omitted from VTK's whitelist of dispatchable data arrays. It is used to test +// the fallback mechanisms of algorithms in the case that array dispatch fails. +// +// .SECTION See Also +// vtkGenericDataArray + +#ifndef vtkTestDataArray_h +#define vtkTestDataArray_h + +#include "vtkCommonCoreModule.h" // For export macro +#include "vtkGenericDataArray.h" + +template +class vtkTestDataArray : public vtkGenericDataArray, + typename ArrayT::ValueType> +{ +public: + typedef ArrayT ArrayType; + typedef typename ArrayType::ValueType ValueType; + typedef vtkTestDataArray SelfType; + typedef vtkGenericDataArray, ValueType> + GenericDataArrayType; + friend class vtkGenericDataArray, ValueType>; + + vtkAbstractTemplateTypeMacro(SelfType, GenericDataArrayType) + vtkAOSArrayNewInstanceMacro(SelfType) + + static vtkTestDataArray* New() + { VTK_STANDARD_NEW_BODY(vtkTestDataArray); } + + virtual void PrintSelf(ostream &os, vtkIndent indent) + { GenericDataArrayType::PrintSelf(os,indent); } + + ValueType GetValue(vtkIdType valueIdx) const + { return this->Array->GetValue(valueIdx); } + void SetValue(vtkIdType valueIdx, ValueType value) + { this->Array->SetValue(valueIdx,value); } + + void GetTypedTuple(vtkIdType tupleIdx, ValueType* tuple) const + { this->Array->SetTypedTuple(tupleIdx,tuple); } + void SetTypedTuple(vtkIdType tupleIdx, const ValueType* tuple) + { this->Array->SetTypedTuple(tupleIdx,tuple); } + + ValueType GetTypedComponent(vtkIdType tupleIdx, int compIdx) const + { return this->Array->GetTypedComponent(tupleIdx,compIdx); } + void SetTypedComponent(vtkIdType tupleIdx, int compIdx, ValueType value) + { this->Array->SetTypedComponent(tupleIdx,compIdx,value); } + + void *GetVoidPointer(vtkIdType valueIdx) + { return this->Array->GetVoidPointer(valueIdx); } + +protected: + vtkTestDataArray() { this->Array = ArrayType::New(); } + ~vtkTestDataArray() { this->Array->Delete(); } + + bool AllocateTuples(vtkIdType numTuples) + { return this->Array->Allocate(numTuples) != 0; } + bool ReallocateTuples(vtkIdType numTuples) + { return this->Array->Allocate(numTuples) != 0; } + +private: + ArrayType* Array; + + // Not implemented. + vtkTestDataArray(const vtkTestDataArray &); // Not implemented. + void operator=(const vtkTestDataArray &); // Not implemented. +}; + +#endif +// VTK-HeaderTest-Exclude: vtkTestDataArray.h diff --git a/Common/Core/vtkTimePointUtility.h b/Common/Core/vtkTimePointUtility.h index 0f20ad1da6d..7bde932652c 100644 --- a/Common/Core/vtkTimePointUtility.h +++ b/Common/Core/vtkTimePointUtility.h @@ -99,7 +99,6 @@ class VTKCOMMONCORE_EXPORT vtkTimePointUtility : public vtkObject // Retrieve the milliseconds from the start of the last second. static int GetMillisecond(vtkTypeUInt64 time); - //BTX enum { ISO8601_DATETIME_MILLIS = 0, ISO8601_DATETIME = 1, @@ -126,7 +125,6 @@ class VTKCOMMONCORE_EXPORT vtkTimePointUtility : public vtkObject // the second argument. The value will be set to true if the // string was parsed successfully, false otherwise. static vtkTypeUInt64 ISO8601ToTimePoint(const char* str, bool* ok = NULL); - //ETX // Description: // Converts a VTK timepoint into one of the following ISO8601 diff --git a/Common/Core/vtkTypeList.h b/Common/Core/vtkTypeList.h new file mode 100644 index 00000000000..5bde214bde2 --- /dev/null +++ b/Common/Core/vtkTypeList.h @@ -0,0 +1,152 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkTypeList.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +//////////////////////////////////////////////////////////////////////////////// +// The Loki Library +// Copyright (c) 2001 by Andrei Alexandrescu +// This code accompanies the book: +// Alexandrescu, Andrei. "Modern C++ Design: Generic Programming and Design +// Patterns Applied". Copyright (c) 2001. Addison-Wesley. +// Permission to use, copy, modify, distribute and sell this software for any +// purpose is hereby granted without fee, provided that the above copyright +// notice appear in all copies and that both that copyright notice and this +// permission notice appear in supporting documentation. +// The author or Addison-Wesley Longman make no representations about the +// suitability of this software for any purpose. It is provided "as is" +// without express or implied warranty. +//////////////////////////////////////////////////////////////////////////////// + +// .NAME vtkTypeList - TypeList implementation and utilities. +// +// .SECTION Description +// vtkTypeList provides a way to collect a list of types using C++ templates. +// In VTK, this is used heavily by the vtkArrayDispatch system to instantiate +// templated code for specific array implementations. The book "Modern C++ +// Design: Generic Programming and Design Patterns Applied" by Andrei +// Alexandrescu provides additional details and applications for typeLists. This +// implementation is heavily influenced by the example code in the book. +// +// Note that creating a typelist in C++ is simplified greatly by using the +// vtkTypeList_Create_N macros defined in the CMake-generated +// vtkTypeListMacros.h header. +// +// .SECTION See Also +// vtkArrayDispatch vtkTypeListMacros + +#ifndef vtkTypeList_h +#define vtkTypeList_h + +#include "vtkTypeListMacros.h" + +namespace vtkTypeList +{ + +//------------------------------------------------------------------------------ +// Description: +// Used to terminate a TypeList. +struct NullType {}; + +//------------------------------------------------------------------------------ +// Description: +// Generic implementation of TypeList. +template +struct TypeList +{ + typedef T Head; + typedef U Tail; +}; + +//------------------------------------------------------------------------------ +// Description: +// Sets Result to T if Exp is true, or F if Exp is false. +template +struct Select; + +//------------------------------------------------------------------------------ +// Description: +// Sets member Result to true if a conversion exists to convert type From to +// type To. Member SameType will be true if the types are identical. +template +struct CanConvert; + +//------------------------------------------------------------------------------ +// Description: +// Sets the enum value Result to the index of type T in the TypeList TList. +// Result will equal -1 if the type is not found. +template +struct IndexOf; + +//------------------------------------------------------------------------------ +// Description: +// Erase the first element of type T from TypeList TList, storing the new list +// in Result. +template +struct Erase; + +//------------------------------------------------------------------------------ +// Description: +// Erase all type T from TypeList TList, storing the new list in Result. +template +struct EraseAll; + +//------------------------------------------------------------------------------ +// Description: +// Remove all duplicate types from TypeList TList, storing the new list in +// Result. +template +struct Unique; + +//------------------------------------------------------------------------------ +// Description: +// Replace the first instance of Bad with Good in the TypeList TList, storing +// the new list in Result. +template +struct Replace; + +//------------------------------------------------------------------------------ +// Description: +// Replace all instances of Bad with Good in the TypeList TList, storing the +// new list in Result. +template +struct ReplaceAll; + +//------------------------------------------------------------------------------ +// Description: +// Given a type T and a TypeList TList, store the most derived type of T in +// TList as Result. If no subclasses of T exist in TList, T will be set as +// Result, even if T itself is not in TList. +template +struct MostDerived; + +//------------------------------------------------------------------------------ +// Description: +// Sort the TypeList from most-derived to least-derived type, storing the +// sorted TypeList in Result. Note that the input TypeList cannot have duplicate +// types (see Unique). +template +struct DerivedToFront; + +//------------------------------------------------------------------------------ +// Description: +// Appends type T to TypeList TList and stores the result in Result. +template +struct Append; + +} // end namespace vtkTypeList + +#include "vtkTypeList.txx" + +#endif // vtkTypeList_h +// VTK-HeaderTest-Exclude: vtkTypeList.h diff --git a/Common/Core/vtkTypeList.txx b/Common/Core/vtkTypeList.txx new file mode 100644 index 00000000000..1aa409fe219 --- /dev/null +++ b/Common/Core/vtkTypeList.txx @@ -0,0 +1,316 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkTypeList.txx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#ifndef vtkTypeList_txx +#define vtkTypeList_txx + +#include "vtkTypeList.h" + +namespace vtkTypeList +{ + +//------------------------------------------------------------------------------ +// Description: +// Sets Result to T if Exp is true, or F if Exp is false. +template +struct Select // True case: +{ + typedef T Result; +}; + +// False case: +template +struct Select +{ + typedef F Result; +}; + +//------------------------------------------------------------------------------ +// Description: +// Sets member Result to true if a conversion exists to convert type From to +// type To. Member SameType will be true if the types are identical. +template +struct CanConvert +{ +private: + typedef char Small; + class Big { char dummy[2]; }; + static Small DoTest(const To&); // Not implemented + static Big DoTest(...); // Not implemented + static From* MakeFrom(); // Not implemented +public: + enum { + Result = (sizeof(DoTest(*MakeFrom())) == sizeof(Small)), + SameType = false + }; +}; + +// Specialize for SameType: +template +struct CanConvert +{ + enum { Result = true, SameType = true }; +}; + +//------------------------------------------------------------------------------ +// Description: +// Sets the enum value Result to the index of type T in the TypeList TList. +// Result will equal -1 if the type is not found. + +// Terminal case: +template +struct IndexOf +{ + enum { Result = -1 }; +}; + +// Matching case: +template +struct IndexOf, T> +{ + enum { Result = 0 }; +}; + +// Recursive case: +template +struct IndexOf, T> +{ +private: + enum { TailResult = IndexOf::Result }; +public: + enum { Result = TailResult == -1 ? -1 : 1 + TailResult }; +}; + +//------------------------------------------------------------------------------ +// Description: +// Erase the first element of type T from TypeList TList. + +// Terminal case: +template +struct Erase +{ + typedef NullType Result; +}; + +// Match: +template +struct Erase, T> +{ + typedef Tail Result; +}; + +// No match: +template +struct Erase, T> +{ + typedef TypeList::Result> Result; +}; + +//------------------------------------------------------------------------------ +// Description: +// Erase all type T from TypeList TList. + +// Terminal case: +template +struct EraseAll +{ + typedef NullType Result; +}; + +// Match: +template +struct EraseAll, T> +{ + typedef typename EraseAll::Result Result; +}; + +// No match: +template +struct EraseAll, T> +{ + typedef TypeList::Result> Result; +}; + +//------------------------------------------------------------------------------ +// Description: +// Remove all duplicate types from TypeList TList + +// Terminal case: +template <> +struct Unique +{ + typedef NullType Result; +}; + +template +struct Unique > +{ +private: + typedef typename Unique::Result UniqueTail; + typedef typename Erase::Result NewTail; +public: + typedef TypeList Result; +}; + +//------------------------------------------------------------------------------ +// Description: +// Replace the first instance of Bad with Good in the TypeList TList. + +// Terminal case: +template +struct Replace +{ + typedef NullType Result; +}; + +// Match: +template +struct Replace, Bad, Good> +{ + typedef TypeList Result; +}; + +// No match: +template +struct Replace, Bad, Good> +{ + typedef TypeList::Result> Result; +}; + +// Trivial case: +template +struct Replace, T, T> +{ + typedef TypeList Result; +}; + +//------------------------------------------------------------------------------ +// Description: +// Replace all instances of Bad with Good in the TypeList TList. + +// Terminal case: +template +struct ReplaceAll +{ + typedef NullType Result; +}; + +// Match: +template +struct ReplaceAll, Bad, Good> +{ + typedef TypeList::Result> Result; +}; + +// No match: +template +struct ReplaceAll, Bad, Good> +{ + typedef TypeList::Result> Result; +}; + +// Trivial case: +template +struct ReplaceAll, T, T> +{ + typedef TypeList Result; +}; + +//------------------------------------------------------------------------------ +// Description: +// Given a type T and a TypeList TList, store the most derived type of T in +// TList as Result. If no subclasses of T exist in TList, T will be set as +// Result, even if T itself is not in TList. + +// Terminal case: +template +struct MostDerived +{ + typedef T Result; +}; + +// Recursive case: +template +struct MostDerived, T> +{ +private: + typedef typename MostDerived::Result TailResult; +public: + typedef + typename Select< + CanConvert::Result, Head, TailResult + >::Result Result; +}; + +//------------------------------------------------------------------------------ +// Description: +// Sort the TypeList from most-derived to least-derived type, storing the +// sorted TypeList in Result. Note that the input TypeList cannot have duplicate +// types (see Unique). + +// Terminal case: +template <> +struct DerivedToFront +{ + typedef NullType Result; +}; + +// Recursive case: +template +struct DerivedToFront > +{ +private: + typedef typename MostDerived::Result Derived; + typedef typename Replace::Result Replaced; + typedef typename DerivedToFront::Result NewTail; +public: + typedef TypeList Result; +}; + +//------------------------------------------------------------------------------ +// Description: +// Appends type T to TypeList TList and stores the result in Result. + +// Corner case, both are NullType: +template < > +struct Append +{ + typedef vtkTypeList::NullType Result; +}; + +// Terminal case (Single type): +template +struct Append +{ + typedef vtkTypeList::TypeList Result; +}; + +// Terminal case (TypeList): +template +struct Append > +{ + typedef vtkTypeList::TypeList Result; +}; + +// Recursive case: +template +struct Append, T> +{ + typedef vtkTypeList::TypeList::Result > Result; +}; + +} + +#endif // vtkTypeList_txx diff --git a/Common/Core/vtkTypeListMacros.h.in b/Common/Core/vtkTypeListMacros.h.in new file mode 100644 index 00000000000..5337be67dd5 --- /dev/null +++ b/Common/Core/vtkTypeListMacros.h.in @@ -0,0 +1 @@ +${VTK_TYPELISTMACRO_HEADER_CONTENTS} diff --git a/Common/Core/vtkTypeTemplate.h b/Common/Core/vtkTypeTemplate.h index 6ae8f80701b..3c268190eb6 100644 --- a/Common/Core/vtkTypeTemplate.h +++ b/Common/Core/vtkTypeTemplate.h @@ -28,13 +28,16 @@ #ifndef vtkTypeTemplate_h #define vtkTypeTemplate_h -#include "vtkObjectBase.h" +#include "vtkObject.h" #include #include +// This class is legacy. See vtkTemplateTypeMacro in vtkSetGet.h for the +// replacement. +#ifndef VTK_LEGACY_REMOVE + template -class vtkTypeTemplate : - public BaseT +class vtkTypeTemplate : public BaseT { public: typedef BaseT Superclass; @@ -82,7 +85,11 @@ class vtkTypeTemplate : return this->IsTypeOf(type); } - vtkTypeTemplate() {} + vtkTypeTemplate() + { + VTK_LEGACY_REPLACED_BODY(vtkTypeTemplate, "VTK 7.1", + vtkTemplateTypeMacro (vtkSetGet.h)); + } private: // not implemented: @@ -101,6 +108,7 @@ class vtkTypeTemplate : } }; -#endif +#endif // VTK_LEGACY_REMOVE +#endif // header guard // VTK-HeaderTest-Exclude: vtkTypeTemplate.h diff --git a/Common/Core/vtkTypedArray.h b/Common/Core/vtkTypedArray.h index b3230785284..d0d0a89209b 100644 --- a/Common/Core/vtkTypedArray.h +++ b/Common/Core/vtkTypedArray.h @@ -45,19 +45,19 @@ #define vtkTypedArray_h #include "vtkArray.h" -#include "vtkTypeTemplate.h" class vtkArrayCoordinates; template -class vtkTypedArray : public vtkTypeTemplate, vtkArray> +class vtkTypedArray : public vtkArray { public: + vtkTemplateTypeMacro(vtkTypedArray, vtkArray) typedef typename vtkArray::CoordinateT CoordinateT; typedef typename vtkArray::SizeT SizeT; - using vtkTypeTemplate, vtkArray>::GetVariantValue; - using vtkTypeTemplate, vtkArray>::SetVariantValue; + using vtkArray::GetVariantValue; + using vtkArray::SetVariantValue; void PrintSelf(ostream &os, vtkIndent indent); diff --git a/Common/Core/vtkTypedArray.h.in b/Common/Core/vtkTypedArray.h.in index 5af26976d8f..5465efefc72 100644 --- a/Common/Core/vtkTypedArray.h.in +++ b/Common/Core/vtkTypedArray.h.in @@ -36,6 +36,13 @@ public: vtkTypeMacro(vtkType@VTK_TYPE_NAME@Array,vtkTypeArrayBase); void PrintSelf(ostream& os, vtkIndent indent); + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkType@VTK_TYPE_NAME@Array* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + protected: vtkType@VTK_TYPE_NAME@Array(); ~vtkType@VTK_TYPE_NAME@Array(); @@ -45,6 +52,9 @@ private: void operator=(const vtkType@VTK_TYPE_NAME@Array&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkType@VTK_TYPE_NAME@Array) + #undef vtkTypeArrayBase #endif diff --git a/Common/Core/vtkTypedDataArray.h b/Common/Core/vtkTypedDataArray.h index 1f761d45f9e..9797a6a309d 100644 --- a/Common/Core/vtkTypedDataArray.h +++ b/Common/Core/vtkTypedDataArray.h @@ -18,49 +18,48 @@ // This templated class decorates vtkDataArray with additional type-specific // methods that can be used to interact with the data. // +// NOTE: This class has been made obsolete by the newer vtkGenericDataArray. +// // .SECTION Caveats // This class uses vtkTypeTraits to implement GetDataType(). Since vtkIdType // is a typedef for either a 32- or 64-bit integer, subclasses that are designed // to hold vtkIdTypes will, by default, return an incorrect value from // GetDataType(). To fix this, such subclasses should override GetDataType() to // return VTK_ID_TYPE. +// +// .SECTION See Also +// vtkGenericDataArray #ifndef vtkTypedDataArray_h #define vtkTypedDataArray_h -#include "vtkDataArray.h" +#include "vtkGenericDataArray.h" #include "vtkCommonCoreModule.h" // For export macro -#include "vtkTypeTemplate.h" // For vtkTypeTemplate #include "vtkTypeTraits.h" // For type metadata template class vtkTypedDataArrayIterator; template class vtkTypedDataArray : - public vtkTypeTemplate, vtkDataArray> + public vtkGenericDataArray, Scalar> { + typedef vtkGenericDataArray, Scalar> + GenericDataArrayType; public: - // Description: - // Typedef to get the type of value stored in the array. - typedef Scalar ValueType; + vtkTemplateTypeMacro(vtkTypedDataArray, GenericDataArrayType) + typedef typename Superclass::ValueType ValueType; // Description: // Typedef to a suitable iterator class. - // Rather than using this member directly, consider using - // vtkDataArrayIteratorMacro for safety and efficiency. typedef vtkTypedDataArrayIterator Iterator; // Description: // Return an iterator initialized to the first element of the data. - // Rather than using this member directly, consider using - // vtkDataArrayIteratorMacro for safety and efficiency. Iterator Begin(); // Description: // Return an iterator initialized to first element past the end of the data. - // Rather than using this member directly, consider using - // vtkDataArrayIteratorMacro for safety and efficiency. Iterator End(); // Description: @@ -92,16 +91,16 @@ class vtkTypedDataArray : // Description: // Set the tuple value at the ith location in the array. - virtual void SetTupleValue(vtkIdType i, const ValueType *t) = 0; + virtual void SetTypedTuple(vtkIdType i, const ValueType *t) = 0; // Description: // Insert (memory allocation performed) the tuple into the ith location // in the array. - virtual void InsertTupleValue(vtkIdType i, const ValueType *t) = 0; + virtual void InsertTypedTuple(vtkIdType i, const ValueType *t) = 0; // Description: // Insert (memory allocation performed) the tuple onto the end of the array. - virtual vtkIdType InsertNextTupleValue(const ValueType *t) = 0; + virtual vtkIdType InsertNextTypedTuple(const ValueType *t) = 0; // Description: // Return the indices where a specific value appears. @@ -110,7 +109,7 @@ class vtkTypedDataArray : // Description: // Get the data at a particular index. - virtual ValueType GetValue(vtkIdType idx) = 0; + virtual ValueType GetValue(vtkIdType idx) const = 0; // Description: // Get a reference to the scalar value at a particular index. @@ -123,7 +122,7 @@ class vtkTypedDataArray : // Description: // Copy the tuple value into a user-provided array. - virtual void GetTupleValue(vtkIdType idx, ValueType *t) = 0; + virtual void GetTypedTuple(vtkIdType idx, ValueType *t) const = 0; // Description: // Insert data at the end of the array. Return its location in the array. @@ -133,19 +132,43 @@ class vtkTypedDataArray : // Insert data at a specified position in the array. virtual void InsertValue(vtkIdType idx, ValueType v) = 0; + virtual ValueType GetTypedComponent(vtkIdType tupleIdx, int comp) const; + virtual void SetTypedComponent(vtkIdType tupleIdx, int comp, ValueType v); + // Description: // Method for type-checking in FastDownCast implementations. virtual int GetArrayType() { return vtkAbstractArray::TypedDataArray; } + // Reintroduced as pure virtual since the base vtkGenericDataArray method + // requires new allocation/resize APIs, though existing MappedDataArrays + // would just use the vtkDataArray-level virtuals. + virtual int Allocate(vtkIdType size, vtkIdType ext = 1000) = 0; + virtual int Resize(vtkIdType numTuples) = 0; + protected: vtkTypedDataArray(); ~vtkTypedDataArray(); + // Description: + // Needed for vtkGenericDataArray API, but just aborts. Override Allocate + // instead. + virtual bool AllocateTuples(vtkIdType numTuples); + + // Description: + // Needed for vtkGenericDataArray API, but just aborts. Override Resize + // instead. + virtual bool ReallocateTuples(vtkIdType numTuples); + private: vtkTypedDataArray(const vtkTypedDataArray &); // Not implemented. void operator=(const vtkTypedDataArray &); // Not implemented. + + friend class vtkGenericDataArray, Scalar>; }; +// Declare vtkArrayDownCast implementations for typed containers: +vtkArrayDownCast_TemplateFastCastMacro(vtkTypedDataArray) + // Included here to resolve chicken/egg issue with container/iterator: #include "vtkTypedDataArrayIterator.h" // For iterator diff --git a/Common/Core/vtkTypedDataArray.txx b/Common/Core/vtkTypedDataArray.txx index 6a4d44ac5af..b7224eaf8ad 100644 --- a/Common/Core/vtkTypedDataArray.txx +++ b/Common/Core/vtkTypedDataArray.txx @@ -30,6 +30,26 @@ vtkTypedDataArray::~vtkTypedDataArray() { } +//------------------------------------------------------------------------------ +template +bool vtkTypedDataArray::AllocateTuples(vtkIdType) +{ + vtkErrorMacro(<<"This method is not preferred for vtkTypedDataArray " + "implementations. Either add an appropriate implementation, or " + "use Allocate instead."); + return false; +} + +//------------------------------------------------------------------------------ +template +bool vtkTypedDataArray::ReallocateTuples(vtkIdType) +{ + vtkErrorMacro(<<"This method is not preferred for vtkTypedDataArray " + "implementations. Either add an appropriate implementation, or " + "use Resize instead."); + return false; +} + //------------------------------------------------------------------------------ template inline int vtkTypedDataArray::GetDataType() @@ -55,20 +75,39 @@ void vtkTypedDataArray::SetNumberOfValues(vtkIdType number) this->Modified(); } +//------------------------------------------------------------------------------ +template inline +typename vtkTypedDataArray::ValueType +vtkTypedDataArray::GetTypedComponent(vtkIdType tupleIdx, int comp) const +{ + return this->GetValue(tupleIdx * this->NumberOfComponents + comp); +} + +//------------------------------------------------------------------------------ +template inline +void vtkTypedDataArray::SetTypedComponent(vtkIdType tupleIdx, int comp, + ValueType v) +{ + this->SetValue(tupleIdx * this->NumberOfComponents + comp, v); +} + //------------------------------------------------------------------------------ template inline vtkTypedDataArray * vtkTypedDataArray::FastDownCast(vtkAbstractArray *source) { - switch (source->GetArrayType()) + if (source) { - case vtkAbstractArray::DataArrayTemplate: - case vtkAbstractArray::TypedDataArray: - case vtkAbstractArray::MappedDataArray: - if (source->GetDataType() == vtkTypeTraits::VTK_TYPE_ID) - { - return static_cast*>(source); - } - break; + switch (source->GetArrayType()) + { + case vtkAbstractArray::TypedDataArray: + case vtkAbstractArray::MappedDataArray: + if (vtkDataTypesCompare(source->GetDataType(), + vtkTypeTraits::VTK_TYPE_ID)) + { + return static_cast*>(source); + } + break; + } } return NULL; } diff --git a/Common/Core/vtkTypedDataArrayIterator.h b/Common/Core/vtkTypedDataArrayIterator.h index dd2883380dd..b749aed175a 100644 --- a/Common/Core/vtkTypedDataArrayIterator.h +++ b/Common/Core/vtkTypedDataArrayIterator.h @@ -23,6 +23,9 @@ // vtkTypedDataArray API functions to retrieve values. It is especially helpful // for safely iterating through subclasses of vtkMappedDataArray, which may // not use the same memory layout as a typical vtkDataArray. +// +// NOTE: This class has been superceded by the newer vtkGenericDataArray and +// vtkArrayDispatch mechanism. #ifndef vtkTypedDataArrayIterator_h #define vtkTypedDataArrayIterator_h diff --git a/Common/Core/vtkUnicodeStringArray.cxx b/Common/Core/vtkUnicodeStringArray.cxx index 162ee2ba82f..57a38546da2 100644 --- a/Common/Core/vtkUnicodeStringArray.cxx +++ b/Common/Core/vtkUnicodeStringArray.cxx @@ -13,6 +13,11 @@ =========================================================================*/ +#include "vtkUnicodeString.h" + +#include "vtkArrayIteratorTemplate.txx" +VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(vtkUnicodeString); + #include "vtkIdList.h" #include "vtkObjectFactory.h" #include "vtkUnicodeStringArray.h" @@ -80,7 +85,7 @@ void vtkUnicodeStringArray::SetNumberOfTuples(vtkIdType number) void vtkUnicodeStringArray::SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) { - vtkUnicodeStringArray* const array = vtkUnicodeStringArray::SafeDownCast(source); + vtkUnicodeStringArray* const array = vtkArrayDownCast(source); if(!array) { vtkWarningMacro("Input and output array data types do not match."); @@ -93,7 +98,7 @@ void vtkUnicodeStringArray::SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* void vtkUnicodeStringArray::InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* source) { - vtkUnicodeStringArray* const array = vtkUnicodeStringArray::SafeDownCast(source); + vtkUnicodeStringArray* const array = vtkArrayDownCast(source); if(!array) { vtkWarningMacro("Input and output array data types do not match."); @@ -111,7 +116,7 @@ void vtkUnicodeStringArray::InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, vtkAbstractArray *source) { vtkUnicodeStringArray* const array = - vtkUnicodeStringArray::SafeDownCast(source); + vtkArrayDownCast(source); if(!array) { vtkWarningMacro("Input and output array data types do not match."); @@ -152,7 +157,7 @@ void vtkUnicodeStringArray::InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType srcStart, vtkAbstractArray *source) { - vtkUnicodeStringArray* sa = vtkUnicodeStringArray::SafeDownCast(source); + vtkUnicodeStringArray* sa = vtkArrayDownCast(source); if (!sa) { vtkWarningMacro("Input and outputs array data types do not match."); @@ -190,7 +195,7 @@ void vtkUnicodeStringArray::InsertTuples(vtkIdType dstStart, vtkIdType n, vtkIdType vtkUnicodeStringArray::InsertNextTuple(vtkIdType j, vtkAbstractArray* source) { - vtkUnicodeStringArray* const array = vtkUnicodeStringArray::SafeDownCast(source); + vtkUnicodeStringArray* const array = vtkArrayDownCast(source); if(!array) { vtkWarningMacro("Input and output array data types do not match."); @@ -219,7 +224,7 @@ void vtkUnicodeStringArray::DeepCopy(vtkAbstractArray* da) if(this == da) return; - vtkUnicodeStringArray* const array = vtkUnicodeStringArray::SafeDownCast(da); + vtkUnicodeStringArray* const array = vtkArrayDownCast(da); if(!array) { vtkWarningMacro("Input and output array data types do not match."); diff --git a/Common/Core/vtkUnicodeStringArray.h b/Common/Core/vtkUnicodeStringArray.h index d442bf29ee7..80c5adf4394 100644 --- a/Common/Core/vtkUnicodeStringArray.h +++ b/Common/Core/vtkUnicodeStringArray.h @@ -67,7 +67,7 @@ class VTKCOMMONCORE_EXPORT vtkUnicodeStringArray : virtual void SetVoidArray(void *array, vtkIdType size, int save, int deleteMethod); virtual unsigned long GetActualMemorySize(); // in bytes virtual int IsNumeric(); - virtual vtkArrayIterator* NewIterator(); + virtual VTK_NEWINSTANCE vtkArrayIterator* NewIterator(); virtual vtkVariant GetVariantValue(vtkIdType idx); virtual vtkIdType LookupValue(vtkVariant value); virtual void LookupValue(vtkVariant value, vtkIdList* ids); @@ -94,10 +94,9 @@ class VTKCOMMONCORE_EXPORT vtkUnicodeStringArray : vtkUnicodeStringArray(const vtkUnicodeStringArray&); // Not implemented. void operator=(const vtkUnicodeStringArray&); // Not implemented. -//BTX class Implementation; Implementation* Internal; -//ETX + }; #endif diff --git a/Common/Core/vtkUnsignedCharArray.cxx b/Common/Core/vtkUnsignedCharArray.cxx index 5a1957ecb4e..30a2c7bd933 100644 --- a/Common/Core/vtkUnsignedCharArray.cxx +++ b/Common/Core/vtkUnsignedCharArray.cxx @@ -13,12 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned char); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned char); + #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(unsigned char); -#define vtkUnsignedCharArray_cxx #include "vtkUnsignedCharArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkUnsignedCharArray.h b/Common/Core/vtkUnsignedCharArray.h index 2a670859cd0..c89ff05094c 100644 --- a/Common/Core/vtkUnsignedCharArray.h +++ b/Common/Core/vtkUnsignedCharArray.h @@ -21,36 +21,38 @@ #ifndef vtkUnsignedCharArray_h #define vtkUnsignedCharArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkUnsignedCharArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE unsigned char -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkUnsignedCharArray : public vtkDataArray { public: vtkTypeMacro(vtkUnsignedCharArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkUnsignedCharArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(unsigned char); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkUnsignedCharArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static unsigned char GetDataTypeValueMin() { return VTK_UNSIGNED_CHAR_MIN; } @@ -64,11 +66,14 @@ class VTKCOMMONCORE_EXPORT vtkUnsignedCharArray : public vtkDataArray ~vtkUnsignedCharArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkUnsignedCharArray(const vtkUnsignedCharArray&); // Not implemented. void operator=(const vtkUnsignedCharArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkUnsignedCharArray) + #endif diff --git a/Common/Core/vtkUnsignedIntArray.cxx b/Common/Core/vtkUnsignedIntArray.cxx index 8b4cf55f3d4..be5fa9b49b3 100644 --- a/Common/Core/vtkUnsignedIntArray.cxx +++ b/Common/Core/vtkUnsignedIntArray.cxx @@ -13,12 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned int); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned int); + #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(unsigned int); -#define vtkUnsignedIntArray_cxx #include "vtkUnsignedIntArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkUnsignedIntArray.h b/Common/Core/vtkUnsignedIntArray.h index 7fcc781f82c..c12198112ec 100644 --- a/Common/Core/vtkUnsignedIntArray.h +++ b/Common/Core/vtkUnsignedIntArray.h @@ -25,36 +25,38 @@ #ifndef vtkUnsignedIntArray_h #define vtkUnsignedIntArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkUnsignedIntArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE unsigned int -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkUnsignedIntArray : public vtkDataArray { public: vtkTypeMacro(vtkUnsignedIntArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkUnsignedIntArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(unsigned int); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkUnsignedIntArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static unsigned int GetDataTypeValueMin() { return VTK_UNSIGNED_INT_MIN; } @@ -68,11 +70,14 @@ class VTKCOMMONCORE_EXPORT vtkUnsignedIntArray : public vtkDataArray ~vtkUnsignedIntArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkUnsignedIntArray(const vtkUnsignedIntArray&); // Not implemented. void operator=(const vtkUnsignedIntArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkUnsignedIntArray) + #endif diff --git a/Common/Core/vtkUnsignedLongArray.cxx b/Common/Core/vtkUnsignedLongArray.cxx index 2ad128887ff..f4a4d11d829 100644 --- a/Common/Core/vtkUnsignedLongArray.cxx +++ b/Common/Core/vtkUnsignedLongArray.cxx @@ -13,12 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned long); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned long); + #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(unsigned long); -#define vtkUnsignedLongArray_cxx #include "vtkUnsignedLongArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkUnsignedLongArray.h b/Common/Core/vtkUnsignedLongArray.h index c62002073f7..9bc8fd28faf 100644 --- a/Common/Core/vtkUnsignedLongArray.h +++ b/Common/Core/vtkUnsignedLongArray.h @@ -27,36 +27,38 @@ #ifndef vtkUnsignedLongArray_h #define vtkUnsignedLongArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkUnsignedLongArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE unsigned long -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkUnsignedLongArray : public vtkDataArray { public: vtkTypeMacro(vtkUnsignedLongArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkUnsignedLongArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(unsigned long); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkUnsignedLongArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast(Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static unsigned long GetDataTypeValueMin() { return VTK_UNSIGNED_LONG_MIN; } @@ -70,11 +72,14 @@ class VTKCOMMONCORE_EXPORT vtkUnsignedLongArray : public vtkDataArray ~vtkUnsignedLongArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkUnsignedLongArray(const vtkUnsignedLongArray&); // Not implemented. void operator=(const vtkUnsignedLongArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkUnsignedLongArray) + #endif diff --git a/Common/Core/vtkUnsignedLongLongArray.cxx b/Common/Core/vtkUnsignedLongLongArray.cxx index 7e2121fa238..a15e0319b4d 100644 --- a/Common/Core/vtkUnsignedLongLongArray.cxx +++ b/Common/Core/vtkUnsignedLongLongArray.cxx @@ -13,13 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned long long); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned long long); + #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(unsigned long long); - -#define vtkUnsignedLongLongArray_cxx #include "vtkUnsignedLongLongArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkUnsignedLongLongArray.h b/Common/Core/vtkUnsignedLongLongArray.h index ccb83b67ea9..83f728773f4 100644 --- a/Common/Core/vtkUnsignedLongLongArray.h +++ b/Common/Core/vtkUnsignedLongLongArray.h @@ -25,36 +25,39 @@ #ifndef vtkUnsignedLongLongArray_h #define vtkUnsignedLongLongArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkUnsignedLongLongArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE unsigned long long -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkUnsignedLongLongArray : public vtkDataArray { public: vtkTypeMacro(vtkUnsignedLongLongArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkUnsignedLongLongArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(unsigned long long); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkUnsignedLongLongArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast( + Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static unsigned long long GetDataTypeValueMin() {return VTK_UNSIGNED_LONG_LONG_MIN;} @@ -68,11 +71,14 @@ class VTKCOMMONCORE_EXPORT vtkUnsignedLongLongArray : public vtkDataArray ~vtkUnsignedLongLongArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkUnsignedLongLongArray(const vtkUnsignedLongLongArray&); // Not implemented. void operator=(const vtkUnsignedLongLongArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkUnsignedLongLongArray) + #endif diff --git a/Common/Core/vtkUnsignedShortArray.cxx b/Common/Core/vtkUnsignedShortArray.cxx index a99d0c7fc29..a8bbe89422d 100644 --- a/Common/Core/vtkUnsignedShortArray.cxx +++ b/Common/Core/vtkUnsignedShortArray.cxx @@ -13,12 +13,13 @@ =========================================================================*/ // Instantiate superclass first to give the template a DLL interface. -#include "vtkDataArrayTemplate.txx" -VTK_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned short); +#define VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATING +#include "vtkAOSDataArrayTemplate.txx" +VTK_AOS_DATA_ARRAY_TEMPLATE_INSTANTIATE(unsigned short); + #include "vtkArrayIteratorTemplate.txx" VTK_ARRAY_ITERATOR_TEMPLATE_INSTANTIATE(unsigned short); -#define vtkUnsignedShortArray_cxx #include "vtkUnsignedShortArray.h" #include "vtkObjectFactory.h" diff --git a/Common/Core/vtkUnsignedShortArray.h b/Common/Core/vtkUnsignedShortArray.h index 1545f88ffb1..cedd4a03a0a 100644 --- a/Common/Core/vtkUnsignedShortArray.h +++ b/Common/Core/vtkUnsignedShortArray.h @@ -25,36 +25,39 @@ #ifndef vtkUnsignedShortArray_h #define vtkUnsignedShortArray_h -// Tell the template header how to give our superclass a DLL interface. -#if !defined(vtkUnsignedShortArray_cxx) -# define VTK_DATA_ARRAY_TEMPLATE_TYPE unsigned short -#endif - #include "vtkCommonCoreModule.h" // For export macro #include "vtkDataArray.h" -#include "vtkDataArrayTemplate.h" // Real Superclass +#include "vtkAOSDataArrayTemplate.h" // Real Superclass // Fake the superclass for the wrappers. -#ifndef __WRAP__ -#define vtkDataArray vtkDataArrayTemplate +#ifndef __VTK_WRAP__ +#define vtkDataArray vtkAOSDataArrayTemplate #endif class VTKCOMMONCORE_EXPORT vtkUnsignedShortArray : public vtkDataArray { public: vtkTypeMacro(vtkUnsignedShortArray, vtkDataArray) -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #undef vtkDataArray #endif static vtkUnsignedShortArray* New(); void PrintSelf(ostream& os, vtkIndent indent); // This macro expands to the set of method declarations that - // make up the interface of vtkDataArrayTemplate, which is ignored + // make up the interface of vtkAOSDataArrayTemplate, which is ignored // by the wrappers. -#if defined(__WRAP__) || defined (__WRAP_GCCXML__) +#if defined(__VTK_WRAP__) || defined (__WRAP_GCCXML__) vtkCreateWrappedArrayInterface(unsigned short); #endif + // Description: + // A faster alternative to SafeDownCast for downcasting vtkAbstractArrays. + static vtkUnsignedShortArray* FastDownCast(vtkAbstractArray *source) + { + return static_cast( + Superclass::FastDownCast(source)); + } + // Description: // Get the minimum data value in its native type. static unsigned short GetDataTypeValueMin() { return VTK_UNSIGNED_SHORT_MIN; } @@ -68,11 +71,14 @@ class VTKCOMMONCORE_EXPORT vtkUnsignedShortArray : public vtkDataArray ~vtkUnsignedShortArray(); private: - //BTX - typedef vtkDataArrayTemplate RealSuperclass; - //ETX + + typedef vtkAOSDataArrayTemplate RealSuperclass; + vtkUnsignedShortArray(const vtkUnsignedShortArray&); // Not implemented. void operator=(const vtkUnsignedShortArray&); // Not implemented. }; +// Define vtkArrayDownCast implementation: +vtkArrayDownCast_FastCastMacro(vtkUnsignedShortArray) + #endif diff --git a/Common/Core/vtkVariant.h b/Common/Core/vtkVariant.h index a20f3c62d0a..21d266bdcfa 100644 --- a/Common/Core/vtkVariant.h +++ b/Common/Core/vtkVariant.h @@ -40,7 +40,6 @@ // The following should be eventually placed in vtkSetGet.h // -//BTX // This is same as extended template macro with an additional case for VTK_VARIANT #define vtkExtraExtendedTemplateMacro(call) \ vtkExtendedTemplateMacro(call); \ @@ -50,7 +49,6 @@ #define vtkExtendedArrayIteratorTemplateMacro(call) \ vtkArrayIteratorTemplateMacro(call); \ vtkArrayIteratorTemplateMacroCase(VTK_VARIANT, vtkVariant, call); -//ETX class vtkStdString; class vtkUnicodeString; @@ -64,9 +62,7 @@ class vtkVariant; #endif struct vtkVariantLessThan; -//BTX VTKCOMMONCORE_EXPORT ostream& operator << ( ostream& os, const vtkVariant& val ); -//ETX class VTKCOMMONCORE_EXPORT vtkVariant { @@ -373,12 +369,10 @@ class VTKCOMMONCORE_EXPORT vtkVariant bool operator<=(const vtkVariant &other) const; bool operator>=(const vtkVariant &other) const; -//BTX friend VTKCOMMONCORE_EXPORT ostream& operator << ( ostream& os, const vtkVariant& val ); -//ETX private: -//BTX + template T ToNumeric(bool *valid, T* vtkNotUsed(ignored)) const; @@ -409,10 +403,8 @@ class VTKCOMMONCORE_EXPORT vtkVariant friend struct vtkVariantEqual; friend struct vtkVariantStrictWeakOrder; friend struct vtkVariantStrictEquality; -//ETX -}; -//BTX +}; #include "vtkVariantInlineOperators.h" // needed for operator== and company @@ -449,7 +441,5 @@ struct VTKCOMMONCORE_EXPORT vtkVariantStrictEquality bool operator()(const vtkVariant &s1, const vtkVariant &s2) const; }; -//ETX - #endif // VTK-HeaderTest-Exclude: vtkVariant.h diff --git a/Common/Core/vtkVariantArray.cxx b/Common/Core/vtkVariantArray.cxx index 75ecc18d514..436fe08a9b3 100644 --- a/Common/Core/vtkVariantArray.cxx +++ b/Common/Core/vtkVariantArray.cxx @@ -184,7 +184,7 @@ void vtkVariantArray::SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* sourc { if (source->IsA("vtkVariantArray")) { - vtkVariantArray* a = vtkVariantArray::SafeDownCast(source); + vtkVariantArray* a = vtkArrayDownCast(source); vtkIdType loci = i * this->NumberOfComponents; vtkIdType locj = j * a->GetNumberOfComponents(); for (vtkIdType cur = 0; cur < this->NumberOfComponents; cur++) @@ -194,7 +194,7 @@ void vtkVariantArray::SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* sourc } else if (source->IsA("vtkDataArray")) { - vtkDataArray* a = vtkDataArray::SafeDownCast(source); + vtkDataArray* a = vtkArrayDownCast(source); vtkIdType loci = i * this->NumberOfComponents; vtkIdType locj = j * a->GetNumberOfComponents(); for (vtkIdType cur = 0; cur < this->NumberOfComponents; cur++) @@ -209,7 +209,7 @@ void vtkVariantArray::SetTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* sourc } else if (source->IsA("vtkStringArray")) { - vtkStringArray* a = vtkStringArray::SafeDownCast(source); + vtkStringArray* a = vtkArrayDownCast(source); vtkIdType loci = i * this->NumberOfComponents; vtkIdType locj = j * a->GetNumberOfComponents(); for (vtkIdType cur = 0; cur < this->NumberOfComponents; cur++) @@ -229,7 +229,7 @@ void vtkVariantArray::InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* so { if (source->IsA("vtkVariantArray")) { - vtkVariantArray* a = vtkVariantArray::SafeDownCast(source); + vtkVariantArray* a = vtkArrayDownCast(source); vtkIdType loci = i * this->NumberOfComponents; vtkIdType locj = j * a->GetNumberOfComponents(); for (vtkIdType cur = 0; cur < this->NumberOfComponents; cur++) @@ -239,7 +239,7 @@ void vtkVariantArray::InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* so } else if (source->IsA("vtkDataArray")) { - vtkDataArray* a = vtkDataArray::SafeDownCast(source); + vtkDataArray* a = vtkArrayDownCast(source); vtkIdType loci = i * this->NumberOfComponents; vtkIdType locj = j * a->GetNumberOfComponents(); for (vtkIdType cur = 0; cur < this->NumberOfComponents; cur++) @@ -251,7 +251,7 @@ void vtkVariantArray::InsertTuple(vtkIdType i, vtkIdType j, vtkAbstractArray* so } else if (source->IsA("vtkStringArray")) { - vtkStringArray* a = vtkStringArray::SafeDownCast(source); + vtkStringArray* a = vtkArrayDownCast(source); vtkIdType loci = i * this->NumberOfComponents; vtkIdType locj = j * a->GetNumberOfComponents(); for (vtkIdType cur = 0; cur < this->NumberOfComponents; cur++) @@ -284,7 +284,7 @@ void vtkVariantArray::InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, return; } - if (vtkVariantArray* va = vtkVariantArray::SafeDownCast(source)) + if (vtkVariantArray* va = vtkArrayDownCast(source)) { for (vtkIdType idIndex = 0; idIndex < numIds; ++idIndex) { @@ -310,7 +310,7 @@ void vtkVariantArray::InsertTuples(vtkIdList *dstIds, vtkIdList *srcIds, } } } - else if (vtkStringArray* sa = vtkStringArray::SafeDownCast(source)) + else if (vtkStringArray* sa = vtkArrayDownCast(source)) { for (vtkIdType idIndex = 0; idIndex < numIds; ++idIndex) { @@ -368,7 +368,7 @@ vtkIdType vtkVariantArray::InsertNextTuple(vtkIdType j, vtkAbstractArray* source { if (source->IsA("vtkVariantArray")) { - vtkVariantArray* a = vtkVariantArray::SafeDownCast(source); + vtkVariantArray* a = vtkArrayDownCast(source); vtkIdType locj = j * a->GetNumberOfComponents(); for (vtkIdType cur = 0; cur < this->NumberOfComponents; cur++) { @@ -377,7 +377,7 @@ vtkIdType vtkVariantArray::InsertNextTuple(vtkIdType j, vtkAbstractArray* source } else if (source->IsA("vtkDataArray")) { - vtkDataArray* a = vtkDataArray::SafeDownCast(source); + vtkDataArray* a = vtkArrayDownCast(source); vtkIdType locj = j * a->GetNumberOfComponents(); for (vtkIdType cur = 0; cur < this->NumberOfComponents; cur++) { @@ -388,7 +388,7 @@ vtkIdType vtkVariantArray::InsertNextTuple(vtkIdType j, vtkAbstractArray* source } else if (source->IsA("vtkStringArray")) { - vtkStringArray* a = vtkStringArray::SafeDownCast(source); + vtkStringArray* a = vtkArrayDownCast(source); vtkIdType locj = j * a->GetNumberOfComponents(); for (vtkIdType cur = 0; cur < this->NumberOfComponents; cur++) { @@ -435,7 +435,7 @@ void vtkVariantArray::DeepCopy(vtkAbstractArray *aa) return; } - vtkVariantArray *va = vtkVariantArray::SafeDownCast( aa ); + vtkVariantArray *va = vtkArrayDownCast( aa ); if ( va == NULL ) { vtkErrorMacro(<< "Shouldn't Happen: Couldn't downcast array into a vtkVariantArray." ); diff --git a/Common/Core/vtkVariantArray.h b/Common/Core/vtkVariantArray.h index 3735fe7ba76..7898aa7515e 100644 --- a/Common/Core/vtkVariantArray.h +++ b/Common/Core/vtkVariantArray.h @@ -35,17 +35,14 @@ class vtkVariantArrayLookup; -//BTX /// Forward declaration required for Boost serialization namespace boost { namespace serialization { class access; } } -//ETX class VTKCOMMONCORE_EXPORT vtkVariantArray : public vtkAbstractArray { -//BTX + /// Friendship required for Boost serialization friend class boost::serialization::access; -//ETX public: static vtkVariantArray* New(); @@ -189,7 +186,7 @@ class VTKCOMMONCORE_EXPORT vtkVariantArray : public vtkAbstractArray // Description: // Subclasses must override this method and provide the right // kind of templated vtkArrayIteratorTemplate. - virtual vtkArrayIterator* NewIterator(); + virtual VTK_NEWINSTANCE vtkArrayIterator* NewIterator(); // // Additional functions @@ -223,7 +220,6 @@ class VTKCOMMONCORE_EXPORT vtkVariantArray : public vtkAbstractArray // Return the array index of the inserted value. vtkIdType InsertNextValue(vtkVariant value); - //BTX // Description: // Return a pointer to the location in the internal array at the specified index. vtkVariant* GetPointer(vtkIdType id); @@ -231,7 +227,6 @@ class VTKCOMMONCORE_EXPORT vtkVariantArray : public vtkAbstractArray // Description: // Set the internal array used by this object. void SetArray(vtkVariant* arr, vtkIdType size, int save); - //ETX // Description: // Specify the number of values for this object to hold. Does an @@ -279,12 +274,11 @@ class VTKCOMMONCORE_EXPORT vtkVariantArray : public vtkAbstractArray vtkVariantArray(); // Pointer to data - //BTX + vtkVariant* Array; // Function to resize data vtkVariant* ResizeAndExtend(vtkIdType sz); - //ETX int SaveUserArray; diff --git a/Common/Core/vtkVariantCast.h b/Common/Core/vtkVariantCast.h index ddedfbbae49..75dcd298e81 100644 --- a/Common/Core/vtkVariantCast.h +++ b/Common/Core/vtkVariantCast.h @@ -59,6 +59,12 @@ inline char vtkVariantCast(const vtkVariant& value, bool* valid) return value.ToChar(valid); } +template<> +inline signed char vtkVariantCast(const vtkVariant& value, bool* valid) +{ + return value.ToSignedChar(valid); +} + template<> inline unsigned char vtkVariantCast(const vtkVariant& value, bool* valid) { diff --git a/Common/Core/vtkWin32Header.h b/Common/Core/vtkWin32Header.h index b3dc5b79f54..08c36e1452c 100644 --- a/Common/Core/vtkWin32Header.h +++ b/Common/Core/vtkWin32Header.h @@ -45,7 +45,7 @@ Do_not_include_vtkWin32Header_directly__vtkSystemIncludes_includes_it; // // Windows specific stuff------------------------------------------ -#if defined(_WIN32) || defined(WIN32) +#if defined(_WIN32) // define strict header for windows #ifndef STRICT @@ -83,7 +83,7 @@ Do_not_include_vtkWin32Header_directly__vtkSystemIncludes_includes_it; # endif // Enable workaround for windows header name mangling. // See VTK/Utilities/Upgrading/README.WindowsMangling.txt for details. -#if !defined(__WRAP__) +#if !defined(__VTK_WRAP__) # define VTK_WORKAROUND_WINDOWS_MANGLE #endif diff --git a/Common/Core/vtkWrappingHints.h b/Common/Core/vtkWrappingHints.h new file mode 100644 index 00000000000..e59638272fd --- /dev/null +++ b/Common/Core/vtkWrappingHints.h @@ -0,0 +1,31 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkWrappingHints.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkWrappingHints - hint macros for wrappers +// .SECTION Description +// The macros defined in this file can be used to supply hints for the +// wrappers. + +#ifndef vtkWrappingHints_h +#define vtkWrappingHints_h + +#ifdef __VTK_WRAP__ +// The return value points to a newly-created VTK object. +#define VTK_NEWINSTANCE [[vtk::newinstance]] +#else +#define VTK_NEWINSTANCE +#endif + +#endif +// VTK-HeaderTest-Exclude: vtkWrappingHints.h diff --git a/Common/DataModel/CMakeLists.txt b/Common/DataModel/CMakeLists.txt index 37ac41beb36..a092506071e 100644 --- a/Common/DataModel/CMakeLists.txt +++ b/Common/DataModel/CMakeLists.txt @@ -9,6 +9,7 @@ set(Module_SRCS vtkAnnotation.cxx vtkAnnotationLayers.cxx vtkArrayData.cxx + vtkArrayListTemplate.txx vtkAttributesErrorMetric.cxx vtkBiQuadraticQuad.cxx vtkBiQuadraticQuadraticHexahedron.cxx @@ -213,6 +214,7 @@ set(Module_SRCS ) set(${vtk-module}_HDRS + vtkArrayListTemplate.h vtkCellType.h vtkMappedUnstructuredGrid.h vtkMappedUnstructuredGridCellIterator.h @@ -260,6 +262,7 @@ set_source_files_properties( set_source_files_properties( vtkAMRBox + vtkArrayListTemplate.txx vtkAtom vtkBond vtkBoundingBox diff --git a/Common/DataModel/Testing/Cxx/TestBiQuadraticQuad.cxx b/Common/DataModel/Testing/Cxx/TestBiQuadraticQuad.cxx index 19f7182b039..db5383ac1c8 100644 --- a/Common/DataModel/Testing/Cxx/TestBiQuadraticQuad.cxx +++ b/Common/DataModel/Testing/Cxx/TestBiQuadraticQuad.cxx @@ -74,7 +74,7 @@ int TestBiQuadraticQuad(int, char*[]) prober->Update(); vtkDataArray* data = prober->GetOutput()->GetPointData()->GetScalars(); - vtkDoubleArray* doubleData = vtkDoubleArray::SafeDownCast(data); + vtkDoubleArray* doubleData = vtkArrayDownCast(data); double interpolated(0.0); if (doubleData) diff --git a/Common/DataModel/Testing/Cxx/TestCellIterators.cxx b/Common/DataModel/Testing/Cxx/TestCellIterators.cxx index c4e79d57df6..f2aa46cf2e6 100644 --- a/Common/DataModel/Testing/Cxx/TestCellIterators.cxx +++ b/Common/DataModel/Testing/Cxx/TestCellIterators.cxx @@ -331,7 +331,7 @@ double benchmarkPointsIteration(vtkUnstructuredGrid *grid) vtkIdType cellSize; vtkPoints *points = grid->GetPoints(); - vtkFloatArray *pointDataArray = vtkFloatArray::SafeDownCast(points->GetData()); + vtkFloatArray *pointDataArray = vtkArrayDownCast(points->GetData()); if (!pointDataArray) { return -1.0; @@ -411,7 +411,7 @@ double benchmarkPointsIteration(vtkCellIterator *iter) return -1.0; } vtkFloatArray *pointArray = - vtkFloatArray::SafeDownCast(iter->GetPoints()->GetData()); + vtkArrayDownCast(iter->GetPoints()->GetData()); float *pointsData; float *pointsDataEnd; @@ -489,7 +489,7 @@ double benchmarkPiecewiseIteration(vtkUnstructuredGrid *grid) // Setup for points: vtkPoints *points = grid->GetPoints(); - vtkFloatArray *pointDataArray = vtkFloatArray::SafeDownCast(points->GetData()); + vtkFloatArray *pointDataArray = vtkArrayDownCast(points->GetData()); if (!pointDataArray) { return -1.0; diff --git a/Common/DataModel/Testing/Cxx/TestPolyDataRemoveCell.cxx b/Common/DataModel/Testing/Cxx/TestPolyDataRemoveCell.cxx index 3e3f81dcb78..0ae6550dd94 100644 --- a/Common/DataModel/Testing/Cxx/TestPolyDataRemoveCell.cxx +++ b/Common/DataModel/Testing/Cxx/TestPolyDataRemoveCell.cxx @@ -93,7 +93,7 @@ int TestPolyDataRemoveCell(int , char *[]) { data[j+1] = pts[j]; } - cellPoints->SetTupleValue(i, data); + cellPoints->SetTypedTuple(i, data); } poly->GetCellData()->AddArray(cellPoints); cellPoints->Delete(); @@ -114,8 +114,8 @@ int TestPolyDataRemoveCell(int , char *[]) } // the arrays should have been changed so get them again... - cellTypes = vtkIntArray::SafeDownCast(poly->GetCellData()->GetArray(ctName)); - cellPoints = vtkIdTypeArray::SafeDownCast(poly->GetCellData()->GetArray(cpName)); + cellTypes = vtkArrayDownCast(poly->GetCellData()->GetArray(ctName)); + cellPoints = vtkArrayDownCast(poly->GetCellData()->GetArray(cpName)); // check the cell types and arrays for(i=0;iGetNumberOfCells();i++) @@ -133,7 +133,7 @@ int TestPolyDataRemoveCell(int , char *[]) vtkIdType npts, *pts; poly->GetCellPoints(i, npts, pts); vtkIdType data[4]; - cellPoints->GetTupleValue(i, data); + cellPoints->GetTypedTuple(i, data); if(data[0] != npts) { cout << "Problem with the number of points for cell " << i << endl; diff --git a/Common/DataModel/Testing/Cxx/TestPolyDataRemoveDeletedCells.cxx b/Common/DataModel/Testing/Cxx/TestPolyDataRemoveDeletedCells.cxx index 62c19adc166..d00d91e9a68 100644 --- a/Common/DataModel/Testing/Cxx/TestPolyDataRemoveDeletedCells.cxx +++ b/Common/DataModel/Testing/Cxx/TestPolyDataRemoveDeletedCells.cxx @@ -230,7 +230,7 @@ int TestPolyDataRemoveDeletedCells (int, char*[]) pd->RemoveDeletedCells(); - vtkIntArray *newScalars = vtkIntArray::SafeDownCast(pd->GetCellData()->GetScalars()); + vtkIntArray *newScalars = vtkArrayDownCast(pd->GetCellData()->GetScalars()); int retVal = VTK_SUCCESS; diff --git a/Common/DataModel/Testing/Cxx/TestQuadraticPolygonFilters.cxx b/Common/DataModel/Testing/Cxx/TestQuadraticPolygonFilters.cxx index e1f58c86db1..6c3f97c6756 100644 --- a/Common/DataModel/Testing/Cxx/TestQuadraticPolygonFilters.cxx +++ b/Common/DataModel/Testing/Cxx/TestQuadraticPolygonFilters.cxx @@ -263,7 +263,7 @@ vtkIdType GetCellIdFromPickerPosition(vtkRenderer *ren, int x, int y) vtkIdType cellId = -1; if (picker->GetDataSet()) { - vtkIdTypeArray * ids = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray * ids = vtkArrayDownCast( picker->GetDataSet()->GetCellData()->GetArray("CellID")); cellId = ids->GetValue(picker->GetCellId()); } diff --git a/Common/DataModel/Testing/Cxx/TestTable.cxx b/Common/DataModel/Testing/Cxx/TestTable.cxx index 425e72a41ab..903f60d483f 100644 --- a/Common/DataModel/Testing/Cxx/TestTable.cxx +++ b/Common/DataModel/Testing/Cxx/TestTable.cxx @@ -77,16 +77,16 @@ void CheckEqual(vtkTable* table, vector > & stdTable) double val; if (arr->IsA("vtkVariantArray")) { - val = vtkVariantArray::SafeDownCast(arr)->GetValue(i).ToDouble(); + val = vtkArrayDownCast(arr)->GetValue(i).ToDouble(); } else if (arr->IsA("vtkStringArray")) { - vtkVariant v(vtkStringArray::SafeDownCast(arr)->GetValue(i)); + vtkVariant v(vtkArrayDownCast(arr)->GetValue(i)); val = v.ToDouble(); } else if (arr->IsA("vtkDataArray")) { - val = vtkDataArray::SafeDownCast(arr)->GetTuple1(i); + val = vtkArrayDownCast(arr)->GetTuple1(i); } else { diff --git a/Common/DataModel/vtkAbstractCellLocator.h b/Common/DataModel/vtkAbstractCellLocator.h index 88e751bc840..d5156588b33 100644 --- a/Common/DataModel/vtkAbstractCellLocator.h +++ b/Common/DataModel/vtkAbstractCellLocator.h @@ -22,11 +22,9 @@ // When deriving a class from vtkAbstractCellLocator, one should include the // 'hidden' member functions by the following construct in the derived class // \verbatim -// //BTX // using vtkAbstractCellLocator::IntersectWithLine; // using vtkAbstractCellLocator::FindClosestPoint; // using vtkAbstractCellLocator::FindClosestPointWithinRadius; -// //ETX // \endverbatim // @@ -259,9 +257,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkAbstractCellLocator : public vtkLocator int LazyEvaluation; int UseExistingSearchStructure; vtkGenericCell *GenericCell; -//BTX - begin tcl exclude double (*CellBounds)[6]; -//ETX - end tcl exclude private: vtkAbstractCellLocator(const vtkAbstractCellLocator&); // Not implemented. diff --git a/Common/DataModel/vtkAnimationScene.h b/Common/DataModel/vtkAnimationScene.h index e6368a307e8..f52a49055e3 100644 --- a/Common/DataModel/vtkAnimationScene.h +++ b/Common/DataModel/vtkAnimationScene.h @@ -96,13 +96,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkAnimationScene: public vtkAnimationCue // Returns if the animation is being played. int IsInPlay() { return this->InPlay; } -//BTX enum PlayModes { PLAYMODE_SEQUENCE=0, PLAYMODE_REALTIME=1 }; -//ETX protected: vtkAnimationScene(); diff --git a/Common/DataModel/vtkAnnotation.h b/Common/DataModel/vtkAnnotation.h index 40301dfe72c..fa18b21f338 100644 --- a/Common/DataModel/vtkAnnotation.h +++ b/Common/DataModel/vtkAnnotation.h @@ -108,7 +108,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkAnnotation : public vtkDataObject // Get the modified time of this object. virtual unsigned long GetMTime(); -//BTX protected: vtkAnnotation(); ~vtkAnnotation(); @@ -118,7 +117,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkAnnotation : public vtkDataObject private: vtkAnnotation(const vtkAnnotation&); // Not implemented. void operator=(const vtkAnnotation&); // Not implemented. -//ETX + }; #endif diff --git a/Common/DataModel/vtkAnnotationLayers.h b/Common/DataModel/vtkAnnotationLayers.h index 898762dd1ef..9bffb2d52cb 100644 --- a/Common/DataModel/vtkAnnotationLayers.h +++ b/Common/DataModel/vtkAnnotationLayers.h @@ -93,7 +93,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkAnnotationLayers : public vtkDataObject // The modified time for this object. virtual unsigned long GetMTime(); -//BTX protected: vtkAnnotationLayers(); ~vtkAnnotationLayers(); @@ -105,7 +104,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkAnnotationLayers : public vtkDataObject private: vtkAnnotationLayers(const vtkAnnotationLayers&); // Not implemented. void operator=(const vtkAnnotationLayers&); // Not implemented. -//ETX + }; #endif diff --git a/Common/DataModel/vtkArrayData.h b/Common/DataModel/vtkArrayData.h index b020bff7778..688dcab7448 100644 --- a/Common/DataModel/vtkArrayData.h +++ b/Common/DataModel/vtkArrayData.h @@ -88,10 +88,9 @@ class VTKCOMMONDATAMODEL_EXPORT vtkArrayData : public vtkDataObject vtkArrayData(const vtkArrayData&); // Not implemented void operator=(const vtkArrayData&); // Not implemented -//BTX class implementation; implementation* const Implementation; -//ETX + }; #endif diff --git a/Common/DataModel/vtkArrayListTemplate.h b/Common/DataModel/vtkArrayListTemplate.h new file mode 100644 index 00000000000..e777e4c7cbf --- /dev/null +++ b/Common/DataModel/vtkArrayListTemplate.h @@ -0,0 +1,309 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkArrayListTemplate.h + + Copyright (c) Kitware, Inc. + All rights reserved. + See LICENSE file for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkArrayListTemplate - thread-safe and efficient data attribute manipulation + +// .SECTION Description +// vtkArrayListTemplate supplements the vtkDataSetAttributes class to provide +// threaded processing of data arrays. It is also more efficient for certain +// interpolation operations. The expectation is that it will be replaced one +// day once vtkPointData, vtkCellData, vtkDataSetAttributes, and vtkFieldData +// properly support multithreading and/or are redesigned. Note that this +// implementation does not support incremental operations (like InsertNext()). +// +// Generally the way this helper class is used is to first invoke +// vtkDataSetAttributes::CopyInterpolate() or InterpolateAllocate() which +// performs the initial magic of constructing input and output arrays. Then +// the input attributes, and output attributes, are passed to initialize the +// internal structures. Essentially these internal structures are pairs of +// arrays of the same type, which can be efficently accessed and +// assigned. The operations on these array pairs (e.g., interpolation) occur +// using a typeless, virtual dispatch base class. + +// .SECTION See Also +// vtkFieldData vtkDataSetAttributes vtkPointData vtkCellData + +#ifndef vtkArrayListTemplate_h +#define vtkArrayListTemplate_h + +#include "vtkDataArray.h" +#include "vtkDataSetAttributes.h" +#include "vtkSmartPointer.h" +#include "vtkStdString.h" + +#include +#include + +// Create a generic class supporting virtual dispatch to type-specific +// subclasses. +struct BaseArrayPair +{ + vtkIdType Num; + int NumComp; + vtkSmartPointer OutputArray; + + BaseArrayPair(vtkIdType num, int numComp, vtkDataArray *outArray) : + Num(num), NumComp(numComp), OutputArray(outArray) + { + } + virtual ~BaseArrayPair() + { + } + + virtual void Copy(vtkIdType inId, vtkIdType outId) = 0; + virtual void Interpolate(int numWeights, const vtkIdType *ids, + const double *weights, vtkIdType outId) = 0; + virtual void InterpolateEdge(vtkIdType v0, vtkIdType v1, + double t, vtkIdType outId) = 0; + virtual void AssignNullValue(vtkIdType outId) = 0; + virtual void Realloc(vtkIdType sze) = 0; +}; + +// Type specific interpolation on a matched pair of data arrays +template +struct ArrayPair : public BaseArrayPair +{ + T *Input; + T *Output; + T NullValue; + + ArrayPair(T *in, T *out, vtkIdType num, int numComp, vtkDataArray *outArray, T null) : + BaseArrayPair(num,numComp,outArray), Input(in), Output(out), NullValue(null) + { + } + virtual ~ArrayPair() //calm down some finicky compilers + { + } + + virtual void Copy(vtkIdType inId, vtkIdType outId) + { + for (int j=0; j < this->NumComp; ++j) + { + this->Output[outId*this->NumComp+j] = this->Input[inId*this->NumComp+j]; + } + } + + virtual void Interpolate(int numWeights, const vtkIdType *ids, + const double *weights, vtkIdType outId) + { + for (int j=0; j < this->NumComp; ++j) + { + double v = 0.0; + for (vtkIdType i=0; i < numWeights; ++i) + { + v += weights[i] * static_cast(this->Input[ids[i]*this->NumComp+j]); + } + this->Output[outId*this->NumComp+j] = static_cast(v); + } + } + + virtual void InterpolateEdge(vtkIdType v0, vtkIdType v1, double t, vtkIdType outId) + { + double v; + vtkIdType numComp=this->NumComp; + for (int j=0; j < numComp; ++j) + { + v = this->Input[v0*numComp+j] + + t * (this->Input[v1*numComp+j] - this->Input[v0*numComp+j]); + this->Output[outId*numComp+j] = static_cast(v); + } + } + + virtual void AssignNullValue(vtkIdType outId) + { + for (int j=0; j < this->NumComp; ++j) + { + this->Output[outId*this->NumComp+j] = this->NullValue; + } + } + + virtual void Realloc(vtkIdType sze) + { + this->OutputArray->WriteVoidPointer(0,sze*this->NumComp); + this->Output = static_cast(this->OutputArray->GetVoidPointer(0)); + } + +}; + +// Type specific interpolation on a pair of data arrays with different types, where the +// output type is expected to be a real type (i.e., float or double). +template +struct RealArrayPair : public BaseArrayPair +{ + TInput *Input; + TOutput *Output; + TOutput NullValue; + + RealArrayPair(TInput *in, TOutput *out, vtkIdType num, int numComp, vtkDataArray *outArray, TOutput null) : + BaseArrayPair(num,numComp,outArray), Input(in), Output(out), NullValue(null) + { + } + virtual ~RealArrayPair() //calm down some finicky compilers + { + } + + virtual void Copy(vtkIdType inId, vtkIdType outId) + { + for (int j=0; j < this->NumComp; ++j) + { + this->Output[outId*this->NumComp+j] = static_cast(this->Input[inId*this->NumComp+j]); + } + } + + virtual void Interpolate(int numWeights, const vtkIdType *ids, + const double *weights, vtkIdType outId) + { + for (int j=0; j < this->NumComp; ++j) + { + double v = 0.0; + for (vtkIdType i=0; i < numWeights; ++i) + { + v += weights[i] * static_cast(this->Input[ids[i]*this->NumComp+j]); + } + this->Output[outId*this->NumComp+j] = static_cast(v); + } + } + + virtual void InterpolateEdge(vtkIdType v0, vtkIdType v1, double t, vtkIdType outId) + { + double v; + vtkIdType numComp=this->NumComp; + for (int j=0; j < numComp; ++j) + { + v = this->Input[v0*numComp+j] + + t * (this->Input[v1*numComp+j] - this->Input[v0*numComp+j]); + this->Output[outId*numComp+j] = static_cast(v); + } + } + + virtual void AssignNullValue(vtkIdType outId) + { + for (int j=0; j < this->NumComp; ++j) + { + this->Output[outId*this->NumComp+j] = this->NullValue; + } + } + + virtual void Realloc(vtkIdType sze) + { + this->OutputArray->WriteVoidPointer(0,sze*this->NumComp); + this->Output = static_cast(this->OutputArray->GetVoidPointer(0)); + } + +}; + +// Forward declarations. This makes working with vtkTemplateMacro easier. +struct ArrayList; + +template +void CreateArrayPair(ArrayList *list, T *inData, T *outData, + vtkIdType numPts, int numComp, T nullValue); + + +// A list of the arrays to interpolate, and a method to invoke interpolation on the list +struct ArrayList +{ + // The list of arrays, and the arrays not to process + std::vector Arrays; + std::vector ExcludedArrays; + + // Add the arrays to interpolate here (from attribute data) + void AddArrays(vtkIdType numOutPts, vtkDataSetAttributes *inPD, + vtkDataSetAttributes *outPD, double nullValue=0.0, + bool promote=true); + + // Add a pair of arrays (manual insertion). Returns the output array created, + // if any. No array may be created if \c inArray was previously marked as + // excluded using ExcludeArray(). + vtkDataArray* AddArrayPair(vtkIdType numPts, vtkDataArray *inArray, + vtkStdString &outArrayName, double nullValue, bool promote); + + // Any array excluded here is not added by AddArrays() or AddArrayPair, hence not + // processed. Also check whether an array is excluded. + void ExcludeArray(vtkDataArray *da); + bool IsExcluded(vtkDataArray *da); + + // Loop over the array pairs and copy data from one to another + void Copy(vtkIdType inId, vtkIdType outId) + { + for (std::vector::iterator it = Arrays.begin(); + it != Arrays.end(); ++it) + { + (*it)->Copy(inId, outId); + } + } + + // Loop over the arrays and have them interpolate themselves + void Interpolate(int numWeights, const vtkIdType *ids, const double *weights, vtkIdType outId) + { + for (std::vector::iterator it = Arrays.begin(); + it != Arrays.end(); ++it) + { + (*it)->Interpolate(numWeights, ids, weights, outId); + } + } + + // Loop over the arrays perform edge interpolation + void InterpolateEdge(vtkIdType v0, vtkIdType v1, double t, vtkIdType outId) + { + for (std::vector::iterator it = Arrays.begin(); + it != Arrays.end(); ++it) + { + (*it)->InterpolateEdge(v0, v1, t, outId); + } + } + + // Loop over the arrays and assign the null value + void AssignNullValue(vtkIdType outId) + { + for (std::vector::iterator it = Arrays.begin(); + it != Arrays.end(); ++it) + { + (*it)->AssignNullValue(outId); + } + } + + // Extend (realloc) the arrays + void Realloc(vtkIdType sze) + { + for (std::vector::iterator it = Arrays.begin(); + it != Arrays.end(); ++it) + { + (*it)->Realloc(sze); + } + } + + // Only you can prevent memory leaks! + ~ArrayList() + { + for (std::vector::iterator it = Arrays.begin(); + it != Arrays.end(); ++it) + { + delete (*it); + } + } + + // Return the number of arrays + vtkIdType GetNumberOfArrays() + { + return Arrays.size(); + } + +}; + + +#include "vtkArrayListTemplate.txx" + +#endif +// VTK-HeaderTest-Exclude: vtkArrayListTemplate.h diff --git a/Common/DataModel/vtkArrayListTemplate.txx b/Common/DataModel/vtkArrayListTemplate.txx new file mode 100644 index 00000000000..267a549396f --- /dev/null +++ b/Common/DataModel/vtkArrayListTemplate.txx @@ -0,0 +1,179 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkArrayListTemplate.txx + + Copyright (c) Kitware, Inc. + All rights reserved. + See LICENSE file for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkArrayListTemplate.h" +#include "vtkFloatArray.h" + +#include + +#ifndef vtkArrayListTemplate_txx +#define vtkArrayListTemplate_txx + +//---------------------------------------------------------------------------- +// Sort of a little object factory (in conjunction w/ vtkTemplateMacro()) +template +void CreateArrayPair(ArrayList *list, T *inData, T *outData, + vtkIdType numPts, int numComp, vtkDataArray *outArray, T nullValue) +{ + ArrayPair *pair = new ArrayPair(inData,outData,numPts,numComp,outArray,nullValue); + list->Arrays.push_back(pair); +} + +//---------------------------------------------------------------------------- +// Sort of a little object factory (in conjunction w/ vtkTemplateMacro()) +template +void CreateRealArrayPair(ArrayList *list, T *inData, float *outData,vtkIdType numPts, + int numComp, vtkDataArray *outArray, float nullValue) +{ + RealArrayPair *pair = + new RealArrayPair(inData,outData,numPts,numComp,outArray,nullValue); + list->Arrays.push_back(pair); +} + +//---------------------------------------------------------------------------- +// Indicate arrays not to process +inline void ArrayList:: +ExcludeArray(vtkDataArray *da) +{ + ExcludedArrays.push_back(da); +} + +//---------------------------------------------------------------------------- +// Has the specified array been excluded? +inline bool ArrayList:: +IsExcluded(vtkDataArray *da) +{ + return (std::find(ExcludedArrays.begin(), ExcludedArrays.end(), da) != ExcludedArrays.end()); +} + +//---------------------------------------------------------------------------- +// Add an array pair (input,output) using the name provided for the output. +inline vtkDataArray* ArrayList:: +AddArrayPair(vtkIdType numPts, vtkDataArray *inArray, + vtkStdString &outArrayName, double nullValue, bool promote) +{ + if (this->IsExcluded(inArray)) + { + return NULL; + } + + int iType = inArray->GetDataType(); + vtkDataArray *outArray; + if ( promote && iType != VTK_FLOAT && iType != VTK_DOUBLE ) + { + outArray = vtkFloatArray::New(); + outArray->SetNumberOfComponents(inArray->GetNumberOfComponents()); + outArray->SetNumberOfTuples(inArray->GetNumberOfTuples()); + outArray->SetName(outArrayName); + void *iD = inArray->GetVoidPointer(0); + void *oD = outArray->GetVoidPointer(0); + switch (iType) + { + vtkTemplateMacro(CreateRealArrayPair(this, static_cast(iD), + static_cast(oD),numPts,inArray->GetNumberOfComponents(), + outArray,static_cast(nullValue))); + }//over all VTK types + } + else + { + outArray = inArray->NewInstance(); + outArray->SetNumberOfComponents(inArray->GetNumberOfComponents()); + outArray->SetNumberOfTuples(inArray->GetNumberOfTuples()); + outArray->SetName(outArrayName); + void *iD = inArray->GetVoidPointer(0); + void *oD = outArray->GetVoidPointer(0); + switch (iType) + { + vtkTemplateMacro(CreateArrayPair(this, static_cast(iD), + static_cast(oD),numPts,inArray->GetNumberOfComponents(), + outArray,static_cast(nullValue))); + }//over all VTK types + }//promote integral types + + assert(outArray->GetReferenceCount() > 1); + outArray->FastDelete(); + return outArray; +} + +//---------------------------------------------------------------------------- +// Add the arrays to interpolate here. This presumes that vtkDataSetAttributes::CopyData() or +// vtkDataSetAttributes::InterpolateData() has been called, and the input and output array +// names match. +inline void ArrayList:: +AddArrays(vtkIdType numOutPts, vtkDataSetAttributes *inPD, vtkDataSetAttributes *outPD, + double nullValue, bool promote) +{ + // Build the vector of interpolation pairs. Note that InterpolateAllocate should have + // been called at this point (output arrays created and allocated). + char *name; + vtkDataArray *iArray, *oArray; + int iType, oType; + void *iD, *oD; + int iNumComp, oNumComp; + int i, numArrays = outPD->GetNumberOfArrays(); + + for (i=0; i < numArrays; ++i) + { + oArray = outPD->GetArray(i); + if ( oArray && ! this->IsExcluded(oArray) ) + { + name = oArray->GetName(); + iArray = inPD->GetArray(name); + if ( iArray && ! this->IsExcluded(iArray) ) + { + iType = iArray->GetDataType(); + oType = oArray->GetDataType(); + iNumComp = iArray->GetNumberOfComponents(); + oNumComp = oArray->GetNumberOfComponents(); + if ( promote && oType != VTK_FLOAT && oType != VTK_DOUBLE ) + { + oType = VTK_FLOAT; + vtkFloatArray *fArray = vtkFloatArray::New(); + fArray->SetName(oArray->GetName()); + fArray->SetNumberOfComponents(oNumComp); + outPD->AddArray(fArray); //nasty side effect will replace current array in the same spot + oArray = fArray; + fArray->Delete(); + } + oArray->SetNumberOfTuples(numOutPts); + + assert( iNumComp == oNumComp ); + if ( iType == oType ) + { + iD = iArray->GetVoidPointer(0); + oD = oArray->GetVoidPointer(0); + switch (iType) + { + vtkTemplateMacro(CreateArrayPair(this, static_cast(iD), + static_cast(oD),numOutPts,oNumComp, + oArray,static_cast(nullValue))); + }//over all VTK types + }//if matching types + else //promoted type + { + iD = iArray->GetVoidPointer(0); + oD = oArray->GetVoidPointer(0); + switch (iType) + { + vtkTemplateMacro(CreateRealArrayPair(this, static_cast(iD), + static_cast(oD),numOutPts,iNumComp, + oArray,static_cast(nullValue))); + }//over all VTK types + }//if promoted pair + }//if matching input array + }//if output array + }//for each candidate array +} + +#endif diff --git a/Common/DataModel/vtkBSPCuts.h b/Common/DataModel/vtkBSPCuts.h index 98f1f1a7983..1b47918d0b1 100644 --- a/Common/DataModel/vtkBSPCuts.h +++ b/Common/DataModel/vtkBSPCuts.h @@ -98,12 +98,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkBSPCuts : public vtkDataObject void PrintTree(); void PrintArrays(); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkBSPCuts* GetData(vtkInformation* info); static vtkBSPCuts* GetData(vtkInformationVector* v, int i=0); - //ETX // Description: // Restore data object to initial state, diff --git a/Common/DataModel/vtkBSPIntersections.h b/Common/DataModel/vtkBSPIntersections.h index f67a34edf26..8e83068caba 100644 --- a/Common/DataModel/vtkBSPIntersections.h +++ b/Common/DataModel/vtkBSPIntersections.h @@ -149,13 +149,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkBSPIntersections : public vtkObject double CellBoundsCache[6]; // to speed cell intersection queries -//BTX enum { XDIM = 0, // don't change these values YDIM = 1, ZDIM = 2 }; -//ETX private: diff --git a/Common/DataModel/vtkBoundingBox.h b/Common/DataModel/vtkBoundingBox.h index f2816ecbfd5..2aca1888781 100644 --- a/Common/DataModel/vtkBoundingBox.h +++ b/Common/DataModel/vtkBoundingBox.h @@ -48,8 +48,8 @@ class VTKCOMMONDATAMODEL_EXPORT vtkBoundingBox // Description: // Equality Operator - int operator==(const vtkBoundingBox &bbox)const; - int operator!=(const vtkBoundingBox &bbox)const; + bool operator==(const vtkBoundingBox &bbox)const; + bool operator!=(const vtkBoundingBox &bbox)const; // Description: // Set the bounds explicitly of the box (vtk Style) @@ -308,7 +308,7 @@ inline vtkBoundingBox &vtkBoundingBox::operator=(const vtkBoundingBox &bbox) return *this; } -inline int vtkBoundingBox::operator==(const vtkBoundingBox &bbox)const +inline bool vtkBoundingBox::operator==(const vtkBoundingBox &bbox)const { return ((this->MinPnt[0] == bbox.MinPnt[0]) && (this->MinPnt[1] == bbox.MinPnt[1]) && @@ -318,7 +318,7 @@ inline int vtkBoundingBox::operator==(const vtkBoundingBox &bbox)const (this->MaxPnt[2] == bbox.MaxPnt[2])); } -inline int vtkBoundingBox::operator!=(const vtkBoundingBox &bbox)const +inline bool vtkBoundingBox::operator!=(const vtkBoundingBox &bbox)const { return !((*this) == bbox); } diff --git a/Common/DataModel/vtkCellLinks.h b/Common/DataModel/vtkCellLinks.h index 1a6df8e51d7..266605f0c2a 100644 --- a/Common/DataModel/vtkCellLinks.h +++ b/Common/DataModel/vtkCellLinks.h @@ -42,13 +42,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkCellLinks : public vtkAbstractCellLinks { public: - //BTX class Link { public: unsigned short ncells; vtkIdType *cells; }; - //ETX // Description: // Standard methods to instantiate, print, and obtain type information. diff --git a/Common/DataModel/vtkCompositeDataIterator.h b/Common/DataModel/vtkCompositeDataIterator.h index 26a85808c14..32d822eef2a 100644 --- a/Common/DataModel/vtkCompositeDataIterator.h +++ b/Common/DataModel/vtkCompositeDataIterator.h @@ -93,7 +93,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkCompositeDataIterator : public vtkObject // Returns if the iteration is in reverse order. vtkGetMacro(Reverse, int); -//BTX protected: vtkCompositeDataIterator(); virtual ~vtkCompositeDataIterator(); @@ -104,7 +103,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkCompositeDataIterator : public vtkObject private: vtkCompositeDataIterator(const vtkCompositeDataIterator&); // Not implemented. void operator=(const vtkCompositeDataIterator&); // Not implemented. -//ETX + }; #endif diff --git a/Common/DataModel/vtkCompositeDataSet.h b/Common/DataModel/vtkCompositeDataSet.h index e56f54f1db2..d8eebac3d5f 100644 --- a/Common/DataModel/vtkCompositeDataSet.h +++ b/Common/DataModel/vtkCompositeDataSet.h @@ -47,7 +47,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkCompositeDataSet : public vtkDataObject // Description: // Return a new iterator (the iterator has to be deleted by user). - virtual vtkCompositeDataIterator* NewIterator() =0; + virtual VTK_NEWINSTANCE vtkCompositeDataIterator* NewIterator() =0; // Description: // Return class name of data type (see vtkType.h for @@ -80,12 +80,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkCompositeDataSet : public vtkDataObject // is valid only after the pipeline has updated. virtual unsigned long GetActualMemorySize(); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkCompositeDataSet* GetData(vtkInformation* info); static vtkCompositeDataSet* GetData(vtkInformationVector* v, int i=0); - //ETX // Description: // Restore data object to initial state, @@ -114,7 +112,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkCompositeDataSet : public vtkDataObject // ***THIS IS AN EXPERIMENTAL KEY SUBJECT TO CHANGE WITHOUT NOTICE*** static vtkInformationIntegerKey* CURRENT_PROCESS_CAN_LOAD_BLOCK(); -//BTX protected: vtkCompositeDataSet(); virtual ~vtkCompositeDataSet(); @@ -122,7 +119,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkCompositeDataSet : public vtkDataObject vtkCompositeDataSet(const vtkCompositeDataSet&); // Not implemented. void operator=(const vtkCompositeDataSet&); // Not implemented. -//ETX + }; #endif diff --git a/Common/DataModel/vtkCylinder.cxx b/Common/DataModel/vtkCylinder.cxx index c29e8f9eb45..9c11923899a 100644 --- a/Common/DataModel/vtkCylinder.cxx +++ b/Common/DataModel/vtkCylinder.cxx @@ -91,7 +91,6 @@ void vtkCylinder::SetAxis(double a[3]) // If axis length is zero, then don't change it if ( vtkMath::Normalize(a) < DBL_EPSILON ) { - vtkErrorMacro("Attempt to define cylinder with zero-length axis"); return; } diff --git a/Common/DataModel/vtkDataObject.h b/Common/DataModel/vtkDataObject.h index dce54f33e45..8071ef855e1 100644 --- a/Common/DataModel/vtkDataObject.h +++ b/Common/DataModel/vtkDataObject.h @@ -25,8 +25,7 @@ // concrete subclass of vtkDataSet before they can actually be displayed. // // .SECTION See Also -// vtkDataSet vtkFieldData vtkDataObjectSource vtkDataObjectFilter -// vtkDataObjectMapper vtkDataObjectToDataSet +// vtkDataSet vtkFieldData vtkDataObjectToDataSetFilter // vtkFieldDataToAttributeDataFilter #ifndef vtkDataObject_h @@ -211,7 +210,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObject : public vtkObject // matches the update extent. virtual void Crop(const int* updateExtent); - //BTX // Description: // Possible values for the FIELD_ASSOCIATION information entry. enum FieldAssociations @@ -225,9 +223,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObject : public vtkObject FIELD_ASSOCIATION_ROWS, NUMBER_OF_ASSOCIATIONS }; - //ETX - //BTX // Description: // Possible attribute types. // POINT_THEN_CELL is provided for consistency with FieldAssociations. @@ -242,7 +238,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObject : public vtkObject ROW, NUMBER_OF_ATTRIBUTE_TYPES }; - //ETX // Description: // Returns the attributes of the data object of the specified @@ -277,7 +272,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObject : public vtkObject // Get the number of elements for a specific attribute type (POINT, CELL, etc.). virtual vtkIdType GetNumberOfElements(int type); - //BTX // Description: // Possible values for the FIELD_OPERATION information entry. enum FieldOperations @@ -287,7 +281,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObject : public vtkObject FIELD_OPERATION_MODIFIED, FIELD_OPERATION_REMOVED }; - //ETX // Description: // Given an integer association type, this static method returns a string type @@ -356,12 +349,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObject : public vtkObject // \ingroup InformationKeys static vtkInformationDataObjectKey* SIL(); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkDataObject* GetData(vtkInformation* info); static vtkDataObject* GetData(vtkInformationVector* v, int i=0); - //ETX protected: diff --git a/Common/DataModel/vtkDataObjectCollection.h b/Common/DataModel/vtkDataObjectCollection.h index 9276c020ead..bb2b730acce 100644 --- a/Common/DataModel/vtkDataObjectCollection.h +++ b/Common/DataModel/vtkDataObjectCollection.h @@ -52,7 +52,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObjectCollection : public vtkCollection return static_cast(this->GetItemAsObject(i)); } - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. @@ -60,7 +59,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObjectCollection : public vtkCollection { return static_cast(this->GetNextItemAsObject(cookie)); } - //ETX protected: vtkDataObjectCollection() {} diff --git a/Common/DataModel/vtkDataObjectTree.h b/Common/DataModel/vtkDataObjectTree.h index ca7ebbd67e4..85c1dd40f33 100644 --- a/Common/DataModel/vtkDataObjectTree.h +++ b/Common/DataModel/vtkDataObjectTree.h @@ -56,7 +56,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObjectTree : public vtkCompositeDataSet // Use NewTreeIterator when you have a pointer to a vtkDataObjectTree // and NewIterator when you have a pointer to a vtkCompositeDataSet; // NewIterator is inherited and calls NewTreeIterator internally. - virtual vtkCompositeDataIterator* NewIterator(); + virtual VTK_NEWINSTANCE vtkCompositeDataIterator* NewIterator(); // Description: // Copies the tree structure from the input. All pointers to non-composite @@ -118,14 +118,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObjectTree : public vtkCompositeDataSet // might be expansive. virtual vtkIdType GetNumberOfPoints(); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkDataObjectTree* GetData(vtkInformation* info); static vtkDataObjectTree* GetData(vtkInformationVector* v, int i=0); - //ETX -//BTX protected: vtkDataObjectTree(); ~vtkDataObjectTree(); @@ -174,7 +171,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObjectTree : public vtkCompositeDataSet private: vtkDataObjectTree(const vtkDataObjectTree&); // Not implemented. void operator=(const vtkDataObjectTree&); // Not implemented. -//ETX + }; #endif diff --git a/Common/DataModel/vtkDataObjectTreeIterator.h b/Common/DataModel/vtkDataObjectTreeIterator.h index aae3d9fa2dc..197b689288c 100644 --- a/Common/DataModel/vtkDataObjectTreeIterator.h +++ b/Common/DataModel/vtkDataObjectTreeIterator.h @@ -94,7 +94,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObjectTreeIterator : public vtkCompositeD vtkGetMacro(TraverseSubTree, int); vtkBooleanMacro(TraverseSubTree, int); -//BTX protected: vtkDataObjectTreeIterator(); virtual ~vtkDataObjectTreeIterator(); @@ -135,7 +134,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataObjectTreeIterator : public vtkCompositeD // Cannot be called when this->IsDoneWithTraversal() return 1. void UpdateLocation(); -//ETX + }; #endif diff --git a/Common/DataModel/vtkDataSet.cxx b/Common/DataModel/vtkDataSet.cxx index b19618df6cf..25bdb6bce2a 100644 --- a/Common/DataModel/vtkDataSet.cxx +++ b/Common/DataModel/vtkDataSet.cxx @@ -516,7 +516,7 @@ void vtkDataSet::GenerateGhostArray(int zeroExt[6], bool cellOnly) if (!cellOnly) { vtkSmartPointer ghostPoints = - vtkUnsignedCharArray::SafeDownCast( + vtkArrayDownCast( this->PointData->GetArray(vtkDataSetAttributes::GhostArrayName())); if (!ghostPoints) { @@ -586,7 +586,7 @@ void vtkDataSet::GenerateGhostArray(int zeroExt[6], bool cellOnly) // ---- CELLS ---- vtkSmartPointer ghostCells = - vtkUnsignedCharArray::SafeDownCast( + vtkArrayDownCast( this->CellData->GetArray(vtkDataSetAttributes::GhostArrayName())); if (!ghostCells) { @@ -754,12 +754,12 @@ vtkUnsignedCharArray* vtkDataSet::GetPointGhostArray() { if(!this->PointGhostArrayCached) { - this->PointGhostArray = vtkUnsignedCharArray::SafeDownCast( + this->PointGhostArray = vtkArrayDownCast( this->GetPointData()->GetArray(vtkDataSetAttributes::GhostArrayName())); this->PointGhostArrayCached = true; } assert (this->PointGhostArray == - vtkUnsignedCharArray::SafeDownCast( + vtkArrayDownCast( this->GetPointData()->GetArray( vtkDataSetAttributes::GhostArrayName()))); return this->PointGhostArray; @@ -768,7 +768,7 @@ vtkUnsignedCharArray* vtkDataSet::GetPointGhostArray() //---------------------------------------------------------------------------- void vtkDataSet::UpdatePointGhostArrayCache() { - this->PointGhostArray = vtkUnsignedCharArray::SafeDownCast( + this->PointGhostArray = vtkArrayDownCast( this->GetPointData()->GetArray(vtkDataSetAttributes::GhostArrayName())); this->PointGhostArrayCached = true; } @@ -796,13 +796,13 @@ vtkUnsignedCharArray* vtkDataSet::GetCellGhostArray() { if(!this->CellGhostArrayCached) { - this->CellGhostArray = vtkUnsignedCharArray::SafeDownCast( + this->CellGhostArray = vtkArrayDownCast( this->GetCellData()->GetArray(vtkDataSetAttributes::GhostArrayName())); this->CellGhostArrayCached = true; } assert ( this->CellGhostArray == - vtkUnsignedCharArray::SafeDownCast( + vtkArrayDownCast( this->GetCellData()->GetArray(vtkDataSetAttributes::GhostArrayName()))); return this->CellGhostArray; } @@ -810,7 +810,7 @@ vtkUnsignedCharArray* vtkDataSet::GetCellGhostArray() //---------------------------------------------------------------------------- void vtkDataSet::UpdateCellGhostArrayCache() { - this->CellGhostArray = vtkUnsignedCharArray::SafeDownCast( + this->CellGhostArray = vtkArrayDownCast( this->GetCellData()->GetArray(vtkDataSetAttributes::GhostArrayName())); this->CellGhostArrayCached = true; } diff --git a/Common/DataModel/vtkDataSet.h b/Common/DataModel/vtkDataSet.h index 51c765d8e73..e04f205484c 100644 --- a/Common/DataModel/vtkDataSet.h +++ b/Common/DataModel/vtkDataSet.h @@ -313,14 +313,12 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSet : public vtkDataObject void ShallowCopy(vtkDataObject *src); void DeepCopy(vtkDataObject *src); -//BTX enum FieldDataType { DATA_OBJECT_FIELD=0, POINT_DATA_FIELD=1, CELL_DATA_FIELD=2 }; -//ETX // Description: // This method checks to see if the cell and point attributes @@ -341,12 +339,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSet : public vtkDataObject } virtual void GenerateGhostArray(int zeroExt[6], bool cellOnly); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkDataSet* GetData(vtkInformation* info); static vtkDataSet* GetData(vtkInformationVector* v, int i=0); - //ETX // Description: // Returns the attributes of the data object as a vtkFieldData. @@ -453,9 +449,8 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSet : public vtkDataObject static void OnDataModified( vtkObject* source, unsigned long eid, void* clientdata, void *calldata); - //BTX friend class vtkImageAlgorithmToDataSetFriendship; - //ETX + private: vtkDataSet(const vtkDataSet&); // Not implemented. void operator=(const vtkDataSet&); // Not implemented. diff --git a/Common/DataModel/vtkDataSetAttributes.cxx b/Common/DataModel/vtkDataSetAttributes.cxx index 5bec5363703..af4ab1705ca 100644 --- a/Common/DataModel/vtkDataSetAttributes.cxx +++ b/Common/DataModel/vtkDataSetAttributes.cxx @@ -14,25 +14,25 @@ =========================================================================*/ #include "vtkDataSetAttributes.h" +#include "vtkArrayDispatch.h" #include "vtkArrayIteratorIncludes.h" +#include "vtkAssume.h" #include "vtkCell.h" -#include "vtkMath.h" #include "vtkCharArray.h" -#include "vtkUnsignedCharArray.h" -#include "vtkShortArray.h" -#include "vtkUnsignedShortArray.h" -#include "vtkIntArray.h" -#include "vtkUnsignedIntArray.h" -#include "vtkLongArray.h" -#include "vtkMappedDataArray.h" -#include "vtkUnsignedLongArray.h" +#include "vtkDataArrayAccessor.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkIdTypeArray.h" -#include "vtkObjectFactory.h" -#include "vtkTypedDataArrayIterator.h" #include "vtkInformation.h" - +#include "vtkIntArray.h" +#include "vtkLongArray.h" +#include "vtkMath.h" +#include "vtkObjectFactory.h" +#include "vtkShortArray.h" +#include "vtkUnsignedCharArray.h" +#include "vtkUnsignedIntArray.h" +#include "vtkUnsignedLongArray.h" +#include "vtkUnsignedShortArray.h" #include namespace @@ -438,51 +438,65 @@ void vtkDataSetAttributes::PassData(vtkFieldData* fd) } //---------------------------------------------------------------------------- -// This is a version of vtkDataSetAttributesCopyValues adapted to work with -// vtkTypedDataArrayIterators. -template -void vtkTypedIteratorDataSetAttributesCopyValues( - vtkTypedDataArrayIterator destIter, const int *outExt, - vtkIdType outIncs[3], - vtkTypedDataArrayIterator srcIter, const int *inExt, - vtkIdType inIncs[3]) -{ - // For vtkMappedDataArray subclasses. - vtkTypedDataArrayIterator inZIter; - vtkTypedDataArrayIterator outZIter; - vtkTypedDataArrayIterator inYIter; - vtkTypedDataArrayIterator outYIter; - vtkTypedDataArrayIterator inIter; - vtkTypedDataArrayIterator outIter; - - // Set the starting iterators. - inZIter = srcIter + - (outExt[0] - inExt[0]) * inIncs[0] + - (outExt[2] - inExt[2]) * inIncs[1] + - (outExt[4] - inExt[4]) * inIncs[2]; - outZIter = destIter; - - int rowLength = outIncs[1]; - - for (int zIdx = outExt[4]; zIdx <= outExt[5]; ++zIdx) - { - inIter = inZIter; - outIter = outZIter; - for (int yIdx = outExt[2]; yIdx <= outExt[3]; ++yIdx) +namespace { +struct CopyStructuredDataWorker +{ + const int *OutExt; + const int *InExt; + + CopyStructuredDataWorker(const int *outExt, const int *inExt) + : OutExt(outExt), InExt(inExt) + {} + + template + void operator()(Array1T *dest, Array2T *src) + { + // get outExt relative to the inExt to keep the logic simple. This assumes + // that outExt is a subset of the inExt. + const int relOutExt[6] = { + this->OutExt[0] - this->InExt[0], + this->OutExt[1] - this->InExt[0], + this->OutExt[2] - this->InExt[2], + this->OutExt[3] - this->InExt[2], + this->OutExt[4] - this->InExt[4], + this->OutExt[5] - this->InExt[4] + }; + + // Give the compiler a hand -- allow optimizations that require both arrays + // to have the same stride. + VTK_ASSUME(src->GetNumberOfComponents() == dest->GetNumberOfComponents()); + + vtkDataArrayAccessor d(dest); + vtkDataArrayAccessor s(src); + + const int dims[3] = { this->InExt[1] - this->InExt[0] + 1, + this->InExt[3] - this->InExt[2] + 1, + this->InExt[5] - this->InExt[4] + 1}; + + vtkIdType outTupleIdx = 0; + for (int outz = relOutExt[4]; outz <= relOutExt[5]; ++outz) { - for (int c = 0; c < rowLength; ++c) + const vtkIdType zfactor = static_cast(outz) * dims[1]; + for (int outy = relOutExt[2]; outy <= relOutExt[3]; ++outy) { - *outIter = *inIter; - ++outIter; - ++inIter; + const vtkIdType yfactor = (zfactor + outy) * dims[0]; + for (int outx = relOutExt[0]; outx <= relOutExt[1]; ++outx) + { + const vtkIdType inTupleIdx = yfactor + outx; + for (int comp = 0, max = dest->GetNumberOfComponents(); + comp < max; ++comp) + { + d.Set(outTupleIdx, comp, s.Get(inTupleIdx, comp)); + } + outTupleIdx++; + } } - inIter += inIncs[1]; - outIter += outIncs[1]; } - inZIter += inIncs[2]; - outZIter += outIncs[2]; - } -} + dest->DataChanged(); + } +}; + +} // end anon namespace //---------------------------------------------------------------------------- template @@ -602,12 +616,14 @@ void vtkDataSetAttributes::CopyStructuredData(vtkDataSetAttributes *fromPd, outArray->SetNumberOfTuples(zIdx); } - if (inArray->HasStandardMemoryLayout() && - outArray->HasStandardMemoryLayout()) + // We get very little performance improvement from this, but we'll leave the + // legacy code around until we've done through benchmarking. + vtkDataArray *inDA = vtkArrayDownCast(inArray); + vtkDataArray *outDA = vtkArrayDownCast(outArray); + if (!inDA || !outDA) // String array, etc { vtkArrayIterator* srcIter = inArray->NewIterator(); vtkArrayIterator* destIter = outArray->NewIterator(); - switch (inArray->GetDataType()) { vtkArrayIteratorTemplateMacro( @@ -620,24 +636,12 @@ void vtkDataSetAttributes::CopyStructuredData(vtkDataSetAttributes *fromPd, } else { - switch (inArray->GetDataType()) + CopyStructuredDataWorker worker(outExt, inExt); + if (!vtkArrayDispatch::Dispatch2SameValueType::Execute(outDA, inDA, + worker)) { - vtkTemplateMacro( - vtkTypedDataArray *typedIn = - vtkTypedDataArray::FastDownCast(inArray); - vtkTypedDataArray *typedOut = - vtkTypedDataArray::FastDownCast(outArray); - if (typedIn == NULL || typedOut == NULL) - { - vtkGenericWarningMacro("Cannot copy to/from a mapped data array " - "from/into an array that does not derive " - "from vtkTypedDataArray."); - continue; - } - vtkTypedIteratorDataSetAttributesCopyValues( - vtkTypedDataArrayIterator(typedOut), outExt, outIncs, - vtkTypedDataArrayIterator(typedIn), inExt, inIncs) - ); // end vtkTemplateMacro + // Fallback to vtkDataArray API (e.g. vtkBitArray): + worker(outDA, inDA); } } } @@ -712,10 +716,10 @@ void vtkDataSetAttributes::InternalCopyAllocate(vtkDataSetAttributes* pd, { newAA->Allocate(aa->GetNumberOfTuples()); } - vtkDataArray* newDA = vtkDataArray::SafeDownCast(newAA); + vtkDataArray* newDA = vtkArrayDownCast(newAA); if (newDA) { - vtkDataArray* da = vtkDataArray::SafeDownCast(aa); + vtkDataArray* da = vtkArrayDownCast(aa); newDA->SetLookupTable(da->GetLookupTable()); } } @@ -1149,7 +1153,7 @@ int vtkDataSetAttributes::SetActiveAttribute(int index, int attributeType) { if (attributeType != PEDIGREEIDS) { - vtkDataArray* darray = vtkDataArray::SafeDownCast( + vtkDataArray* darray = vtkArrayDownCast( this->Data[index]); if (!darray) { @@ -1255,7 +1259,7 @@ vtkDataArray* vtkDataSetAttributes::GetAttribute(int attributeType) } else { - return vtkDataArray::SafeDownCast(this->Data[index]); + return vtkArrayDownCast(this->Data[index]); } } @@ -1279,7 +1283,7 @@ vtkAbstractArray* vtkDataSetAttributes::GetAbstractAttribute(int attributeType) // which is an enum defined vtkDataSetAttributes) int vtkDataSetAttributes::SetAttribute(vtkAbstractArray* aa, int attributeType) { - if (aa && attributeType != PEDIGREEIDS && !vtkDataArray::SafeDownCast(aa)) + if (aa && attributeType != PEDIGREEIDS && !vtkArrayDownCast(aa)) { vtkWarningMacro("Can not set attribute " << vtkDataSetAttributes::AttributeNames[attributeType] @@ -1638,7 +1642,7 @@ void vtkDataSetAttributes::InternalCopyAllocate( newAA->Allocate(list.NumberOfTuples,ext); } - if ( (newDA = vtkDataArray::SafeDownCast(newAA)) ) + if ( (newDA = vtkArrayDownCast(newAA)) ) { newDA->SetLookupTable(list.LUT[i]); } @@ -2232,9 +2236,9 @@ void vtkDataSetAttributes::FieldList::SetField( // Store the lookup table this->LUT[index]=0; - if (vtkDataArray::SafeDownCast(aa)) + if (vtkArrayDownCast(aa)) { - this->LUT[index]=vtkDataArray::SafeDownCast(aa)->GetLookupTable(); + this->LUT[index]= vtkArrayDownCast(aa)->GetLookupTable(); } // Store the information this->FieldInformation[index] = 0; diff --git a/Common/DataModel/vtkDataSetAttributes.h b/Common/DataModel/vtkDataSetAttributes.h index 949a75ed7a6..3ede9bc9052 100644 --- a/Common/DataModel/vtkDataSetAttributes.h +++ b/Common/DataModel/vtkDataSetAttributes.h @@ -80,7 +80,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSetAttributes : public vtkFieldData virtual void ShallowCopy(vtkFieldData *pd); // -- attribute types ----------------------------------------------------- -//BTX + // Always keep NUM_ATTRIBUTES as the last entry enum AttributeTypes { @@ -101,7 +101,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSetAttributes : public vtkFieldData EXACT, NOLIMIT }; -//ETX // ----------- ghost points and ghost cells ------------------------------------------- //The following bit fields are consistent with VisIt ghost zones specification @@ -268,7 +267,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSetAttributes : public vtkFieldData // -- attribute copy properties ------------------------------------------ -//BTX enum AttributeCopyOperations { COPYTUPLE=0, @@ -276,7 +274,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSetAttributes : public vtkFieldData PASSDATA=2, ALLCOPY //all of the above }; -//ETX // Description: // Specify whether to copy the data attribute referred to by index. @@ -576,7 +573,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSetAttributes : public vtkFieldData vtkDataSetAttributes *from2, vtkIdType id, double t); -//BTX class FieldList; // field list copy operations ------------------------------------------ @@ -616,9 +612,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSetAttributes : public vtkFieldData vtkIdList *ids, double *weights); friend class vtkDataSetAttributes::FieldList; -//ETX -//BTX protected: vtkDataSetAttributes(); ~vtkDataSetAttributes(); @@ -730,7 +724,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSetAttributes : public vtkFieldData int CurrentInput; }; -//ETX + }; #endif diff --git a/Common/DataModel/vtkDataSetCollection.h b/Common/DataModel/vtkDataSetCollection.h index 17393afb140..c05a7527c0a 100644 --- a/Common/DataModel/vtkDataSetCollection.h +++ b/Common/DataModel/vtkDataSetCollection.h @@ -52,13 +52,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDataSetCollection : public vtkCollection vtkDataSet *GetDataSet(int i) { return static_cast(this->GetItemAsObject(i));}; - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkDataSet *GetNextDataSet(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkDataSetCollection() {} diff --git a/Common/DataModel/vtkDirectedAcyclicGraph.h b/Common/DataModel/vtkDirectedAcyclicGraph.h index 7b4f7e4d782..fd515404149 100644 --- a/Common/DataModel/vtkDirectedAcyclicGraph.h +++ b/Common/DataModel/vtkDirectedAcyclicGraph.h @@ -59,12 +59,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDirectedAcyclicGraph : public vtkDirectedGrap // Return what type of dataset this is. virtual int GetDataObjectType() {return VTK_DIRECTED_ACYCLIC_GRAPH;} - //BTX // Description: // Retrieve a graph from an information vector. static vtkDirectedAcyclicGraph *GetData(vtkInformation *info); static vtkDirectedAcyclicGraph *GetData(vtkInformationVector *v, int i=0); - //ETX protected: vtkDirectedAcyclicGraph(); diff --git a/Common/DataModel/vtkDirectedGraph.h b/Common/DataModel/vtkDirectedGraph.h index 3abb3832fc5..fb56ed2f44a 100644 --- a/Common/DataModel/vtkDirectedGraph.h +++ b/Common/DataModel/vtkDirectedGraph.h @@ -49,12 +49,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDirectedGraph : public vtkGraph // Return what type of dataset this is. virtual int GetDataObjectType() {return VTK_DIRECTED_GRAPH;} - //BTX // Description: // Retrieve a graph from an information vector. static vtkDirectedGraph *GetData(vtkInformation *info); static vtkDirectedGraph *GetData(vtkInformationVector *v, int i=0); - //ETX // Description: // Check the storage, and accept it if it is a valid diff --git a/Common/DataModel/vtkDistributedGraphHelper.h b/Common/DataModel/vtkDistributedGraphHelper.h index ff30b5f0966..f49dfa29360 100644 --- a/Common/DataModel/vtkDistributedGraphHelper.h +++ b/Common/DataModel/vtkDistributedGraphHelper.h @@ -97,7 +97,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDistributedGraphHelper : public vtkObject // Builds a distributed ID consisting of the given owner and the local ID. vtkIdType MakeDistributedId(int owner, vtkIdType local); - //BTX // Description: // Set the pedigreeId -> processor distribution function that determines // how vertices are distributed when they are associated with @@ -106,7 +105,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDistributedGraphHelper : public vtkObject // hashed distribution will be used. void SetVertexPedigreeIdDistribution(vtkVertexPedigreeIdDistribution Func, void *userData); - //ETX // Description: // Determine which processor owns the vertex with the given pedigree ID. @@ -221,7 +219,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDistributedGraphHelper : public vtkObject // The graph to which this distributed graph helper is already attached. vtkGraph *Graph; - //BTX // Description: // The distribution function used to map a pedigree ID to a processor. vtkVertexPedigreeIdDistribution VertexDistribution; @@ -245,15 +242,13 @@ class VTKCOMMONDATAMODEL_EXPORT vtkDistributedGraphHelper : public vtkObject // Description: // Number of bits required to represent {vertex,edge} index int indexBits; - //ETX private: vtkDistributedGraphHelper(const vtkDistributedGraphHelper&); // Not implemented void operator=(const vtkDistributedGraphHelper&); // Not implemented - //BTX friend class vtkGraph; - //ETX + }; #endif // vtkDistributedGraphHelper_h diff --git a/Common/DataModel/vtkEdgeListIterator.h b/Common/DataModel/vtkEdgeListIterator.h index 0fec6225f9f..35f32a761a4 100644 --- a/Common/DataModel/vtkEdgeListIterator.h +++ b/Common/DataModel/vtkEdgeListIterator.h @@ -40,10 +40,10 @@ class vtkGraph; class vtkGraphEdge; -//BTX + struct vtkEdgeType; struct vtkOutEdgeType; -//ETX + class VTKCOMMONDATAMODEL_EXPORT vtkEdgeListIterator : public vtkObject { public: @@ -54,11 +54,9 @@ class VTKCOMMONDATAMODEL_EXPORT vtkEdgeListIterator : public vtkObject vtkGetObjectMacro(Graph, vtkGraph); virtual void SetGraph(vtkGraph *graph); - //BTX // Description: // Returns the next edge in the graph. vtkEdgeType Next(); - //ETX // Description: // Just like Next(), but diff --git a/Common/DataModel/vtkExtractStructuredGridHelper.cxx b/Common/DataModel/vtkExtractStructuredGridHelper.cxx index a2b132f45ad..c43b29dc18e 100644 --- a/Common/DataModel/vtkExtractStructuredGridHelper.cxx +++ b/Common/DataModel/vtkExtractStructuredGridHelper.cxx @@ -493,7 +493,8 @@ void vtkExtractStructuredGridHelper::CopyCellData(int inExt[6], int outExt[6], for( K(ijk)=KMIN(outCellExt); K(ijk) <= KMAX(outCellExt); ++K(ijk) ) { K(src_ijk) = useMapping ? this->GetMappedExtentValue(2, K(ijk)) : K(ijk); - if (K(src_ijk) == KMAX(this->InputWholeExtent) && K(src_ijk) != 0) + if (K(src_ijk) == KMAX(this->InputWholeExtent) && + KMIN(this->InputWholeExtent) != KMAX(this->InputWholeExtent)) { --K(src_ijk); } @@ -501,7 +502,8 @@ void vtkExtractStructuredGridHelper::CopyCellData(int inExt[6], int outExt[6], for( J(ijk)=JMIN(outCellExt); J(ijk) <= JMAX(outCellExt); ++J(ijk) ) { J(src_ijk) = useMapping ? this->GetMappedExtentValue(1, J(ijk)) : J(ijk); - if (J(src_ijk) == JMAX(this->InputWholeExtent) && J(src_ijk) != 0) + if (J(src_ijk) == JMAX(this->InputWholeExtent) && + JMIN(this->InputWholeExtent) != JMAX(this->InputWholeExtent)) { --J(src_ijk); } @@ -534,7 +536,8 @@ void vtkExtractStructuredGridHelper::CopyCellData(int inExt[6], int outExt[6], { I(src_ijk) = useMapping ? this->GetMappedExtentValue(0, I(ijk)) : I(ijk); - if (I(src_ijk) == IMAX(this->InputWholeExtent) && I(src_ijk) != 0) + if (I(src_ijk) == IMAX(this->InputWholeExtent) && + IMIN(this->InputWholeExtent) != IMAX(this->InputWholeExtent)) { --I(src_ijk); } diff --git a/Common/DataModel/vtkFieldData.cxx b/Common/DataModel/vtkFieldData.cxx index a32db8297f4..9280f96c1f3 100644 --- a/Common/DataModel/vtkFieldData.cxx +++ b/Common/DataModel/vtkFieldData.cxx @@ -387,7 +387,7 @@ void vtkFieldData::SetArray(int i, vtkAbstractArray *data) // if range. vtkDataArray *vtkFieldData::GetArray(int i) { - return vtkDataArray::SafeDownCast(this->GetAbstractArray(i)); + return vtkArrayDownCast(this->GetAbstractArray(i)); } //---------------------------------------------------------------------------- @@ -506,7 +506,7 @@ int vtkFieldData::GetArrayContainingComponent(int i, int& arrayComp) vtkDataArray *vtkFieldData::GetArray(const char *arrayName, int &index) { int i; - vtkDataArray* da = vtkDataArray::SafeDownCast(this->GetAbstractArray( + vtkDataArray* da = vtkArrayDownCast(this->GetAbstractArray( arrayName, i)); index = (da)? i : -1; return da; diff --git a/Common/DataModel/vtkFieldData.h b/Common/DataModel/vtkFieldData.h index 80e02103f15..03153be1408 100644 --- a/Common/DataModel/vtkFieldData.h +++ b/Common/DataModel/vtkFieldData.h @@ -317,8 +317,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkFieldData : public vtkObject // Release all data but do not delete object. virtual void InitializeFields(); -//BTX - struct CopyFieldFlag { char* ArrayName; @@ -420,9 +418,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkFieldData : public vtkObject int Detached; }; - -//ETX - }; diff --git a/Common/DataModel/vtkGenericAttributeCollection.h b/Common/DataModel/vtkGenericAttributeCollection.h index db7b53ae6a6..27b4979ba27 100644 --- a/Common/DataModel/vtkGenericAttributeCollection.h +++ b/Common/DataModel/vtkGenericAttributeCollection.h @@ -175,13 +175,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGenericAttributeCollection : public vtkObject // \post positive_result: result>=0 vtkGetMacro(NumberOfAttributesToInterpolate, int); - //BTX // Description: // Indices of attributes to interpolate. // \pre not_empty: !IsEmpty() // \post valid_result: GetNumberOfAttributesToInterpolate()>0 int *GetAttributesToInterpolate(); - //ETX // Description // Does the array `attributes' of size `size' have `attribute'? diff --git a/Common/DataModel/vtkGenericDataSet.h b/Common/DataModel/vtkGenericDataSet.h index de33c2b60d1..df99aaf2ef3 100644 --- a/Common/DataModel/vtkGenericDataSet.h +++ b/Common/DataModel/vtkGenericDataSet.h @@ -235,12 +235,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGenericDataSet : public vtkDataObject // Estimated size needed after tessellation (or special operation) virtual vtkIdType GetEstimatedSize() = 0; - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkGenericDataSet* GetData(vtkInformation* info); static vtkGenericDataSet* GetData(vtkInformationVector* v, int i=0); - //ETX protected: // Description: diff --git a/Common/DataModel/vtkGenericEdgeTable.h b/Common/DataModel/vtkGenericEdgeTable.h index 631b91ad319..c59bec53ba0 100644 --- a/Common/DataModel/vtkGenericEdgeTable.h +++ b/Common/DataModel/vtkGenericEdgeTable.h @@ -119,7 +119,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGenericEdgeTable : public vtkObject void DumpTable(); void LoadFactor(); -//BTX class PointEntry { public: @@ -153,7 +152,7 @@ class PointEntry this->Reference = other.Reference; } - void operator=(const PointEntry &other) + PointEntry& operator=(const PointEntry &other) { if(this != &other) { @@ -172,6 +171,7 @@ class PointEntry memcpy(this->Scalar, other.Scalar, sizeof(double)*c); this->Reference = other.Reference; } + return *this; } }; @@ -204,11 +204,11 @@ class EdgeEntry this->CellId = copy.CellId; } - void operator=(const EdgeEntry& entry) + EdgeEntry& operator=(const EdgeEntry& entry) { if(this == &entry) { - return; + return *this; } this->E1 = entry.E1; this->E2 = entry.E2; @@ -216,9 +216,9 @@ class EdgeEntry this->ToSplit = entry.ToSplit; this->PtId = entry.PtId; this->CellId = entry.CellId; + return *this; } }; -//ETX protected: vtkGenericEdgeTable(); diff --git a/Common/DataModel/vtkGraph.h b/Common/DataModel/vtkGraph.h index 030aed11c37..c2e5a99c282 100644 --- a/Common/DataModel/vtkGraph.h +++ b/Common/DataModel/vtkGraph.h @@ -223,7 +223,6 @@ class vtkVertexListIterator; class vtkVariant; class vtkVariantArray; -//BTX // Forward declare some boost stuff even if boost wrappers // are turned off. namespace boost @@ -270,7 +269,6 @@ struct vtkEdgeType : vtkEdgeBase vtkIdType Source; vtkIdType Target; }; -//ETX class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject { @@ -344,11 +342,9 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject // distributed graph, the vertex v must be local to this processor. virtual vtkIdType GetOutDegree(vtkIdType v); - //BTX // Description: // Random-access method for retrieving outgoing edges from vertex v. virtual vtkOutEdgeType GetOutEdge(vtkIdType v, vtkIdType index); - //ETX // Description: // Random-access method for retrieving outgoing edges from vertex v. @@ -370,11 +366,9 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject // distributed graph, the vertex v must be local to this processor. virtual vtkIdType GetInDegree(vtkIdType v); - //BTX // Description: // Random-access method for retrieving incoming edges to vertex v. virtual vtkInEdgeType GetInEdge(vtkIdType v, vtkIdType index); - //ETX // Description: // Random-access method for retrieving incoming edges to vertex v. @@ -413,7 +407,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject // returns the number of local vertices in the graph. virtual vtkIdType GetNumberOfVertices(); - // BTX // Description: // Sets the distributed graph helper of this graph, turning it into a // distributed graph. This operation can only be executed on an empty @@ -423,7 +416,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject // Description: // Retrieves the distributed graph helper for this graph vtkDistributedGraphHelper *GetDistributedGraphHelper(); - //ETX // Description: // Retrieve the vertex with the given pedigree ID. If successful, @@ -465,12 +457,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject // Reclaim unused memory. virtual void Squeeze(); - //BTX // Description: // Retrieve a graph from an information vector. static vtkGraph *GetData(vtkInformation *info); static vtkGraph *GetData(vtkInformationVector *v, int i=0); - //ETX // Description: // Reorder the outgoing vertices of a vertex. @@ -496,14 +486,12 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject vtkIdType GetSourceVertex(vtkIdType e); vtkIdType GetTargetVertex(vtkIdType e); - //BTX // Description: // Get/Set the internal edge control points associated with each edge. // The size of the pts array is 3*npts, and holds the x,y,z // location of each edge control point. void SetEdgePoints(vtkIdType e, vtkIdType npts, double* pts); void GetEdgePoints(vtkIdType e, vtkIdType& npts, double*& pts); - //ETX // Description: // Get the number of edge points associated with an edge. @@ -581,7 +569,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject bool ToUndirectedGraph(vtkUndirectedGraph* g); protected: - //BTX + vtkGraph(); ~vtkGraph(); @@ -633,7 +621,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject // Description: // Removes a collection of edges from the graph. void RemoveEdgesInternal(vtkIdTypeArray* arr, bool directed); - //ETX // Description: // Subclasses override this method to accept the structure @@ -678,7 +665,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject // Builds a mapping from edge id to source/target vertex id. void BuildEdgeList(); - //BTX // Description: // Friend iterator classes. friend class vtkAdjacentVertexIterator; @@ -688,7 +674,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject friend class boost::vtk_edge_iterator; friend class boost::vtk_in_edge_pointer_iterator; friend class boost::vtk_out_edge_pointer_iterator; - //ETX // Description: // The vertex and edge data. @@ -713,16 +698,14 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraph : public vtkDataObject vtkGetObjectMacro(EdgeList, vtkIdTypeArray); virtual void SetEdgeList(vtkIdTypeArray* list); vtkIdTypeArray *EdgeList; - //ETX + private: vtkGraph(const vtkGraph&); // Not implemented. void operator=(const vtkGraph&); // Not implemented. }; -//BTX bool VTKCOMMONDATAMODEL_EXPORT operator==(vtkEdgeBase e1, vtkEdgeBase e2); bool VTKCOMMONDATAMODEL_EXPORT operator!=(vtkEdgeBase e1, vtkEdgeBase e2); VTKCOMMONDATAMODEL_EXPORT ostream& operator<<(ostream& out, vtkEdgeBase e); -//ETX #endif diff --git a/Common/DataModel/vtkGraphInternals.h b/Common/DataModel/vtkGraphInternals.h index a7a4aaf77c6..5af7de21d94 100644 --- a/Common/DataModel/vtkGraphInternals.h +++ b/Common/DataModel/vtkGraphInternals.h @@ -34,14 +34,13 @@ //---------------------------------------------------------------------------- // class vtkVertexAdjacencyList //---------------------------------------------------------------------------- -//BTX + class vtkVertexAdjacencyList { public: std::vector InEdges; std::vector OutEdges; }; -//ETX //---------------------------------------------------------------------------- // class vtkGraphInternals @@ -50,10 +49,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraphInternals : public vtkObject { public: static vtkGraphInternals *New(); - //BTX + vtkTypeMacro(vtkGraphInternals, vtkObject); std::vector Adjacency; - //ETX + vtkIdType NumberOfEdges; vtkIdType LastRemoteEdgeId; @@ -67,7 +66,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraphInternals : public vtkObject // vtkMutableDirectedGraph. bool UsingPedigreeIds; - //BTX // Description: // Convenience method for removing an edge from an out edge list. void RemoveEdgeFromOutList(vtkIdType e, std::vector& outEdges); @@ -83,7 +81,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkGraphInternals : public vtkObject // Description: // Convenience method for renaming an edge in an in edge list. void ReplaceEdgeFromInList(vtkIdType from, vtkIdType to, std::vector& inEdges); - //ETX protected: vtkGraphInternals(); diff --git a/Common/DataModel/vtkHierarchicalBoxDataSet.h b/Common/DataModel/vtkHierarchicalBoxDataSet.h index 1b77bd231f4..5506d86a058 100644 --- a/Common/DataModel/vtkHierarchicalBoxDataSet.h +++ b/Common/DataModel/vtkHierarchicalBoxDataSet.h @@ -38,18 +38,17 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHierarchicalBoxDataSet: // Description: // Return a new iterator (the iterator has to be deleted by user). - virtual vtkCompositeDataIterator* NewIterator(); + virtual VTK_NEWINSTANCE vtkCompositeDataIterator* NewIterator(); // Description: // Return class name of data type (see vtkType.h for definitions). virtual int GetDataObjectType() {return VTK_HIERARCHICAL_BOX_DATA_SET;} - // BTX // Description: // Retrieve an instance of this class from an information object. static vtkHierarchicalBoxDataSet* GetData(vtkInformation* info); static vtkHierarchicalBoxDataSet* GetData(vtkInformationVector* v, int i=0); - // ETX + protected: vtkHierarchicalBoxDataSet(); virtual ~vtkHierarchicalBoxDataSet(); diff --git a/Common/DataModel/vtkHyperOctree.cxx b/Common/DataModel/vtkHyperOctree.cxx index b93d8caf8f9..e07e6645156 100644 --- a/Common/DataModel/vtkHyperOctree.cxx +++ b/Common/DataModel/vtkHyperOctree.cxx @@ -3656,7 +3656,7 @@ void vtkHyperOctree::EvaluateDualCorner( leaves[corner] = neighborhood[corner].GetLeafIndex(); } - this->CornerLeafIds->InsertNextTupleValue(leaves); + this->CornerLeafIds->InsertNextTypedTuple(leaves); } //---------------------------------------------------------------------------- diff --git a/Common/DataModel/vtkHyperOctree.h b/Common/DataModel/vtkHyperOctree.h index 0df630ad0f2..749b2ee2527 100644 --- a/Common/DataModel/vtkHyperOctree.h +++ b/Common/DataModel/vtkHyperOctree.h @@ -478,12 +478,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperOctree : public vtkDataSet // IS THREAD SAFE. unsigned long GetActualMemorySize(); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkHyperOctree* GetData(vtkInformation* info); static vtkHyperOctree* GetData(vtkInformationVector* v, int i=0); - //ETX protected: // Constructor with default bounds (0,1, 0,1, 0,1). @@ -501,9 +499,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperOctree : public vtkDataSet vtkHyperOctreeCursor *TmpChild; // to avoid allocation in the loop - //BTX friend class vtkHyperOctreeLightWeightCursor; - //ETX // Initialize the arrays if necessary, then return it. void UpdateDualArrays(); @@ -560,9 +556,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperOctree : public vtkDataSet void operator=(const vtkHyperOctree&); // Not implemented. }; - -//BTX - class VTKCOMMONDATAMODEL_EXPORT vtkHyperOctreeLightWeightCursor { public: @@ -581,6 +574,4 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperOctreeLightWeightCursor unsigned short Level; }; -//ETX - #endif diff --git a/Common/DataModel/vtkHyperTree.h b/Common/DataModel/vtkHyperTree.h index 621d1fbfd1d..ad43b4ade01 100644 --- a/Common/DataModel/vtkHyperTree.h +++ b/Common/DataModel/vtkHyperTree.h @@ -160,6 +160,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperTree : public vtkObject // Return an instance of a templated hypertree for given branch // factor and dimension // This is done to hide templates. + VTK_NEWINSTANCE static vtkHyperTree* CreateInstance( unsigned int branchFactor, unsigned int dimension ); diff --git a/Common/DataModel/vtkHyperTreeGrid.cxx b/Common/DataModel/vtkHyperTreeGrid.cxx index d24ef66dd19..da55535f42a 100644 --- a/Common/DataModel/vtkHyperTreeGrid.cxx +++ b/Common/DataModel/vtkHyperTreeGrid.cxx @@ -1754,7 +1754,7 @@ void vtkHyperTreeGrid::TraverseDualLeaf( vtkHyperTreeGridSuperCursor* superCurso if ( owner ) { - this->Connectivity->InsertNextTupleValue( leaves ); + this->Connectivity->InsertNextTypedTuple( leaves ); } } // cornerIdx } diff --git a/Common/DataModel/vtkHyperTreeGrid.h b/Common/DataModel/vtkHyperTreeGrid.h index 683e8c42b45..3e656e58d23 100644 --- a/Common/DataModel/vtkHyperTreeGrid.h +++ b/Common/DataModel/vtkHyperTreeGrid.h @@ -59,11 +59,10 @@ class vtkVoxel; class VTKCOMMONDATAMODEL_EXPORT vtkHyperTreeGrid : public vtkDataSet { public: -//BTX + class vtkHyperTreeSimpleCursor; class vtkHyperTreeIterator; struct vtkHyperTreeGridSuperCursor; -//ETX static vtkInformationIntegerKey* LEVELS(); static vtkInformationIntegerKey* DIMENSION(); @@ -322,8 +321,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperTreeGrid : public vtkDataSet // Generate the table before calling InitializeSuperCursorChild. void GenerateSuperCursorTraversalTable(); -//BTX -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ // Description: // Initialize a super cursor to point to one of the root trees // in the grid. The super cursor points to a node in a tree and @@ -342,7 +340,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperTreeGrid : public vtkDataSet vtkHyperTreeGridSuperCursor* child, unsigned int childIdx ); #endif -//ETX // Description: // The number of children each node can have. @@ -393,8 +390,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperTreeGrid : public vtkDataSet void DeleteInternalArrays(); void DeleteTrees(); -//BTX -#if !defined(__WRAP__) && !defined(__WRAP_GCCXML__) +#if !defined(__VTK_WRAP__) && !defined(__WRAP_GCCXML__) void TraverseDualRecursively( vtkHyperTreeGridSuperCursor*, unsigned int ); void TraverseDualMaskedLeaf( vtkHyperTreeGridSuperCursor* ); @@ -403,7 +399,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperTreeGrid : public vtkDataSet void EvaluateDualCorner( vtkHyperTreeSimpleCursor* ); #endif -//ETX // Used to advance the super cursor; One Entry per cursor node. // Private. @@ -431,15 +426,12 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperTreeGrid : public vtkDataSet vtkCellLinks* Links; void BuildLinks(); -//BTX vtkIdType RecursiveFindPoint( double x[3], vtkHyperTreeSimpleCursor* cursor, double* origin, double* size); -//ETX public: -//BTX // A simplified hyper tree cursor, to be used by the hyper tree // grid supercursor. class VTKCOMMONDATAMODEL_EXPORT vtkHyperTreeSimpleCursor @@ -506,7 +498,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkHyperTreeGrid : public vtkDataSet return this->Cursors + this->MiddleCursorId + idx; } }; -//ETX private: vtkHyperTreeGrid(const vtkHyperTreeGrid&); // Not implemented. diff --git a/Common/DataModel/vtkImageData.h b/Common/DataModel/vtkImageData.h index 5659a893334..408f2f23dec 100644 --- a/Common/DataModel/vtkImageData.h +++ b/Common/DataModel/vtkImageData.h @@ -357,12 +357,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkImageData : public vtkDataSet // The extent type is a 3D extent virtual int GetExtentType() { return VTK_3D_EXTENT; }; - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkImageData* GetData(vtkInformation* info); static vtkImageData* GetData(vtkInformationVector* v, int i=0); - //ETX protected: vtkImageData(); @@ -403,9 +401,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkImageData : public vtkDataSet void InternalImageDataCopy(vtkImageData *src); private: - //BTX friend class vtkUniformGrid; - //ETX // for the GetCell method vtkVertex *Vertex; diff --git a/Common/DataModel/vtkImplicitDataSet.h b/Common/DataModel/vtkImplicitDataSet.h index e15a1eaf310..bead10ed74e 100644 --- a/Common/DataModel/vtkImplicitDataSet.h +++ b/Common/DataModel/vtkImplicitDataSet.h @@ -87,7 +87,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkImplicitDataSet : public vtkImplicitFunction vtkImplicitDataSet(); ~vtkImplicitDataSet(); - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; vtkDataSet *DataSet; double OutValue; diff --git a/Common/DataModel/vtkImplicitFunctionCollection.h b/Common/DataModel/vtkImplicitFunctionCollection.h index 2f0855580e7..8aefd418e1c 100644 --- a/Common/DataModel/vtkImplicitFunctionCollection.h +++ b/Common/DataModel/vtkImplicitFunctionCollection.h @@ -41,7 +41,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkImplicitFunctionCollection : public vtkCollec // Get the next implicit function in the list. vtkImplicitFunction *GetNextItem(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. @@ -51,7 +50,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkImplicitFunctionCollection : public vtkCollec return static_cast( this->GetNextItemAsObject(cookie)); }; - //ETX protected: vtkImplicitFunctionCollection() {} diff --git a/Common/DataModel/vtkImplicitSelectionLoop.cxx b/Common/DataModel/vtkImplicitSelectionLoop.cxx index fd493116bc3..c82fad8f7ab 100644 --- a/Common/DataModel/vtkImplicitSelectionLoop.cxx +++ b/Common/DataModel/vtkImplicitSelectionLoop.cxx @@ -123,7 +123,7 @@ double vtkImplicitSelectionLoop::EvaluateFunction(double x[3]) xProj[2] >= this->Bounds[4] && xProj[2] <= this->Bounds[5] && this->Polygon-> PointInPolygon(xProj , numPts, - vtkDoubleArray::SafeDownCast(this->Polygon->Points->GetData())->GetPointer(0), + vtkArrayDownCast(this->Polygon->Points->GetData())->GetPointer(0), this->Bounds,this->Normal) == 1 ) { inside = 1; diff --git a/Common/DataModel/vtkImplicitWindowFunction.h b/Common/DataModel/vtkImplicitWindowFunction.h index c9d3d91675f..8358c4a7311 100644 --- a/Common/DataModel/vtkImplicitWindowFunction.h +++ b/Common/DataModel/vtkImplicitWindowFunction.h @@ -77,14 +77,14 @@ class VTKCOMMONDATAMODEL_EXPORT vtkImplicitWindowFunction : public vtkImplicitFu // Description: // Participate in garbage collection. - virtual void Register(vtkObjectBase* o); - virtual void UnRegister(vtkObjectBase* o); + void Register(vtkObjectBase* o) VTK_OVERRIDE; + void UnRegister(vtkObjectBase* o) VTK_OVERRIDE; protected: vtkImplicitWindowFunction(); ~vtkImplicitWindowFunction(); - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; vtkImplicitFunction *ImplicitFunction; double WindowRange[2]; diff --git a/Common/DataModel/vtkInEdgeIterator.h b/Common/DataModel/vtkInEdgeIterator.h index c8bc2f21f5e..f77a3f44d36 100644 --- a/Common/DataModel/vtkInEdgeIterator.h +++ b/Common/DataModel/vtkInEdgeIterator.h @@ -55,7 +55,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkInEdgeIterator : public vtkObject vtkGetObjectMacro(Graph, vtkGraph); vtkGetMacro(Vertex, vtkIdType); - //BTX // Description: // Returns the next edge in the graph. inline vtkInEdgeType Next() @@ -64,7 +63,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkInEdgeIterator : public vtkObject ++this->Current; return e; } - //ETX // Description: // Just like Next(), but diff --git a/Common/DataModel/vtkIncrementalOctreeNode.h b/Common/DataModel/vtkIncrementalOctreeNode.h index 457faba3b43..f5489839725 100644 --- a/Common/DataModel/vtkIncrementalOctreeNode.h +++ b/Common/DataModel/vtkIncrementalOctreeNode.h @@ -186,7 +186,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkIncrementalOctreeNode : public vtkObject // are added to vtkIdList by vtkIdList::SetId(). void ExportAllPointIdsByDirectSet( vtkIdType * pntIdx, vtkIdList * idList ); -//BTX protected: vtkIncrementalOctreeNode(); @@ -330,7 +329,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkIncrementalOctreeNode : public vtkObject vtkIncrementalOctreeNode( const vtkIncrementalOctreeNode & );// Not implemented void operator = ( const vtkIncrementalOctreeNode & ); // Not implemented -//ETX + }; // In-lined for performance diff --git a/Common/DataModel/vtkIncrementalOctreePointLocator.h b/Common/DataModel/vtkIncrementalOctreePointLocator.h index e01419d58a1..8305d6075b3 100644 --- a/Common/DataModel/vtkIncrementalOctreePointLocator.h +++ b/Common/DataModel/vtkIncrementalOctreePointLocator.h @@ -275,7 +275,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkIncrementalOctreePointLocator : public vtkInc void InsertPointWithoutChecking ( const double point[3], vtkIdType & pntId, int insert ); -//BTX protected: vtkIncrementalOctreePointLocator(); @@ -434,6 +433,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkIncrementalOctreePointLocator : public vtkInc vtkIncrementalOctreePointLocator ( const vtkIncrementalOctreePointLocator & ); // Not implemented void operator = ( const vtkIncrementalOctreePointLocator & );// Not implemented -//ETX + }; #endif diff --git a/Common/DataModel/vtkKdTree.cxx b/Common/DataModel/vtkKdTree.cxx index 4505088cc6a..903a747bfb3 100644 --- a/Common/DataModel/vtkKdTree.cxx +++ b/Common/DataModel/vtkKdTree.cxx @@ -1817,7 +1817,7 @@ void vtkKdTree::BuildLocatorFromPoints(vtkPoints **ptArrays, int numPtArrays) if (pointArrayType == VTK_FLOAT) { vtkDataArray *da = ptArrays[i]->GetData(); - vtkFloatArray *fa = vtkFloatArray::SafeDownCast(da); + vtkFloatArray *fa = vtkArrayDownCast(da); memcpy(points + ptId, fa->GetPointer(0), sizeof(float) * nvals ); ptId += nvals; } diff --git a/Common/DataModel/vtkKdTree.h b/Common/DataModel/vtkKdTree.h index 21a01efe348..02070103196 100644 --- a/Common/DataModel/vtkKdTree.h +++ b/Common/DataModel/vtkKdTree.h @@ -567,13 +567,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkKdTree : public vtkLocator int DivideTest(int numberOfPoints, int level); -//BTX enum { XDIM = 0, // don't change these values YDIM = 1, ZDIM = 2 }; -//ETX int ValidDirections; @@ -664,7 +662,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkKdTree : public vtkLocator static void SetDataBoundsToSpatialBounds(vtkKdNode *kd); static void ZeroNumberOfPoints(vtkKdNode *kd); -//BTX // Recursive helper for public FindPointsWithinRadius void FindPointsWithinRadius(vtkKdNode* node, double R2, const double x[3], vtkIdList* ids); @@ -692,7 +689,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkKdTree : public vtkLocator vtkIdList **boundaryCells; vtkIdList *emptyList; }; -//ETX void InitializeCellLists(); vtkIdList *GetList(int regionId, vtkIdList **which); @@ -750,9 +746,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkKdTree : public vtkLocator int dims[3], double origin[3], double spacing[3]); void ClearLastBuildCache(); -//BTX static void __printTree(vtkKdNode *kd, int depth, int verbose); -//ETX static int MidValue(int dim, float *c1, int nvals, double &coord); @@ -760,12 +754,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkKdTree : public vtkLocator static float FindMaxLeftHalf(int dim, float *c1, int K); static void _Select(int dim, float *X, int *ids, int L, int R, int K); -//BTX static int ComputeLevel(vtkKdNode *kd); static int SelfOrder(int id, vtkKdNode *kd); static int findRegion(vtkKdNode *node, float x, float y, float z); static int findRegion(vtkKdNode *node, double x, double y, double z); -//ETX static vtkKdNode **_GetRegionsAtLevel(int level, vtkKdNode **nodes, vtkKdNode *kd); @@ -783,9 +775,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkKdTree : public vtkLocator int GenerateRepresentationUsingDataBounds; -//BTX struct _cellList CellList; -//ETX // Region Ids, by data set by cell id - this list is large (one // int per cell) but accelerates creation of cell lists diff --git a/Common/DataModel/vtkLocator.h b/Common/DataModel/vtkLocator.h index 58cef49f91a..625c4862d08 100644 --- a/Common/DataModel/vtkLocator.h +++ b/Common/DataModel/vtkLocator.h @@ -149,7 +149,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkLocator : public vtkObject vtkTimeStamp BuildTime; // time at which locator was built - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; private: vtkLocator(const vtkLocator&); // Not implemented. diff --git a/Common/DataModel/vtkMappedUnstructuredGrid.h b/Common/DataModel/vtkMappedUnstructuredGrid.h index 4900f63e240..7ebae81ca7e 100644 --- a/Common/DataModel/vtkMappedUnstructuredGrid.h +++ b/Common/DataModel/vtkMappedUnstructuredGrid.h @@ -34,11 +34,7 @@ // member (for points/nodes) or added directly to vtkPointData, vtkCellData, or // vtkFieldData for attribute information. Filters used in the pipeline will // need to be modified to remove calls to vtkDataArray::GetVoidPointer and use -// vtkTypedDataArrayIterators instead. -// See vtkDataArrayIteratorMacro.h for a (relatively) simple way to write -// processing algorithms that will use efficient raw memory accesses for -// standard VTK data arrays and safe iterators for non-standard data arrays in a -// single templated implementation. +// a suitable vtkArrayDispatch instead. // // Introducing an arbitrary topology implementation into VTK requires the use of // the vtkMappedUnstructuredGrid class. Unlike the data array counterpart, the @@ -145,18 +141,15 @@ #include "vtkMappedUnstructuredGridCellIterator.h" // For default cell iterator #include "vtkNew.h" // For vtkNew #include "vtkSmartPointer.h" // For vtkSmartPointer -#include "vtkTypeTemplate.h" // For vtkTypeTemplate template > class vtkMappedUnstructuredGrid: - public vtkTypeTemplate, - vtkUnstructuredGridBase> + public vtkUnstructuredGridBase { + typedef vtkMappedUnstructuredGrid SelfType; public: - typedef - vtkTypeTemplate, - vtkUnstructuredGridBase> Superclass; + vtkTemplateTypeMacro(SelfType, vtkUnstructuredGridBase) typedef Implementation ImplementationType; typedef CellIterator CellIteratorType; @@ -205,7 +198,7 @@ class vtkMappedUnstructuredGrid: // We need to fake the superclass for the wrappers, otherwise they will choke on // the template: -#ifndef __WRAP__ +#ifndef __VTK_WRAP__ #define vtkMakeExportedMappedUnstructuredGrid(_className, _impl, _exportDecl) \ class _exportDecl _className : \ @@ -249,7 +242,7 @@ private: \ void operator=(const _className&); \ }; -#else // __WRAP__ +#else // __VTK_WRAP__ #define vtkMakeExportedMappedUnstructuredGrid(_className, _impl, _exportDecl) \ class _exportDecl _className : \ @@ -281,7 +274,7 @@ private: \ void operator=(const _className&); \ }; -#endif // __WRAP__ +#endif // __VTK_WRAP__ #define vtkMakeMappedUnstructuredGrid(_className, _impl) \ vtkMakeExportedMappedUnstructuredGrid(_className, _impl, ) diff --git a/Common/DataModel/vtkMappedUnstructuredGridCellIterator.h b/Common/DataModel/vtkMappedUnstructuredGridCellIterator.h index d26f01fc614..b8d5d8f35f6 100644 --- a/Common/DataModel/vtkMappedUnstructuredGridCellIterator.h +++ b/Common/DataModel/vtkMappedUnstructuredGridCellIterator.h @@ -26,17 +26,16 @@ #include "vtkCellIterator.h" #include "vtkSmartPointer.h" // For vtkSmartPointer -#include "vtkTypeTemplate.h" // For vtkTypeTemplate template class vtkMappedUnstructuredGrid; template -class vtkMappedUnstructuredGridCellIterator : - public vtkTypeTemplate, - vtkCellIterator> +class vtkMappedUnstructuredGridCellIterator : public vtkCellIterator { public: + vtkTemplateTypeMacro(vtkMappedUnstructuredGridCellIterator, + vtkCellIterator) typedef Implementation ImplementationType; typedef vtkMappedUnstructuredGridCellIterator ThisType; static vtkMappedUnstructuredGridCellIterator *New(); diff --git a/Common/DataModel/vtkMolecule.cxx b/Common/DataModel/vtkMolecule.cxx index 4fc0682cbd5..88b6d0ad315 100644 --- a/Common/DataModel/vtkMolecule.cxx +++ b/Common/DataModel/vtkMolecule.cxx @@ -117,7 +117,7 @@ void vtkMolecule::PrintSelf(ostream &os, vtkIndent indent) vtkAtom vtkMolecule::AppendAtom(unsigned short atomicNumber, const vtkVector3f &pos) { - vtkUnsignedShortArray *atomicNums = vtkUnsignedShortArray::SafeDownCast + vtkUnsignedShortArray *atomicNums = vtkArrayDownCast (this->GetVertexData()->GetScalars()); assert(atomicNums); @@ -148,7 +148,7 @@ unsigned short vtkMolecule::GetAtomAtomicNumber(vtkIdType id) { assert(id >= 0 && id < this->GetNumberOfAtoms()); - vtkUnsignedShortArray *atomicNums = vtkUnsignedShortArray::SafeDownCast + vtkUnsignedShortArray *atomicNums = vtkArrayDownCast (this->GetVertexData()->GetScalars()); assert(atomicNums); @@ -161,7 +161,7 @@ void vtkMolecule::SetAtomAtomicNumber(vtkIdType id, unsigned short atomicNum) { assert(id >= 0 && id < this->GetNumberOfAtoms()); - vtkUnsignedShortArray *atomicNums = vtkUnsignedShortArray::SafeDownCast + vtkUnsignedShortArray *atomicNums = vtkArrayDownCast (this->GetVertexData()->GetScalars()); assert(atomicNums); @@ -190,7 +190,7 @@ void vtkMolecule::SetAtomPosition(vtkIdType id, double x, double y, double z) vtkVector3f vtkMolecule::GetAtomPosition(vtkIdType id) { assert(id >= 0 && id < this->GetNumberOfAtoms()); - vtkFloatArray *positions = vtkFloatArray::SafeDownCast(this->Points->GetData()); + vtkFloatArray *positions = vtkArrayDownCast(this->Points->GetData()); assert(positions != NULL); float *data = static_cast(positions->GetVoidPointer(id * 3)); return vtkVector3f(data); @@ -215,7 +215,7 @@ vtkIdType vtkMolecule::GetNumberOfAtoms() vtkBond vtkMolecule::AppendBond(const vtkIdType atom1, const vtkIdType atom2, const unsigned short order) { - vtkUnsignedShortArray *bondOrders = vtkUnsignedShortArray::SafeDownCast + vtkUnsignedShortArray *bondOrders = vtkArrayDownCast (this->GetEdgeData()->GetScalars()); assert(bondOrders); @@ -249,7 +249,7 @@ void vtkMolecule::SetBondOrder(vtkIdType bondId, unsigned short order) { assert(bondId >= 0 && bondId < this->GetNumberOfBonds()); - vtkUnsignedShortArray *bondOrders = vtkUnsignedShortArray::SafeDownCast + vtkUnsignedShortArray *bondOrders = vtkArrayDownCast (this->GetEdgeData()->GetScalars()); assert(bondOrders); @@ -263,7 +263,7 @@ unsigned short vtkMolecule::GetBondOrder(vtkIdType bondId) { assert(bondId >= 0 && bondId < this->GetNumberOfBonds()); - vtkUnsignedShortArray *bondOrders = vtkUnsignedShortArray::SafeDownCast + vtkUnsignedShortArray *bondOrders = vtkArrayDownCast (this->GetEdgeData()->GetScalars()); assert(bondOrders); @@ -297,7 +297,7 @@ vtkPoints * vtkMolecule::GetAtomicPositionArray() //---------------------------------------------------------------------------- vtkUnsignedShortArray * vtkMolecule::GetAtomicNumberArray() { - vtkUnsignedShortArray *atomicNums = vtkUnsignedShortArray::SafeDownCast + vtkUnsignedShortArray *atomicNums = vtkArrayDownCast (this->GetVertexData()->GetScalars()); assert(atomicNums); diff --git a/Common/DataModel/vtkMolecule.h b/Common/DataModel/vtkMolecule.h index b89274db897..df73231e987 100644 --- a/Common/DataModel/vtkMolecule.h +++ b/Common/DataModel/vtkMolecule.h @@ -69,10 +69,9 @@ #include "vtkCommonDataModelModule.h" // For export macro #include "vtkUndirectedGraph.h" -//BTX #include "vtkAtom.h" // Simple proxy class dependent on vtkMolecule #include "vtkBond.h" // Simple proxy class dependent on vtkMolecule -//ETX + #include "vtkVector.h" // Small templated vector convenience class class vtkPlane; @@ -92,7 +91,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMolecule : public vtkUndirectedGraph // Return what type of dataset this is. virtual int GetDataObjectType() {return VTK_MOLECULE;} -//BTX // Description: // Add new atom with atomic number 0 (dummy atom) at origin. Return // a vtkAtom that refers to the new atom. @@ -137,7 +135,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMolecule : public vtkUndirectedGraph // Description: // Return a vtkAtom that refers to the bond with the specified id. vtkBond GetBond(vtkIdType bondId); -//ETX // Description: // Return the number of bonds in the molecule. @@ -182,12 +179,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMolecule : public vtkUndirectedGraph vtkPoints * GetAtomicPositionArray(); vtkUnsignedShortArray * GetAtomicNumberArray(); -//BTX // Description: // Set/Get the AbstractElectronicData-subclassed object for this molecule. vtkGetObjectMacro(ElectronicData, vtkAbstractElectronicData); virtual void SetElectronicData(vtkAbstractElectronicData*); -//ETX // Description: // Shallow copies the data object into this molecule. diff --git a/Common/DataModel/vtkMultiBlockDataSet.h b/Common/DataModel/vtkMultiBlockDataSet.h index 59f26e58f7f..3397927abad 100644 --- a/Common/DataModel/vtkMultiBlockDataSet.h +++ b/Common/DataModel/vtkMultiBlockDataSet.h @@ -87,12 +87,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMultiBlockDataSet : public vtkDataObjectTree vtkInformation* GetMetaData(unsigned int blockno) { return this->Superclass::GetChildMetaData(blockno); } - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkMultiBlockDataSet* GetData(vtkInformation* info); static vtkMultiBlockDataSet* GetData(vtkInformationVector* v, int i=0); - //ETX // Description: // Unhiding superclass method. @@ -104,7 +102,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMultiBlockDataSet : public vtkDataObjectTree virtual int HasMetaData(vtkCompositeDataIterator* iter) { return this->Superclass::HasMetaData(iter); } -//BTX protected: vtkMultiBlockDataSet(); ~vtkMultiBlockDataSet(); @@ -112,7 +109,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMultiBlockDataSet : public vtkDataObjectTree private: vtkMultiBlockDataSet(const vtkMultiBlockDataSet&); // Not implemented. void operator=(const vtkMultiBlockDataSet&); // Not implemented. -//ETX + }; #endif diff --git a/Common/DataModel/vtkMultiPieceDataSet.h b/Common/DataModel/vtkMultiPieceDataSet.h index aed75bda195..283004084ab 100644 --- a/Common/DataModel/vtkMultiPieceDataSet.h +++ b/Common/DataModel/vtkMultiPieceDataSet.h @@ -79,12 +79,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMultiPieceDataSet : public vtkDataObjectTree vtkInformation* GetMetaData(unsigned int pieceno) { return this->Superclass::GetChildMetaData(pieceno); } - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkMultiPieceDataSet* GetData(vtkInformation* info); static vtkMultiPieceDataSet* GetData(vtkInformationVector* v, int i=0); - //ETX // Description: // Unhiding superclass method. @@ -96,7 +94,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMultiPieceDataSet : public vtkDataObjectTree virtual int HasMetaData(vtkCompositeDataIterator* iter) { return this->Superclass::HasMetaData(iter); } -//BTX protected: vtkMultiPieceDataSet(); ~vtkMultiPieceDataSet(); @@ -104,7 +101,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMultiPieceDataSet : public vtkDataObjectTree private: vtkMultiPieceDataSet(const vtkMultiPieceDataSet&); // Not implemented. void operator=(const vtkMultiPieceDataSet&); // Not implemented. -//ETX + }; #endif diff --git a/Common/DataModel/vtkMutableDirectedGraph.h b/Common/DataModel/vtkMutableDirectedGraph.h index 3a013d6776f..b3c7677398f 100644 --- a/Common/DataModel/vtkMutableDirectedGraph.h +++ b/Common/DataModel/vtkMutableDirectedGraph.h @@ -105,7 +105,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMutableDirectedGraph : public vtkDirectedGrap // the delays associated with returning the vertex index. vtkIdType AddVertex(const vtkVariant& pedigreeId); -//BTX // Description: // Adds a directed edge from \p u to \p v, // where \p u and \p v are vertex indices, @@ -114,9 +113,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMutableDirectedGraph : public vtkDirectedGrap // \p vtkEdgeType contains fields for \p Source vertex index, // \p Target vertex index, and edge index \p Id. vtkEdgeType AddEdge(vtkIdType u, vtkIdType v); -//ETX -//BTX // Description: // Adds a directed edge from \p u to \p v, // where \p u and \p v are vertex indices, @@ -130,9 +127,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMutableDirectedGraph : public vtkDirectedGrap // \p Target vertex index, and edge index \p Id. vtkEdgeType AddEdge(vtkIdType u, vtkIdType v, vtkVariantArray *propertyArr); -//ETX - //BTX // Description: // Adds a directed edge from \p u to \p v, // where \p u is a vertex pedigree ID and \p v is a vertex index, @@ -175,7 +170,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMutableDirectedGraph : public vtkDirectedGrap vtkEdgeType AddEdge(const vtkVariant& u, const vtkVariant& v, vtkVariantArray *propertyArr = 0); - //ETX // Description: // Adds a vertex to the graph. diff --git a/Common/DataModel/vtkMutableUndirectedGraph.h b/Common/DataModel/vtkMutableUndirectedGraph.h index 9f0b95b4cd2..0f60f023559 100644 --- a/Common/DataModel/vtkMutableUndirectedGraph.h +++ b/Common/DataModel/vtkMutableUndirectedGraph.h @@ -105,7 +105,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMutableUndirectedGraph : public vtkUndirected // the delays associated with returning the vertex index. vtkIdType AddVertex(const vtkVariant& pedigreeId); - //BTX // Description: // Adds an undirected edge from \p u to \p v, // where \p u and \p v are vertex indices, @@ -172,8 +171,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkMutableUndirectedGraph : public vtkUndirected const vtkVariant& v, vtkVariantArray *propertyArr = 0); - //ETX - // Description: // Adds a vertex to the graph. // diff --git a/Common/DataModel/vtkNonMergingPointLocator.h b/Common/DataModel/vtkNonMergingPointLocator.h index ac0ae845bb2..43f5b55f5bb 100644 --- a/Common/DataModel/vtkNonMergingPointLocator.h +++ b/Common/DataModel/vtkNonMergingPointLocator.h @@ -44,14 +44,12 @@ class VTKCOMMONDATAMODEL_EXPORT vtkNonMergingPointLocator : public vtkPointLocat vtkTypeMacro( vtkNonMergingPointLocator, vtkPointLocator ); void PrintSelf( ostream & os, vtkIndent indent ); -//BTX // Description: // Determine whether a given point x has been inserted into the points list. // Return the id of the already inserted point if it is true, or -1 else. // Note this function always returns -1 since any point is always inserted. virtual vtkIdType IsInsertedPoint( const double [3] ) { return -1; } virtual vtkIdType IsInsertedPoint( double, double, double ) { return -1; } -//ETX // Description: // Determine whether a given point x has been inserted into the points list. diff --git a/Common/DataModel/vtkNonOverlappingAMR.h b/Common/DataModel/vtkNonOverlappingAMR.h index 8c8e609352e..9ed206f0d1b 100644 --- a/Common/DataModel/vtkNonOverlappingAMR.h +++ b/Common/DataModel/vtkNonOverlappingAMR.h @@ -38,14 +38,12 @@ class VTKCOMMONDATAMODEL_EXPORT vtkNonOverlappingAMR : public vtkUniformGridAMR // Returns object type (see vtkType.h for definitions). virtual int GetDataObjectType() {return VTK_NON_OVERLAPPING_AMR; } - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkNonOverlappingAMR* GetData(vtkInformation* info) { return vtkNonOverlappingAMR::SafeDownCast(Superclass::GetData(info)); } static vtkNonOverlappingAMR* GetData(vtkInformationVector* v, int i=0) { return vtkNonOverlappingAMR::SafeDownCast(Superclass::GetData(v, i)); } - //ETX protected: vtkNonOverlappingAMR(); diff --git a/Common/DataModel/vtkOctreePointLocator.h b/Common/DataModel/vtkOctreePointLocator.h index 505b53612ee..f07f5bb984f 100644 --- a/Common/DataModel/vtkOctreePointLocator.h +++ b/Common/DataModel/vtkOctreePointLocator.h @@ -173,7 +173,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkOctreePointLocator : public vtkAbstractPointL static void DeleteAllDescendants(vtkOctreePointLocatorNode* octant); -//BTX // Description: // Recursive helper for public FindPointsWithinRadius. radiusSquared // is the square of the radius and is used in order to avoid the @@ -194,8 +193,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkOctreePointLocator : public vtkAbstractPointL int DivideTest(int size, int level); -//ETX - void AddPolys(vtkOctreePointLocatorNode *node, vtkPoints *pts, vtkCellArray *polys); // Description: diff --git a/Common/DataModel/vtkOctreePointLocatorNode.h b/Common/DataModel/vtkOctreePointLocatorNode.h index 23050048d15..b284b457fc5 100644 --- a/Common/DataModel/vtkOctreePointLocatorNode.h +++ b/Common/DataModel/vtkOctreePointLocatorNode.h @@ -75,13 +75,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkOctreePointLocatorNode : public vtkObject double yMax, double zMin, double zMax); void GetDataBounds(double *b) const; -//BTX // Description: // Get a pointer to the 3 bound minima (xmin, ymin and zmin) or the // 3 bound maxima (xmax, ymax, zmax). Don't free this pointer. vtkGetMacro(MinBounds, double*); vtkGetMacro(MaxBounds, double*); -//ETX // Description: // Set the xmin, ymin and zmin value of the bounds of this region @@ -101,13 +99,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkOctreePointLocatorNode : public vtkObject this->MaxBounds[2] = maxBounds[2]; } -//BTX // Description: // Get a pointer to the 3 data bound minima (xmin, ymin and zmin) or the // 3 data bound maxima (xmax, ymax, zmax). Don't free this pointer. vtkGetMacro(MinDataBounds, double*); vtkGetMacro(MaxDataBounds, double*); -//ETX // Description: // Set the xmin, ymin and zmin value of the bounds of this diff --git a/Common/DataModel/vtkOutEdgeIterator.h b/Common/DataModel/vtkOutEdgeIterator.h index 743ed5b2b7e..ba9135f2558 100644 --- a/Common/DataModel/vtkOutEdgeIterator.h +++ b/Common/DataModel/vtkOutEdgeIterator.h @@ -55,7 +55,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkOutEdgeIterator : public vtkObject vtkGetObjectMacro(Graph, vtkGraph); vtkGetMacro(Vertex, vtkIdType); - //BTX // Description: // Returns the next edge in the graph. inline vtkOutEdgeType Next() @@ -64,7 +63,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkOutEdgeIterator : public vtkObject ++this->Current; return e; } - //ETX // Description: // Just like Next(), but diff --git a/Common/DataModel/vtkOverlappingAMR.h b/Common/DataModel/vtkOverlappingAMR.h index 2cc1f7e4522..71a41efa26f 100644 --- a/Common/DataModel/vtkOverlappingAMR.h +++ b/Common/DataModel/vtkOverlappingAMR.h @@ -48,7 +48,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkOverlappingAMR: public vtkUniformGridAMR // Description: // Return a new iterator (the iterator has to be deleted by the user). - virtual vtkCompositeDataIterator* NewIterator(); + virtual VTK_NEWINSTANCE vtkCompositeDataIterator* NewIterator(); //Description: //Get/Set the global origin of the amr data set @@ -76,14 +76,12 @@ class VTKCOMMONDATAMODEL_EXPORT vtkOverlappingAMR: public vtkUniformGridAMR static vtkInformationIdTypeKey* NUMBER_OF_BLANKED_POINTS(); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkOverlappingAMR* GetData(vtkInformation* info) { return vtkOverlappingAMR::SafeDownCast(Superclass::GetData(info)); } static vtkOverlappingAMR* GetData(vtkInformationVector* v, int i=0) { return vtkOverlappingAMR::SafeDownCast(Superclass::GetData(v, i)); } - //ETX // Description: // Sets the refinement of a given level. The spacing at level diff --git a/Common/DataModel/vtkPath.cxx b/Common/DataModel/vtkPath.cxx index 6da9c189680..bda749fe892 100644 --- a/Common/DataModel/vtkPath.cxx +++ b/Common/DataModel/vtkPath.cxx @@ -99,7 +99,7 @@ void vtkPath::InsertNextPoint(float pts[], int code) { this->Points->InsertNextPoint(pts); - vtkIntArray *codes = vtkIntArray::SafeDownCast( + vtkIntArray *codes = vtkArrayDownCast( this->PointData->GetScalars()); assert("control point code array is int type" && codes); codes->InsertNextValue(code); @@ -116,7 +116,7 @@ void vtkPath::InsertNextPoint(double x, double y, double z, int code) { this->Points->InsertNextPoint(x, y, z); - vtkIntArray *codes = vtkIntArray::SafeDownCast( + vtkIntArray *codes = vtkArrayDownCast( this->PointData->GetScalars()); assert("control point code array is int type" && codes); codes->InsertNextValue(code); @@ -131,5 +131,5 @@ void vtkPath::SetCodes(vtkIntArray *codes) //---------------------------------------------------------------------------- vtkIntArray *vtkPath::GetCodes() { - return vtkIntArray::SafeDownCast(this->PointData->GetScalars()); + return vtkArrayDownCast(this->PointData->GetScalars()); } diff --git a/Common/DataModel/vtkPath.h b/Common/DataModel/vtkPath.h index 485ab0b5aaf..cf5d3e67dc6 100644 --- a/Common/DataModel/vtkPath.h +++ b/Common/DataModel/vtkPath.h @@ -15,8 +15,8 @@ // .NAME vtkPath - concrete dataset representing a path defined by Bezier // curves. // .SECTION Description -// vtkPath provides a container for paths composed of line segment and -// 2nd/3rd order Bezier curves. +// vtkPath provides a container for paths composed of line segments, +// 2nd-order (quadratic) and 3rd-order (cubic) Bezier curves. #ifndef vtkPath_h #define vtkPath_h diff --git a/Common/DataModel/vtkPiecewiseFunction.h b/Common/DataModel/vtkPiecewiseFunction.h index eb9f54e6cd0..a46cbc6903f 100644 --- a/Common/DataModel/vtkPiecewiseFunction.h +++ b/Common/DataModel/vtkPiecewiseFunction.h @@ -153,12 +153,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkPiecewiseFunction : public vtkDataObject // in turn simply calls RemoveAllPoints() void Initialize(); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkPiecewiseFunction* GetData(vtkInformation* info); static vtkPiecewiseFunction* GetData(vtkInformationVector* v, int i=0); - //ETX // Description: // Toggle whether to allow duplicate scalar values in the piecewise diff --git a/Common/DataModel/vtkPixelExtent.h b/Common/DataModel/vtkPixelExtent.h index bfc8229c853..b5b0f009dcf 100644 --- a/Common/DataModel/vtkPixelExtent.h +++ b/Common/DataModel/vtkPixelExtent.h @@ -94,7 +94,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkPixelExtent // Description: // Test for equivalence. - int operator==(const vtkPixelExtent &other) const; + bool operator==(const vtkPixelExtent &other) const; // Description: // Return non-zero if this extent conatins the other. @@ -417,7 +417,7 @@ int vtkPixelExtent::Empty() const //----------------------------------------------------------------------------- inline -int vtkPixelExtent::operator==(const vtkPixelExtent &other) const +bool vtkPixelExtent::operator==(const vtkPixelExtent &other) const { if ( (this->Data[0] == other.Data[0]) && (this->Data[1] == other.Data[1]) diff --git a/Common/DataModel/vtkPlaneCollection.h b/Common/DataModel/vtkPlaneCollection.h index d54c8c13dad..99f60b1d0d0 100644 --- a/Common/DataModel/vtkPlaneCollection.h +++ b/Common/DataModel/vtkPlaneCollection.h @@ -46,12 +46,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkPlaneCollection : public vtkCollection vtkPlane *GetItem(int i) { return static_cast(this->GetItemAsObject(i));}; - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkPlane *GetNextPlane(vtkCollectionSimpleIterator &cookie); - //ETX protected: vtkPlaneCollection() {} diff --git a/Common/DataModel/vtkPointSet.cxx b/Common/DataModel/vtkPointSet.cxx index cc33f17ccfd..b2985b78453 100644 --- a/Common/DataModel/vtkPointSet.cxx +++ b/Common/DataModel/vtkPointSet.cxx @@ -266,7 +266,7 @@ vtkIdType vtkPointSet::FindCell(double x[3], vtkCell *cell, this->Locator->BuildLocator(); } - if ( this->Points->GetMTime() > this->Locator->GetMTime() ) + if ( this->Points->GetMTime() > this->Locator->GetBuildTime() ) { this->Locator->SetDataSet(this); this->Locator->BuildLocator(); diff --git a/Common/DataModel/vtkPointSet.h b/Common/DataModel/vtkPointSet.h index 6cfbada82f2..cd08b83c97b 100644 --- a/Common/DataModel/vtkPointSet.h +++ b/Common/DataModel/vtkPointSet.h @@ -100,15 +100,13 @@ class VTKCOMMONDATAMODEL_EXPORT vtkPointSet : public vtkDataSet // Description: // Overwritten to handle the data/locator loop - virtual void Register(vtkObjectBase* o); - virtual void UnRegister(vtkObjectBase* o); + void Register(vtkObjectBase* o) VTK_OVERRIDE; + void UnRegister(vtkObjectBase* o) VTK_OVERRIDE; - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkPointSet* GetData(vtkInformation* info); static vtkPointSet* GetData(vtkInformationVector* v, int i=0); - //ETX protected: vtkPointSet(); @@ -117,7 +115,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkPointSet : public vtkDataSet vtkPoints *Points; vtkPointLocator *Locator; - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; private: void Cleanup(); diff --git a/Common/DataModel/vtkPolyData.cxx b/Common/DataModel/vtkPolyData.cxx index 620e5fadcbc..8f1c23184af 100644 --- a/Common/DataModel/vtkPolyData.cxx +++ b/Common/DataModel/vtkPolyData.cxx @@ -1390,6 +1390,10 @@ void vtkPolyData::Reset() { this->Strips->Reset(); } + + // discard Links and Cells + this->DeleteLinks(); + this->DeleteCells(); } //---------------------------------------------------------------------------- diff --git a/Common/DataModel/vtkPolyData.h b/Common/DataModel/vtkPolyData.h index 714821cab29..6986ab0292c 100644 --- a/Common/DataModel/vtkPolyData.h +++ b/Common/DataModel/vtkPolyData.h @@ -408,14 +408,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkPolyData : public vtkPointSet // It does not remove unused points. void RemoveGhostCells(); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkPolyData* GetData(vtkInformation* info); static vtkPolyData* GetData(vtkInformationVector* v, int i=0); - //ETX -//BTX // Description: // Scalar field critical point classification (for manifold 2D meshes). // Reference: J. Milnor "Morse Theory", Princeton University Press, 1963. @@ -443,7 +440,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkPolyData : public vtkPointSet SADDLE = 1, MAXIMUM = 2 }; -//ETX + int GetScalarFieldCriticalIndex (vtkIdType pointId, vtkDataArray *scalarField); int GetScalarFieldCriticalIndex (vtkIdType pointId, int fieldId); diff --git a/Common/DataModel/vtkPolyDataCollection.h b/Common/DataModel/vtkPolyDataCollection.h index 4ce075f5c7c..f9d2d5dae7a 100644 --- a/Common/DataModel/vtkPolyDataCollection.h +++ b/Common/DataModel/vtkPolyDataCollection.h @@ -47,13 +47,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkPolyDataCollection : public vtkCollection vtkPolyData *GetNextItem() { return static_cast(this->GetNextItemAsObject());}; - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkPolyData *GetNextPolyData(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkPolyDataCollection() {} diff --git a/Common/DataModel/vtkPolyhedron.cxx b/Common/DataModel/vtkPolyhedron.cxx index 96d8c9d2319..3f9df6c8e24 100644 --- a/Common/DataModel/vtkPolyhedron.cxx +++ b/Common/DataModel/vtkPolyhedron.cxx @@ -1563,7 +1563,7 @@ vtkCell *vtkPolyhedron::GetEdge(int edgeId) // Return the requested edge vtkIdType edge[2]; - this->Edges->GetTupleValue(edgeId,edge); + this->Edges->GetTypedTuple(edgeId,edge); // Recall that edge tuples are stored in canonical numbering for (int i=0; i<2; i++) @@ -1607,7 +1607,7 @@ int vtkPolyhedron::GenerateEdges() if ( this->EdgeTable->IsEdge(edge[0],edge[1]) == (-1) ) { this->EdgeTable->InsertEdge(edge[0],edge[1]); - this->Edges->InsertNextTupleValue(edge); + this->Edges->InsertNextTypedTuple(edge); } } face += face[0] + 1; diff --git a/Common/DataModel/vtkPolyhedron.h b/Common/DataModel/vtkPolyhedron.h index e46071127ad..c707dd2bfdd 100644 --- a/Common/DataModel/vtkPolyhedron.h +++ b/Common/DataModel/vtkPolyhedron.h @@ -277,10 +277,9 @@ class VTKCOMMONDATAMODEL_EXPORT vtkPolyhedron : public vtkCell3D vtkPolyhedron(const vtkPolyhedron&); // Not implemented. void operator=(const vtkPolyhedron&); // Not implemented. - //BTX class vtkInternal; vtkInternal * Internal; - //ETX + }; //---------------------------------------------------------------------------- diff --git a/Common/DataModel/vtkRectilinearGrid.h b/Common/DataModel/vtkRectilinearGrid.h index e43ae6b5c36..d0410998e56 100644 --- a/Common/DataModel/vtkRectilinearGrid.h +++ b/Common/DataModel/vtkRectilinearGrid.h @@ -182,12 +182,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkRectilinearGrid : public vtkDataSet // and the source generated more than the update extent. virtual void Crop(const int* updateExtent); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkRectilinearGrid* GetData(vtkInformation* info); static vtkRectilinearGrid* GetData(vtkInformationVector* v, int i=0); - //ETX protected: vtkRectilinearGrid(); diff --git a/Common/DataModel/vtkReebGraph.cxx b/Common/DataModel/vtkReebGraph.cxx index a3973ceb69f..eac02fd3748 100644 --- a/Common/DataModel/vtkReebGraph.cxx +++ b/Common/DataModel/vtkReebGraph.cxx @@ -1232,11 +1232,11 @@ double vtkReebGraph::Implementation::ComputeCustomMetric( { int edgeId = -1, start = -1, end = -1; - vtkDataArray *vertexInfo = vtkDataArray::SafeDownCast( + vtkDataArray *vertexInfo = vtkArrayDownCast( this->Parent->GetVertexData()->GetAbstractArray("Vertex Ids")); if(!vertexInfo) return vtkReebGraphGetArcPersistence(this, a); - vtkVariantArray *edgeInfo = vtkVariantArray::SafeDownCast( + vtkVariantArray *edgeInfo = vtkArrayDownCast( this->Parent->GetEdgeData()->GetAbstractArray("Vertex Ids")); if(!edgeInfo) return vtkReebGraphGetArcPersistence(this, a); @@ -1565,7 +1565,7 @@ int vtkReebGraph::Implementation::CommitSimplification() vtkEdgeListIterator *eIt = vtkEdgeListIterator::New(); this->Parent->GetEdges(eIt); - vtkVariantArray *edgeInfo = vtkVariantArray::SafeDownCast( + vtkVariantArray *edgeInfo = vtkArrayDownCast( this->Parent->GetEdgeData()->GetAbstractArray("Vertex Ids")); vtkDataArray *vertexInfo = this->Parent->GetVertexData()->GetArray("Vertex Ids"); diff --git a/Common/DataModel/vtkSelection.h b/Common/DataModel/vtkSelection.h index d8e6e036f07..924574251ea 100644 --- a/Common/DataModel/vtkSelection.h +++ b/Common/DataModel/vtkSelection.h @@ -28,10 +28,8 @@ #include "vtkCommonDataModelModule.h" // For export macro #include "vtkDataObject.h" -//BTX class vtkSelectionNode; struct vtkSelectionInternals; -//ETX class VTKCOMMONDATAMODEL_EXPORT vtkSelection : public vtkDataObject { @@ -107,16 +105,14 @@ class VTKCOMMONDATAMODEL_EXPORT vtkSelection : public vtkDataObject // Description: // Dumps the contents of the selection, giving basic information only. virtual void Dump(); - //BTX + virtual void Dump(ostream& os); - //ETX // Description: // Retrieve a vtkSelection stored inside an invormation object. static vtkSelection* GetData(vtkInformation* info); static vtkSelection* GetData(vtkInformationVector* v, int i=0); -//BTX protected: vtkSelection(); ~vtkSelection(); @@ -126,7 +122,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkSelection : public vtkDataObject void operator=(const vtkSelection&); // Not implemented. vtkSelectionInternals* Internal; -//ETX + }; #endif diff --git a/Common/DataModel/vtkSelectionNode.h b/Common/DataModel/vtkSelectionNode.h index aba24cb8f20..6a20c239bdd 100644 --- a/Common/DataModel/vtkSelectionNode.h +++ b/Common/DataModel/vtkSelectionNode.h @@ -46,7 +46,6 @@ #include "vtkCommonDataModelModule.h" // For export macro #include "vtkObject.h" -//BTX class vtkAbstractArray; class vtkDataSetAttributes; class vtkInformation; @@ -55,7 +54,6 @@ class vtkInformationIntegerKey; class vtkInformationObjectBaseKey; class vtkProp; class vtkTable; -//ETX class VTKCOMMONDATAMODEL_EXPORT vtkSelectionNode : public vtkObject { @@ -113,7 +111,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkSelectionNode : public vtkObject // THRESHOLDS means the points and cells with values within a set of ranges // GetContentType() returns -1 if the content type is not set. static vtkInformationIntegerKey* CONTENT_TYPE(); -//BTX + enum SelectionContent { SELECTIONS, // Deprecated. @@ -127,7 +125,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkSelectionNode : public vtkObject BLOCKS, // used to select blocks within a composite dataset. QUERY }; -//ETX // Description: // Get or set the content type of the selection. @@ -141,7 +138,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkSelectionNode : public vtkObject // Vertex and edge types are also available for graph classes. // GetFieldType() returns -1 if the field type is not set. static vtkInformationIntegerKey* FIELD_TYPE(); -//BTX + enum SelectionField { CELL, @@ -151,7 +148,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkSelectionNode : public vtkObject EDGE, ROW }; -//ETX // Description: // Get or set the field type of the selection. @@ -248,7 +244,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkSelectionNode : public vtkObject // Compares Properties of self and other to ensure that they are exactly same. bool EqualProperties(vtkSelectionNode* other, bool fullcompare=true); -//BTX protected: vtkSelectionNode(); ~vtkSelectionNode(); @@ -260,7 +255,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkSelectionNode : public vtkObject private: vtkSelectionNode(const vtkSelectionNode&); // Not implemented. void operator=(const vtkSelectionNode&); // Not implemented. -//ETX + }; #endif diff --git a/Common/DataModel/vtkSimpleCellTessellator.h b/Common/DataModel/vtkSimpleCellTessellator.h index c14d3bd64f2..1274bbeb14b 100644 --- a/Common/DataModel/vtkSimpleCellTessellator.h +++ b/Common/DataModel/vtkSimpleCellTessellator.h @@ -381,10 +381,9 @@ class VTKCOMMONDATAMODEL_EXPORT vtkSimpleCellTessellator : public vtkGenericCell vtkSimpleCellTessellator(const vtkSimpleCellTessellator&); // Not implemented. void operator=(const vtkSimpleCellTessellator&); // Not implemented. - //BTX friend class vtkTetraTile; friend class vtkTriangleTile; - //ETX + }; #endif diff --git a/Common/DataModel/vtkSpline.h b/Common/DataModel/vtkSpline.h index 96b0397438a..1b0a09ba988 100644 --- a/Common/DataModel/vtkSpline.h +++ b/Common/DataModel/vtkSpline.h @@ -16,7 +16,7 @@ // .SECTION Description // vtkSpline interpolates a set of data points (i.e., interpolation means // that the spline passes through the points). vtkSpline is an abstract -// class: its subclasses vtkCardinalSpline and vtkKochenekSpline do the +// class: its subclasses vtkCardinalSpline and vtkKochanekSpline do the // interpolation. Note that this spline maps the 1D parametric coordinate // t into a single value x. Thus if you want to use the spline to // interpolate points (i.e. x[3]), you have to create three splines for @@ -45,7 +45,7 @@ // values outside this range are clamped within this range. // .SECTION See Also -// vtkCardinalSpline vtkKochenekSpline vtkParametricSpline +// vtkCardinalSpline vtkKochanekSpline vtkParametricSpline // vtkParametricFunctionSource diff --git a/Common/DataModel/vtkStaticPointLocator.cxx b/Common/DataModel/vtkStaticPointLocator.cxx index afdd9cf6286..22e266593a5 100644 --- a/Common/DataModel/vtkStaticPointLocator.cxx +++ b/Common/DataModel/vtkStaticPointLocator.cxx @@ -23,11 +23,13 @@ #include "vtkPolyData.h" #include "vtkSMPTools.h" +#include + vtkStandardNewMacro(vtkStaticPointLocator); // There are stack-allocated bucket neighbor lists. This is the initial // value. Too small and heap allocation kicks in. -static const int VTK_INITIAL_BUCKET_SIZE=1000; +static const int VTK_INITIAL_BUCKET_SIZE=10000; //----------------------------------------------------------------------------- // The following code supports threaded point locator construction. The locator @@ -157,33 +159,35 @@ class NeighborBuckets int *GetPoint(vtkIdType i) { - return (this->Count > i ? &(this->P[3*i]) : 0); + return this->P + 3*i; +// return (this->Count > i ? this->P + 3*i : 0); } vtkIdType InsertNextBucket(const int x[3]) { // Re-allocate if beyond the current max size. // (Increase by VTK_INITIAL_BUCKET_SIZE) - if (this->Count == this->MaxSize) - { - int *tmp = this->P; + int *tmp; + vtkIdType offset=this->Count*3; - this->MaxSize += VTK_INITIAL_BUCKET_SIZE; + if (this->Count >= this->MaxSize) + { + tmp = this->P; + this->MaxSize *= 2; this->P = new int[this->MaxSize*3]; - for(vtkIdType i=0; i<3*this->Count; i++) - { - this->P[i] = tmp[i]; - } - if ( tmp != &(this->InitialBuffer[0]) ) + memcpy(this->P, tmp, offset*sizeof(int)); + + if ( tmp != this->InitialBuffer ) { - delete[] tmp; + delete [] tmp; } } - this->P[3*this->Count] = x[0]; - this->P[3*this->Count+1] = x[1]; - this->P[3*this->Count+2] = x[2]; + tmp = this->P + offset; + *tmp++ = *x++; + *tmp++ = *x++; + *tmp = *x; this->Count++; return this->Count-1; } @@ -1046,52 +1050,62 @@ FindClosestNPoints(int N, const double x[3], vtkIdList *result) } //----------------------------------------------------------------------------- +// The Radius defines a block of buckets which the sphere of radis R may +// touch. template void BucketList:: FindPointsWithinRadius(double R, const double x[3], vtkIdList *result) { - int i, j; double dist2; double pt[3]; vtkIdType ptId, cno, numIds; - int ijk[3], *nei; double R2 = R*R; - NeighborBuckets buckets; const LocatorTuple *ids; + double xMin[3], xMax[3]; + int i, j, k, ii, jOffset, kOffset, ijkMin[3], ijkMax[3]; - // Find the bucket the point is in. - // - this->GetBucketIndices(x, ijk); - - // Get all buckets within a distance - this->GetOverlappingBuckets (&buckets, x, ijk, R, 0); + // Determine the range of indices in each direction based on radius R + xMin[0] = x[0] - R; + xMin[1] = x[1] - R; + xMin[2] = x[2] - R; + xMax[0] = x[0] + R; + xMax[1] = x[1] + R; + xMax[2] = x[2] + R; - // add the original bucket - buckets.InsertNextBucket(ijk); + // Find the footprint in the locator + this->GetBucketIndices(xMin, ijkMin); + this->GetBucketIndices(xMax, ijkMax); // Clear out previous results result->Reset(); - // Add points within radius - for (i=0; ixD + nei[2]*this->xyD; - - if ( (numIds = this->GetNumberOfIds(cno)) > 0 ) + kOffset = k*this->xyD; + for ( j=ijkMin[1]; j <= ijkMax[1]; ++j) { - ids = this->GetIds(cno); - for (j=0; j < numIds; j++) + jOffset = j*this->xD; + for ( i=ijkMin[0]; i <= ijkMax[0]; ++i) { - ptId = ids[j].PtId; - this->DataSet->GetPoint(ptId, pt); - dist2 = vtkMath::Distance2BetweenPoints(x,pt); - if (dist2 <= R2) + cno = i + jOffset + kOffset; + + if ( (numIds = this->GetNumberOfIds(cno)) > 0 ) { - result->InsertNextId(ptId); - } - } - } - } + ids = this->GetIds(cno); + for (ii=0; ii < numIds; ii++) + { + ptId = ids[ii].PtId; + this->DataSet->GetPoint(ptId, pt); + dist2 = vtkMath::Distance2BetweenPoints(x,pt); + if (dist2 <= R2) + { + result->InsertNextId(ptId); + } + }//for all points in bucket + }//if points in bucket + }//i-footprint + }//j-footprint + }//k-footprint } //----------------------------------------------------------------------------- @@ -1326,6 +1340,7 @@ vtkStaticPointLocator::vtkStaticPointLocator() this->Divisions[0] = this->Divisions[1] = this->Divisions[2] = 50; this->H[0] = this->H[1] = this->H[2] = 0.0; this->Buckets = NULL; + this->LargeIds = false; } //----------------------------------------------------------------------------- @@ -1391,6 +1406,7 @@ void vtkStaticPointLocator::BuildLocator() // hopefully it is cached or otherwise accelerated. // bounds = this->DataSet->GetBounds(); + int numNonZeroWidths = 3; for (i=0; i<3; i++) { this->Bounds[2*i] = bounds[2*i]; @@ -1398,19 +1414,34 @@ void vtkStaticPointLocator::BuildLocator() if ( this->Bounds[2*i+1] <= this->Bounds[2*i] ) //prevent zero width { this->Bounds[2*i+1] = this->Bounds[2*i] + 1.0; + numNonZeroWidths--; } } if ( this->Automatic ) { - level = static_cast(numPts) / this->NumberOfPointsPerBucket; - level = ceil( pow(static_cast(level), - static_cast(0.33333333))); + if ( numNonZeroWidths > 0 ) + { + level = static_cast(numPts) / this->NumberOfPointsPerBucket; + level = ceil( pow(static_cast(level), + static_cast(1.0/static_cast(numNonZeroWidths)))); + } + else + { + level = 1; //all points end up in thesame bucket and are concident! + } for (i=0; i<3; i++) { - ndivs[i] = static_cast(level); + if ( bounds[2*i+1] > bounds[2*i] ) + { + ndivs[i] = static_cast(level); + } + else + { + ndivs[i] = 1; + } } - } + }//automatic else { for (i=0; i<3; i++) @@ -1440,14 +1471,14 @@ void vtkStaticPointLocator::BuildLocator() // This is done for performance (e.g., the sort is faster) and significant // memory savings. // - if ( numPts >= VTK_INT_MAX ) + if ( numPts >= VTK_INT_MAX || numBuckets >= VTK_INT_MAX ) { - this->LargeIds = 1; + this->LargeIds = true; this->Buckets = new BucketList(this,numPts,numBuckets); } else { - this->LargeIds = 0; + this->LargeIds = false; this->Buckets = new BucketList(this,numPts,numBuckets); } @@ -1463,6 +1494,11 @@ void vtkStaticPointLocator::BuildLocator() // with the templated BucketList class. Note that a lot of the complexity here // is due to the desire to use different id types (int versus vtkIdType) for the // purposes of increasing speed and reducing memory. +// +// You're probably wondering why an if check (on LargeIds) is used to +// static_cast on BukcetList type, when virtual inheritance could be +// used. Benchmarking shows a small speed difference due to inlining, which +// the use of virtual methods short circuits. //----------------------------------------------------------------------------- // Given a position x, return the id of the point closest to it. diff --git a/Common/DataModel/vtkStaticPointLocator.h b/Common/DataModel/vtkStaticPointLocator.h index 1621a192bbe..bc70dcc8e8c 100644 --- a/Common/DataModel/vtkStaticPointLocator.h +++ b/Common/DataModel/vtkStaticPointLocator.h @@ -142,6 +142,12 @@ friend class vtkBucketList; // provide an instance of vtkIdList to contain the result. void GetBucketIds(vtkIdType bNum, vtkIdList *bList); + // Description: + // Inform the user as to whether large ids are being used. This flag only + // has meaning after the locator has been built. Large ids are used when the + // number of binned points, or the number of bins, is >= the signed integer + // max value. + bool GetLargeIds() {return this->LargeIds;} protected: vtkStaticPointLocator(); @@ -151,7 +157,7 @@ friend class vtkBucketList; int Divisions[3]; // Number of sub-divisions in x-y-z directions double H[3]; // Width of each bucket in x-y-z directions vtkBucketList *Buckets; // Lists of point ids in each bucket - int LargeIds; //indicate whether integer ids are small or large + bool LargeIds; //indicate whether integer ids are small or large private: vtkStaticPointLocator(const vtkStaticPointLocator&); // Not implemented. diff --git a/Common/DataModel/vtkStructuredExtent.h b/Common/DataModel/vtkStructuredExtent.h index e391d0a806d..9c896fe9709 100644 --- a/Common/DataModel/vtkStructuredExtent.h +++ b/Common/DataModel/vtkStructuredExtent.h @@ -59,7 +59,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkStructuredExtent : public vtkObject // Given the extents, computes the dimensions. static void GetDimensions(const int ext[6], int dims[3]); -//BTX protected: vtkStructuredExtent(); ~vtkStructuredExtent(); @@ -67,7 +66,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkStructuredExtent : public vtkObject private: vtkStructuredExtent(const vtkStructuredExtent&); // Not implemented. void operator=(const vtkStructuredExtent&); // Not implemented. -//ETX + }; //---------------------------------------------------------------------------- diff --git a/Common/DataModel/vtkStructuredGrid.h b/Common/DataModel/vtkStructuredGrid.h index 773a2fa1d19..eea178acd30 100644 --- a/Common/DataModel/vtkStructuredGrid.h +++ b/Common/DataModel/vtkStructuredGrid.h @@ -178,12 +178,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkStructuredGrid : public vtkPointSet // and the source generated more than the update extent. virtual void Crop(const int* updateExtent); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkStructuredGrid* GetData(vtkInformation* info); static vtkStructuredGrid* GetData(vtkInformationVector* v, int i=0); - //ETX // Description: // Get a point in the grid. If adjustForExtent is true, (i,j,k) is diff --git a/Common/DataModel/vtkStructuredPointsCollection.h b/Common/DataModel/vtkStructuredPointsCollection.h index fcb2f56e06b..f9aff3f1070 100644 --- a/Common/DataModel/vtkStructuredPointsCollection.h +++ b/Common/DataModel/vtkStructuredPointsCollection.h @@ -45,7 +45,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkStructuredPointsCollection : public vtkCollec vtkStructuredPoints *GetNextItem() { return static_cast(this->GetNextItemAsObject());}; - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. @@ -53,7 +52,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkStructuredPointsCollection : public vtkCollec vtkCollectionSimpleIterator &cookie) { return static_cast( this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkStructuredPointsCollection() {} diff --git a/Common/DataModel/vtkTable.cxx b/Common/DataModel/vtkTable.cxx index e8c26638445..1dcc25a8733 100644 --- a/Common/DataModel/vtkTable.cxx +++ b/Common/DataModel/vtkTable.cxx @@ -237,9 +237,9 @@ vtkIdType vtkTable::InsertNextBlankRow(double default_num_val) { vtkAbstractArray* arr = this->GetColumn(i); int comps = arr->GetNumberOfComponents(); - if (vtkDataArray::SafeDownCast(arr)) + if (vtkArrayDownCast(arr)) { - vtkDataArray* data = vtkDataArray::SafeDownCast(arr); + vtkDataArray* data = vtkArrayDownCast(arr); double* tuple = new double[comps]; for (int j = 0; j < comps; j++) { @@ -248,25 +248,25 @@ vtkIdType vtkTable::InsertNextBlankRow(double default_num_val) data->InsertNextTuple(tuple); delete[] tuple; } - else if (vtkStringArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { - vtkStringArray* data = vtkStringArray::SafeDownCast(arr); + vtkStringArray* data = vtkArrayDownCast(arr); for (int j = 0; j < comps; j++) { data->InsertNextValue(vtkStdString("")); } } - else if (vtkVariantArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { - vtkVariantArray* data = vtkVariantArray::SafeDownCast(arr); + vtkVariantArray* data = vtkArrayDownCast(arr); for (int j = 0; j < comps; j++) { data->InsertNextValue(vtkVariant()); } } - else if (vtkUnicodeStringArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { - vtkUnicodeStringArray* data = vtkUnicodeStringArray::SafeDownCast(arr); + vtkUnicodeStringArray* data = vtkArrayDownCast(arr); for (int j = 0; j < comps; j++) { data->InsertNextValue(vtkUnicodeString::from_utf8("")); @@ -306,25 +306,25 @@ void vtkTable::RemoveRow(vtkIdType row) { vtkAbstractArray* arr = this->GetColumn(i); int comps = arr->GetNumberOfComponents(); - if (vtkDataArray::SafeDownCast(arr)) + if (vtkArrayDownCast(arr)) { - vtkDataArray* data = vtkDataArray::SafeDownCast(arr); + vtkDataArray* data = vtkArrayDownCast(arr); data->RemoveTuple(row); } - else if (vtkStringArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { // Manually move all elements past the index back one place. - vtkStringArray* data = vtkStringArray::SafeDownCast(arr); + vtkStringArray* data = vtkArrayDownCast(arr); for (int j = comps*row; j < comps*data->GetNumberOfTuples() - 1; j++) { data->SetValue(j, data->GetValue(j+1)); } data->Resize(data->GetNumberOfTuples() - 1); } - else if (vtkVariantArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { // Manually move all elements past the index back one place. - vtkVariantArray* data = vtkVariantArray::SafeDownCast(arr); + vtkVariantArray* data = vtkArrayDownCast(arr); for (int j = comps*row; j < comps*data->GetNumberOfTuples() - 1; j++) { data->SetValue(j, data->GetValue(j+1)); @@ -404,19 +404,19 @@ void vtkTable::SetValue(vtkIdType row, vtkIdType col, vtkVariant value) return; } int comps = arr->GetNumberOfComponents(); - if (vtkDataArray::SafeDownCast(arr)) + if (vtkArrayDownCast(arr)) { - vtkDataArray* data = vtkDataArray::SafeDownCast(arr); + vtkDataArray* data = vtkArrayDownCast(arr); if (comps == 1) { data->SetVariantValue(row, value); } else { - if (value.IsArray() && vtkDataArray::SafeDownCast(value.ToArray()) && + if (value.IsArray() && vtkArrayDownCast(value.ToArray()) && value.ToArray()->GetNumberOfComponents() == comps) { - data->SetTuple(row, vtkDataArray::SafeDownCast(value.ToArray())->GetTuple(0)); + data->SetTuple(row, vtkArrayDownCast(value.ToArray())->GetTuple(0)); } else { @@ -425,19 +425,19 @@ void vtkTable::SetValue(vtkIdType row, vtkIdType col, vtkVariant value) } } } - else if (vtkStringArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { - vtkStringArray* data = vtkStringArray::SafeDownCast(arr); + vtkStringArray* data = vtkArrayDownCast(arr); if (comps == 1) { data->SetValue(row, value.ToString()); } else { - if (value.IsArray() && vtkStringArray::SafeDownCast(value.ToArray()) && + if (value.IsArray() && vtkArrayDownCast(value.ToArray()) && value.ToArray()->GetNumberOfComponents() == comps) { - data->SetTuple(row, 0, vtkStringArray::SafeDownCast(value.ToArray())); + data->SetTuple(row, 0, vtkArrayDownCast(value.ToArray())); } else { @@ -446,9 +446,9 @@ void vtkTable::SetValue(vtkIdType row, vtkIdType col, vtkVariant value) } } } - else if (vtkVariantArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { - vtkVariantArray* data = vtkVariantArray::SafeDownCast(arr); + vtkVariantArray* data = vtkArrayDownCast(arr); if (comps == 1) { data->SetValue(row, value); @@ -466,19 +466,19 @@ void vtkTable::SetValue(vtkIdType row, vtkIdType col, vtkVariant value) } } } - else if(vtkUnicodeStringArray::SafeDownCast(arr)) + else if(vtkArrayDownCast(arr)) { - vtkUnicodeStringArray* data = vtkUnicodeStringArray::SafeDownCast(arr); + vtkUnicodeStringArray* data = vtkArrayDownCast(arr); if(comps==1) { data->SetValue(row, value.ToUnicodeString()); } else { - if(value.IsArray() && vtkUnicodeStringArray::SafeDownCast(value.ToArray()) && + if(value.IsArray() && vtkArrayDownCast(value.ToArray()) && value.ToArray()->GetNumberOfComponents() == comps) { - data->SetTuple(row, 0, vtkUnicodeStringArray::SafeDownCast(value.ToArray())); + data->SetTuple(row, 0, vtkArrayDownCast(value.ToArray())); } else { @@ -527,7 +527,7 @@ vtkVariant vtkTable::GetValue(vtkIdType row, vtkIdType col) { return vtkVariant(); } - if (vtkDataArray::SafeDownCast(arr)) + if (vtkArrayDownCast(arr)) { if (comps == 1) { @@ -553,9 +553,9 @@ vtkVariant vtkTable::GetValue(vtkIdType row, vtkIdType col) return v; } } - else if (vtkStringArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { - vtkStringArray* data = vtkStringArray::SafeDownCast(arr); + vtkStringArray* data = vtkArrayDownCast(arr); if (comps == 1) { return vtkVariant(data->GetValue(row)); @@ -571,9 +571,9 @@ vtkVariant vtkTable::GetValue(vtkIdType row, vtkIdType col) return v; } } - else if (vtkUnicodeStringArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { - vtkUnicodeStringArray* data = vtkUnicodeStringArray::SafeDownCast(arr); + vtkUnicodeStringArray* data = vtkArrayDownCast(arr); if (comps == 1) { return vtkVariant(data->GetValue(row)); @@ -589,9 +589,9 @@ vtkVariant vtkTable::GetValue(vtkIdType row, vtkIdType col) return v; } } - else if (vtkVariantArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { - vtkVariantArray* data = vtkVariantArray::SafeDownCast(arr); + vtkVariantArray* data = vtkArrayDownCast(arr); if (comps == 1) { return data->GetValue(row); diff --git a/Common/DataModel/vtkTree.h b/Common/DataModel/vtkTree.h index 31903869701..763e8361a97 100644 --- a/Common/DataModel/vtkTree.h +++ b/Common/DataModel/vtkTree.h @@ -83,11 +83,9 @@ class VTKCOMMONDATAMODEL_EXPORT vtkTree : public vtkDirectedAcyclicGraph // Get the parent of a vertex. vtkIdType GetParent(vtkIdType v); -//BTX // Description: // Get the edge connecting the vertex to its parent. vtkEdgeType GetParentEdge(vtkIdType v); -//ETX // Description: // Get the level of the vertex in the tree. The root vertex has level 0. @@ -99,12 +97,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkTree : public vtkDirectedAcyclicGraph // Return whether the vertex is a leaf (i.e. it has no children). bool IsLeaf(vtkIdType vertex); - //BTX // Description: // Retrieve a graph from an information vector. static vtkTree *GetData(vtkInformation *info); static vtkTree *GetData(vtkInformationVector *v, int i=0); - //ETX // Description: // Reorder the children of a parent vertex. diff --git a/Common/DataModel/vtkTreeBFSIterator.h b/Common/DataModel/vtkTreeBFSIterator.h index d1b6cfc5530..f68ec6f36f5 100644 --- a/Common/DataModel/vtkTreeBFSIterator.h +++ b/Common/DataModel/vtkTreeBFSIterator.h @@ -51,14 +51,12 @@ class VTKCOMMONDATAMODEL_EXPORT vtkTreeBFSIterator : public vtkTreeIterator vtkTreeBFSIteratorInternals* Internals; vtkIntArray* Color; - //BTX enum ColorType { WHITE, GRAY, BLACK }; - //ETX private: vtkTreeBFSIterator(const vtkTreeBFSIterator &); // Not implemented. diff --git a/Common/DataModel/vtkTreeDFSIterator.h b/Common/DataModel/vtkTreeDFSIterator.h index 5fbccd648b7..5bda9744490 100644 --- a/Common/DataModel/vtkTreeDFSIterator.h +++ b/Common/DataModel/vtkTreeDFSIterator.h @@ -49,13 +49,11 @@ class VTKCOMMONDATAMODEL_EXPORT vtkTreeDFSIterator : public vtkTreeIterator vtkTypeMacro(vtkTreeDFSIterator, vtkTreeIterator); virtual void PrintSelf(ostream& os, vtkIndent indent); - //BTX enum ModeType { DISCOVER, FINISH }; - //ETX // Description: // Set the visit mode of the iterator. Mode can be @@ -79,14 +77,12 @@ class VTKCOMMONDATAMODEL_EXPORT vtkTreeDFSIterator : public vtkTreeIterator vtkTreeDFSIteratorInternals* Internals; vtkIntArray* Color; - //BTX enum ColorType { WHITE, GRAY, BLACK }; - //ETX private: vtkTreeDFSIterator(const vtkTreeDFSIterator &); // Not implemented. diff --git a/Common/DataModel/vtkUndirectedGraph.h b/Common/DataModel/vtkUndirectedGraph.h index 29fad86dc89..dd5c2e556e7 100644 --- a/Common/DataModel/vtkUndirectedGraph.h +++ b/Common/DataModel/vtkUndirectedGraph.h @@ -57,12 +57,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUndirectedGraph : public vtkGraph // Returns the full degree of the vertex. virtual vtkIdType GetInDegree(vtkIdType v); - //BTX // Description: // Random-access method for retrieving the in edges of a vertex. // For an undirected graph, this is the same as the out edges. virtual vtkInEdgeType GetInEdge(vtkIdType v, vtkIdType i); - //ETX // Description: // Random-access method for retrieving incoming edges to vertex v. @@ -72,12 +70,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUndirectedGraph : public vtkGraph virtual void GetInEdge(vtkIdType v, vtkIdType i, vtkGraphEdge* e) { this->Superclass::GetInEdge(v, i, e); } - //BTX // Description: // Retrieve a graph from an information vector. static vtkUndirectedGraph *GetData(vtkInformation *info); static vtkUndirectedGraph *GetData(vtkInformationVector *v, int i=0); - //ETX // Description: // Initialize the iterator to get the incoming edges to a vertex. @@ -95,11 +91,9 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUndirectedGraph : public vtkGraph vtkUndirectedGraph(); ~vtkUndirectedGraph(); - //BTX // Description: // For iterators, returns the same edge list as GetOutEdges(). virtual void GetInEdges(vtkIdType v, const vtkInEdgeType *& edges, vtkIdType & nedges); - //ETX private: vtkUndirectedGraph(const vtkUndirectedGraph&); // Not implemented. diff --git a/Common/DataModel/vtkUniformGrid.h b/Common/DataModel/vtkUniformGrid.h index ac6660b3fa9..7889eb7df10 100644 --- a/Common/DataModel/vtkUniformGrid.h +++ b/Common/DataModel/vtkUniformGrid.h @@ -74,7 +74,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUniformGrid : public vtkImageData // Returns the data description of this uniform grid instance. int GetGridDescription(); - // BTX // Description: // Initialize with no ghost cell arrays, from the definition in // the given box. The box is expetced to be 3D, if you have 2D @@ -104,7 +103,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUniformGrid : public vtkImageData // (X,X,0)(X,X,0) // Returns 0 if the initialization failed. int Initialize(const vtkAMRBox *def, double* origin, double* spacing, int nGhostsI,int nGhostsJ,int nGhostsK); - //ETX // Description: // Methods for supporting blanking of cells. Blanking turns on or off @@ -149,12 +147,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUniformGrid : public vtkImageData virtual vtkImageData* NewImageDataCopy(); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkUniformGrid* GetData(vtkInformation* info); static vtkUniformGrid* GetData(vtkInformationVector* v, int i=0); - //ETX protected: vtkUniformGrid(); diff --git a/Common/DataModel/vtkUniformGridAMR.h b/Common/DataModel/vtkUniformGridAMR.h index b6168944e2a..1f5a00c60d1 100644 --- a/Common/DataModel/vtkUniformGridAMR.h +++ b/Common/DataModel/vtkUniformGridAMR.h @@ -38,7 +38,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUniformGridAMR: public vtkCompositeDataSet // Description: // Return a new iterator (the iterator has to be deleted by the user). - virtual vtkCompositeDataIterator* NewIterator(); + virtual VTK_NEWINSTANCE vtkCompositeDataIterator* NewIterator(); // Description: // Return class name of data type (see vtkType.h for definitions). @@ -118,7 +118,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUniformGridAMR: public vtkCompositeDataSet // Retrieve an instance of this class from an information object. static vtkUniformGridAMR* GetData(vtkInformation* info); static vtkUniformGridAMR* GetData(vtkInformationVector* v, int i=0); - //ETX protected: vtkUniformGridAMR(); diff --git a/Common/DataModel/vtkUniformGridAMRDataIterator.h b/Common/DataModel/vtkUniformGridAMRDataIterator.h index 234b7a9a0d8..9d9109bc528 100644 --- a/Common/DataModel/vtkUniformGridAMRDataIterator.h +++ b/Common/DataModel/vtkUniformGridAMRDataIterator.h @@ -81,8 +81,6 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUniformGridAMRDataIterator : // IsDoneWithTraversal() returns 0. virtual int IsDoneWithTraversal(); - -//BTX protected: vtkUniformGridAMRDataIterator(); ~vtkUniformGridAMRDataIterator(); @@ -97,7 +95,7 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUniformGridAMRDataIterator : vtkAMRDataInternals* AMRData; void GetCurrentIndexPair(unsigned int& level, unsigned int& id); -//ETX + }; #endif diff --git a/Common/DataModel/vtkUnstructuredGrid.cxx b/Common/DataModel/vtkUnstructuredGrid.cxx index e20286b435a..cfc08132294 100644 --- a/Common/DataModel/vtkUnstructuredGrid.cxx +++ b/Common/DataModel/vtkUnstructuredGrid.cxx @@ -1100,6 +1100,7 @@ void vtkUnstructuredGrid::SetCells(int *types, vtkCellArray *cells) if (types[i] == VTK_POLYHEDRON) { containPolyhedron = true; + break; // We can terminate early } } diff --git a/Common/DataModel/vtkUnstructuredGrid.h b/Common/DataModel/vtkUnstructuredGrid.h index 245cb91ceb1..c45b9c97967 100644 --- a/Common/DataModel/vtkUnstructuredGrid.h +++ b/Common/DataModel/vtkUnstructuredGrid.h @@ -232,12 +232,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUnstructuredGrid : // (has the vtkDataSetAttributes::DUPLICATECELL bit set). void RemoveGhostCells(); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkUnstructuredGrid* GetData(vtkInformation* info); static vtkUnstructuredGrid* GetData(vtkInformationVector* v, int i=0); - //ETX // Description: // Special support for polyhedron. Return NULL for all other cell types. diff --git a/Common/DataModel/vtkUnstructuredGridBase.h b/Common/DataModel/vtkUnstructuredGridBase.h index bc8a6c7a9aa..9bd3393c64b 100644 --- a/Common/DataModel/vtkUnstructuredGridBase.h +++ b/Common/DataModel/vtkUnstructuredGridBase.h @@ -93,12 +93,10 @@ class VTKCOMMONDATAMODEL_EXPORT vtkUnstructuredGridBase : public vtkPointSet // Traverse cells and determine if cells are all of the same type. virtual int IsHomogeneous() = 0; - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkUnstructuredGridBase* GetData(vtkInformation* info); static vtkUnstructuredGridBase* GetData(vtkInformationVector* v, int i=0); - //ETX protected: vtkUnstructuredGridBase(); diff --git a/Common/DataModel/vtkXMLDataElement.h b/Common/DataModel/vtkXMLDataElement.h index b9ff535a81b..f197167dcab 100644 --- a/Common/DataModel/vtkXMLDataElement.h +++ b/Common/DataModel/vtkXMLDataElement.h @@ -96,14 +96,12 @@ class VTKCOMMONDATAMODEL_EXPORT vtkXMLDataElement : public vtkObject void SetVectorAttribute(const char* name, int length, const double* value); void SetVectorAttribute(const char* name, int length, const unsigned long* value); - //BTX int GetScalarAttribute(const char* name, long long& value); int GetVectorAttribute(const char* name, int length, long long* value); void SetVectorAttribute(const char* name, int length, long long const* value); int GetScalarAttribute(const char* name, unsigned long long& value); int GetVectorAttribute(const char* name, int length, unsigned long long* value); void SetVectorAttribute(const char* name, int length, unsigned long long const* value); - //ETX // Description: // Get the attribute with the given name and converted to a word type @@ -274,10 +272,8 @@ class VTKCOMMONDATAMODEL_EXPORT vtkXMLDataElement : public vtkObject void PrintCharacterData(ostream &os,vtkIndent indent); static void PrintWithEscapedData(ostream& os, const char* data); - //BTX friend class vtkXMLDataParser; friend class vtkXMLMaterialParser; - //ETX private: vtkXMLDataElement(const vtkXMLDataElement&); // Not implemented. diff --git a/Common/ExecutionModel/Testing/Cxx/CMakeLists.txt b/Common/ExecutionModel/Testing/Cxx/CMakeLists.txt index c821cca9ec9..adb9f4946cc 100644 --- a/Common/ExecutionModel/Testing/Cxx/CMakeLists.txt +++ b/Common/ExecutionModel/Testing/Cxx/CMakeLists.txt @@ -5,6 +5,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestMetaData.cxx TestSetInputDataObject.cxx TestTemporalSupport.cxx + TestThreadedImageAlgorithmSplitExtent.cxx TestTrivialConsumer.cxx UnitTestSimpleScalarTree.cxx ) diff --git a/Common/ExecutionModel/Testing/Cxx/TestCopyAttributeData.cxx b/Common/ExecutionModel/Testing/Cxx/TestCopyAttributeData.cxx index 82c057d8cee..735313928f9 100644 --- a/Common/ExecutionModel/Testing/Cxx/TestCopyAttributeData.cxx +++ b/Common/ExecutionModel/Testing/Cxx/TestCopyAttributeData.cxx @@ -144,7 +144,7 @@ int TestCopyAttributeData(int,char *[]) vtkDataArray *outPointVectors = output->GetPointData()->GetVectors(); vtkDataArray *outCellScalars = output->GetCellData()->GetScalars(); - vtkStringArray *outCellStrings = vtkStringArray::SafeDownCast( + vtkStringArray *outCellStrings = vtkArrayDownCast( output->GetCellData()->GetAbstractArray("CellStrings")); for (int zId = outExt[4]; zId <= outExt[5]; zId++) diff --git a/Common/ExecutionModel/Testing/Cxx/TestThreadedImageAlgorithmSplitExtent.cxx b/Common/ExecutionModel/Testing/Cxx/TestThreadedImageAlgorithmSplitExtent.cxx new file mode 100644 index 00000000000..8a1e95143f3 --- /dev/null +++ b/Common/ExecutionModel/Testing/Cxx/TestThreadedImageAlgorithmSplitExtent.cxx @@ -0,0 +1,255 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestThreadedImageAlgorithmSplitExtent.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +// This test checks the SplitExtent method of vtkThreadedImageAlgorithm. + +#include "vtkNew.h" +#include "vtkThreadedImageAlgorithm.h" + +#define TEST_SUCCESS 0 +#define TEST_FAILURE 1 + +// A simple subclass of vtkThreadedImageAlgorithm to test +class ThreadedImageAlgorithmTester : + public vtkThreadedImageAlgorithm +{ +public: + static ThreadedImageAlgorithmTester *New(); + vtkTypeMacro(ThreadedImageAlgorithmTester,vtkThreadedImageAlgorithm); + void SetSplitPath(const int path[3], int len); + bool TestSplitExtent(int extent[6], vtkIdType pieces); +}; + +ThreadedImageAlgorithmTester *ThreadedImageAlgorithmTester::New() +{ + return new ThreadedImageAlgorithmTester; +} + +// The SplitPath is protected, so add a method to set it. +void ThreadedImageAlgorithmTester::SetSplitPath(const int path[3], int len) +{ + len = (len < 0 ? 0 : len); + len = (len > 3 ? 3 : len); + for (int i = 0; i < len; i++) + { + this->SplitPath[i] = path[i]; + } + this->SplitPathLength = len; +} + +// Test splitting the extent into the given number of pieces. +bool ThreadedImageAlgorithmTester::TestSplitExtent( + int extent[6], vtkIdType pieces) +{ + bool success = true; + + int size[3] = { + extent[1] - extent[0] + 1, + extent[3] - extent[2] + 1, + extent[5] - extent[4] + 1 + }; + + vtkIdType n = this->SplitExtent(0, extent, 0, pieces); + + int divs[3] = { 1, 1, 1 }; + vtkIdType inc = 1; + int checkAxis = 0; + vtkIdType i; + for (i = 0; i < n; i += inc) + { + int split[6]; + vtkIdType m = this->SplitExtent(split, extent, i, pieces); + + // accelerate check by increasing increment after first row + if (checkAxis < 1 && split[2] > 0) + { + divs[checkAxis] = i; + inc = i; + checkAxis = 1; + } + if (checkAxis < 2 && split[4] > 0) + { + divs[checkAxis] = i/inc; + inc = i; + checkAxis = 2; + } + + // check for constancy of division + if (m != n) + { + std::cerr << "SplitExtent changed the number of pieces from " + << n << " to " << m << "!\n"; + success = false; + break; + } + + // check that SplitPath was used + if (this->SplitPathLength < 3) + { + int k; + for (k = 0; k < 3; k++) + { + if ((this->SplitPathLength == 1 && k != this->SplitPath[0]) || + (k != this->SplitPath[0] && k != this->SplitPath[1])) + { + if (split[2*k] != extent[2*k] || + split[2*k + 1] != extent[2*k + 1]) + { + success = false; + break; + } + } + } + if (!success) + { + std::cerr << "Split axis " << k << " is not in split path!\n"; + break; + } + } + + // check that MinimumPieceSize was used + for (int j = 0; j < 3; j++) + { + if (size[j] >= this->MinimumPieceSize[j] && + split[2*j + 1] - split[2*j] + 1 < this->MinimumPieceSize[j]) + { + success = false; + } + } + if (!success) + { + std::cerr << "Split piece [" + << split[0] << " " << split[1] << " " + << split[2] << " " << split[3] << " " + << split[4] << " " << split[5] + << "] smaller than MinimumPieceSize!\n"; + break; + } + } + + // check that the maximum possible split was used + if (success) + { + divs[checkAxis] = i/inc; + + for (int j = 0; j < this->SplitPathLength; j++) + { + int k = this->SplitPath[j]; + if ((divs[k] + 1)*this->MinimumPieceSize[k] <= size[k] && + (divs[k] + 1)*divs[(k+1)%3]*divs[(k+2)%3] <= pieces) + { + std::cerr << "Divisions [" + << divs[0] << " " << divs[1] << " " << divs[2]; + std::cerr << "] could be increased along axis " << k << "\n"; + success = false; + } + } + } + + if (!success) + { + std::cerr << "Extent: " + << extent[0] << " " << extent[1] << " " + << extent[2] << " " << extent[3] << " " + << extent[4] << " " << extent[5] << "\n"; + std::cerr << "Piece: " << i << " of " << n << "\n"; + std::cerr << "MinimumPieceSize: " + << this->MinimumPieceSize[0] << " " + << this->MinimumPieceSize[1] << " " + << this->MinimumPieceSize[2] << "\n"; + std::cerr << "SplitMode: " + << (this->SplitMode == SLAB ? "Slab\n" : + (this->SplitMode == BEAM ? "Beam\n" : + (this->SplitMode == BLOCK ? "Block\n" : "Unknown\n"))); + std::cerr << "SplitPath:"; + for (int k = 0; k < this->SplitPathLength; k++) + { + std::cerr << " " << this->SplitPath[k]; + } + std::cerr << "\n"; + } + + return success; +} + +int TestThreadedImageAlgorithmSplitExtent(int, char*[]) +{ + vtkNew tester; + + const int splitPaths[6][3] = { + { 2, 1, 0 }, + { 1, 2, 0 }, + { 0, 2, 1 }, + { 2, 0, 1 }, + { 1, 0, 2 }, + { 0, 1, 2 } + }; + + for (int mode = 0; mode < 3; mode++) + { + if (mode == 0) + { + tester->SetSplitModeToSlab(); + } + else if (mode == 1) + { + tester->SetSplitModeToBeam(); + } + else + { + tester->SetSplitModeToBlock(); + } + + for (int xmin = 1; xmin <= 8; xmin++) + { + for (int ymin = 1; ymin <= 7; ymin += 3) + { + for (int zmin = 1; zmin <= 8; zmin += 7) + { + tester->SetMinimumPieceSize(xmin, ymin, zmin); + + for (int path = 0; path < 15; path++) + { + tester->SetSplitPath(splitPaths[path%6], 3 - path/6); + + for (int xsize = 1; xsize <= 100; xsize += 99) + { + for (int ysize = 1; ysize <= 92; ysize += 13) + { + for (int zsize = 1; zsize <= 10; zsize++) + { + int extent[6] = { 0, xsize - 1, 0, ysize - 1, 0, zsize - 1 }; + + vtkIdType maxpieces = xsize*ysize*zsize; + maxpieces = (maxpieces > 100 ? 100 : maxpieces); + vtkIdType inc = 1 + maxpieces/5; + for (vtkIdType pieces = 1; pieces <= maxpieces; pieces += inc) + { + if (!tester->TestSplitExtent(extent, pieces)) + { + return TEST_FAILURE; + } + } + } + } + } + } + } + } + } + } + + return TEST_SUCCESS; +} diff --git a/Common/ExecutionModel/vtkAlgorithm.cxx b/Common/ExecutionModel/vtkAlgorithm.cxx index 82228d42e6b..128311d1162 100644 --- a/Common/ExecutionModel/vtkAlgorithm.cxx +++ b/Common/ExecutionModel/vtkAlgorithm.cxx @@ -361,7 +361,7 @@ vtkDataArray *vtkAlgorithm::GetInputArrayToProcess( vtkDataArray* vtkAlgorithm::GetInputArrayToProcess (int idx, vtkInformationVector **inputVector, int& association) { - return vtkDataArray::SafeDownCast( + return vtkArrayDownCast( this->GetInputAbstractArrayToProcess(idx, inputVector, association)); } @@ -377,7 +377,7 @@ vtkDataArray *vtkAlgorithm::GetInputArrayToProcess( vtkDataArray* vtkAlgorithm::GetInputArrayToProcess (int idx, int connection, vtkInformationVector **inputVector, int& association) { - return vtkDataArray::SafeDownCast(this->GetInputAbstractArrayToProcess( + return vtkArrayDownCast(this->GetInputAbstractArrayToProcess( idx, connection, inputVector, association)); } @@ -394,7 +394,7 @@ vtkDataArray* vtkAlgorithm::GetInputArrayToProcess(int idx, vtkDataObject* input, int& association) { - return vtkDataArray::SafeDownCast(this->GetInputAbstractArrayToProcess(idx, + return vtkArrayDownCast(this->GetInputAbstractArrayToProcess(idx, input, association)); } diff --git a/Common/ExecutionModel/vtkAlgorithm.h b/Common/ExecutionModel/vtkAlgorithm.h index c3fc20d3fd8..32d03f4cbd5 100644 --- a/Common/ExecutionModel/vtkAlgorithm.h +++ b/Common/ExecutionModel/vtkAlgorithm.h @@ -170,8 +170,8 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkAlgorithm : public vtkObject // Description: // Participate in garbage collection. - virtual void Register(vtkObjectBase* o); - virtual void UnRegister(vtkObjectBase* o); + void Register(vtkObjectBase* o) VTK_OVERRIDE; + void UnRegister(vtkObjectBase* o) VTK_OVERRIDE; // Description: // Set/Get the AbortExecute flag for the process object. Process objects @@ -782,7 +782,7 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkAlgorithm : public vtkObject char *ProgressText; // Garbage collection support. - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; // executive methods below diff --git a/Common/ExecutionModel/vtkDemandDrivenPipeline.h b/Common/ExecutionModel/vtkDemandDrivenPipeline.h index 18d5622401b..0c5628a20d9 100644 --- a/Common/ExecutionModel/vtkDemandDrivenPipeline.h +++ b/Common/ExecutionModel/vtkDemandDrivenPipeline.h @@ -212,10 +212,7 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkDemandDrivenPipeline : public vtkExecuti vtkTimeStamp InformationTime; vtkTimeStamp DataTime; -//BTX friend class vtkCompositeDataPipeline; -//ETX - vtkInformation *InfoRequest; vtkInformation *DataObjectRequest; diff --git a/Common/ExecutionModel/vtkExecutive.h b/Common/ExecutionModel/vtkExecutive.h index 5fade96612f..85a0ed44c58 100644 --- a/Common/ExecutionModel/vtkExecutive.h +++ b/Common/ExecutionModel/vtkExecutive.h @@ -149,8 +149,8 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkExecutive : public vtkObject // Description: // Participate in garbage collection. - virtual void Register(vtkObjectBase* o); - virtual void UnRegister(vtkObjectBase* o); + void Register(vtkObjectBase* o) VTK_OVERRIDE; + void UnRegister(vtkObjectBase* o) VTK_OVERRIDE; // Description: // Information key to store the executive/port number producing an @@ -175,10 +175,9 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkExecutive : public vtkObject static vtkInformationIntegerKey* ALGORITHM_DIRECTION(); static vtkInformationIntegerKey* FORWARD_DIRECTION(); static vtkInformationKeyVectorKey* KEYS_TO_COPY(); - //BTX + enum { RequestUpstream, RequestDownstream }; enum { BeforeForward, AfterForward }; - //ETX // Description: // An API to CallAlgorithm that allows you to pass in the info objects to @@ -219,7 +218,7 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkExecutive : public vtkObject virtual int UpdateDataObject()=0; // Garbage collection support. - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; virtual void SetAlgorithm(vtkAlgorithm* algorithm); @@ -242,9 +241,8 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkExecutive : public vtkObject // Internal implementation details. vtkExecutiveInternals* ExecutiveInternal; - //BTX friend class vtkAlgorithmToExecutiveFriendship; - //ETX + private: vtkExecutive(const vtkExecutive&); // Not implemented. void operator=(const vtkExecutive&); // Not implemented. diff --git a/Common/ExecutionModel/vtkExtentRCBPartitioner.h b/Common/ExecutionModel/vtkExtentRCBPartitioner.h index 01774591547..14600df2416 100644 --- a/Common/ExecutionModel/vtkExtentRCBPartitioner.h +++ b/Common/ExecutionModel/vtkExtentRCBPartitioner.h @@ -179,9 +179,7 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkExtentRCBPartitioner : public vtkObject bool ExtentIsPartitioned; - // BTX std::vector PartitionExtents; - // ETX private: vtkExtentRCBPartitioner( const vtkExtentRCBPartitioner& );// Not implemented diff --git a/Common/ExecutionModel/vtkHierarchicalBoxDataSetAlgorithm.h b/Common/ExecutionModel/vtkHierarchicalBoxDataSetAlgorithm.h index eae132099f8..af71e5b01d4 100644 --- a/Common/ExecutionModel/vtkHierarchicalBoxDataSetAlgorithm.h +++ b/Common/ExecutionModel/vtkHierarchicalBoxDataSetAlgorithm.h @@ -51,7 +51,6 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkHierarchicalBoxDataSetAlgorithm : public vtkInformationVector** inputVector, vtkInformationVector* outputVector); -//BTX protected: vtkHierarchicalBoxDataSetAlgorithm(); ~vtkHierarchicalBoxDataSetAlgorithm(); @@ -99,7 +98,7 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkHierarchicalBoxDataSetAlgorithm : public private: vtkHierarchicalBoxDataSetAlgorithm(const vtkHierarchicalBoxDataSetAlgorithm&); // Not implemented. void operator=(const vtkHierarchicalBoxDataSetAlgorithm&); // Not implemented. -//ETX + }; #endif diff --git a/Common/ExecutionModel/vtkSimpleScalarTree.h b/Common/ExecutionModel/vtkSimpleScalarTree.h index e88a8334439..eceb0bdd217 100644 --- a/Common/ExecutionModel/vtkSimpleScalarTree.h +++ b/Common/ExecutionModel/vtkSimpleScalarTree.h @@ -47,9 +47,7 @@ #include "vtkCommonExecutionModelModule.h" // For export macro #include "vtkScalarTree.h" -//BTX class vtkScalarNode; -//ETX class VTKCOMMONEXECUTIONMODEL_EXPORT vtkSimpleScalarTree : public vtkScalarTree { diff --git a/Common/ExecutionModel/vtkThreadedImageAlgorithm.cxx b/Common/ExecutionModel/vtkThreadedImageAlgorithm.cxx index c794f181783..6eea07af584 100644 --- a/Common/ExecutionModel/vtkThreadedImageAlgorithm.cxx +++ b/Common/ExecutionModel/vtkThreadedImageAlgorithm.cxx @@ -24,13 +24,39 @@ #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkSMPTools.h" +// If SMP backend is Sequential then fall back to vtkMultiThreader, +// else enable the newer vtkSMPTools code path by default. +#ifdef VTK_SMP_Sequential +bool vtkThreadedImageAlgorithm::GlobalDefaultEnableSMP = false; +#else +bool vtkThreadedImageAlgorithm::GlobalDefaultEnableSMP = true; +#endif //---------------------------------------------------------------------------- vtkThreadedImageAlgorithm::vtkThreadedImageAlgorithm() { this->Threader = vtkMultiThreader::New(); this->NumberOfThreads = this->Threader->GetNumberOfThreads(); + + // SMP default settings + this->EnableSMP = vtkThreadedImageAlgorithm::GlobalDefaultEnableSMP; + + // Splitting method + this->SplitMode = SLAB; + this->SplitPath[0] = 2; + this->SplitPath[1] = 1; + this->SplitPath[2] = 0; + this->SplitPathLength = 3; + + // Minumum block size + this->MinimumPieceSize[0] = 16; + this->MinimumPieceSize[1] = 1; + this->MinimumPieceSize[2] = 1; + + // The desired block size in bytes + this->DesiredBytesPerPiece = 65536; } //---------------------------------------------------------------------------- @@ -39,14 +65,44 @@ vtkThreadedImageAlgorithm::~vtkThreadedImageAlgorithm() this->Threader->Delete(); } +//---------------------------------------------------------------------------- +void vtkThreadedImageAlgorithm::SetGlobalDefaultEnableSMP(bool enable) +{ + if (enable != vtkThreadedImageAlgorithm::GlobalDefaultEnableSMP) + { + vtkThreadedImageAlgorithm::GlobalDefaultEnableSMP = enable; + } +} + +//---------------------------------------------------------------------------- +bool vtkThreadedImageAlgorithm::GetGlobalDefaultEnableSMP() +{ + return vtkThreadedImageAlgorithm::GlobalDefaultEnableSMP; +} + //---------------------------------------------------------------------------- void vtkThreadedImageAlgorithm::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "NumberOfThreads: " << this->NumberOfThreads << "\n"; + os << indent << "EnableSMP: " << (this->EnableSMP ? "On\n" : "Off\n"); + os << indent << "GlobalDefaultEnableSMP: " + << (vtkThreadedImageAlgorithm::GlobalDefaultEnableSMP ? + "On\n" : "Off\n"); + os << indent << "MinimumPieceSize: " + << this->MinimumPieceSize[0] << " " + << this->MinimumPieceSize[1] << " " + << this->MinimumPieceSize[2] << "\n"; + os << indent << "DesiredBytesPerPiece: " + << this->DesiredBytesPerPiece << "\n"; + os << indent << "SplitMode: " + << (this->SplitMode == SLAB ? "Slab\n" : + (this->SplitMode == BEAM ? "Beam\n" : + (this->SplitMode == BLOCK ? "Block\n" : "Unknown\n"))); } +//---------------------------------------------------------------------------- struct vtkImageThreadStruct { vtkThreadedImageAlgorithm *Filter; @@ -68,59 +124,234 @@ int vtkThreadedImageAlgorithm::SplitExtent(int splitExt[6], int startExt[6], int num, int total) { - int splitAxis; - int min, max; + // split path (the order in which to split the axes) + int pathlen = this->SplitPathLength; + int mode = this->SplitMode; + int axis0 = this->SplitPath[0]; + int axis1 = this->SplitPath[1]; + int axis2 = this->SplitPath[2]; + int path[3] = { axis0, axis1, axis2 }; + + // divisions + int divs[3] = { 1, 1, 1 }; + + // this needs 64 bits to avoid overflow in the math below + const vtkTypeInt64 size[3] = { + startExt[1] - startExt[0] + 1, + startExt[3] - startExt[2] + 1, + startExt[5] - startExt[4] + 1 }; + + // check for valid extent + if (size[0] <= 0 || size[1] <= 0 || size[2] <= 0) + { + return 0; + } - vtkDebugMacro("SplitExtent: ( " << startExt[0] << ", " << startExt[1] << ", " - << startExt[2] << ", " << startExt[3] << ", " - << startExt[4] << ", " << startExt[5] << "), " - << num << " of " << total); + // divide out the minimum block size + int maxdivs[3] = { 1, 1, 1 }; + for (int i = 0; i < 3; i++) + { + if (size[i] > this->MinimumPieceSize[i] && this->MinimumPieceSize[i] > 0) + { + maxdivs[i] = size[i]/this->MinimumPieceSize[i]; + } + } - // start with same extent - memcpy(splitExt, startExt, 6 * sizeof(int)); + // make sure total is not greater than max number of pieces + vtkTypeInt64 maxPieces = maxdivs[axis0]; + vtkTypeInt64 maxPieces2D = maxPieces; + if (pathlen > 1) + { + maxPieces *= maxdivs[axis1]; + maxPieces2D = maxPieces; + if (pathlen > 2) + { + maxPieces *= maxdivs[axis2]; + } + } + if (total > maxPieces) + { + total = maxPieces; + } - splitAxis = 2; - min = startExt[4]; - max = startExt[5]; - while (min >= max) + if (mode == SLAB || pathlen < 2) { - // empty extent so cannot split - if (min > max) + // split the axes in the given order + divs[axis0] = maxdivs[axis0]; + if (total < maxdivs[axis0]) { - return 1; + divs[axis0] = total; } - --splitAxis; - if (splitAxis < 0) - { // cannot split - vtkDebugMacro(" Cannot Split"); - return 1; + else if (pathlen > 1) + { + divs[axis1] = maxdivs[axis1]; + int q = total/divs[axis0]; + if (q < maxdivs[axis1]) + { + divs[axis1] = q; + } + else if (pathlen > 2) + { + divs[axis2] = q/divs[axis1]; + } } - min = startExt[splitAxis*2]; - max = startExt[splitAxis*2+1]; } - - // determine the actual number of pieces that will be generated - int range = max - min + 1; - int valuesPerThread = static_cast(ceil(range/static_cast(total))); - int maxThreadIdUsed = static_cast(ceil(range/static_cast(valuesPerThread))) - 1; - if (num < maxThreadIdUsed) + else if (mode == BEAM || pathlen < 3) { - splitExt[splitAxis*2] = splitExt[splitAxis*2] + num*valuesPerThread; - splitExt[splitAxis*2+1] = splitExt[splitAxis*2] + valuesPerThread - 1; + // split two of the axes first, leave third axis for last + if (total < maxPieces2D) + { + // split until we get the desired number of pieces + while (divs[axis0]*divs[axis1] < total) + { + axis0 = path[0]; + axis1 = path[1]; + + // if necessary, swap axes to keep a good aspect ratio + if (size[axis0]*divs[axis1] < size[axis1]*divs[axis0]) + { + axis0 = path[1]; + axis1 = path[0]; + } + + // compute the new split for this axis + divs[axis0] = divs[axis1]*size[axis0]/size[axis1] + 1; + } + + // compute final division + divs[axis0] = total/divs[axis1]; + if (divs[axis0] > maxdivs[axis0]) + { + divs[axis0] = maxdivs[axis0]; + } + divs[axis1] = total/divs[axis0]; + if (divs[axis1] > maxdivs[axis1]) + { + divs[axis1] = maxdivs[axis1]; + divs[axis0] = total/divs[axis1]; + } + } + else + { + // maximum split for first two axes + divs[axis0] = maxdivs[axis0]; + divs[axis1] = maxdivs[axis1]; + if (pathlen > 2) + { + // split the third axis + divs[axis2] = total/(divs[axis0]*divs[axis1]); + } + } } - if (num == maxThreadIdUsed) + else // block mode: keep blocks roughly cube shaped { - splitExt[splitAxis*2] = splitExt[splitAxis*2] + num*valuesPerThread; + // split until we get the desired number of pieces + while (divs[0]*divs[1]*divs[2] < total) + { + axis0 = path[0]; + axis1 = path[1]; + axis2 = path[2]; + + // check whether z or y is best candidate for splitting + if (size[axis0]*divs[axis1] < size[axis1]*divs[axis0]) + { + axis1 = axis0; + axis0 = path[1]; + } + + if (pathlen > 2) + { + // check if x is the best candidate for splitting + if (size[axis0]*divs[path[2]] < size[path[2]]*divs[axis0]) + { + axis2 = axis1; + axis1 = axis0; + axis0 = path[2]; + } + // now find the second best candidate + if (size[axis1]*divs[axis2] < size[axis2]*divs[axis1]) + { + int tmp = axis2; + axis2 = axis1; + axis1 = tmp; + } + } + + // compute the new split for this axis + divs[axis0] = divs[axis1]*size[axis0]/size[axis1] + 1; + + // if axis0 reached maxdivs, remove it from the split path + if (divs[axis0] >= maxdivs[axis0]) + { + divs[axis0] = maxdivs[axis0]; + if (--pathlen == 1) + { + break; + } + if (axis0 != path[2]) + { + if (axis0 != path[1]) + { + path[0] = path[1]; + } + path[1] = path[2]; + path[2] = axis0; + } + } + } + + // compute the final division + divs[axis0] = total/(divs[axis1]*divs[axis2]); + if (divs[axis0] > maxdivs[axis0]) + { + divs[axis0] = maxdivs[axis0]; + } + divs[axis1] = total/(divs[axis0]*divs[axis2]); + if (divs[axis1] > maxdivs[axis1]) + { + divs[axis1] = maxdivs[axis1]; + } + divs[axis2] = total/(divs[axis0]*divs[axis1]); + if (divs[axis2] > maxdivs[axis2]) + { + divs[axis2] = maxdivs[axis2]; + } } - vtkDebugMacro(" Split Piece: ( " <Extent[i] = extent[i]; + } + } + + // Called by vtkSMPTools to execute the algorithm over specific pieces. + void operator()(vtkIdType begin, vtkIdType end) + { + this->Algorithm->SMPRequestData( + this->Request, this->InputsInfo, this->OutputsInfo, + this->Inputs, this->Outputs, + begin, end, this->NumberOfPieces, this->Extent); + } + +private: + vtkThreadedImageAlgorithmFunctor(); + + vtkThreadedImageAlgorithm *Algorithm; + vtkInformation *Request; + vtkInformationVector **InputsInfo; + vtkInformationVector *OutputsInfo; + vtkImageData ***Inputs; + vtkImageData **Outputs; + int Extent[6]; + vtkIdType NumberOfPieces; +}; + +//---------------------------------------------------------------------------- +// The execute method created by the subclass. +void vtkThreadedImageAlgorithm::SMPRequestData( + vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector, + vtkImageData ***inData, + vtkImageData **outData, + vtkIdType begin, + vtkIdType end, + vtkIdType numPieces, + int extent[6]) +{ + for (vtkIdType piece = begin; piece < end; piece++) + { + int splitExt[6] = { 0, -1, 0, -1, 0, -1 }; + + vtkIdType total = this->SplitExtent(splitExt, extent, piece, numPieces); + + // check for valid piece and extent + if (piece < total && + splitExt[0] <= splitExt[1] && + splitExt[2] <= splitExt[3] && + splitExt[4] <= splitExt[5]) + { + this->ThreadedRequestData( + request, inputVector, outputVector, inData, outData, splitExt, piece); + } + } +} + +//---------------------------------------------------------------------------- +void vtkThreadedImageAlgorithm::PrepareImageData( + vtkInformationVector** inputVector, + vtkInformationVector* outputVector, + vtkImageData*** inDataObjects, + vtkImageData** outDataObjects) +{ + vtkImageData* firstInput = 0; + vtkImageData* firstOutput = 0; + + // now we must create the output array + int numOutputPorts = this->GetNumberOfOutputPorts(); + for (int i = 0; i < numOutputPorts; i++) + { + vtkInformation* info = outputVector->GetInformationObject(i); + vtkImageData *outData = vtkImageData::SafeDownCast( + info->Get(vtkDataObject::DATA_OBJECT())); + if (i == 0) + { + firstOutput = outData; + } + if (outDataObjects) + { + outDataObjects[i] = outData; + } + if (outData) + { + int updateExtent[6]; + info->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), + updateExtent); + + // unlike geometry filters, for image filters data is pre-allocated + // in the superclass (which means, in this class) + this->AllocateOutputData(outData, info, updateExtent); + } + } + + // now create the inputs array + int numInputPorts = this->GetNumberOfInputPorts(); + for (int i = 0; i < numInputPorts; i++) + { + vtkInformationVector* portInfo = inputVector[i]; + int numConnections = portInfo->GetNumberOfInformationObjects(); + for (int j = 0; j < numConnections; j++) + { + vtkInformation* info = portInfo->GetInformationObject(j); + vtkImageData *inData = vtkImageData::SafeDownCast( + info->Get(vtkDataObject::DATA_OBJECT())); + if (i == 0 && j == 0) + { + firstInput = inData; + } + if (inDataObjects && inDataObjects[i]) + { + inDataObjects[i][j] = inData; + } + } + } + + // copy other arrays + if (firstInput && firstOutput) + { + this->CopyAttributeData(firstInput, firstOutput, inputVector); + } +} //---------------------------------------------------------------------------- // This is the superclasses style of Execute method. Convert it into @@ -221,81 +598,125 @@ int vtkThreadedImageAlgorithm::RequestData( vtkInformationVector** inputVector, vtkInformationVector* outputVector) { - int i; - - // setup the threasd structure + // setup the thread structure vtkImageThreadStruct str; str.Filter = this; str.Request = request; str.InputsInfo = inputVector; str.OutputsInfo = outputVector; - - // now we must create the output array + str.Inputs = 0; str.Outputs = 0; - if (this->GetNumberOfOutputPorts()) + + // create an array for input data objects + int numInputPorts = this->GetNumberOfInputPorts(); + if (numInputPorts) { - str.Outputs = new vtkImageData * [this->GetNumberOfOutputPorts()]; - for (i = 0; i < this->GetNumberOfOutputPorts(); ++i) + str.Inputs = new vtkImageData ** [numInputPorts]; + for (int i = 0; i < numInputPorts; i++) { - vtkInformation* info = outputVector->GetInformationObject(i); - vtkImageData *outData = vtkImageData::SafeDownCast( - info->Get(vtkDataObject::DATA_OBJECT())); - str.Outputs[i] = outData; - if (outData) - { - int updateExtent[6]; - info->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), - updateExtent); - - // unlike geometry filters, for image filters data is pre-allocated - // in the superclass (which means, in this class) - this->AllocateOutputData(outData, info, updateExtent); - } + int numConnections = inputVector[i]->GetNumberOfInformationObjects(); + str.Inputs[i] = new vtkImageData * [numConnections]; } } - // now create the inputs array - str.Inputs = 0; - if (this->GetNumberOfInputPorts()) + // create an array for output data objects + int numOutputPorts = this->GetNumberOfOutputPorts(); + if (numOutputPorts) { - str.Inputs = new vtkImageData ** [this->GetNumberOfInputPorts()]; - for (i = 0; i < this->GetNumberOfInputPorts(); ++i) - { - str.Inputs[i] = 0; - vtkInformationVector* portInfo = inputVector[i]; + str.Outputs = new vtkImageData * [numOutputPorts]; + } + + // allocate the output data and call CopyAttributeData + this->PrepareImageData(inputVector, outputVector, str.Inputs, str.Outputs); + + if (this->EnableSMP) + { + // SMP is enabled, use vtkSMPTools to thread the filter + int updateExtent[6] = { 0, -1, 0, -1, 0, -1 }; - if (portInfo->GetNumberOfInformationObjects()) + // need bytes per voxel to compute block size + int bytesPerVoxel = 1; + + // get the update extent from the output, if there is an output + if (numOutputPorts) + { + vtkImageData *outData = str.Outputs[0]; + if (outData) { - int j; - str.Inputs[i] = - new vtkImageData *[portInfo->GetNumberOfInformationObjects()]; - for (j = 0; j < portInfo->GetNumberOfInformationObjects(); ++j) + bytesPerVoxel = (outData->GetScalarSize() * + outData->GetNumberOfScalarComponents()); + outData->GetExtent(updateExtent); + } + } + else + { + // if no output, get update extent from the first input + for (int inPort = 0; inPort < numInputPorts; inPort++) + { + if (this->GetNumberOfInputConnections(inPort)) { - vtkInformation* info = portInfo->GetInformationObject(j); - str.Inputs[i][j] = vtkImageData::SafeDownCast( - info->Get(vtkDataObject::DATA_OBJECT())); + vtkImageData *inData = str.Inputs[inPort][0]; + if (inData) + { + bytesPerVoxel = (inData->GetScalarSize() * + inData->GetNumberOfScalarComponents()); + inData->GetExtent(updateExtent); + break; + } } } } - } - // copy other arrays - if (str.Inputs && str.Inputs[0] && str.Outputs) - { - this->CopyAttributeData(str.Inputs[0][0],str.Outputs[0],inputVector); - } + // verify that there is an extent for execution + if (updateExtent[0] <= updateExtent[1] && + updateExtent[2] <= updateExtent[3] && + updateExtent[4] <= updateExtent[5]) + { + // compute a reasonable number of pieces, this will be a multiple of + // the number of available threads and relative to the data size + vtkTypeInt64 bytesize = ( + static_cast(updateExtent[1] - updateExtent[0] + 1)* + static_cast(updateExtent[3] - updateExtent[2] + 1)* + static_cast(updateExtent[5] - updateExtent[4] + 1)* + bytesPerVoxel); + vtkTypeInt64 bytesPerPiece = this->DesiredBytesPerPiece; + vtkIdType pieces = vtkSMPTools::GetEstimatedNumberOfThreads(); + if (bytesPerPiece > 0 && bytesPerPiece < bytesize) + { + vtkTypeInt64 b = pieces*bytesPerPiece; + pieces *= (bytesize + b - 1)/b; + } + // do a dummy execution of SplitExtent to compute the number of pieces + int subExtent[6]; + pieces = this->SplitExtent(subExtent, updateExtent, 0, pieces); - this->Threader->SetNumberOfThreads(this->NumberOfThreads); - this->Threader->SetSingleMethod(vtkThreadedImageAlgorithmThreadedExecute, &str); + // always shut off debugging to avoid threading problems with GetMacros + bool debug = this->Debug; + this->Debug = false; - // always shut off debugging to avoid threading problems with GetMacros - bool debug = this->Debug; - this->Debug = false; - this->Threader->SingleMethodExecute(); - this->Debug = debug; + vtkThreadedImageAlgorithmFunctor functor( + this, request, inputVector, outputVector, + str.Inputs, str.Outputs, updateExtent, pieces); + + vtkSMPTools::For(0, pieces, functor); + + this->Debug = debug; + } + } + else + { + // if SMP is not enabled, use the vtkMultiThreader + this->Threader->SetNumberOfThreads(this->NumberOfThreads); + this->Threader->SetSingleMethod(vtkThreadedImageAlgorithmThreadedExecute, &str); + // always shut off debugging to avoid threading problems with GetMacros + bool debug = this->Debug; + this->Debug = false; + this->Threader->SingleMethodExecute(); + this->Debug = debug; + } // free up the arrays - for (i = 0; i < this->GetNumberOfInputPorts(); ++i) + for (int i = 0; i < numInputPorts; i++) { delete [] str.Inputs[i]; } @@ -333,4 +754,3 @@ void vtkThreadedImageAlgorithm::ThreadedExecute( (void)threadId; vtkErrorMacro("Subclass should override this method!!!"); } - diff --git a/Common/ExecutionModel/vtkThreadedImageAlgorithm.h b/Common/ExecutionModel/vtkThreadedImageAlgorithm.h index ba2b43712bc..c05678f9c69 100644 --- a/Common/ExecutionModel/vtkThreadedImageAlgorithm.h +++ b/Common/ExecutionModel/vtkThreadedImageAlgorithm.h @@ -55,7 +55,44 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkThreadedImageAlgorithm : public vtkImage int extent[6], int threadId); // Description: - // Get/Set the number of threads to create when rendering + // Enable/Disable SMP for threading. + vtkGetMacro(EnableSMP, bool); + vtkSetMacro(EnableSMP, bool); + + // Description: + // Global Disable SMP for all derived Imaging filters. + static void SetGlobalDefaultEnableSMP(bool enable); + static bool GetGlobalDefaultEnableSMP(); + + // Description: + // The minimum piece size when volume is split for execution. + // By default, the minimum size is (16,1,1). + vtkSetVector3Macro(MinimumPieceSize, int); + vtkGetVector3Macro(MinimumPieceSize, int); + + // Description: + // The desired bytes per piece when volume is split for execution. + // When SMP is enabled, this is used to subdivide the volume into pieces. + // Smaller pieces allow for better dynamic load balancing, but increase + // the total overhead. The default is 65536 bytes. + vtkSetMacro(DesiredBytesPerPiece, vtkIdType); + vtkGetMacro(DesiredBytesPerPiece, vtkIdType); + + // Description: + // Set the method used to divide the volume into pieces. + // Slab mode splits the volume along the Z direction first, + // Beam mode splits evenly along the Z and Y directions, and + // Block mode splits evenly along all three directions. + // Most filters use Slab mode as the default. + vtkSetClampMacro(SplitMode, int, 0, 2); + void SetSplitModeToSlab() { this->SetSplitMode(SLAB); } + void SetSplitModeToBeam() { this->SetSplitMode(BEAM); } + void SetSplitModeToBlock() { this->SetSplitMode(BLOCK); } + vtkGetMacro(SplitMode, int); + + // Description: + // Get/Set the number of threads to create when rendering. + // This is ignored if EnableSMP is On. vtkSetClampMacro( NumberOfThreads, int, 1, VTK_MAX_THREADS ); vtkGetMacro( NumberOfThreads, int ); @@ -71,6 +108,22 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkThreadedImageAlgorithm : public vtkImage vtkMultiThreader *Threader; int NumberOfThreads; + bool EnableSMP; + static bool GlobalDefaultEnableSMP; + + enum SplitModeEnum + { + SLAB = 0, + BEAM = 1, + BLOCK = 2 + }; + + int SplitMode; + int SplitPath[3]; + int SplitPathLength; + int MinimumPieceSize[3]; + vtkIdType DesiredBytesPerPiece; + // Description: // This is called by the superclass. // This is the method you should override. @@ -78,16 +131,34 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkThreadedImageAlgorithm : public vtkImage vtkInformationVector** inputVector, vtkInformationVector* outputVector); + // Description: + // Execute ThreadedRequestData for the given set of pieces. + // The extent will be broken into the number of pieces specified, + // and ThreadedRequestData will be called for all pieces starting + // at "begin" and up to but not including "end". + virtual void SMPRequestData(vtkInformation *request, + vtkInformationVector **inputVector, + vtkInformationVector *outputVector, + vtkImageData ***inData, + vtkImageData **outData, + vtkIdType begin, vtkIdType end, + vtkIdType pieces, int extent[6]); + + // Description: + // Allocate space for output data and copy attributes from first input. + // If the inDataObjects and outDataObjects are not passed as zero, then + // they must be large enough to store the data objects for all inputs and + // outputs. + virtual void PrepareImageData(vtkInformationVector **inputVector, + vtkInformationVector *outputVector, + vtkImageData ***inDataObjects=0, + vtkImageData **outDataObjects=0); + private: vtkThreadedImageAlgorithm(const vtkThreadedImageAlgorithm&); // Not implemented. void operator=(const vtkThreadedImageAlgorithm&); // Not implemented. + + friend class vtkThreadedImageAlgorithmFunctor; }; #endif - - - - - - - diff --git a/Common/ExecutionModel/vtkTrivialProducer.h b/Common/ExecutionModel/vtkTrivialProducer.h index 9c730186b4c..f6e070828c9 100644 --- a/Common/ExecutionModel/vtkTrivialProducer.h +++ b/Common/ExecutionModel/vtkTrivialProducer.h @@ -80,7 +80,7 @@ class VTKCOMMONEXECUTIONMODEL_EXPORT vtkTrivialProducer : public vtkAlgorithm int WholeExtent[6]; - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; private: vtkTrivialProducer(const vtkTrivialProducer&); // Not implemented. void operator=(const vtkTrivialProducer&); // Not implemented. diff --git a/Common/Math/Testing/Cxx/TestQuaternion.cxx b/Common/Math/Testing/Cxx/TestQuaternion.cxx index 360a6c48698..64f0357cb53 100644 --- a/Common/Math/Testing/Cxx/TestQuaternion.cxx +++ b/Common/Math/Testing/Cxx/TestQuaternion.cxx @@ -381,7 +381,7 @@ int TestQuaternionConversions() //this test uses vtkQuaterniond // Logarithm vtkQuaterniond logQuat; logQuat = quat.UnitLog(); - if (!(logQuat.Compare(vtkQuaterniond(0, -0.378151, 0.252101, 0.00012), + if (!(logQuat.Compare(vtkQuaterniond(0, -0.19628, 0.13085, 0.00007), 0.00001))) { std::cerr << "Error vtkQuaterniond UnitLogQuaternion() failed: " @@ -391,7 +391,7 @@ int TestQuaternionConversions() //this test uses vtkQuaterniond // Exponential vtkQuaterniond expQuat = quat.UnitExp(); - if (!(expQuat.Compare(vtkQuaterniond(0.89075, -0.37815, 0.25210, 0.00012), + if (!(expQuat.Compare(vtkQuaterniond(-0.89429, 0.37234, -0.24822, -0.00012), 0.00001))) { std::cerr << "Error vtkQuaterniond UnitExpQuaternion() failed: " @@ -399,6 +399,15 @@ int TestQuaternionConversions() //this test uses vtkQuaterniond ++retVal; } + // UnitExp(UnitLog(q)) on a normalized quaternion is an identity operation + vtkQuaterniond normQuat = quat.Normalized(); + if (!(normQuat.Compare(logQuat.UnitExp(), 0.00001))) + { + std::cerr << "Error vtkQuaterniond UnitExp(UnitLog(q)) is not identity: " + << logQuat.UnitExp() << " vs. " << normQuat << std::endl; + ++retVal; + } + //To VTK vtkQuaterniond vtkQuat = quat.NormalizedWithAngleInDegrees(); if (!(vtkQuat.Compare( diff --git a/Common/Math/vtkAmoebaMinimizer.h b/Common/Math/vtkAmoebaMinimizer.h index bc7bc7d70ae..405c78ec4bd 100644 --- a/Common/Math/vtkAmoebaMinimizer.h +++ b/Common/Math/vtkAmoebaMinimizer.h @@ -154,11 +154,9 @@ class VTKCOMMONMATH_EXPORT vtkAmoebaMinimizer : public vtkObject vtkAmoebaMinimizer(); ~vtkAmoebaMinimizer(); -//BTX void (*Function)(void *); void (*FunctionArgDelete)(void *); void *FunctionArg; -//ETX int NumberOfParameters; char **ParameterNames; @@ -177,7 +175,7 @@ class VTKCOMMONMATH_EXPORT vtkAmoebaMinimizer : public vtkObject private: // specific to amoeba simplex minimization -//BTX + double **AmoebaVertices; double *AmoebaValues; double *AmoebaSum; @@ -191,7 +189,6 @@ class VTKCOMMONMATH_EXPORT vtkAmoebaMinimizer : public vtkObject double TryAmoeba(double sum[], int high, double fac); int PerformAmoeba(); int CheckParameterTolerance(); -//ETX vtkAmoebaMinimizer(const vtkAmoebaMinimizer&); // Not implemented. void operator=(const vtkAmoebaMinimizer&); // Not implemented. diff --git a/Common/Math/vtkInitialValueProblemSolver.h b/Common/Math/vtkInitialValueProblemSolver.h index df059917583..81053fb19d6 100644 --- a/Common/Math/vtkInitialValueProblemSolver.h +++ b/Common/Math/vtkInitialValueProblemSolver.h @@ -103,14 +103,12 @@ class VTKCOMMONMATH_EXPORT vtkInitialValueProblemSolver : public vtkObject // 0 otherwise virtual int IsAdaptive() { return this->Adaptive; } -//BTX enum ErrorCodes { OUT_OF_DOMAIN = 1, NOT_INITIALIZED = 2, UNEXPECTED_VALUE = 3 }; -//ETX protected: vtkInitialValueProblemSolver(); diff --git a/Common/Math/vtkQuaternion.h b/Common/Math/vtkQuaternion.h index 39bd1cde951..136bac6031f 100644 --- a/Common/Math/vtkQuaternion.h +++ b/Common/Math/vtkQuaternion.h @@ -100,13 +100,13 @@ template class vtkQuaternion : public vtkTuple // Description: // Convert this quaternion to a unit log quaternion. // The unit log quaternion is defined by: - // [w, x, y, z] = [0.0, v*sin(theta)]. + // [w, x, y, z] = [0.0, v*theta]. void ToUnitLog(); // Description: // Return the unit log version of this quaternion. // The unit log quaternion is defined by: - // [w, x, y, z] = [0.0, v*sin(theta)]. + // [w, x, y, z] = [0.0, v*theta]. vtkQuaternion UnitLog() const; // Description: diff --git a/Common/Math/vtkQuaternion.txx b/Common/Math/vtkQuaternion.txx index fe079171135..1c79734f15d 100644 --- a/Common/Math/vtkQuaternion.txx +++ b/Common/Math/vtkQuaternion.txx @@ -221,25 +221,27 @@ template const T& vtkQuaternion::GetZ() const template T vtkQuaternion::GetRotationAngleAndAxis(T axis[3]) const { - vtkQuaternion normedQuat(*this); - normedQuat.Normalize(); - - T angle = acos(normedQuat.GetW()) * 2.0; - T f = sin( angle * 0.5 ); + T w = this->GetW(); + T x = this->GetX(); + T y = this->GetY(); + T z = this->GetZ(); + T f = sqrt(x*x + y*y + z*z); if (f != 0.0) { - axis[0] = normedQuat.GetX() / f; - axis[1] = normedQuat.GetY() / f; - axis[2] = normedQuat.GetZ() / f; + axis[0] = x / f; + axis[1] = y / f; + axis[2] = z / f; } else { + w = 1.0; axis[0] = 0.0; axis[1] = 0.0; axis[2] = 0.0; } - return angle; + // atan2() provides a more accurate angle result than acos() + return 2.0*atan2(f, w); } //---------------------------------------------------------------------------- @@ -259,17 +261,16 @@ vtkQuaternion::SetRotationAngleAndAxis (const T& angle, T axisNorm = x*x + y*y + z*z; if (axisNorm != 0.0) { - T w = cos(angle / 2.0); - this->SetW(w); - - T f = sin( angle / 2.0); + T f = sin(0.5*angle); + this->SetW(cos(0.5*angle)); this->SetX((x / axisNorm) * f); this->SetY((y / axisNorm) * f); this->SetZ((z / axisNorm) * f); } else { - this->Set(0.0, 0.0, 0.0, 0.0); + // set the quaternion for "no rotation" + this->Set(1.0, 0.0, 0.0, 0.0); } } @@ -473,25 +474,24 @@ template void vtkQuaternion::FromMatrix3x3(const T A[3][3]) template vtkQuaternion vtkQuaternion ::Slerp(T t, const vtkQuaternion& q1) const { - T axis0[3], axis1[3]; + T axis0[3], axis1[3], cross[3]; this->GetRotationAngleAndAxis(axis0); q1.GetRotationAngleAndAxis(axis1); const T dot = vtkMath::Dot(axis0, axis1); - double t1, t2; + vtkMath::Cross(axis0, axis1, cross); + const T f = vtkMath::Norm(cross); // To avoid division by zero, perform a linear interpolation (LERP), if our // quarternions are nearly in the same direction, otherwise resort // to spherical linear interpolation. In the limiting case (for small // angles), SLERP is equivalent to LERP. - if ((1.0 - fabs(dot)) < 1e-6) - { - t1 = 1.0-t; - t2 = t; - } - else + T t1 = 1.0-t; + T t2 = t; + + if (f > 1e-6) { - const T theta = acos( dot ); + const T theta = atan2(f, dot); t1 = sin((1.0-t)*theta)/sin(theta); t2 = sin(t*theta)/sin(theta); } @@ -522,10 +522,9 @@ template vtkQuaternion vtkQuaternion template void vtkQuaternion::ToUnitLog() { T axis[3]; - T angle = this->GetRotationAngleAndAxis(axis); - T sinAngle = sin(angle); + T angle = 0.5*this->GetRotationAngleAndAxis(axis); - this->Set(0.0, sinAngle*axis[0], sinAngle*axis[1], sinAngle*axis[2]); + this->Set(0.0, angle*axis[0], angle*axis[1], angle*axis[2]); } //---------------------------------------------------------------------------- @@ -539,11 +538,20 @@ template vtkQuaternion vtkQuaternion::UnitLog() const //---------------------------------------------------------------------------- template void vtkQuaternion::ToUnitExp() { - T axis[3]; - T angle = this->GetRotationAngleAndAxis(axis); + T x = this->GetX(); + T y = this->GetY(); + T z = this->GetZ(); + T angle = sqrt(x*x + y*y + z*z); T sinAngle = sin(angle); + T cosAngle = cos(angle); + if (angle != 0.0) + { + x /= angle; + y /= angle; + z /= angle; + } - this->Set(cos(angle), sinAngle*axis[0], sinAngle*axis[1], sinAngle*axis[2]); + this->Set(cosAngle, sinAngle*x, sinAngle*y, sinAngle*z); } //---------------------------------------------------------------------------- diff --git a/Common/Math/vtkQuaternionInterpolator.h b/Common/Math/vtkQuaternionInterpolator.h index 51bbcf2e6cf..f7879764e31 100644 --- a/Common/Math/vtkQuaternionInterpolator.h +++ b/Common/Math/vtkQuaternionInterpolator.h @@ -106,13 +106,11 @@ class VTKCOMMONMATH_EXPORT vtkQuaternionInterpolator : public vtkObject void InterpolateQuaternion(double t, vtkQuaterniond& q); void InterpolateQuaternion(double t, double q[4]); -//BTX // Description: // Enums to control the type of interpolation to use. enum {INTERPOLATION_TYPE_LINEAR=0, INTERPOLATION_TYPE_SPLINE }; -//ETX // Description: // Specify which type of function to use for interpolation. By default diff --git a/Common/Math/vtkRungeKutta45.cxx b/Common/Math/vtkRungeKutta45.cxx index 571a242ef29..63fbc8010e6 100644 --- a/Common/Math/vtkRungeKutta45.cxx +++ b/Common/Math/vtkRungeKutta45.cxx @@ -196,7 +196,6 @@ int vtkRungeKutta45::ComputeNextStep(double* xprev, double* dxprev, } } - delTActual = delT; return 0; } diff --git a/Common/Misc/vtkErrorCode.h b/Common/Misc/vtkErrorCode.h index 38124a16d83..bc8532c9799 100644 --- a/Common/Misc/vtkErrorCode.h +++ b/Common/Misc/vtkErrorCode.h @@ -29,7 +29,7 @@ class VTKCOMMONMISC_EXPORT vtkErrorCode static const char *GetStringFromErrorCode(unsigned long event); static unsigned long GetErrorCodeFromString(const char *event); static unsigned long GetLastSystemError(); -//BTX + // all the currently defined error codes // developers can use -- vtkErrorCode::UserError + int to // specify their own errors. @@ -48,7 +48,7 @@ class VTKCOMMONMISC_EXPORT vtkErrorCode UnknownError, UserError = 40000 }; -//ETX + }; #endif /* vtkErrorCode_h */ diff --git a/Common/Misc/vtkFunctionParser.cxx b/Common/Misc/vtkFunctionParser.cxx index 48222b1db42..f2535d41e80 100644 --- a/Common/Misc/vtkFunctionParser.cxx +++ b/Common/Misc/vtkFunctionParser.cxx @@ -16,6 +16,7 @@ #include "vtkObjectFactory.h" #include +#include vtkStandardNewMacro(vtkFunctionParser); @@ -25,12 +26,6 @@ static double vtkParserVectorErrorResult[3] = { VTK_PARSER_ERROR_RESULT, //----------------------------------------------------------------------------- vtkFunctionParser::vtkFunctionParser() { - this->NumberOfScalarVariables = 0; - this->NumberOfVectorVariables = 0; - this->ScalarVariableNames = NULL; - this->VectorVariableNames = NULL; - this->ScalarVariableValues = NULL; - this->VectorVariableValues = NULL; this->Function = NULL; this->FunctionWithSpaces = NULL; this->ByteCode = NULL; @@ -57,44 +52,6 @@ vtkFunctionParser::vtkFunctionParser() //----------------------------------------------------------------------------- vtkFunctionParser::~vtkFunctionParser() { - int i; - - if (this->ScalarVariableNames) - { - for (i = 0; i < this->NumberOfScalarVariables; i++) - { - delete [] this->ScalarVariableNames[i]; - this->ScalarVariableNames[i] = NULL; - } - delete [] this->ScalarVariableNames; - this->ScalarVariableNames = NULL; - } - - if (this->VectorVariableNames) - { - for (i = 0; i < this->NumberOfVectorVariables; i++) - { - delete [] this->VectorVariableNames[i]; - this->VectorVariableNames[i] = NULL; - } - delete [] this->VectorVariableNames; - this->VectorVariableNames = NULL; - } - - delete [] this->ScalarVariableValues; - this->ScalarVariableValues = NULL; - - if (this->VectorVariableValues) - { - for (i = 0; i < this->NumberOfVectorVariables; i++) - { - delete [] this->VectorVariableValues[i]; - this->VectorVariableValues[i] = NULL; - } - delete [] this->VectorVariableValues; - this->VectorVariableValues = NULL; - } - delete [] this->Function; this->Function = NULL; @@ -145,6 +102,8 @@ void vtkFunctionParser::SetFunction(const char *function) } this->FunctionMTime.Modified(); + this->ScalarVariableNeeded.clear(); + this->VectorVariableNeeded.clear(); this->Modified(); } @@ -185,7 +144,7 @@ int vtkFunctionParser::Parse() for (i = 0; i < this->ByteCodeSize; i++) { if ((this->ByteCode[i] >= VTK_PARSER_BEGIN_VARIABLES + - this->NumberOfScalarVariables) || + this->GetNumberOfScalarVariables()) || (this->ByteCode[i] == VTK_PARSER_IHAT) || (this->ByteCode[i] == VTK_PARSER_JHAT) || (this->ByteCode[i] == VTK_PARSER_KHAT)) @@ -204,6 +163,9 @@ int vtkFunctionParser::Parse() } } + // Collect meta-data about variables that are needed for evaluation of the + // function. + this->UpdateNeededVariables(); this->ParseMTime.Modified(); return 1; } @@ -439,8 +401,7 @@ int vtkFunctionParser::DisambiguateOperators() tempStackPtr--; break; default: - if ((this->ByteCode[i] - VTK_PARSER_BEGIN_VARIABLES) < - this->NumberOfScalarVariables) + if ((this->ByteCode[i] - VTK_PARSER_BEGIN_VARIABLES) < this->GetNumberOfScalarVariables()) { tempStackPtr++; tempStack[tempStackPtr] = 0; @@ -876,7 +837,7 @@ bool vtkFunctionParser::Evaluate() } default: if ((this->ByteCode[numBytesProcessed] - - VTK_PARSER_BEGIN_VARIABLES) < this->NumberOfScalarVariables) + VTK_PARSER_BEGIN_VARIABLES) < this->GetNumberOfScalarVariables()) { this->Stack[++stackPosition] = this->ScalarVariableValues[this->ByteCode[numBytesProcessed] - @@ -885,7 +846,7 @@ bool vtkFunctionParser::Evaluate() else { int vectorNum = this->ByteCode[numBytesProcessed] - - VTK_PARSER_BEGIN_VARIABLES - this->NumberOfScalarVariables; + VTK_PARSER_BEGIN_VARIABLES - this->GetNumberOfScalarVariables(); this->Stack[++stackPosition] = this->VectorVariableValues[vectorNum][0]; this->Stack[++stackPosition] = @@ -948,21 +909,21 @@ double *vtkFunctionParser::GetVectorResult() } //----------------------------------------------------------------------------- -char* vtkFunctionParser::GetScalarVariableName(int i) +const char* vtkFunctionParser::GetScalarVariableName(int i) { - if (i >= 0 && i < this->NumberOfScalarVariables) + if (i >= 0 && i < this->GetNumberOfScalarVariables()) { - return this->ScalarVariableNames[i]; + return this->ScalarVariableNames[i].c_str(); } return NULL; } //----------------------------------------------------------------------------- -char* vtkFunctionParser::GetVectorVariableName(int i) +const char* vtkFunctionParser::GetVectorVariableName(int i) { - if (i >= 0 && i < this->NumberOfVectorVariables) + if (i >= 0 && i < this->GetNumberOfVectorVariables()) { - return this->VectorVariableNames[i]; + return this->VectorVariableNames[i].c_str(); } return NULL; } @@ -970,20 +931,18 @@ char* vtkFunctionParser::GetVectorVariableName(int i) //----------------------------------------------------------------------------- int vtkFunctionParser::IsVariableName(int currentIndex) { - int i; - - for (i = 0; i < this->NumberOfScalarVariables; i++) + for (int i = 0, max = this->GetNumberOfScalarVariables(); i < max; i++) { - if (strncmp(this->ScalarVariableNames[i], &this->Function[currentIndex], - strlen(this->ScalarVariableNames[i])) == 0) + if (strncmp(this->ScalarVariableNames[i].c_str(), &this->Function[currentIndex], + this->ScalarVariableNames[i].size()) == 0) { return 1; } } - for (i = 0; i < this->NumberOfVectorVariables; i++) + for (int i = 0, max = this->GetNumberOfVectorVariables(); i < max; i++) { - if (strncmp(this->VectorVariableNames[i], &this->Function[currentIndex], - strlen(this->VectorVariableNames[i])) == 0) + if (strncmp(this->VectorVariableNames[i].c_str(), &this->Function[currentIndex], + this->VectorVariableNames[i].size()) == 0) { return 1; } @@ -1002,14 +961,10 @@ int vtkFunctionParser::IsElementaryOperator(int op) void vtkFunctionParser::SetScalarVariableValue(const char* inVariableName, double value) { - int i; - double *tempValues; - char** tempNames; char* variableName = this->RemoveSpacesFrom(inVariableName); - - for (i = 0; i < this->NumberOfScalarVariables; i++) + for (int i = 0, max = this->GetNumberOfScalarVariables(); i < max; i++) { - if (strcmp(variableName, this->ScalarVariableNames[i]) == 0) + if (strcmp(variableName, this->ScalarVariableNames[i].c_str()) == 0) { if (this->ScalarVariableValues[i] != value) { @@ -1021,42 +976,8 @@ void vtkFunctionParser::SetScalarVariableValue(const char* inVariableName, return; } } - - tempValues = new double [this->NumberOfScalarVariables]; - tempNames = new char *[this->NumberOfScalarVariables]; - for (i = 0; i < this->NumberOfScalarVariables; i++) - { - tempValues[i] = this->ScalarVariableValues[i]; - tempNames[i] = new char [strlen(this->ScalarVariableNames[i]) + 1]; - strcpy(tempNames[i], this->ScalarVariableNames[i]); - delete [] this->ScalarVariableNames[i]; - this->ScalarVariableNames[i] = NULL; - } - - delete [] this->ScalarVariableValues; - this->ScalarVariableValues = NULL; - - delete [] this->ScalarVariableNames; - this->ScalarVariableNames = NULL; - - this->ScalarVariableValues = new double [this->NumberOfScalarVariables + 1]; - this->ScalarVariableNames = new char *[this->NumberOfScalarVariables + 1]; - for (i = 0; i < this->NumberOfScalarVariables; i++) - { - this->ScalarVariableValues[i] = tempValues[i]; - this->ScalarVariableNames[i] = new char [strlen(tempNames[i]) + 1]; - strcpy(this->ScalarVariableNames[i], tempNames[i]); - delete [] tempNames[i]; - tempNames[i] = NULL; - } - delete [] tempValues; - delete [] tempNames; - - this->ScalarVariableValues[i] = value; - this->ScalarVariableNames[i] = new char [strlen(variableName) + 1]; - strcpy(this->ScalarVariableNames[i], variableName); - this->NumberOfScalarVariables++; - + this->ScalarVariableValues.push_back(value); + this->ScalarVariableNames.push_back(variableName); this->VariableMTime.Modified(); this->Modified(); delete [] variableName; @@ -1065,7 +986,7 @@ void vtkFunctionParser::SetScalarVariableValue(const char* inVariableName, //----------------------------------------------------------------------------- void vtkFunctionParser::SetScalarVariableValue(int i, double value) { - if (i < 0 || i >= this->NumberOfScalarVariables) + if (i < 0 || i >= this->GetNumberOfScalarVariables()) { return; } @@ -1081,12 +1002,10 @@ void vtkFunctionParser::SetScalarVariableValue(int i, double value) //----------------------------------------------------------------------------- double vtkFunctionParser::GetScalarVariableValue(const char* inVariableName) { - int i; char* variableName = this->RemoveSpacesFrom(inVariableName); - - for (i = 0; i < this->NumberOfScalarVariables; i++) + for (int i = 0, max = this->GetNumberOfScalarVariables(); i < max; i++) { - if (strcmp(variableName, this->ScalarVariableNames[i]) == 0) + if (strcmp(variableName, this->ScalarVariableNames[i].c_str()) == 0) { delete [] variableName; return this->ScalarVariableValues[i]; @@ -1101,7 +1020,7 @@ double vtkFunctionParser::GetScalarVariableValue(const char* inVariableName) //----------------------------------------------------------------------------- double vtkFunctionParser::GetScalarVariableValue(int i) { - if (i < 0 || i >= this->NumberOfScalarVariables) + if (i < 0 || i >= this->GetNumberOfScalarVariables()) { vtkErrorMacro("GetScalarVariableValue: scalar variable number " << i << " does not exist"); @@ -1116,14 +1035,10 @@ void vtkFunctionParser::SetVectorVariableValue(const char* inVariableName, double xValue, double yValue, double zValue) { - int i; - double **tempValues; - char** tempNames; char* variableName = this->RemoveSpacesFrom(inVariableName); - - for (i = 0; i < this->NumberOfVectorVariables; i++) + for (int i = 0, max = this->GetNumberOfVectorVariables(); i < max; i++) { - if (strcmp(variableName, this->VectorVariableNames[i]) == 0) + if (strcmp(variableName, this->VectorVariableNames[i].c_str()) == 0) { if (this->VectorVariableValues[i][0] != xValue || this->VectorVariableValues[i][1] != yValue || @@ -1140,53 +1055,12 @@ void vtkFunctionParser::SetVectorVariableValue(const char* inVariableName, } } - tempValues = new double *[this->NumberOfVectorVariables]; - tempNames = new char *[this->NumberOfVectorVariables]; - for (i = 0; i < this->NumberOfVectorVariables; i++) - { - tempValues[i] = new double[3]; - tempValues[i][0] = this->VectorVariableValues[i][0]; - tempValues[i][1] = this->VectorVariableValues[i][1]; - tempValues[i][2] = this->VectorVariableValues[i][2]; - tempNames[i] = new char [strlen(this->VectorVariableNames[i]) + 1]; - strcpy(tempNames[i], this->VectorVariableNames[i]); - delete [] this->VectorVariableNames[i]; - this->VectorVariableNames[i] = NULL; - delete [] this->VectorVariableValues[i]; - this->VectorVariableValues[i] = NULL; - } - - delete [] this->VectorVariableValues; - this->VectorVariableValues = NULL; - - delete [] this->VectorVariableNames; - this->VectorVariableNames = NULL; - - this->VectorVariableValues = new double *[this->NumberOfVectorVariables + 1]; - this->VectorVariableNames = new char *[this->NumberOfVectorVariables + 1]; - for (i = 0; i < this->NumberOfVectorVariables; i++) - { - this->VectorVariableValues[i] = new double[3]; - this->VectorVariableValues[i][0] = tempValues[i][0]; - this->VectorVariableValues[i][1] = tempValues[i][1]; - this->VectorVariableValues[i][2] = tempValues[i][2]; - this->VectorVariableNames[i] = new char [strlen(tempNames[i]) + 1]; - strcpy(this->VectorVariableNames[i], tempNames[i]); - delete [] tempNames[i]; - tempNames[i] = NULL; - delete [] tempValues[i]; - tempValues[i] = NULL; - } - delete [] tempValues; - delete [] tempNames; - - this->VectorVariableValues[i] = new double[3]; - this->VectorVariableValues[i][0] = xValue; - this->VectorVariableValues[i][1] = yValue; - this->VectorVariableValues[i][2] = zValue; - this->VectorVariableNames[i] = new char [strlen(variableName) + 1]; - strcpy(this->VectorVariableNames[i], variableName); - this->NumberOfVectorVariables++; + this->VectorVariableNames.push_back(variableName); + vtkTuple val; + val[0] = xValue; + val[1] = yValue; + val[2] = zValue; + this->VectorVariableValues.push_back(val); this->VariableMTime.Modified(); this->Modified(); @@ -1197,7 +1071,7 @@ void vtkFunctionParser::SetVectorVariableValue(const char* inVariableName, void vtkFunctionParser::SetVectorVariableValue(int i, double xValue, double yValue, double zValue) { - if (i < 0 || i >= this->NumberOfVectorVariables) + if (i < 0 || i >= this->GetNumberOfVectorVariables()) { return; } @@ -1216,15 +1090,14 @@ void vtkFunctionParser::SetVectorVariableValue(int i, double xValue, //----------------------------------------------------------------------------- double* vtkFunctionParser::GetVectorVariableValue(const char* inVariableName) { - int i; char* variableName = this->RemoveSpacesFrom(inVariableName); - for (i = 0; i < this->NumberOfVectorVariables; i++) + for (int i = 0, max = this->GetNumberOfVectorVariables(); i < max; i++) { - if (strcmp(variableName, this->VectorVariableNames[i]) == 0) + if (strcmp(variableName, this->VectorVariableNames[i].c_str()) == 0) { delete [] variableName; - return this->VectorVariableValues[i]; + return this->VectorVariableValues[i].GetData(); } } vtkErrorMacro("GetVectorVariableValue: vector variable name " << variableName @@ -1236,13 +1109,13 @@ double* vtkFunctionParser::GetVectorVariableValue(const char* inVariableName) //----------------------------------------------------------------------------- double* vtkFunctionParser::GetVectorVariableValue(int i) { - if (i < 0 || i >= this->NumberOfVectorVariables) + if (i < 0 || i >= this->GetNumberOfVectorVariables()) { vtkErrorMacro("GetVectorVariableValue: vector variable number " << i << " does not exist"); return vtkParserVectorErrorResult; } - return this->VectorVariableValues[i]; + return this->VectorVariableValues[i].GetData(); } //----------------------------------------------------------------------------- @@ -1295,20 +1168,20 @@ int vtkFunctionParser::OperatorWithinVariable(int idx) { char *tmpString = NULL; - for ( int i = 0; i < this->NumberOfScalarVariables; i ++ ) + for ( int i = 0, max = this->GetNumberOfScalarVariables(); i < max; i ++ ) { int end = 0; - if ( strchr( this->ScalarVariableNames[i], this->Function[idx] ) != 0 ) + if ( strchr( this->ScalarVariableNames[i].c_str(), this->Function[idx] ) != 0 ) { - if ( ( tmpString = strstr( this->Function, this->ScalarVariableNames[i] ) ) ) + if ( ( tmpString = strstr( this->Function, this->ScalarVariableNames[i].c_str() ) ) ) { do { if (tmpString) { int start = static_cast(tmpString - this->Function); - end = start + static_cast( strlen(this->ScalarVariableNames[i]) ); + end = start + static_cast( this->ScalarVariableNames[i].size() ); // the variable being investigated does contain an operator (at idx) if ( start <= idx && idx <= end ) return 1; @@ -1317,7 +1190,7 @@ int vtkFunctionParser::OperatorWithinVariable(int idx) // variable name (being investigated) preceding "idx" in this->Function[] // As suggested by 7islands, a greedy search is used here if ( end <= idx ) // to save strstr() whenever possible - tmpString = strstr( this->Function + end, this->ScalarVariableNames[i] ); + tmpString = strstr( this->Function + end, this->ScalarVariableNames[i].c_str() ); } else break; } while ( end <= idx ); @@ -1325,20 +1198,20 @@ int vtkFunctionParser::OperatorWithinVariable(int idx) } } - for ( int i = 0; i < this->NumberOfVectorVariables; i ++ ) + for ( int i = 0, max = this->GetNumberOfVectorVariables(); i < max; i ++ ) { int end = 0; - if ( strchr( this->VectorVariableNames[i], this->Function[idx] ) != 0 ) + if ( strchr( this->VectorVariableNames[i].c_str(), this->Function[idx] ) != 0 ) { - if ( ( tmpString = strstr( this->Function, this->VectorVariableNames[i] ) ) ) + if ( ( tmpString = strstr( this->Function, this->VectorVariableNames[i].c_str() ) ) ) { do { if (tmpString) { int start = static_cast(tmpString - this->Function); - end = start + static_cast( strlen(this->VectorVariableNames[i]) ); + end = start + static_cast( this->VectorVariableNames[i].size() ); // the variable being investigated does contain an operator (at idx) if ( start <= idx && idx <= end ) return 1; @@ -1347,7 +1220,7 @@ int vtkFunctionParser::OperatorWithinVariable(int idx) // variable name (being investigated) preceding "idx" in this->Function[] // As suggested by 7islands, a greedy search is used here if ( end <= idx ) // to save strstr() whenever possible - tmpString = strstr( this->Function + end, this->VectorVariableNames[i] ); + tmpString = strstr( this->Function + end, this->VectorVariableNames[i].c_str() ); } else break; } while ( end <= idx ); @@ -1925,15 +1798,15 @@ int vtkFunctionParser::GetMathConstantStringLength(int mathConstantNumber) //----------------------------------------------------------------------------- int vtkFunctionParser::GetVariableNameLength(int variableNumber) { - if (variableNumber < this->NumberOfScalarVariables) + if (variableNumber < this->GetNumberOfScalarVariables()) { - return static_cast(strlen(this->ScalarVariableNames[variableNumber])); + return static_cast(this->ScalarVariableNames[variableNumber].size()); } else { - return static_cast(strlen( + return static_cast( this->VectorVariableNames[variableNumber - - this->NumberOfScalarVariables])); + this->GetNumberOfScalarVariables()].size()); } } @@ -2010,13 +1883,13 @@ unsigned char vtkFunctionParser::GetElementaryOperatorNumber(char op) //----------------------------------------------------------------------------- unsigned char vtkFunctionParser::GetOperandNumber(int currentIndex) { - int i, variableIndex = -1; + int variableIndex = -1; if (isdigit(this->Function[currentIndex]) || this->Function[currentIndex] == '.') // Number { double *tempImmediates = new double[this->ImmediatesSize]; - for (i = 0; i < this->ImmediatesSize; i++) + for (int i = 0; i < this->ImmediatesSize; i++) { // Copy current immediates to a temporary array tempImmediates[i] = this->Immediates[i]; } @@ -2026,7 +1899,7 @@ unsigned char vtkFunctionParser::GetOperandNumber(int currentIndex) this->Immediates = new double[this->ImmediatesSize + 1]; // Copy contents of temporary array back to Immediates. - for (i = 0; i < this->ImmediatesSize; i++) + for (int i = 0; i < this->ImmediatesSize; i++) { this->Immediates[i] = tempImmediates[i]; } @@ -2057,15 +1930,15 @@ unsigned char vtkFunctionParser::GetOperandNumber(int currentIndex) //Bug 7396. If a scalar variable name is a subset of a vector var name it will //casue the scripting to crash. So instead of ending once we find a var name that matches in scalars //we will also check vectors - for (i = 0; i < this->NumberOfScalarVariables; i++) + for (int i = 0, max = this->GetNumberOfScalarVariables(); i < max; i++) { // Variable - if (strncmp(&this->Function[currentIndex], this->ScalarVariableNames[i], - strlen(this->ScalarVariableNames[i])) == 0) + if (strncmp(&this->Function[currentIndex], this->ScalarVariableNames[i].c_str(), + this->ScalarVariableNames[i].size()) == 0) { if (variableIndex == -1 || - strlen(this->ScalarVariableNames[i]) > currentLen ) + this->ScalarVariableNames[i].size() > currentLen ) { - currentLen = strlen(this->ScalarVariableNames[i]); + currentLen = this->ScalarVariableNames[i].size(); variableIndex = i; } } @@ -2075,16 +1948,16 @@ unsigned char vtkFunctionParser::GetOperandNumber(int currentIndex) scalarVar = true; } - for (i = 0; i < this->NumberOfVectorVariables; i++) + for (int i = 0, max = this->GetNumberOfVectorVariables(); i < max; i++) { // Variable - if (strncmp(&this->Function[currentIndex], this->VectorVariableNames[i], - strlen(this->VectorVariableNames[i])) == 0) + if (strncmp(&this->Function[currentIndex], this->VectorVariableNames[i].c_str(), + this->VectorVariableNames[i].size()) == 0) { if (variableIndex == -1 - || strlen(this->VectorVariableNames[i]) > currentLen ) + || this->VectorVariableNames[i].size() > currentLen ) { scalarVar = false; - currentLen = strlen(this->VectorVariableNames[i]); + currentLen = this->VectorVariableNames[i].size(); variableIndex = i; } } @@ -2092,8 +1965,7 @@ unsigned char vtkFunctionParser::GetOperandNumber(int currentIndex) if (variableIndex >= 0) { //add the offset if vector - variableIndex = (scalarVar)? - variableIndex:this->NumberOfScalarVariables + variableIndex; + variableIndex = scalarVar? variableIndex : (this->GetNumberOfScalarVariables() + variableIndex); return static_cast( VTK_PARSER_BEGIN_VARIABLES + variableIndex); } @@ -2104,43 +1976,15 @@ unsigned char vtkFunctionParser::GetOperandNumber(int currentIndex) //----------------------------------------------------------------------------- void vtkFunctionParser::RemoveScalarVariables() { - int i; - - for (i = 0; i < this->NumberOfScalarVariables; i++) - { - delete [] this->ScalarVariableNames[i]; - this->ScalarVariableNames[i] = NULL; - } - if (this->NumberOfScalarVariables > 0) - { - delete [] this->ScalarVariableNames; - this->ScalarVariableNames = NULL; - delete [] this->ScalarVariableValues; - this->ScalarVariableValues = NULL; - } - this->NumberOfScalarVariables = 0; + this->ScalarVariableNames.clear(); + this->ScalarVariableValues.clear(); } //----------------------------------------------------------------------------- void vtkFunctionParser::RemoveVectorVariables() { - int i; - - for (i = 0; i < this->NumberOfVectorVariables; i++) - { - delete [] this->VectorVariableNames[i]; - this->VectorVariableNames[i] = NULL; - delete [] this->VectorVariableValues[i]; - this->VectorVariableValues[i] = NULL; - } - if (this->NumberOfVectorVariables > 0) - { - delete [] this->VectorVariableNames; - this->VectorVariableNames = NULL; - delete [] this->VectorVariableValues; - this->VectorVariableValues = NULL; - } - this->NumberOfVectorVariables = 0; + this->VectorVariableNames.clear(); + this->VectorVariableValues.clear(); } //----------------------------------------------------------------------------- @@ -2482,7 +2326,6 @@ void vtkFunctionParser::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); - int i; os << indent << "Function: " << (this->GetFunction() ? this->GetFunction() : "(none)") << endl; @@ -2490,19 +2333,13 @@ void vtkFunctionParser::PrintSelf(ostream& os, vtkIndent indent) os << indent << "FunctionWithSpaces: " << (this->FunctionWithSpaces ? this->FunctionWithSpaces : "(none)") << endl; - os << indent << "NumberOfScalarVariables: " - << this->GetNumberOfScalarVariables() << endl; - - for (i = 0; i < this->NumberOfScalarVariables; i++) + for (int i = 0, max = this->GetNumberOfScalarVariables(); i < max; i++) { os << indent << " " << this->GetScalarVariableName(i) << ": " << this->GetScalarVariableValue(i) << endl; } - os << indent << "NumberOfVectorVariables: " - << this->GetNumberOfVectorVariables() << endl; - - for (i = 0; i < this->NumberOfVectorVariables; i++) + for (int i = 0, max = this->GetNumberOfVectorVariables(); i < max; i++) { os << indent << " " << this->GetVectorVariableName(i) << ": (" << this->GetVectorVariableValue(i)[0] << ", " @@ -2581,3 +2418,95 @@ int vtkFunctionParser::FindPositionInOriginalFunction(const int &pos) return origPos; } + +//----------------------------------------------------------------------------- +void vtkFunctionParser::UpdateNeededVariables() +{ + this->ScalarVariableNeeded.clear(); + this->ScalarVariableNeeded.resize(this->ScalarVariableNames.size(), false); + + this->VectorVariableNeeded.clear(); + this->VectorVariableNeeded.resize(this->VectorVariableNames.size(), false); + + unsigned char numscalars = static_cast(this->GetNumberOfScalarVariables()); + + for (int cc=0; cc < this->ByteCodeSize; ++cc) + { + unsigned char code = this->ByteCode[cc]; + if (code < VTK_PARSER_BEGIN_VARIABLES) + { + continue; + } + code -= VTK_PARSER_BEGIN_VARIABLES; + if (code >= numscalars) + { + this->VectorVariableNeeded[code - numscalars] = true; + } + else + { + this->ScalarVariableNeeded[code] = true; + } + } +} + +//----------------------------------------------------------------------------- +bool vtkFunctionParser::GetScalarVariableNeeded(int i) +{ + if (i < 0 || i >= static_cast(this->ScalarVariableNeeded.size())) + { + return false; + } + return this->ScalarVariableNeeded[i]; +} + +//----------------------------------------------------------------------------- +bool vtkFunctionParser::GetScalarVariableNeeded(const char* inVariableName) +{ + char* variableName = this->RemoveSpacesFrom(inVariableName); + std::vector::const_iterator iter = std::find( + this->ScalarVariableNames.begin(), this->ScalarVariableNames.end(), + std::string(variableName)); + delete [] variableName; + if (iter != this->ScalarVariableNames.end()) + { + return this->GetScalarVariableNeeded( + static_cast(iter - this->ScalarVariableNames.begin())); + } + else + { + vtkErrorMacro("GetScalarVariableNeeded: scalar variable name " << variableName + << " does not exist"); + return false; + } +} + +//----------------------------------------------------------------------------- +bool vtkFunctionParser::GetVectorVariableNeeded(int i) +{ + if (i < 0 || i >= static_cast(this->VectorVariableNeeded.size())) + { + return false; + } + return this->VectorVariableNeeded[i]; +} + +//----------------------------------------------------------------------------- +bool vtkFunctionParser::GetVectorVariableNeeded(const char* inVariableName) +{ + char* variableName = this->RemoveSpacesFrom(inVariableName); + std::vector::const_iterator iter = std::find( + this->VectorVariableNames.begin(), this->VectorVariableNames.end(), + std::string(variableName)); + delete [] variableName; + if (iter != this->VectorVariableNames.end()) + { + return this->GetVectorVariableNeeded( + static_cast(iter - this->VectorVariableNames.begin())); + } + else + { + vtkErrorMacro("GetVectorVariableNeeded: scalar variable name " << variableName + << " does not exist"); + return false; + } +} diff --git a/Common/Misc/vtkFunctionParser.h b/Common/Misc/vtkFunctionParser.h index 821b371e6b1..69985eca35f 100644 --- a/Common/Misc/vtkFunctionParser.h +++ b/Common/Misc/vtkFunctionParser.h @@ -43,6 +43,9 @@ #include "vtkCommonMiscModule.h" // For export macro #include "vtkObject.h" +#include "vtkTuple.h" // needed for vtkTuple +#include // needed for vector +#include // needed for string. #define VTK_PARSER_IMMEDIATE 1 #define VTK_PARSER_UNARY_MINUS 2 @@ -200,19 +203,35 @@ class VTKCOMMONMISC_EXPORT vtkFunctionParser : public vtkObject // Description: // Get the number of scalar variables. - vtkGetMacro(NumberOfScalarVariables,int); + int GetNumberOfScalarVariables() + { return static_cast(this->ScalarVariableNames.size()); } // Description: // Get the number of vector variables. - vtkGetMacro(NumberOfVectorVariables,int); + int GetNumberOfVectorVariables() + { return static_cast(this->VectorVariableNames.size()); } // Description: // Get the ith scalar variable name. - char* GetScalarVariableName(int i); + const char* GetScalarVariableName(int i); // Description: // Get the ith vector variable name. - char* GetVectorVariableName(int i); + const char* GetVectorVariableName(int i); + + // Description: + // Returns whether a scalar variable is needed for the function evaluation. + // This is only valid after a successful Parse(). Thus, call GetScalarResult() + // or IsScalarResult() or similar method before calling this. + bool GetScalarVariableNeeded(int i); + bool GetScalarVariableNeeded(const char* variableName); + + // Description: + // Returns whether a vector variable is needed for the function evaluation. + // This is only valid after a successful Parse(). Thus, call GetVectorResult() + // or IsVectorResult() or similar method before calling this. + bool GetVectorVariableNeeded(int i); + bool GetVectorVariableNeeded(const char* variableName); // Description: // Remove all the current variables. @@ -285,6 +304,11 @@ class VTKCOMMONMISC_EXPORT vtkFunctionParser : public vtkObject int DisambiguateOperators(); + // Description: + // Collects meta-data about which variables are needed by the current + // function. This is called only after a successful call to this->Parse(). + void UpdateNeededVariables(); + vtkSetStringMacro(ParseError); int FindPositionInOriginalFunction(const int& pos); @@ -293,12 +317,13 @@ class VTKCOMMONMISC_EXPORT vtkFunctionParser : public vtkObject char* FunctionWithSpaces; int FunctionLength; - int NumberOfScalarVariables; - int NumberOfVectorVariables; - char** ScalarVariableNames; - char** VectorVariableNames; - double* ScalarVariableValues; - double** VectorVariableValues; + std::vector ScalarVariableNames; + std::vector VectorVariableNames; + std::vector ScalarVariableValues; + std::vector > VectorVariableValues; + std::vector ScalarVariableNeeded; + std::vector VectorVariableNeeded; + unsigned char *ByteCode; int ByteCodeSize; double *Immediates; diff --git a/Common/System/Testing/Cxx/otherTimerLog.cxx b/Common/System/Testing/Cxx/otherTimerLog.cxx index fc81994a098..571703bbfff 100644 --- a/Common/System/Testing/Cxx/otherTimerLog.cxx +++ b/Common/System/Testing/Cxx/otherTimerLog.cxx @@ -48,7 +48,7 @@ void otherTimerLogTest(ostream& strm) { a *= a; } -#ifndef WIN32 +#ifndef _WIN32 sleep (1); #else Sleep(1000); diff --git a/Common/System/vtkClientSocket.h b/Common/System/vtkClientSocket.h index ae71e1e1dd9..6dc32c08e15 100644 --- a/Common/System/vtkClientSocket.h +++ b/Common/System/vtkClientSocket.h @@ -39,7 +39,6 @@ class VTKCOMMONSYSTEM_EXPORT vtkClientSocket : public vtkSocket // connection. vtkGetMacro(ConnectingSide, bool); -//BTX protected: vtkClientSocket(); ~vtkClientSocket(); @@ -50,7 +49,7 @@ class VTKCOMMONSYSTEM_EXPORT vtkClientSocket : public vtkSocket private: vtkClientSocket(const vtkClientSocket&); // Not implemented. void operator=(const vtkClientSocket&); // Not implemented. -//ETX + }; diff --git a/Common/System/vtkSocket.h b/Common/System/vtkSocket.h index d779ea11df1..8a2fef25ed2 100644 --- a/Common/System/vtkSocket.h +++ b/Common/System/vtkSocket.h @@ -71,9 +71,7 @@ class VTKCOMMONSYSTEM_EXPORT vtkSocket : public vtkObject int SocketDescriptor; - //BTX friend class vtkSocketCollection; - //ETX // Description: // Creates an endpoint for communication and returns the descriptor. diff --git a/Common/System/vtkTimerLog.h b/Common/System/vtkTimerLog.h index ead1082d384..20ad1498658 100644 --- a/Common/System/vtkTimerLog.h +++ b/Common/System/vtkTimerLog.h @@ -60,7 +60,6 @@ #define VTK_LOG_EVENT_LENGTH 40 -//BTX typedef struct { double WallTime; @@ -68,7 +67,6 @@ typedef struct char Event[VTK_LOG_EVENT_LENGTH]; unsigned char Indent; } vtkTimerLogEntry; -//ETX class VTKCOMMONSYSTEM_EXPORT vtkTimerLog : public vtkObject { @@ -91,12 +89,10 @@ class VTKCOMMONSYSTEM_EXPORT vtkTimerLog : public vtkObject static void SetMaxEntries(int a); static int GetMaxEntries(); -//BTX // Description: // Record a timing event. The event is represented by a formatted // string. static void FormatAndMarkEvent(const char *EventString, ...); -//ETX // Description: // Write the timing table out to a file. Calculate some helpful @@ -109,9 +105,8 @@ class VTKCOMMONSYSTEM_EXPORT vtkTimerLog : public vtkObject // nested. The standard Dumplog ignores the indents. static void MarkStartEvent(const char *EventString); static void MarkEndEvent(const char *EventString); -//BTX + static void DumpLogWithIndents(ostream *os, double threshold); -//ETX // Description: // Programatic access to events. Indexed from 0 to num-1. @@ -194,10 +189,8 @@ class VTKCOMMONSYSTEM_EXPORT vtkTimerLog : public vtkObject double StartTime; double EndTime; - //BTX static void DumpEntry(ostream& os, int index, double time, double deltatime, int tick, int deltatick, const char *event); - //ETX private: vtkTimerLog(const vtkTimerLog&); // Not implemented. diff --git a/Common/Transforms/vtkAbstractTransform.h b/Common/Transforms/vtkAbstractTransform.h index b9df5b8ba84..db58ea266e8 100644 --- a/Common/Transforms/vtkAbstractTransform.h +++ b/Common/Transforms/vtkAbstractTransform.h @@ -221,7 +221,7 @@ class VTKCOMMONTRANSFORMS_EXPORT vtkAbstractTransform : public vtkObject // Description: // Make another transform of the same type. - virtual vtkAbstractTransform *MakeTransform() = 0; + virtual VTK_NEWINSTANCE vtkAbstractTransform *MakeTransform() = 0; // Description: // Check for self-reference. Will return true if concatenating @@ -258,22 +258,20 @@ class VTKCOMMONTRANSFORMS_EXPORT vtkAbstractTransform : public vtkObject private: -//BTX // We need to record the time of the last update, and we also need // to do mutex locking so updates don't collide. These are private // because Update() is not virtual. // If DependsOnInverse is set, then this transform object will // check its inverse on every update, and update itself accordingly // if necessary. -//ETX + vtkTimeStamp UpdateTime; vtkSimpleCriticalSection *UpdateMutex; vtkSimpleCriticalSection *InverseMutex; int DependsOnInverse; -//BTX // MyInverse is a transform which is the inverse of this one. -//ETX + vtkAbstractTransform *MyInverse; int InUnRegister; @@ -283,7 +281,6 @@ class VTKCOMMONTRANSFORMS_EXPORT vtkAbstractTransform : public vtkObject void operator=(const vtkAbstractTransform&); // Not implemented. }; -//BTX //------------------------------------------------------------------------- // A simple data structure to hold both a transform and its inverse. // One of ForwardTransform or InverseTransform might be NULL, @@ -427,6 +424,4 @@ class VTKCOMMONTRANSFORMS_EXPORT vtkTransformConcatenationStack vtkTransformConcatenation **StackBottom; }; -//ETX - #endif diff --git a/Common/Transforms/vtkLandmarkTransform.h b/Common/Transforms/vtkLandmarkTransform.h index 52145cde527..824217bc5ec 100644 --- a/Common/Transforms/vtkLandmarkTransform.h +++ b/Common/Transforms/vtkLandmarkTransform.h @@ -104,7 +104,6 @@ class VTKCOMMONTRANSFORMS_EXPORT vtkLandmarkTransform : public vtkLinearTransfor void operator=(const vtkLandmarkTransform&); // Not implemented. }; -//BTX inline const char *vtkLandmarkTransform::GetModeAsString() { switch (this->Mode) @@ -119,5 +118,5 @@ inline const char *vtkLandmarkTransform::GetModeAsString() return "Unrecognized"; } } -//ETX + #endif diff --git a/Common/Transforms/vtkThinPlateSplineTransform.h b/Common/Transforms/vtkThinPlateSplineTransform.h index 20e24d491a9..040ea091fdc 100644 --- a/Common/Transforms/vtkThinPlateSplineTransform.h +++ b/Common/Transforms/vtkThinPlateSplineTransform.h @@ -68,7 +68,6 @@ class VTKCOMMONTRANSFORMS_EXPORT vtkThinPlateSplineTransform : public vtkWarpTra void SetBasisToR2LogR() { this->SetBasis(VTK_RBF_R2LOGR); }; const char *GetBasisAsString(); -//BTX // Description: // Set the radial basis function to a custom function. You must // supply both the function and its derivative with respect to r. @@ -80,7 +79,6 @@ class VTKCOMMONTRANSFORMS_EXPORT vtkThinPlateSplineTransform : public vtkWarpTra void SetBasisDerivative(double (*dUdr)(double r, double &dU)) { this->BasisDerivative = dUdr; this->Modified(); }; -//ETX // Description: // Set the source landmarks for the warp. If you add or change the @@ -128,11 +126,10 @@ class VTKCOMMONTRANSFORMS_EXPORT vtkThinPlateSplineTransform : public vtkWarpTra vtkPoints *SourceLandmarks; vtkPoints *TargetLandmarks; -//BTX // the radial basis function to use double (*BasisFunction)(double r); double (*BasisDerivative)(double r, double& dUdr); -//ETX + int Basis; int NumberOfPoints; diff --git a/Common/Transforms/vtkTransform.cxx b/Common/Transforms/vtkTransform.cxx index b911b60ea78..9859775a30b 100644 --- a/Common/Transforms/vtkTransform.cxx +++ b/Common/Transforms/vtkTransform.cxx @@ -476,7 +476,7 @@ void vtkTransform::GetOrientationWXYZ(double wxyz[4]) if ( mag != 0.0 ) { - wxyz[0] = 2. * vtkMath::DegreesFromRadians( acos( wxyz[0] ) ); + wxyz[0] = 2.0 * vtkMath::DegreesFromRadians( atan2( mag, wxyz[0] ) ); wxyz[1] /= mag; wxyz[2] /= mag; wxyz[3] /= mag; diff --git a/Common/Transforms/vtkTransformCollection.h b/Common/Transforms/vtkTransformCollection.h index c25477f837e..8f1937595c6 100644 --- a/Common/Transforms/vtkTransformCollection.h +++ b/Common/Transforms/vtkTransformCollection.h @@ -44,13 +44,11 @@ class VTKCOMMONTRANSFORMS_EXPORT vtkTransformCollection : public vtkCollection // list is reached. vtkTransform *GetNextItem(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkTransform *GetNextTransform(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkTransformCollection() {} diff --git a/Deprecated/TestGraphHierarchicalBundle.cxx b/Deprecated/TestGraphHierarchicalBundle.cxx index 7a425fbcaec..74a59817518 100644 --- a/Deprecated/TestGraphHierarchicalBundle.cxx +++ b/Deprecated/TestGraphHierarchicalBundle.cxx @@ -278,7 +278,7 @@ int TestGraphHierarchicalBundle(int argc, char* argv[]) extendedNameArray->InsertNextValue(kitNames->GetValue(k)); } - vtkStringArray* fileArray = vtkStringArray::SafeDownCast( + vtkStringArray* fileArray = vtkArrayDownCast( graph->GetVertexData()->GetAbstractArray("filename")); for (vtkIdType i = 0; i < graph->GetNumberOfVertices(); i++) { diff --git a/Deprecated/vtkStringToTimePoint.cxx b/Deprecated/vtkStringToTimePoint.cxx index 68d0f1f7b13..d1097adc961 100644 --- a/Deprecated/vtkStringToTimePoint.cxx +++ b/Deprecated/vtkStringToTimePoint.cxx @@ -75,7 +75,7 @@ int vtkStringToTimePoint::RequestData( // Get the input array vtkAbstractArray* inputArray = this->GetInputAbstractArrayToProcess(0, inputVector); - vtkStringArray* stringArray = vtkStringArray::SafeDownCast(inputArray); + vtkStringArray* stringArray = vtkArrayDownCast(inputArray); if (stringArray == NULL) { vtkErrorMacro(<< "The input array must be a string array."); diff --git a/Deprecated/vtkTimePointToString.cxx b/Deprecated/vtkTimePointToString.cxx index 76ae75d9dbe..c7c765807e1 100644 --- a/Deprecated/vtkTimePointToString.cxx +++ b/Deprecated/vtkTimePointToString.cxx @@ -126,7 +126,7 @@ int vtkTimePointToString::RequestData( output->ShallowCopy(input); // Get the input array - vtkTypeUInt64Array* inputArray = vtkTypeUInt64Array::SafeDownCast( + vtkTypeUInt64Array* inputArray = vtkArrayDownCast( this->GetInputAbstractArrayToProcess(0, inputVector)); if (inputArray == NULL) diff --git a/Documentation/Doxygen/ArrayDispatch-VTK-7-1.md b/Documentation/Doxygen/ArrayDispatch-VTK-7-1.md new file mode 100644 index 00000000000..f5ac764e54a --- /dev/null +++ b/Documentation/Doxygen/ArrayDispatch-VTK-7-1.md @@ -0,0 +1,1277 @@ +@page VTK-7-1-ArrayDispatch vtkArrayDispatch and Related Tools +@tableofcontents + +# Background # {#VTKAD-Background} + +VTK datasets store most of their important information in subclasses of +`vtkDataArray`. Vertex locations (`vtkPoints::Data`), cell topology +(`vtkCellArray::Ia`), and numeric point, cell, and generic attributes +(`vtkFieldData::Data`) are the dataset features accessed most frequently by VTK +algorithms, and these all rely on the `vtkDataArray` API. + +# Terminology # {#VTKAD-Terminology} + +This page uses the following terms: + +A __ValueType__ is the element type of an array. For instance, `vtkFloatArray` +has a ValueType of `float`. + +An __ArrayType__ is a subclass of `vtkDataArray`. It specifies not only a +ValueType, but an array implementation as well. This becomes important as +`vtkDataArray` subclasses will begin to stray from the typical +"array-of-structs" ordering that has been exclusively used in the past. + +A __dispatch__ is a runtime-resolution of a `vtkDataArray`'s ArrayType, and is +used to call a section of executable code that has been tailored for that +ArrayType. Dispatching has compile-time and run-time components. At +compile-time, the possible ArrayTypes to be used are determined and a worker +code template is generated for each type. At run-time, the type of a specific +array is determined and the proper worker instantiation is called. + +__Template explosion__ refers to a sharp increase in the size of a compiled +binary that results from instantiating a template function or class on many +different types. + +## vtkDataArray ## {#VTKAD-vtkDataArray} + +The data array type hierarchy in VTK has a unique feature when compared to +typical C++ containers: a non-templated base class. All arrays containing +numeric data inherit `vtkDataArray`, a common interface that sports a very +useful API. Without knowing the underlying ValueType stored in data array, an +algorithm or user may still work with any `vtkDataArray` in meaningful ways: +The array can be resized, reshaped, read, and rewritten easily using a generic +API that substitutes double-precision floating point numbers for the array's +actual ValueType. For instance, we can write a simple function that computes +the magnitudes for a set of vectors in one array and store the results in +another using nothing but the typeless `vtkDataArray` API: + +~~~{.cpp} +// 3 component magnitude calculation using the vtkDataArray API. +// Inefficient, but easy to write: +void calcMagnitude(vtkDataArray *vectors, vtkDataArray *magnitude) +{ + vtkIdType numVectors = vectors->GetNumberOfTuples(); + for (vtkIdType tupleIdx = 0; tupleIdx < numVectors; ++tupleIdx) + { + // What data types are magnitude and vectors using? + // We don't care! These methods all use double. + magnitude->SetComponent(tupleIdx, 0, + std::sqrt(vectors->GetComponent(tupleIdx, 0) * + vectors->GetComponent(tupleIdx, 0) + + vectors->GetComponent(tupleIdx, 1) * + vectors->GetComponent(tupleIdx, 1) + + vectors->GetComponent(tupleIdx, 2) * + vectors->GetComponent(tupleIdx, 2)); + } +} +~~~ + +## The Costs of Flexiblity ## {#VTKAD-TheCostsOfFlexiblity} + +However, this flexibility comes at a cost. Passing data through a generic API +has a number of issues: + +__Accuracy__ + +Not all ValueTypes are fully expressible as a `double`. The truncation of +integers with > 52 bits of precision can be a particularly nasty issue. + +__Performance__ + +__Virtual overhead__: The only way to implement such a system is to route the +`vtkDataArray` calls through a run-time resolution of ValueTypes. This is +implemented through the virtual override mechanism of C++, which adds a small +overhead to each API call. + +__Missed optimization__: The virtual indirection described above also prevents +the compiler from being able to make assumptions about the layout of the data +in-memory. This information could be used to perform advanced optimizations, +such as vectorization. + +So what can one do if they want fast, optimized, type-safe access to the data +stored in a `vtkDataArray`? What options are available? + +## The Old Solution: vtkTemplateMacro ## {#VTKAD-vtkTemplateMacro} + +The `vtkTemplateMacro` is described in this section. While it is no longer +considered a best practice to use this construct in new code, it is still +usable and likely to be encountered when reading the VTK source code. Newer +code should use the `vtkArrayDispatch` mechanism, which is detailed later. The +discussion of `vtkTemplateMacro` will help illustrate some of the practical +issues with array dispatching. + +With a few minor exceptions that we won't consider here, prior to VTK 7.1 it +was safe to assume that all numeric `vtkDataArray` objects were also subclasses +of `vtkDataArrayTemplate`. This template class provided the implementation of +all documented numeric data arrays such as `vtkDoubleArray`, `vtkIdTypeArray`, +etc, and stores the tuples in memory as a contiguous array-of-structs (AOS). +For example, if we had an array that stored 3-component tuples as floating +point numbers, we could define a tuple as: + +~~~{.cpp} +struct Tuple { float x; float y; float z; }; +~~~ + +An array-of-structs, or AOS, memory buffer containing this data could be +described as: + +~~~{.cpp} +Tuple ArrayOfStructsBuffer[NumTuples]; +~~~ + +As a result, `ArrayOfStructsBuffer` will have the following memory layout: + +~~~{.cpp} +{ x1, y1, z1, x2, y2, z2, x3, y3, z3, ...} +~~~ + +That is, the components of each tuple are stored in adjacent memory locations, +one tuple after another. While this is not exactly how `vtkDataArrayTemplate` +implemented its memory buffers, it accurately describes the resulting memory +layout. + +`vtkDataArray` also defines a `GetDataType` method, which returns an enumerated +value describing a type. We can used to discover the ValueType stored in the +array. + +Combine the AOS memory convention and `GetDataType()` with a horrific little +method on the data arrays named `GetVoidPointer()`, and a path to efficient, +type-safe access was available. `GetVoidPointer()` does what it says on the +tin: it returns the memory address for the array data's base location as a +`void*`. While this breaks encapsulation and sets off warning bells for the +more pedantic among us, the following technique was safe and efficient when +used correctly: + +~~~{.cpp} +// 3-component magnitude calculation using GetVoidPointer. +// Efficient and fast, but assumes AOS memory layout +template +void calcMagnitudeWorker(ValueType *vectors, ValueType *magnitude, + vtkIdType numVectors) +{ + for (vtkIdType tupleIdx = 0; tupleIdx < numVectors; ++tupleIdx) + { + // We now have access to the raw memory buffers, and assuming + // AOS memory layout, we know how to access them. + magnitude[tupleIdx] = + std::sqrt(vectors[3 * tupleIdx + 0] * + vectors[3 * tupleIdx + 0] + + vectors[3 * tupleIdx + 1] * + vectors[3 * tupleIdx + 1] + + vectors[3 * tupleIdx + 2] * + vectors[3 * tupleIdx + 2]); + } +} + +void calcMagnitude(vtkDataArray *vectors, vtkDataArray *magnitude) +{ + assert("Arrays must have same datatype!" && + vtkDataTypesCompare(vectors->GetDataType(), + magnitude->GetDataType())); + switch (vectors->GetDataType()) + { + vtkTemplateMacro(calcMagnitudeWorker( + static_cast(vectors->GetVoidPointer(0)), + static_cast(magnitude->GetVoidPointer(0)), + vectors->GetNumberOfTuples()); + } +} +~~~ + +The `vtkTemplateMacro`, as you may have guessed, expands into a series of case +statements that determine an array's ValueType from the `int GetDataType()` +return value. The ValueType is then `typedef`'d to `VTK_TT`, and the macro's +argument is called for each numeric type returned from `GetDataType`. In this +case, the call to `calcMagnitudeWorker` is made by the macro, with `VTK_TT` +`typedef`'d to the array's ValueType. + +This is the typical usage pattern for `vtkTemplateMacro`. The `calcMagnitude` +function calls a templated worker implementation that uses efficient, raw +memory access to a typesafe memory buffer so that the worker's code can be as +efficient as possible. But this assumes AOS memory ordering, and as we'll +mention, this assumption may no longer be valid as VTK moves further into the +field of in-situ analysis. + +But first, you may have noticed that the above example using `vtkTemplateMacro` +has introduced a step backwards in terms of functionality. In the +`vtkDataArray` implementation, we didn't care if both arrays were the same +ValueType, but now we have to ensure this, since we cast both arrays' `void` +pointers to `VTK_TT`*. What if vectors is an array of integers, but we want to +calculate floating point magnitudes? + +## vtkTemplateMacro with Multiple Arrays ## {#VTKAD-Dual-vtkTemplateMacro} + +The best solution prior to VTK 7.1 was to use two worker functions. The first +is templated on vector's ValueType, and the second is templated on both array +ValueTypes: + +~~~{.cpp} +// 3-component magnitude calculation using GetVoidPointer and a +// double-dispatch to resolve ValueTypes of both arrays. +// Efficient and fast, but assumes AOS memory layout, lots of boilerplate +// code, and the sensitivity to template explosion issues increases. +template +void calcMagnitudeWorker2(VectorType *vectors, MagnitudeType *magnitude, + vtkIdType numVectors) +{ + for (vtkIdType tupleIdx = 0; tupleIdx < numVectors; ++tupleIdx) + { + // We now have access to the raw memory buffers, and assuming + // AOS memory layout, we know how to access them. + magnitude[tupleIdx] = + std::sqrt(vectors[3 * tupleIdx + 0] * + vectors[3 * tupleIdx + 0] + + vectors[3 * tupleIdx + 1] * + vectors[3 * tupleIdx + 1] + + vectors[3 * tupleIdx + 2] * + vectors[3 * tupleIdx + 2]); + } +} + +// Vector ValueType is known (VectorType), now use vtkTemplateMacro on +// magnitude: +template +void calcMagnitudeWorker1(VectorType *vectors, vtkDataArray *magnitude, + vtkIdType numVectors) +{ + switch (magnitude->GetDataType()) + { + vtkTemplateMacro(calcMagnitudeWorker2(vectors, + static_cast(magnitude->GetVoidPointer(0)), numVectors); + } +} + +void calcMagnitude(vtkDataArray *vectors, vtkDataArray *magnitude) +{ + // Dispatch vectors first: + switch (vectors->GetDataType()) + { + vtkTemplateMacro(calcMagnitudeWorker1( + static_cast(vectors->GetVoidPointer(0)), + magnitude, vectors->GetNumberOfTuples()); + } +} +~~~ + +This works well, but it's a bit ugly and has the same issue as before regarding +memory layout. Double dispatches using this method will also see more problems +regarding binary size. The number of template instantiations that the compiler +needs to generate is determined by `I = T^D`, where `I` is the number of +template instantiations, `T` is the number of types considered, and `D` is the +number of dispatches. As of VTK 7.1, `vtkTemplateMacro` considers 14 data +types, so this double-dispatch will produce 14 instantiations of +`calcMagnitudeWorker1` and 196 instantiations of `calcMagnitudeWorker2`. If we +tried to resolve 3 `vtkDataArray`s into raw C arrays, 2744 instantiations of +the final worker function would be generated. As more arrays are considered, +the need for some form of restricted dispatch becomes very important to keep +this template explosion in check. + +## Data Array Changes in VTK 7.1 ## {#VTKAD-Changes-in-VTK-71} + +Starting with VTK 7.1, the Array-Of-Structs (AOS) memory layout is no longer +the only `vtkDataArray` implementation provided by the library. The +Struct-Of-Arrays (SOA) memory layout is now available throught the +`vtkSOADataArrayTemplate` class. The SOA layout assumes that the components of +an array are stored separately, as in: + +~~~{.cpp} +struct StructOfArraysBuffer +{ + float *x; // Pointer to array containing x components + float *y; // Same for y + float *z; // Same for z +}; +~~~ + +The new SOA arrays were added to improve interoperability between VTK and +simulation packages for live visualization of in-situ results. Many simulations +use the SOA layout for their data, and natively supporting these arrays in VTK +will allow analysis of live data without the need to explicitly copy it into a +VTK data structure. + +As a result of this change, a new mechanism is needed to efficiently access +array data. `vtkTemplateMacro` and `GetVoidPointer` are no longer an acceptable +solution -- implementing `GetVoidPointer` for SOA arrays requires creating a +deep copy of the data into a new AOS buffer, a waste of both processor time and +memory. + +So we need a replacement for `vtkTemplateMacro` that can abstract away things +like storage details while providing performance that is on-par with raw memory +buffer operations. And while we're at it, let's look at removing the tedium of +multi-array dispatch and reducing the problem of 'template explosion'. The +remainder of this page details such a system. + +# Best Practices for vtkDataArray Post-7.1 # {#VTKAD-BestPractices} + +We'll describe a new set of tools that make managing template instantiations +for efficient array access both easy and extensible. As an overview, the +following new features will be discussed: + +* `vtkGenericDataArray`: The new templated base interface for all numeric +`vtkDataArray` subclasses. +* `vtkArrayDispatch`: Collection of code generation tools that allow concise +and precise specification of restrictable dispatch for up to 3 arrays +simultaneously. +* `vtkArrayDownCast`: Access to specialized downcast implementations from code +templates. +* `vtkDataArrayAccessor`: Provides `Get` and `Set` methods for +accessing/modifying array data as efficiently as possible. Allows a single +worker implementation to work efficiently with `vtkGenericDataArray` +subclasses, or fallback to use the `vtkDataArray` API if needed. +* `VTK_ASSUME`: New abstraction for the compiler `__assume` directive to +provide optimization hints. + +These will be discussed more fully, but as a preview, here's our familiar +`calcMagnitude` example implemented using these new tools: + +~~~{.cpp} +// Modern implementation of calcMagnitude using new concepts in VTK 7.1: +// A worker functor. The calculation is implemented in the function template +// for operator(). +struct CalcMagnitudeWorker +{ + // The worker accepts VTK array objects now, not raw memory buffers. + template + void operator()(VectorArray *vectors, MagnitudeArray *magnitude) + { + // This allows the compiler to optimize for the AOS array stride. + VTK_ASSUME(vectors->GetNumberOfComponents() == 3); + VTK_ASSUME(magnitude->GetNumberOfComponents() == 1); + + // These allow this single worker function to be used with both + // the vtkDataArray 'double' API and the more efficient + // vtkGenericDataArray APIs, depending on the template parameters: + vtkDataArrayAccessor v(vectors); + vtkDataArrayAccessor m(magnitude); + + vtkIdType numVectors = vectors->GetNumberOfTuples(); + for (vtkIdType tupleIdx = 0; tupleIdx < numVectors; ++tupleIdx) + { + // Set and Get compile to inlined optimizable raw memory accesses for + // vtkGenericDataArray subclasses. + m.Set(tupleIdx, 0, std::sqrt(v.Get(tupleIdx, 0) * v.Get(tupleIdx, 0) + + v.Get(tupleIdx, 1) * v.Get(tupleIdx, 1) + + v.Get(tupleIdx, 2) * v.Get(tupleIdx, 2))); + } + } +}; + +void calcMagnitude(vtkDataArray *vectors, vtkDataArray *magnitude) +{ + // Create our worker functor: + CalcMagnitudeWorker worker; + + // Define our dispatcher. We'll let vectors have any ValueType, but only + // consider float/double arrays for magnitudes. These combinations will + // use a 'fast-path' implementation generated by the dispatcher: + typedef vtkArrayDispatch::Dispatch2ByValueType + < + vtkArrayDispatch::AllTypes, // ValueTypes allowed by first array + vtkArrayDispatch::Reals // ValueTypes allowed by second array + > Dispatcher; + + // Execute the dispatcher: + if (!Dispatcher::Execute(vectors, magnitude, worker)) + { + // If Execute() fails, it means the dispatch failed due to an + // unsupported array type. In this case, it's likely that the magnitude + // array is using an integral type. This is an uncommon case, so we won't + // generate a fast path for these, but instead call an instantiation of + // CalcMagnitudeWorker::operator(). + // Through the use of vtkDataArrayAccessor, this falls back to using the + // vtkDataArray double API: + worker(vectors, magnitude); + } +} +~~~ + +# vtkGenericDataArray # {#VTKAD-vtkGenericDataArray} + +The `vtkGenericDataArray` class template drives the new `vtkDataArray` class +hierarchy. The ValueType is introduced here, both as a template parameter and a +class-scope `typedef`. This allows a typed API to be written that doesn't +require conversion to/from a common type (as `vtkDataArray` does with double). +It does not implement any storage details, however. Instead, it uses the CRTP +idiom to forward key method calls to a derived class without using a virtual +function call. By eliminating this indirection, `vtkGenericDataArray` defines +an interface that can be used to implement highly efficient code, because the +compiler is able to see past the method calls and optimize the underlying +memory accesses instead. + +There are two main subclasses of `vtkGenericDataArray`: +`vtkAOSDataArrayTemplate` and `vtkSOADataArrayTemplate`. These implement +array-of-structs and struct-of-arrays storage, respectively. + +# vtkTypeList # {#VTKAD-vtkTypeList} + +Type lists are a metaprogramming construct used to generate a list of C++ +types. They are used in VTK to implement restricted array dispatching. As we'll +see, `vtkArrayDispatch` offers ways to reduce the number of generated template +instantiations by enforcing constraints on the arrays used to dispatch. For +instance, if one wanted to only generate templated worker implementations for +`vtkFloatArray` and `vtkIntArray`, a typelist is used to specify this: + +~~~{.cpp} +// Create a typelist of 2 types, vtkFloatArray and vtkIntArray: +typedef vtkTypeList_Create_2(vtkFloatArray, vtkIntArray) MyArrays; + +Worker someWorker = ...; +vtkDataArray *someArray = ...; + +// Use vtkArrayDispatch to generate code paths for these arrays: +vtkArrayDispatch::DispatchByArray(someArray, someWorker); +~~~ + +There's not much to know about type lists as a user, other than how to create +them. As seen above, there is a set of macros named `vtkTypeList_Create_X`, +where X is the number of types in the created list, and the arguments are the +types to place in the list. In the example above, the new type list is +typically bound to a friendlier name using a local `typedef`, which is a common +practice. + +The `vtkTypeList.h` header defines some additional type list operations that +may be useful, such as deleting and appending types, looking up indices, etc. +`vtkArrayDispatch::FilterArraysByValueType` may come in handy, too. But for +working with array dispatches, most users will only need to create new ones, or +use one of the following predefined `vtkTypeLists`: + +* `vtkArrayDispatch::Reals`: All floating point ValueTypes. +* `vtkArrayDispatch::Integrals`: All integral ValueTypes. +* `vtkArrayDispatch::AllTypes`: Union of Reals and Integrals. +* `vtkArrayDispatch::Arrays`: Default list of ArrayTypes to use in dispatches. + +The last one is special -- `vtkArrayDispatch::Arrays` is a typelist of +ArrayTypes set application-wide when VTK is built. This `vtkTypeList` of +`vtkDataArray` subclasses is used for unrestricted dispatches, and is the list +that gets filtered when restricting a dispatch to specific ValueTypes. + +Refining this list allows the user building VTK to have some control over the +dispatch process. If SOA arrays are never going to be used, they can be removed +from dispatch calls, reducing compile times and binary size. On the other hand, +a user applying in-situ techniques may want them available, because they'll be +used to import views of intermediate results. + +By default, `vtkArrayDispatch::Arrays` contains all AOS arrays. The `CMake` +option `VTK_DISPATCH_SOA_ARRAYS` will enable SOA array dispatch as well. More +advanced possibilities exist and are described in +`VTK/CMake/vtkCreateArrayDispatchArrayList.cmake`. + +# vtkArrayDownCast # {#VTKAD-vtkArrayDownCast} + +In VTK, all subclasses of `vtkObject` (including the data arrays) support a +downcast method called `SafeDownCast`. It is used similarly to the C++ +`dynamic_cast` -- given an object, try to cast it to a more derived type or +return `NULL` if the object is not the requested type. Say we have a +`vtkDataArray` and want to test if it is actually a `vtkFloatArray`. We can do +this: + +~~~{.cpp} +void DoSomeAction(vtkDataArray *dataArray) +{ + vtkFloatArray *floatArray = vtkFloatArray::SafeDownCast(dataArray); + if (floatArray) + { + // ... (do work with float array) + } +} +~~~ + +This works, but it can pose a serious problem if `DoSomeAction` is called +repeatedly. `SafeDownCast` works by performing a series of virtual calls and +string comparisons to determine if an object falls into a particular class +hierarchy. These string comparisons add up and can actually dominate +computational resources if an algorithm implementation calls `SafeDownCast` in +a tight loop. + +In such situations, it's ideal to restructure the algorithm so that the +downcast only happens once and the same result is used repeatedly, but +sometimes this is not possible. To lessen the cost of downcasting arrays, a +`FastDownCast` method exists for common subclasses of `vtkAbstractArray`. This +replaces the string comparisons with a single virtual call and a few integer +comparisons and is far cheaper than the more general SafeDownCast. However, not +all array implementations support the `FastDownCast` method. + +This creates a headache for templated code. Take the following example: + +~~~{.cpp} +template +void DoSomeAction(vtkAbstractArray *array) +{ + ArrayType *myArray = ArrayType::SafeDownCast(array); + if (myArray) + { + // ... (do work with myArray) + } +} +~~~ + +We cannot use `FastDownCast` here since not all possible ArrayTypes support it. +But we really want that performance increase for the ones that do -- +`SafeDownCast`s are really slow! `vtkArrayDownCast` fixes this issue: + +~~~{.cpp} +template +void DoSomeAction(vtkAbstractArray *array) +{ + ArrayType *myArray = vtkArrayDownCast(array); + if (myArray) + { + // ... (do work with myArray) + } +} +~~~ + +`vtkArrayDownCast` automatically selects `FastDownCast` when it is defined for +the ArrayType, and otherwise falls back to `SafeDownCast`. This is the +preferred array downcast method for performance, uniformity, and reliability. + +# vtkDataArrayAccessor # {#VTKAD-vtkDataArrayAccessor} + +Array dispatching relies on having templated worker code carry out some +operation. For instance, take this `vtkArrayDispatch` code that locates the +maximum value in an array: + +~~~{.cpp} +// Stores the tuple/component coordinates of the maximum value: +struct FindMax +{ + vtkIdType Tuple; // Result + int Component; // Result + + FindMax() : Tuple(-1), Component(-1) {} + + template + void operator()(ArrayT *array) + { + // The type to use for temporaries, and a temporary to store + // the current maximum value: + typedef typename ArrayT::ValueType ValueType; + ValueType max = std::numeric_limits::min(); + + // Iterate through all tuples and components, noting the location + // of the largest element found. + vtkIdType numTuples = array->GetNumberOfTuples(); + int numComps = array->GetNumberOfComponents(); + for (vtkIdType tupleIdx = 0; tupleIdx < numTuples; ++tupleIdx) + { + for (int compIdx = 0; compIdx < numComps; ++compIdx) + { + if (max < array->GetTypedComponent(tupleIdx, compIdx)) + { + max = array->GetTypedComponent(tupleIdx, compIdx); + this->Tuple = tupleIdx; + this->Component = compIdx; + } + } + } + } +}; + +void someFunction(vtkDataArray *array) +{ + FindMax maxWorker; + vtkArrayDispatch::Dispatch::Execute(array, maxWorker); + // Do work using maxWorker.Tuple and maxWorker.Component... +} +~~~ + +There's a problem, though. Recall that only the arrays in +`vtkArrayDispatch::Arrays` are tested for dispatching. What happens if the +array passed into someFunction wasn't on that list? + +The dispatch will fail, and `maxWorker.Tuple` and `maxWorker.Component` will be +left to their initial values of -1. That's no good. What if `someFunction` is a +critical path where we want to use a fast dispatched worker if possible, but +still have valid results to use if dispatching fails? Well, we can fall back on +the `vtkDataArray` API and do things the slow way in that case. When a +dispatcher is given an unsupported array, Execute() returns false, so let's +just add a backup implementation: + +~~~{.cpp} +// Stores the tuple/component coordinates of the maximum value: +struct FindMax +{ /* As before... */ }; + +void someFunction(vtkDataArray *array) +{ + FindMax maxWorker; + if (!vtkArrayDispatch::Dispatch::Execute(array, maxWorker)) + { + // Reimplement FindMax::operator(), but use the vtkDataArray API's + // "virtual double GetComponent()" instead of the more efficient + // "ValueType GetTypedComponent()" from vtkGenericDataArray. + } +} +~~~ + +Ok, that works. But ugh...why write the same algorithm twice? That's extra +debugging, extra testing, extra maintenance burden, and just plain not fun. + +Enter `vtkDataArrayAccessor`. This utility template does a very simple, yet +useful, job. It provides component and tuple based `Get` and `Set` methods that +will call the corresponding method on the array using either the `vtkDataArray` +or `vtkGenericDataArray` API, depending on the class's template parameter. It +also defines an `APIType`, which can be used to allocate temporaries, etc. This +type is double for `vtkDataArray`s and `vtkGenericDataArray::ValueType` for +`vtkGenericDataArray`s. + +Another nice benefit is that `vtkDataArrayAccessor` has a more compact API. The +only defined methods are Get and Set, and they're overloaded to work on either +tuples or components (though component access is encouraged as it is much, much +more efficient). Note that all non-element access operations (such as +`GetNumberOfTuples`) should still be called on the array pointer using +`vtkDataArray` API. + +Using `vtkDataArrayAccessor`, we can write a single worker template that works +for both `vtkDataArray` and `vtkGenericDataArray`, without a loss of +performance in the latter case. That worker looks like this: + +~~~{.cpp} +// Better, uses vtkDataArrayAccessor: +struct FindMax +{ + vtkIdType Tuple; // Result + int Component; // Result + + FindMax() : Tuple(-1), Component(-1) {} + + template + void operator()(ArrayT *array) + { + // Create the accessor: + vtkDataArrayAccessor access(array); + + // Prepare the temporary. We'll use the accessor's APIType instead of + // ArrayT::ValueType, since that is appropriate for the vtkDataArray + // fallback: + typedef typename vtkDataArrayAccessor::APIType ValueType; + ValueType max = std::numeric_limits::min(); + + // Iterate as before, but use access.Get instead of + // array->GetTypedComponent. GetTypedComponent is still used + // when ArrayT is a vtkGenericDataArray, but + // vtkDataArray::GetComponent is now used as a fallback when ArrayT + // is vtkDataArray. + vtkIdType numTuples = array->GetNumberOfTuples(); + int numComps = array->GetNumberOfComponents(); + for (vtkIdType tupleIdx = 0; tupleIdx < numTuples; ++tupleIdx) + { + for (int compIdx = 0; compIdx < numComps; ++compIdx) + { + if (max < access.Get(tupleIdx, compIdx)) + { + max = access.Get(tupleIdx, compIdx); + this->Tuple = tupleIdx; + this->Component = compIdx; + } + } + } + } +}; +~~~ + +Now when we call `operator()` with say, `ArrayT=vtkFloatArray`, we'll get an +optimized, efficient code path. But we can also call this same implementation +with `ArrayT=vtkDataArray` and still get a correct result (assuming that the +`vtkDataArray`'s double API represents the data well enough). + +Using the `vtkDataArray` fallback path is straightforward. At the call site: + +~~~{.cpp} +void someFunction(vtkDataArray *array) +{ + FindMax maxWorker; + if (!vtkArrayDispatch::Dispatch::Execute(array, maxWorker)) + { + maxWorker(array); // Dispatch failed, call vtkDataArray fallback + } + // Do work using maxWorker.Tuple and maxWorker.Component -- now we know + // for sure that they're initialized! +} +~~~ + +Using the above pattern for calling a worker and always going through +`vtkDataArrayAccessor` to `Get`/`Set` array elements ensures that any worker +implementation can be its own fallback path. + +# VTK_ASSUME # {#VTKAD-VTK_ASSUME} + +While performance testing the new array classes, we compared the performance of +a dispatched worker using the `vtkDataArrayAccessor` class to the same +algorithm using raw memory buffers. We managed to achieve the same performance +out of the box for most cases, using both AOS and SOA array implementations. In +fact, with `--ffast-math` optimizations on GCC 4.9, the optimizer is able to +remove all function calls and apply SIMD vectorized instructions in the +dispatched worker, showing that the new array API is thin enough that the +compiler can see the algorithm in terms of memory access. + +But there was one case where performance suffered. If iterating through an AOS +data array with a known number of components using `GetTypedComponent`, the raw +pointer implementation initially outperformed the dispatched array. To +understand why, note that the AOS implementation of `GetTypedComponent` is along +the lines of: + +~~~{.cpp} +ValueType vtkAOSDataArrayTemplate::GetTypedComponent(vtkIdType tuple, + int comp) const +{ + // AOSData is a ValueType* pointing at the base of the array data. + return this->AOSData[tuple * this->NumberOfComponents + comp]; +} +~~~ + +Because `NumberOfComponents` is unknown at compile time, the optimizer cannot +assume anything about the stride of the components in the array. This leads to +missed optimizations for vectorized read/writes and increased complexity in the +instructions used to iterate through the data. + +For such cases where the number of components is, in fact, known at compile +time (due to a calling function performing some validation, for instance), it +is possible to tell the compiler about this fact using `VTK_ASSUME`. + +`VTK_ASSUME` wraps a compiler-specific `__assume` statement, which is used to +pass such optimization hints. Its argument is an expression of some condition +that is guaranteed to always be true. This allows more aggressive optimizations +when used correctly, but be forewarned that if the condition is not met at +runtime, the results are unpredictable and likely catastrophic. + +But if we're writing a filter that only operates on 3D point sets, we know the +number of components in the point array will always be 3. In this case we can +write: + +~~~{.cpp} +VTK_ASSUME(pointsArray->GetNumberOfComponents() == 3); +~~~ + +in the worker function and this instructs the compiler that the array's +internal `NumberOfComponents` variable will always be 3, and thus the stride of +the array is known. Of course, the caller of this worker function should ensure +that this is a 3-component array and fail gracefully if it is not. + +There are many scenarios where `VTK_ASSUME` can offer a serious performance +boost, the case of known tuple size is a common one that's really worth +remembering. + +# vtkArrayDispatch # {#VTKAD-vtkArrayDispatch} + +The dispatchers implemented in the vtkArrayDispatch namespace provide array +dispatching with customizable restrictions on code generation and a simple +syntax that hides the messy details of type resolution and multi-array +dispatch. There are several "flavors" of dispatch available that operate on up +to three arrays simultaneously. + +## Components Of A Dispatch ## {#VTKAD-ComponentsOfADispatch} + +Using the `vtkArrayDispatch` system requires three elements: the array(s), the +worker, and the dispatcher. + +### The Arrays ### {#VTKAD-TheArrays} + +All dispatched arrays must be subclasses of `vtkDataArray`. It is important to +identify as many restrictions as possible. Must every ArrayType be considered +during dispatch, or is the array's ValueType (or even the ArrayType itself) +restricted? If dispatching multiple arrays at once, are they expected to have +the same ValueType? These scenarios are common, and these conditions can be +used to reduce the number of instantiations of the worker template. + +### The Worker ### {#VTKAD-TheWorker} + +The worker is some generic callable. In C++98, a templated functor is a good +choice. In C++14, a generic lambda is a usable option as well. For our +purposes, we'll only consider the functor approach, as C++14 is a long ways off +for core VTK code. + +At a minimum, the worker functor should define `operator()` to make it +callable. This should be a function template with a template parameter for each +array it should handle. For a three array dispatch, it should look something +like this: + +~~~{.cpp} +struct ThreeArrayWorker +{ + template + void operator()(Array1T *array1, Array2T *array2, Array3T *array3) + { + /* Do stuff... */ + } +}; +~~~ + +At runtime, the dispatcher will call `ThreeWayWorker::operator()` with a set of +`Array1T`, `Array2T`, and `Array3T` that satisfy any dispatch restrictions. + +Workers can be stateful, too, as seen in the `FindMax` worker earlier where the +worker simply identified the component and tuple id of the largest value in the +array. The functor stored them for the caller to use in further analysis: + +~~~{.cpp} +// Example of a stateful dispatch functor: +struct FindMax +{ + // Functor state, holds results that are accessible to the caller: + vtkIdType Tuple; + int Component; + + // Set initial values: + FindMax() : Tuple(-1), Component(-1) {} + + // Template method to set Tuple and Component ivars: + template + void operator()(ArrayT *array) + { + /* Do stuff... */ + } +}; +~~~ + +### The Dispatcher ### {#VTKAD-TheDispatcher} + +The dispatcher is the workhorse of the system. It is responsible for applying +restrictions, resolving array types, and generating the requested template +instantiations. It has responsibilities both at run-time and compile-time. + +During compilation, the dispatcher will identify the valid combinations of +arrays that can be used according to the restrictions. This is done by starting +with a typelist of arrays, either supplied as a template parameter or by +defaulting to `vtkArrayDispatch::Arrays`, and filtering them by ValueType if +needed. For multi-array dispatches, additional restrictions may apply, such as +forcing the second and third arrays to have the same ValueType as the first. It +must then generate the required code for the dispatch -- that is, the templated +worker implementation must be instantiated for each valid combination of +arrays. + +At runtime, it tests each of the dispatched arrays to see if they match one of +the generated code paths. Runtime type resolution is carried out using +`vtkArrayDownCast` to get the best performance available for the arrays of +interest. If it finds a match, it calls the worker's `operator()` method with +the properly typed arrays. If no match is found, it returns `false` without +executing the worker. + +## Restrictions: Why They Matter ## {#VTKAD-RestrictionsWhyTheyMatter} + +We've made several mentions of using restrictions to reduce the number of +template instantiations during a dispatch operation. You may be wondering if it +really matters so much. Let's consider some numbers. + +VTK is configured to use 13 ValueTypes for numeric data. These are the standard +numeric types `float`, `int`, `unsigned char`, etc. By default, VTK will define +`vtkArrayDispatch::Arrays` to use all 13 types with `vtkAOSDataArrayTemplate` +for the standard set of dispatchable arrays. If enabled during compilation, the +SOA data arrays are added to this list for a total of 26 arrays. + +Using these 26 arrays in a single, unrestricted dispatch will result in 26 +instantiations of the worker template. A double dispatch will generate 676 +workers. A triple dispatch with no restrictions creates a whopping 17,576 +functions to handle the possible combinations of arrays. That's a _lot_ of +instructions to pack into the final binary object. + +Applying some simple restrictions can reduce this immensely. Say we know that +the arrays will only contain `float`s or `double`s. This would reduce the +single dispatch to 4 instantiations, the double dispatch to 16, and the triple +to 64. We've just reduced the generated code size significantly. We could even +apply such a restriction to just create some 'fast-paths' and let the integral +types fallback to using the `vtkDataArray` API by using +`vtkDataArrayAccessor`s. Dispatch restriction is a powerful tool for reducing +the compiled size of a binary object. + +Another common restriction is that all arrays in a multi-array dispatch have +the same ValueType, even if that ValueType is not known at compile time. By +specifying this restriction, a double dispatch on all 26 AOS/SOA arrays will +only produce 52 worker instantiations, down from 676. The triple dispatch drops +to 104 instantiations from 17,576. + +Always apply restrictions when they are known, especially for multi-array +dispatches. The savings are worth it. + +## Types of Dispatchers ## {#VTKAD-TypesOfDispatchers} + +Now that we've discussed the components of a dispatch operation, what the +dispatchers do, and the importance of restricting dispatches, let's take a look +at the types of dispatchers available. + +--- + +### vtkArrayDispatch::Dispatch ### {#VTKAD-Dispatch} + +This family of dispatchers take no parameters and perform an unrestricted +dispatch over all arrays in `vtkArrayDispatch::Arrays`. + +__Variations__: +* `vtkArrayDispatch::Dispatch`: Single dispatch. +* `vtkArrayDispatch::Dispatch2`: Double dispatch. +* `vtkArrayDispatch::Dispatch3`: Triple dispatch. + +__Arrays considered__: All arrays in `vtkArrayDispatch::Arrays`. + +__Restrictions__: None. + +__Usecase__: Used when no useful information exists that can be used to apply +restrictions. + +__Example Usage__: + +~~~{.cpp} +vtkArrayDispatch::Dispatch::Execute(array, worker); +~~~ + +--- + +### vtkArrayDispatch::DispatchByArray ### {#VTKAD-DispatchByArray} + +This family of dispatchers takes a `vtkTypeList` of explicit array types to use +during dispatching. They should only be used when an array's exact type is +restricted. If dispatching multiple arrays and only one has such type +restrictions, use `vtkArrayDispatch::Arrays` (or a filtered version) for the +unrestricted arrays. + +__Variations__: +* `vtkArrayDispatch::DispatchByArray`: Single dispatch. +* `vtkArrayDispatch::Dispatch2ByArray`: Double dispatch. +* `vtkArrayDispatch::Dispatch3ByArray`: Triple dispatch. + +__Arrays considered__: All arrays explicitly listed in the parameter lists. + +__Restrictions__: Array must be explicitly listed in the dispatcher's type. + +__Usecase__: Used when one or more arrays have known implementations. + +__Example Usage__: + +An example here would be a filter that processes an input array of some +integral type and produces either a `vtkDoubleArray` or a `vtkFloatArray`, +depending on some condition. Since the input array's implementation is unknown +(it comes from outside the filter), we'll rely on a ValueType-filtered version +of `vtkArrayDispatch::Arrays` for its type. However, we know the output array +is either `vtkDoubleArray` or `vtkFloatArray`, so we'll want to be sure to +apply that restriction: + +~~~{.cpp} +// input has an unknown implementation, but an integral ValueType. +vtkDataArray *input = ...; + +// Output is always either vtkFloatArray or vtkDoubleArray: +vtkDataArray *output = someCondition ? vtkFloatArray::New() + : vtkDoubleArray::New(); + +// Define the valid ArrayTypes for input by filtering +// vtkArrayDispatch::Arrays to remove non-integral types: +typedef typename vtkArrayDispatch::FilterArraysByValueType + < + vtkArrayDispatch::Arrays, + vtkArrayDispatch::Integrals + >::Result InputTypes; + +// For output, create a new vtkTypeList with the only two possibilities: +typedef vtkTypeList_Create_2(vtkFloatArray, vtkDoubleArray) OutputTypes; + +// Typedef the dispatch to a more manageable name: +typedef vtkArrayDispatch::Dispatch2ByArray + < + InputTypes, + OutputTypes + > MyDispatch; + +// Execute the dispatch: +MyDispatch::Execute(input, output, someWorker); +~~~ + +--- + +### vtkArrayDispatch::DispatchByValueType ### {#VTKAD-DispatchByValueType} + +This family of dispatchers takes a vtkTypeList of ValueTypes for each array and +restricts dispatch to only arrays in vtkArrayDispatch::Arrays that have one of +the specified value types. + +__Variations__: +* `vtkArrayDispatch::DispatchByValueType`: Single dispatch. +* `vtkArrayDispatch::Dispatch2ByValueType`: Double dispatch. +* `vtkArrayDispatch::Dispatch3ByValueType`: Triple dispatch. + +__Arrays considered__: All arrays in `vtkArrayDispatch::Arrays` that meet the +ValueType requirements. + +__Restrictions__: Arrays that do not satisfy the ValueType requirements are +eliminated. + +__Usecase__: Used when one or more of the dispatched arrays has an unknown +implementation, but a known (or restricted) ValueType. + +__Example Usage__: + +Here we'll consider a filter that processes three arrays. The first is a +complete unknown. The second is known to hold `unsigned char`, but we don't +know the implementation. The third holds either `double`s or `float`s, but its +implementation is also unknown. + +~~~{.cpp} +// Complete unknown: +vtkDataArray *array1 = ...; +// Some array holding unsigned chars: +vtkDataArray *array2 = ...; +// Some array holding either floats or doubles: +vtkDataArray *array3 = ...; + +// Typedef the dispatch to a more manageable name: +typedef vtkArrayDispatch::Dispatch3ByValueType + < + vtkArrayDispatch::AllTypes, + vtkTypeList_Create_1(unsigned char), + vtkArrayDispatch::Reals + > MyDispatch; + +// Execute the dispatch: +MyDispatch::Execute(array1, array2, array3, someWorker); +~~~ + +--- + +### vtkArrayDispatch::DispatchByArrayWithSameValueType ### {#VTKAD-DispatchByArrayWithSameValueType} + +This family of dispatchers takes a `vtkTypeList` of ArrayTypes for each array +and restricts dispatch to only consider arrays from those typelists, with the +added requirement that all dispatched arrays share a ValueType. + +__Variations__: +* `vtkArrayDispatch::Dispatch2ByArrayWithSameValueType`: Double dispatch. +* `vtkArrayDispatch::Dispatch3ByArrayWithSameValueType`: Triple dispatch. + +__Arrays considered__: All arrays in the explicit typelists that meet the +ValueType requirements. + +__Restrictions__: Combinations of arrays with differing ValueTypes are +eliminated. + +__Usecase__: When one or more arrays are known to belong to a restricted set of +ArrayTypes, and all arrays are known to share the same ValueType, regardless of +implementation. + +__Example Usage__: + +Let's consider a double array dispatch, with `array1` known to be one of four +common array types (AOS `float`, `double`, `int`, and `vtkIdType` arrays), and +the other is a complete unknown, although we know that it holds the same +ValueType as `array1`. + +~~~{.cpp} +// AOS float, double, int, or vtkIdType array: +vtkDataArray *array1 = ...; +// Unknown implementation, but the ValueType matches array1: +vtkDataArray *array2 = ...; + +// array1's possible types: +typedef vtkTypeList_Create_4(vtkFloatArray, vtkDoubleArray, + vtkIntArray, vtkIdTypeArray) Array1Types; + +// array2's possible types: +typedef typename vtkArrayDispatch::FilterArraysByValueType + < + vtkArrayDispatch::Arrays, + vtkTypeList_Create_4(float, double, int, vtkIdType) + > Array2Types; + +// Typedef the dispatch to a more manageable name: +typedef vtkArrayDispatch::Dispatch2ByArrayWithSameValueType + < + Array1Types, + Array2Types + > MyDispatch; + +// Execute the dispatch: +MyDispatch::Execute(array1, array2, someWorker); +~~~ + +--- + +### vtkArrayDispatch::DispatchBySameValueType ### {#VTKAD-DispatchBySameValueType} + +This family of dispatchers takes a single `vtkTypeList` of ValueType and +restricts dispatch to only consider arrays from `vtkArrayDispatch::Arrays` with +those ValueTypes, with the added requirement that all dispatched arrays share a +ValueType. + +__Variations__: +* `vtkArrayDispatch::Dispatch2BySameValueType`: Double dispatch. +* `vtkArrayDispatch::Dispatch3BySameValueType`: Triple dispatch. +* `vtkArrayDispatch::Dispatch2SameValueType`: Double dispatch using +`vtkArrayDispatch::AllTypes`. +* `vtkArrayDispatch::Dispatch3SameValueType`: Triple dispatch using +`vtkArrayDispatch::AllTypes`. + +__Arrays considered__: All arrays in `vtkArrayDispatch::Arrays` that meet the +ValueType requirements. + +__Restrictions__: Combinations of arrays with differing ValueTypes are +eliminated. + +__Usecase__: When one or more arrays are known to belong to a restricted set of +ValueTypes, and all arrays are known to share the same ValueType, regardless of +implementation. + +__Example Usage__: + +Let's consider a double array dispatch, with `array1` known to be one of four +common ValueTypes (`float`, `double`, `int`, and `vtkIdType` arrays), and +`array2` known to have the same ValueType as `array1`. + +~~~{.cpp} +// Some float, double, int, or vtkIdType array: +vtkDataArray *array1 = ...; +// Unknown, but the ValueType matches array1: +vtkDataArray *array2 = ...; + +// The allowed ValueTypes: +typedef vtkTypeList_Create_4(float, double, int, vtkIdType) ValidValueTypes; + +// Typedef the dispatch to a more manageable name: +typedef vtkArrayDispatch::Dispatch2BySameValueType + < + ValidValueTypes + > MyDispatch; + +// Execute the dispatch: +MyDispatch::Execute(array1, array2, someWorker); +~~~ + +--- + +# Advanced Usage # {#VTKAD-AdvancedUsage} + +## Accessing Memory Buffers ## {#VTKAD-AccessingMemoryBuffers} + +Despite the thin `vtkGenericDataArray` API's nice feature that compilers can +optimize memory accesses, sometimes there are still legitimate reasons to +access the underlying memory buffer. This can still be done safely by providing +overloads to your worker's `operator()` method. For instance, +`vtkDataArray::DeepCopy` uses a generic implementation when mixed array +implementations are used, but has optimized overloads for copying between +arrays with the same ValueType and implementation. The worker for this dispatch +is shown below as an example: + +~~~{.cpp} +// Copy tuples from src to dest: +struct DeepCopyWorker +{ + // AoS --> AoS same-type specialization: + template + void operator()(vtkAOSDataArrayTemplate *src, + vtkAOSDataArrayTemplate *dst) + { + std::copy(src->Begin(), src->End(), dst->Begin()); + } + + // SoA --> SoA same-type specialization: + template + void operator()(vtkSOADataArrayTemplate *src, + vtkSOADataArrayTemplate *dst) + { + vtkIdType numTuples = src->GetNumberOfTuples(); + for (int comp; comp < src->GetNumberOfComponents(); ++comp) + { + ValueType *srcBegin = src->GetComponentArrayPointer(comp); + ValueType *srcEnd = srcBegin + numTuples; + ValueType *dstBegin = dst->GetComponentArrayPointer(comp); + + std::copy(srcBegin, srcEnd, dstBegin); + } + } + + // Generic implementation: + template + void operator()(Array1T *src, Array2T *dst) + { + vtkDataArrayAccessor s(src); + vtkDataArrayAccessor d(dst); + + typedef typename vtkDataArrayAccessor::APIType DestType; + + vtkIdType tuples = src->GetNumberOfTuples(); + int comps = src->GetNumberOfComponents(); + + for (vtkIdType t = 0; t < tuples; ++t) + { + for (int c = 0; c < comps; ++c) + { + d.Set(t, c, static_cast(s.Get(t, c))); + } + } + } +}; +~~~ + +# Putting It All Together # {#VTKAD-PuttingItAllTogether} + +Now that we've explored the new tools introduced with VTK 7.1 that allow +efficient, implementation agnostic array access, let's take another look at the +`calcMagnitude` example from before and identify the key features of the +implementation: + +~~~{.cpp} +// Modern implementation of calcMagnitude using new concepts in VTK 7.1: +struct CalcMagnitudeWorker +{ + template + void operator()(VectorArray *vectors, MagnitudeArray *magnitude) + { + VTK_ASSUME(vectors->GetNumberOfComponents() == 3); + VTK_ASSUME(magnitude->GetNumberOfComponents() == 1); + + vtkDataArrayAccessor v(vectors); + vtkDataArrayAccessor m(magnitude); + + vtkIdType numVectors = vectors->GetNumberOfTuples(); + for (vtkIdType tupleIdx = 0; tupleIdx < numVectors; ++tupleIdx) + { + m.Set(tupleIdx, 0, std::sqrt(v.Get(tupleIdx, 0) * v.Get(tupleIdx, 0) + + v.Get(tupleIdx, 1) * v.Get(tupleIdx, 1) + + v.Get(tupleIdx, 2) * v.Get(tupleIdx, 2))); + } + } +}; + +void calcMagnitude(vtkDataArray *vectors, vtkDataArray *magnitude) +{ + CalcMagnitudeWorker worker; + typedef vtkArrayDispatch::Dispatch2ByValueType + < + vtkArrayDispatch::AllTypes, + vtkArrayDispatch::Reals + > Dispatcher; + + if (!Dispatcher::Execute(vectors, magnitude, worker)) + { + worker(vectors, magnitude); // vtkDataArray fallback + } +} +~~~ + +This implementation: + +* Uses dispatch restrictions to reduce the number of instantiated templated +worker functions. + * Assuming 26 types are in `vtkArrayDispatch::Arrays` (13 AOS + 13 SOA). + * The first array is unrestricted. All 26 array types are considered. + * The second array is restricted to `float` or `double` ValueTypes, which + translates to 4 array types (one each, SOA and AOS). + * 26 * 4 = 104 possible combinations exist. We've eliminated 26 * 22 = 572 + combinations that an unrestricted double-dispatch would have generated (it + would create 676 instantiations). +* The calculation is still carried out at `double` precision when the ValueType +restrictions are not met. + * Just because we don't want those other 572 cases to have special code + generated doesn't necessarily mean that we wouldn't want them to run. + * Thanks to `vtkDataArrayAccessor`, we have a fallback implementation that + reuses our templated worker code. + * In this case, the dispatch is really just a fast-path implementation for + floating point output types. +* The performance should be identical to iterating through raw memory buffers. + * The `vtkGenericDataArray` API is transparent to the compiler. The + specialized instantiations of `operator()` can be heavily optimized since the + memory access patterns are known and well-defined. + * Using `VTK_ASSUME` tells the compiler that the arrays have known strides, + allowing further compile-time optimizations. + +Hopefully this has convinced you that the `vtkArrayDispatch` and related tools +are worth using to create flexible, efficient, typesafe implementations for +your work with VTK. Please direct any questions you may have on the subject to +the VTK mailing lists. diff --git a/Documentation/Doxygen/ChangesVTK-7-1.md b/Documentation/Doxygen/ChangesVTK-7-1.md index f387d15b791..7e3ce76324d 100644 --- a/Documentation/Doxygen/ChangesVTK-7-1.md +++ b/Documentation/Doxygen/ChangesVTK-7-1.md @@ -132,3 +132,27 @@ vtkSMPTools The following back-ends have been removed: + Simple: This is not a production level backend and was only used for debugging purposes. + Kaapi: This backend is no longer maintained. + +vtkDataArray Refactor, vtkArrayDispatch and Related Tools +--------------------------------------------------------- + +The `vtkDataArrayTemplate` template class has been replaced by +`vtkAOSDataArrayTemplate` to distinguish it from the new +`vtkSOADataArrayTemplate`. The former uses Array-Of-Structs component ordering +while the latter uses Struct-Of-Arrays component ordering. These both derive +from the new `vtkGenericDataArray` template class and are an initial +implementation of native support for alternate memory layouts in VTK. + +To facilitate working with these arrays efficiently, several new tools have +been added in this release. They are detailed \ref VTK-7-1-ArrayDispatch "here". + +As part of the refactoring effort, several `vtkDataArrayTemplate` methods were +deprecated and replaced with new, const-correct methods with more meaningful +names. + +The old and new method names are listed below: + ++ `GetTupleValue` is now `GetTypedTuple` ++ `SetTupleValue` is now `SetTypedTuple` ++ `InsertTupleValue` is now `InsertTypedTuple` ++ `InsertNextTupleValue` is now `InsertNextTypedTuple` diff --git a/Documentation/dev/git/develop.md b/Documentation/dev/git/develop.md index 86da75ff844..d8ab7105afd 100644 --- a/Documentation/dev/git/develop.md +++ b/Documentation/dev/git/develop.md @@ -344,9 +344,9 @@ The `Do: test` command accepts the following arguments: build the superbuilds related to the project * `--clear` clear previous commands before adding this command - * `--regex-include ` + * `--regex-include ` or `-i ` only build on builders matching `` (a Python regular expression) - * `--regex-exclude ` + * `--regex-exclude ` or `-e ` excludes builds on builders matching `` (a Python regular expression) diff --git a/Documentation/maint/release.md b/Documentation/maint/release.md index e6c1e56ff38..05e73f322c3 100644 --- a/Documentation/maint/release.md +++ b/Documentation/maint/release.md @@ -275,7 +275,7 @@ should create a window on the desktop. When tagging the release, use: ```sh -$ git tag -a -m "VTK $version" v$version $commit_to_be_tagged +$ git tag -s -m "VTK $version" v$version $commit_to_be_tagged ``` ### Uploading diff --git a/Domains/Chemistry/vtkBlueObeliskDataParser.cxx b/Domains/Chemistry/vtkBlueObeliskDataParser.cxx index 9b0e0e92ad9..4ba87f15124 100644 --- a/Domains/Chemistry/vtkBlueObeliskDataParser.cxx +++ b/Domains/Chemistry/vtkBlueObeliskDataParser.cxx @@ -273,7 +273,7 @@ void vtkBlueObeliskDataParser::NewAtomFinished() // Tuple handled differently this->ResizeArrayIfNeeded(this->Target->DefaultColors.GetPointer(), index); - this->Target->DefaultColors->SetTupleValue(index, + this->Target->DefaultColors->SetTypedTuple(index, this->CurrentDefaultColor); this->ResizeAndSetValue(this->CurrentBoilingPoint, this->Target->BoilingPoints.GetPointer(), diff --git a/Domains/Chemistry/vtkMoleculeMapper.cxx b/Domains/Chemistry/vtkMoleculeMapper.cxx index 2a01b11cdef..2e5fdfcffcb 100644 --- a/Domains/Chemistry/vtkMoleculeMapper.cxx +++ b/Domains/Chemistry/vtkMoleculeMapper.cxx @@ -258,7 +258,7 @@ void vtkMoleculeMapper::GetSelectedAtomsAndBonds(vtkSelection *selection, if (selActor && (selActor->GetMapper() == this)) { // Separate the selection ids into atoms and bonds - vtkIdTypeArray *selIds = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray *selIds = vtkArrayDownCast( node->GetSelectionList()); if (selIds) { @@ -476,9 +476,9 @@ void vtkMoleculeMapper::UpdateBondGlyphPolyData() // Set up pointers to the specific color arrays vtkUnsignedCharArray *singleColorArray = - vtkUnsignedCharArray::SafeDownCast(cylColors); + vtkArrayDownCast(cylColors); vtkUnsignedShortArray *discreteColorArray = - vtkUnsignedShortArray::SafeDownCast(cylColors); + vtkArrayDownCast(cylColors); // Remove reference to cylColors cylColors->Delete(); diff --git a/Domains/Chemistry/vtkPeriodicTable.cxx b/Domains/Chemistry/vtkPeriodicTable.cxx index 23e20c7caaa..e4ee8547273 100644 --- a/Domains/Chemistry/vtkPeriodicTable.cxx +++ b/Domains/Chemistry/vtkPeriodicTable.cxx @@ -184,7 +184,7 @@ void vtkPeriodicTable::GetDefaultLUT(vtkLookupTable * lut) float rgb[3]; for (vtkIdType i = 0; static_cast(i) < numColors; ++i) { - colors->GetTupleValue(i, rgb); + colors->GetTypedTuple(i, rgb); lut->SetTableValue(i, rgb[0], rgb[1], rgb[2]); } } @@ -193,14 +193,14 @@ void vtkPeriodicTable::GetDefaultLUT(vtkLookupTable * lut) void vtkPeriodicTable::GetDefaultRGBTuple(unsigned short atomicNum, float rgb[3]) { - this->BlueObeliskData->GetDefaultColors()->GetTupleValue(atomicNum, rgb); + this->BlueObeliskData->GetDefaultColors()->GetTypedTuple(atomicNum, rgb); } //---------------------------------------------------------------------------- vtkColor3f vtkPeriodicTable::GetDefaultRGBTuple(unsigned short atomicNum) { vtkColor3f result; - this->BlueObeliskData->GetDefaultColors()->GetTupleValue(atomicNum, + this->BlueObeliskData->GetDefaultColors()->GetTypedTuple(atomicNum, result.GetData()); return result; } diff --git a/Domains/Chemistry/vtkProteinRibbonFilter.cxx b/Domains/Chemistry/vtkProteinRibbonFilter.cxx index ed93a1c6c89..44e160d4448 100644 --- a/Domains/Chemistry/vtkProteinRibbonFilter.cxx +++ b/Domains/Chemistry/vtkProteinRibbonFilter.cxx @@ -107,9 +107,9 @@ int vtkProteinRibbonFilter::RequestData(vtkInformation *, // Extract alpha-carbon backbone from input poly data vtkStringArray *atomTypes = - vtkStringArray::SafeDownCast(pointData->GetAbstractArray("atom_types")); + vtkArrayDownCast(pointData->GetAbstractArray("atom_types")); vtkIdTypeArray *atomType = - vtkIdTypeArray::SafeDownCast(pointData->GetAbstractArray("atom_type")); + vtkArrayDownCast(pointData->GetAbstractArray("atom_type")); if (!atomTypes || !atomType) { @@ -119,17 +119,17 @@ int vtkProteinRibbonFilter::RequestData(vtkInformation *, // Extract secondary structures information from input poly data vtkIdTypeArray *resi = - vtkIdTypeArray::SafeDownCast(pointData->GetAbstractArray("residue")); + vtkArrayDownCast(pointData->GetAbstractArray("residue")); vtkUnsignedCharArray *chain = - vtkUnsignedCharArray::SafeDownCast(pointData->GetAbstractArray("chain")); + vtkArrayDownCast(pointData->GetAbstractArray("chain")); vtkUnsignedCharArray *atom_ss = - vtkUnsignedCharArray::SafeDownCast(pointData->GetAbstractArray("secondary_structures")); + vtkArrayDownCast(pointData->GetAbstractArray("secondary_structures")); vtkUnsignedCharArray *atom_ssbegin = - vtkUnsignedCharArray::SafeDownCast(pointData->GetAbstractArray("secondary_structures_begin")); + vtkArrayDownCast(pointData->GetAbstractArray("secondary_structures_begin")); vtkUnsignedCharArray *atom_ssend = - vtkUnsignedCharArray::SafeDownCast(pointData->GetAbstractArray("secondary_structures_end")); + vtkArrayDownCast(pointData->GetAbstractArray("secondary_structures_end")); vtkUnsignedCharArray *ishetatm = - vtkUnsignedCharArray::SafeDownCast(pointData->GetAbstractArray("ishetatm")); + vtkArrayDownCast(pointData->GetAbstractArray("ishetatm")); if (!resi || !chain || !atom_ss || !atom_ssbegin || !atom_ssend || !ishetatm) { diff --git a/Domains/ChemistryOpenGL2/vtkOpenGLSphereMapper.cxx b/Domains/ChemistryOpenGL2/vtkOpenGLSphereMapper.cxx index c041c55384c..a233076b874 100644 --- a/Domains/ChemistryOpenGL2/vtkOpenGLSphereMapper.cxx +++ b/Domains/ChemistryOpenGL2/vtkOpenGLSphereMapper.cxx @@ -73,7 +73,8 @@ void vtkOpenGLSphereMapper::ReplaceShaderValues( // we create vertexVC below, so turn off the default // implementation vtkShaderProgram::Substitute(FSSource, - "//VTK::PositionVC::Impl",""); + "//VTK::PositionVC::Impl", + "vec4 vertexVC = vertexVCVSOutput;\n"); // for lights kit and positional the VCDC matrix is already defined // so don't redefine it @@ -87,7 +88,6 @@ void vtkOpenGLSphereMapper::ReplaceShaderValues( vtkShaderProgram::Substitute(FSSource,"//VTK::Normal::Impl", // compute the eye position and unit direction - "vec4 vertexVC = vertexVCVSOutput;\n" " vec3 EyePos;\n" " vec3 EyeDir;\n" " if (cameraParallel != 0) {\n" @@ -167,22 +167,31 @@ void vtkOpenGLSphereMapper::SetCameraShaderParameters( vtkMatrix3x3 *norms; vtkMatrix4x4 *vcdc; cam->GetKeyMatrices(ren,wcvc,norms,vcdc,wcdc); - program->SetUniformMatrix("VCDCMatrix", vcdc); - - if (!actor->GetIsIdentity()) + if (program->IsUniformUsed("VCDCMatrix")) { - vtkMatrix4x4 *mcwc; - vtkMatrix3x3 *anorms; - ((vtkOpenGLActor *)actor)->GetKeyMatrices(mcwc,anorms); - vtkMatrix4x4::Multiply4x4(mcwc, wcvc, this->TempMatrix4); - program->SetUniformMatrix("MCVCMatrix", this->TempMatrix4); + program->SetUniformMatrix("VCDCMatrix", vcdc); } - else + + if (program->IsUniformUsed("MCVCMatrix")) { - program->SetUniformMatrix("MCVCMatrix", wcvc); + if (!actor->GetIsIdentity()) + { + vtkMatrix4x4 *mcwc; + vtkMatrix3x3 *anorms; + ((vtkOpenGLActor *)actor)->GetKeyMatrices(mcwc,anorms); + vtkMatrix4x4::Multiply4x4(mcwc, wcvc, this->TempMatrix4); + program->SetUniformMatrix("MCVCMatrix", this->TempMatrix4); + } + else + { + program->SetUniformMatrix("MCVCMatrix", wcvc); + } } - cellBO.Program->SetUniformi("cameraParallel", cam->GetParallelProjection()); + if (program->IsUniformUsed("cameraParallel")) + { + cellBO.Program->SetUniformi("cameraParallel", cam->GetParallelProjection()); + } } //----------------------------------------------------------------------------- @@ -191,7 +200,8 @@ void vtkOpenGLSphereMapper::SetMapperShaderParameters( vtkRenderer *ren, vtkActor *actor) { if (cellBO.IBO->IndexCount && (this->VBOBuildTime > cellBO.AttributeUpdateTime || - cellBO.ShaderSourceTime > cellBO.AttributeUpdateTime)) + cellBO.ShaderSourceTime > cellBO.AttributeUpdateTime) && + cellBO.Program->IsAttributeUsed("offsetMC")) { cellBO.VAO->Bind(); if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, @@ -202,7 +212,11 @@ void vtkOpenGLSphereMapper::SetMapperShaderParameters( } } - cellBO.Program->SetUniformf("invertedDepth", this->Invert ? -1.0 : 1.0); + if (cellBO.Program->IsUniformUsed("invertedDepth")) + { + cellBO.Program->SetUniformf("invertedDepth", this->Invert ? -1.0 : 1.0); + } + this->Superclass::SetMapperShaderParameters(cellBO,ren,actor); } diff --git a/Domains/ChemistryOpenGL2/vtkOpenGLStickMapper.cxx b/Domains/ChemistryOpenGL2/vtkOpenGLStickMapper.cxx index ed94466c633..7d1b98798a8 100644 --- a/Domains/ChemistryOpenGL2/vtkOpenGLStickMapper.cxx +++ b/Domains/ChemistryOpenGL2/vtkOpenGLStickMapper.cxx @@ -76,7 +76,8 @@ void vtkOpenGLStickMapper::ReplaceShaderValues( // we create vertexVC below, so turn off the default // implementation vtkShaderProgram::Substitute(FSSource, - "//VTK::PositionVC::Impl",""); + "//VTK::PositionVC::Impl", + " vec4 vertexVC = vertexVCVSOutput;\n"); // for lights kit and positional the VCDC matrix is already defined // so don't redefine it @@ -93,7 +94,6 @@ void vtkOpenGLStickMapper::ReplaceShaderValues( // see https://www.cl.cam.ac.uk/teaching/1999/AGraphHCI/SMAG/node2.html vtkShaderProgram::Substitute(FSSource,"//VTK::Normal::Impl", // compute the eye position and unit direction - " vec4 vertexVC = vertexVCVSOutput;\n" " vec3 EyePos;\n" " vec3 EyeDir;\n" " if (cameraParallel != 0) {\n" @@ -237,25 +237,44 @@ void vtkOpenGLStickMapper::SetCameraShaderParameters(vtkOpenGLHelper &cellBO, vtkMatrix3x3 *norms; vtkMatrix4x4 *vcdc; cam->GetKeyMatrices(ren,wcvc,norms,vcdc,wcdc); - program->SetUniformMatrix("VCDCMatrix", vcdc); + + if (program->IsUniformUsed("VCDCMatrix")) + { + program->SetUniformMatrix("VCDCMatrix", vcdc); + } if (!actor->GetIsIdentity()) { vtkMatrix4x4 *mcwc; vtkMatrix3x3 *anorms; ((vtkOpenGLActor *)actor)->GetKeyMatrices(mcwc,anorms); - vtkMatrix4x4::Multiply4x4(mcwc, wcvc, this->TempMatrix4); - program->SetUniformMatrix("MCVCMatrix", this->TempMatrix4); - vtkMatrix3x3::Multiply3x3(anorms, norms, this->TempMatrix3); - program->SetUniformMatrix("normalMatrix", this->TempMatrix3); + if (program->IsUniformUsed("MCVCMatrix")) + { + vtkMatrix4x4::Multiply4x4(mcwc, wcvc, this->TempMatrix4); + program->SetUniformMatrix("MCVCMatrix", this->TempMatrix4); + } + if (program->IsUniformUsed("normalMatrix")) + { + vtkMatrix3x3::Multiply3x3(anorms, norms, this->TempMatrix3); + program->SetUniformMatrix("normalMatrix", this->TempMatrix3); + } } else { - program->SetUniformMatrix("MCVCMatrix", wcvc); - program->SetUniformMatrix("normalMatrix", norms); + if (program->IsUniformUsed("MCVCMatrix")) + { + program->SetUniformMatrix("MCVCMatrix", wcvc); + } + if (program->IsUniformUsed("normalMatrix")) + { + program->SetUniformMatrix("normalMatrix", norms); + } } - cellBO.Program->SetUniformi("cameraParallel", cam->GetParallelProjection()); + if (program->IsUniformUsed("cameraParallel")) + { + cellBO.Program->SetUniformi("cameraParallel", cam->GetParallelProjection()); + } } //----------------------------------------------------------------------------- @@ -271,31 +290,49 @@ void vtkOpenGLStickMapper::SetMapperShaderParameters( bool picking = (ren->GetRenderWindow()->GetIsPicking() || selector != NULL); cellBO.VAO->Bind(); - if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, - "orientMC", this->VBO->ColorOffset+sizeof(float), - this->VBO->Stride, VTK_FLOAT, 3, false)) + if (cellBO.Program->IsAttributeUsed("orientMC")) { - vtkErrorMacro(<< "Error setting 'orientMC' in shader VAO."); + if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, + "orientMC", + this->VBO->ColorOffset + sizeof(float), + this->VBO->Stride, VTK_FLOAT, 3, + false)) + { + vtkErrorMacro(<< "Error setting 'orientMC' in shader VAO."); + } } - if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, - "offsetMC", this->VBO->ColorOffset+4*sizeof(float), - this->VBO->Stride, VTK_UNSIGNED_CHAR, 3, false)) + if (cellBO.Program->IsAttributeUsed("offsetMC")) { - vtkErrorMacro(<< "Error setting 'offsetMC' in shader VAO."); + if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, + "offsetMC", + this->VBO->ColorOffset+4*sizeof(float), + this->VBO->Stride, VTK_UNSIGNED_CHAR, + 3, false)) + { + vtkErrorMacro(<< "Error setting 'offsetMC' in shader VAO."); + } } - if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, - "radiusMC", this->VBO->ColorOffset+5*sizeof(float), - this->VBO->Stride, VTK_FLOAT, 1, false)) + if (cellBO.Program->IsAttributeUsed("radiusMC")) { - vtkErrorMacro(<< "Error setting 'radiusMC' in shader VAO."); + if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, + "radiusMC", + this->VBO->ColorOffset+5*sizeof(float), + this->VBO->Stride, VTK_FLOAT, 1, + false)) + { + vtkErrorMacro(<< "Error setting 'radiusMC' in shader VAO."); + } } if (picking && (!selector || - (this->LastSelectionState >= vtkHardwareSelector::ID_LOW24))) + (this->LastSelectionState >= vtkHardwareSelector::ID_LOW24)) && + cellBO.Program->IsAttributeUsed("selectionId")) { if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, - "selectionId", this->VBO->ColorOffset+6*sizeof(float), - this->VBO->Stride, VTK_UNSIGNED_CHAR, 4, true)) + "selectionId", + this->VBO->ColorOffset+6*sizeof(float), + this->VBO->Stride, VTK_UNSIGNED_CHAR, + 4, true)) { vtkErrorMacro(<< "Error setting 'selectionId' in shader VAO."); } diff --git a/Domains/Microscopy/CMakeLists.txt b/Domains/Microscopy/CMakeLists.txt new file mode 100644 index 00000000000..799ebb413e0 --- /dev/null +++ b/Domains/Microscopy/CMakeLists.txt @@ -0,0 +1,16 @@ +# OpenSlide required +LIST(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}") +find_package(OpenSlide REQUIRED) + +mark_as_advanced(OPENSLIDE_INCLUDE_DIR OPENSLIDE_LIBRARY) + +set(OPENSLIDE_SRCS vtkOpenSlideReader.cxx) + +include_directories(${OPENSLIDE_INCLUDE_DIRS}) + +set(${vtk-module}_SYSTEM_INCLUDE_DIRS + ${OPENSLIDE_INCLUDE_DIRS}) + +vtk_module_library(vtkDomainsMicroscopy ${OPENSLIDE_SRCS}) + +vtk_module_link_libraries(vtkDomainsMicroscopy LINK_PRIVATE ${OPENSLIDE_LIBRARY}) diff --git a/Domains/Microscopy/FindOpenSlide.cmake b/Domains/Microscopy/FindOpenSlide.cmake new file mode 100644 index 00000000000..4ca6cd289ad --- /dev/null +++ b/Domains/Microscopy/FindOpenSlide.cmake @@ -0,0 +1,30 @@ +# A CMake find module for the OpenSlide microscopy file reader library. +# +# http://openslide.org +# +# Once done, this module will define +# OPENSLIDE_FOUND - system has OpenSlide +# OPENSLIDE_INCLUDE_DIRS - the OpenSlide include directory +# OPENSLIDE_LIBRARIES - link to these to use OpenSlide + +# Look for the header. +find_path( OPENSLIDE_INCLUDE_DIR NAMES openslide.h PATHS + /usr/local/include/openslide + /usr/include/openslide) + +mark_as_advanced( OPENSLIDE_INCLUDE_DIR ) + +# Look for the library. +find_library( OPENSLIDE_LIBRARY NAMES openslide ) +mark_as_advanced( OPENSLIDE_LIBRARY ) + +# Handle the QUIETLY and REQUIRED arguments and set OPENSLIDE_FOUND true if all +# the listed variables are TRUE. + +find_package( PackageHandleStandardArgs ) +FIND_PACKAGE_HANDLE_STANDARD_ARGS( OPENSLIDE DEFAULT_MSG OPENSLIDE_LIBRARY OPENSLIDE_INCLUDE_DIR ) + +if( OPENSLIDE_FOUND ) + set( OPENSLIDE_LIBRARIES ${OPENSLIDE_LIBRARY} ) + set( OPENSLIDE_INCLUDE_DIRS ${OPENSLIDE_INCLUDE_DIR} ) +endif() diff --git a/Domains/Microscopy/Testing/Cxx/CMakeLists.txt b/Domains/Microscopy/Testing/Cxx/CMakeLists.txt new file mode 100644 index 00000000000..83be57b3f85 --- /dev/null +++ b/Domains/Microscopy/Testing/Cxx/CMakeLists.txt @@ -0,0 +1,14 @@ + +# OpenSlideReader Tests + +vtk_add_test_cxx(${vtk-module}CxxTests tests + TestOpenSlideReader.cxx + "DATA{${VTK_TEST_INPUT_DIR}/Microscopy/small2.ndpi}" + ) + +vtk_add_test_cxx(${vtk-module}CxxTests tests + TestOpenSlideReaderPartialTIF,TestOpenSlideReaderPartial.cxx + "DATA{${VTK_TEST_INPUT_DIR}/Microscopy/pathology.tif}" + ) + +vtk_test_cxx_executable(${vtk-module}CxxTests tests RENDERING_FACTORY) diff --git a/Domains/Microscopy/Testing/Cxx/TestOpenSlideReader.cxx b/Domains/Microscopy/Testing/Cxx/TestOpenSlideReader.cxx new file mode 100644 index 00000000000..1f70c7ebaad --- /dev/null +++ b/Domains/Microscopy/Testing/Cxx/TestOpenSlideReader.cxx @@ -0,0 +1,76 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOpenSlideReader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include +#include +#include +#include +#include +#include +#include +#include + +// VTK includes +#include + +// C++ includes +#include + +// Main program +int TestOpenSlideReader(int argc, char** argv) +{ + // This test is known to fail with openslide library libopenslide-dev shipped + // with ubuntu 14.04 as of March 31'2016. It does pass on fedora23, or if the + // openslide library is built from source + const char* rasterFileName = vtkTestUtilities::ExpandDataFileName(argc, argv, + "Data/Microscopy/small2.ndpi"); + + //std::cout << "Got Filename: " << rasterFileName << std::endl; + + // Create reader to read shape file. + vtkNew reader; + reader->SetFileName(rasterFileName); + reader->UpdateInformation(); + delete [] rasterFileName; + + // For debug + // reader->SetUpdateExtent(extent); + // vtkNew writer; + // writer->SetInputConnection(reader->GetOutputPort()); + // writer->SetFileName("this.png"); + // writer->SetUpdateExtent(extent); + // writer->Update(); + // writer->Write(); + + // Visualize + vtkNew renderer; + vtkNew window; + window->AddRenderer(renderer.GetPointer()); + + vtkNew renderWindowInteractor; + renderWindowInteractor->SetRenderWindow(window.GetPointer()); + + vtkNew imageViewer; + imageViewer->SetInputConnection(reader->GetOutputPort()); + //imageViewer->SetExtent(1000,1500,1000,1500,0,0); + imageViewer->SetupInteractor(renderWindowInteractor.GetPointer()); + //imageViewer->SetSlice(0); + imageViewer->Render(); + imageViewer->GetRenderer()->ResetCamera(); + renderWindowInteractor->Initialize(); + imageViewer->Render(); + renderWindowInteractor->Start(); + + return EXIT_SUCCESS; +} diff --git a/Domains/Microscopy/Testing/Cxx/TestOpenSlideReaderPartial.cxx b/Domains/Microscopy/Testing/Cxx/TestOpenSlideReaderPartial.cxx new file mode 100644 index 00000000000..41873b85a03 --- /dev/null +++ b/Domains/Microscopy/Testing/Cxx/TestOpenSlideReaderPartial.cxx @@ -0,0 +1,81 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOpenSlideReader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include +#include +#include +#include +#include +#include +#include +#include + +// VTK includes +#include + +// C++ includes +#include + +// Main program +int TestOpenSlideReaderPartial(int argc, char** argv) +{ + if ( argc <= 1 ) + { + std::cout << "Usage: " << argv[0] << " " << endl; + return EXIT_FAILURE; + } + + std::cout << "Got Filename: " << argv[1] << std::endl; + + // Create reader to read shape file. + vtkNew reader; + reader->SetFileName(argv[1]); + reader->UpdateInformation(); + + int extent[6] = {100,299,100,299,0,0}; + + reader->UpdateExtent(extent); + + vtkNew data; + data->ShallowCopy(reader->GetOutput()); + + // // For debug + // vtkNew writer; + // writer->SetInputData(data.GetPointer()); + // writer->SetFileName("this.png"); + // writer->SetUpdateExtent(extent); + // writer->Update(); + // writer->Write(); + + // Visualize + vtkNew renderer; + vtkNew window; + window->AddRenderer(renderer.GetPointer()); + + vtkNew renderWindowInteractor; + renderWindowInteractor->SetRenderWindow(window.GetPointer()); + + vtkNew imageViewer; + imageViewer->SetInputData(data.GetPointer()); + //imageViewer->SetExtent(1000,1500,1000,1500,0,0); + imageViewer->SetupInteractor(renderWindowInteractor.GetPointer()); + //imageViewer->SetSlice(0); + imageViewer->Render(); + imageViewer->GetRenderer()->ResetCamera(); + renderWindowInteractor->Initialize(); + imageViewer->Render(); + renderWindowInteractor->Start(); + + return EXIT_SUCCESS; +} diff --git a/Domains/Microscopy/Testing/Data/Baseline/TestOpenSlideReader.png.md5 b/Domains/Microscopy/Testing/Data/Baseline/TestOpenSlideReader.png.md5 new file mode 100644 index 00000000000..72cb2a1d0d6 --- /dev/null +++ b/Domains/Microscopy/Testing/Data/Baseline/TestOpenSlideReader.png.md5 @@ -0,0 +1 @@ +c89273d8e9e3160cd1ac9d1f3a31bbf7 diff --git a/Domains/Microscopy/Testing/Data/Baseline/TestOpenSlideReaderPartial.png.md5 b/Domains/Microscopy/Testing/Data/Baseline/TestOpenSlideReaderPartial.png.md5 new file mode 100644 index 00000000000..8caf62780db --- /dev/null +++ b/Domains/Microscopy/Testing/Data/Baseline/TestOpenSlideReaderPartial.png.md5 @@ -0,0 +1 @@ +4b2972c7011281baa9a0fb3c883ffb7a diff --git a/Domains/Microscopy/Testing/Data/Baseline/TestOpenSlideReaderPartialTIF.png.md5 b/Domains/Microscopy/Testing/Data/Baseline/TestOpenSlideReaderPartialTIF.png.md5 new file mode 100644 index 00000000000..9882e055857 --- /dev/null +++ b/Domains/Microscopy/Testing/Data/Baseline/TestOpenSlideReaderPartialTIF.png.md5 @@ -0,0 +1 @@ +2513faaa18fd17a568b47e0bf0c10531 diff --git a/Domains/Microscopy/Testing/Python/CMakeLists.txt b/Domains/Microscopy/Testing/Python/CMakeLists.txt new file mode 100644 index 00000000000..c0180a587ef --- /dev/null +++ b/Domains/Microscopy/Testing/Python/CMakeLists.txt @@ -0,0 +1,2 @@ +vtk_add_test_python( + testOpenSlideReader.py,NO_OUTPUT,NO_RT,NO_VALID) diff --git a/Domains/Microscopy/Testing/Python/testOpenSlideReader.py b/Domains/Microscopy/Testing/Python/testOpenSlideReader.py new file mode 100755 index 00000000000..798c8ec411e --- /dev/null +++ b/Domains/Microscopy/Testing/Python/testOpenSlideReader.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +import vtk +from vtk.test import Testing +from vtk.util.misc import vtkGetDataRoot +VTK_DATA_ROOT = vtkGetDataRoot() +import sys + +class TestOpenSlideReader(Testing.vtkTest): + + def testCanReadFile(self): + reader = vtk.vtkOpenSlideReader() + self.assertEqual(reader.CanReadFile(VTK_DATA_ROOT + "/Data/RectGrid2.vtk"), 0) + + def testCanNotReadFile(self): + reader = vtk.vtkOpenSlideReader() + self.assertEqual(reader.CanReadFile(VTK_DATA_ROOT + "/Data/Microscopy/small2.ndpi"), 2) + +if __name__ == "__main__": + Testing.main([(TestOpenSlideReader, 'test')]) diff --git a/Domains/Microscopy/module.cmake b/Domains/Microscopy/module.cmake new file mode 100644 index 00000000000..227f1c8f20c --- /dev/null +++ b/Domains/Microscopy/module.cmake @@ -0,0 +1,16 @@ +vtk_module(vtkDomainsMicroscopy + DESCRIPTION "Readers and writers supporting whole slide images for microscopy domain" + DEPENDS + vtkCommonDataModel + vtkCommonExecutionModel + vtkIOImage + PRIVATE_DEPENDS + vtkIOXML + vtkFiltersSources + TEST_DEPENDS + vtkTestingCore + vtkTestingRendering + vtkInteractionImage + vtkRenderingContext${VTK_RENDERING_BACKEND} + EXCLUDE_FROM_ALL + ) diff --git a/Domains/Microscopy/readme.md b/Domains/Microscopy/readme.md new file mode 100644 index 00000000000..6004ad4ca25 --- /dev/null +++ b/Domains/Microscopy/readme.md @@ -0,0 +1,8 @@ +# vtkOpenSlideReader +- A new image reader for vtk +- Wraps open source [openslide library](https://github.com/openslide/openslide "openslide") which implements read support for many whole slide image formats +- Mainly from microscopy domain +- Requires openslide libraries for building + +# Known issues +- Ubuntu 14.04 contains incorrectly patched version of openjpeg (dependency of openslide), and thus openslide is unable to decode certain .svs files. This issue is not present in later versions of ubuntu or fedora 23. diff --git a/Domains/Microscopy/vtkOpenSlideReader.cxx b/Domains/Microscopy/vtkOpenSlideReader.cxx new file mode 100644 index 00000000000..f13eb5e2649 --- /dev/null +++ b/Domains/Microscopy/vtkOpenSlideReader.cxx @@ -0,0 +1,173 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOpenSlideReader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkOpenSlideReader.h" + +#include "vtkDataArray.h" +#include "vtkImageData.h" +#include "vtkObjectFactory.h" +#include "vtkPointData.h" +#include "vtkToolkits.h" +#include "vtkStreamingDemandDrivenPipeline.h" + +vtkStandardNewMacro(vtkOpenSlideReader); + +void vtkOpenSlideReader::ExecuteInformation() +{ + //std::cout << this->GetFileName() << std::endl; + + this->openslide_handle = openslide_open(this->GetFileName()); + + if(this->openslide_handle == NULL || openslide_get_error(this->openslide_handle) != NULL) + { + vtkErrorWithObjectMacro(this, + "File could not be opened by openslide" + ); + return; + } + + int64_t w, h; + openslide_get_level0_dimensions(this->openslide_handle, &w, &h); + // cout << "OpenSlideInfDims: " << w << ", " << h << endl; + + this->vtkImageReader2::ExecuteInformation(); + + this->DataExtent[0] = 0; + this->DataExtent[1] = w-1; + this->DataExtent[2] = 0; + this->DataExtent[3] = h-1; + this->DataExtent[4] = 0; + this->DataExtent[5] = 0; + + this->SetNumberOfScalarComponents(3); + this->SetDataScalarTypeToUnsignedChar(); +} + + +//---------------------------------------------------------------------------- +// This function reads a data from a file. The datas extent/axes +// are assumed to be the same as the file extent/order. +void vtkOpenSlideReader::ExecuteDataWithInformation(vtkDataObject *output, + vtkInformation *outInfo) +{ + int inExtent[6]; + + vtkStreamingDemandDrivenPipeline::GetUpdateExtent( + outInfo, + inExtent); + + vtkImageData *data = this->AllocateOutputData(output, outInfo); + + if(this->openslide_handle == NULL) + { + vtkErrorWithObjectMacro(this, + "File could not be read by openslide" + ); + return; + } + + //std::cout << "OpenSlideReader Extents: " << data->GetExtent() << std::endl; + + this->ComputeDataIncrements(); + + data->GetPointData()->GetScalars()->SetName("OpenSlideImage"); + //// Leverage openslide to read the region + + // VTK extents have origin at top left and y axis looking downwards + // openslide needs to convert + + int w = inExtent[1] - inExtent[0] + 1; + int h = inExtent[3]- inExtent[2] + 1; + unsigned char * buffer = new unsigned char[w * h * 4]; + + openslide_read_region(this->openslide_handle, (unsigned int *) buffer, + inExtent[0], + this->DataExtent[3]-inExtent[3], + 0, // level + w, + h + ); + + if(openslide_get_error(this->openslide_handle) != NULL) + { + // Buffer is deleted by the openslide in case the error occurs + // delete[] buffer; + vtkErrorWithObjectMacro(this, + "File could not be read by openslide" + ); + return; + } + + unsigned char* outputPtr = (unsigned char*)(data->GetScalarPointer()); + unsigned char* bufPtr = (unsigned char*) buffer; + + // Order = RGBA + for (long y=0; y < h; y++) + { + for(long x=0; x < w; x++) + { + unsigned char* rgba = &bufPtr[((h-1-y)*w + x) * 4]; + unsigned char* rgb = &outputPtr[(y*w + x) * 3]; + // Convert from BGRA to RGB + rgb[2] = rgba[0]; + rgb[1] = rgba[1]; + rgb[0] = rgba[2]; + } + } + + delete[] buffer; + // openslide_close(this->openslide_handle); +} + + +//---------------------------------------------------------------------------- +int vtkOpenSlideReader::CanReadFile(const char* fname) +{ + // 1 - I think I can read the file but I cannot prove it + // 2 - I definitely can read the file + // 3 - I can read the file and I have validated that I am the correct reader for this file + + this->openslide_handle = openslide_open(fname); + + if(this->openslide_handle == NULL || openslide_get_error(this->openslide_handle) != NULL) + { + // Unable to open + return 0; + } + else + { + // Pretty sure + if(this->openslide_handle != NULL) + { + openslide_close(this->openslide_handle); + this->openslide_handle = NULL; + } + return 2; + } +} + +vtkOpenSlideReader::~vtkOpenSlideReader() + { + // Release openslide_handle if being used + if(this->openslide_handle != NULL) + { + openslide_close(this->openslide_handle); + } + } + +//---------------------------------------------------------------------------- +void vtkOpenSlideReader::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); +} diff --git a/Domains/Microscopy/vtkOpenSlideReader.h b/Domains/Microscopy/vtkOpenSlideReader.h new file mode 100644 index 00000000000..e0acb65418b --- /dev/null +++ b/Domains/Microscopy/vtkOpenSlideReader.h @@ -0,0 +1,73 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOpenSlideReader.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkOpenSlideReader - read digital whole slide images supported by +// openslide library +// .SECTION Description +// vtkOpenSlideReader is a source object that uses openslide library to +// read multiple supported image formats used for whole slide images in +// microscopy community. +// +// .SECTION See Also +// vtkPTIFWriter + +#ifndef vtkOpenSlideReader_h +#define vtkOpenSlideReader_h + +#include "vtkDomainsMicroscopyModule.h" // For export macro +#include "vtkImageReader2.h" + +extern "C" { +#include "openslide/openslide.h" // For openslide support +} + +class VTKDOMAINSMICROSCOPY_EXPORT vtkOpenSlideReader : public vtkImageReader2 +{ +public: + static vtkOpenSlideReader *New(); + vtkTypeMacro(vtkOpenSlideReader,vtkImageReader2); + virtual void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Is the given file supported ? + int CanReadFile(const char* fname); + + // Description: + // Get the file extensions for this format. + // Returns a string with a space separated list of extensions in + // the format .extension + virtual const char* GetFileExtensions() + { + return ".ndpi .svs"; // TODO: Get exaustive list of formats + } + + // Description: + // Return a descriptive name for the file format that might be useful in a GUI. + virtual const char* GetDescriptiveName() + { + return "Openslide::WholeSlideImage"; + } +protected: + vtkOpenSlideReader() {} + ~vtkOpenSlideReader(); + + virtual void ExecuteInformation(); + virtual void ExecuteDataWithInformation(vtkDataObject *out, vtkInformation *outInfo); +private: + openslide_t *openslide_handle; + + vtkOpenSlideReader(const vtkOpenSlideReader&); // Not implemented. + void operator=(const vtkOpenSlideReader&); // Not implemented. +}; +#endif diff --git a/Examples/Build/vtkMy/Common/vtkmyCommonWin32Header.h b/Examples/Build/vtkMy/Common/vtkmyCommonWin32Header.h index 3f38827496b..6ae59457528 100644 --- a/Examples/Build/vtkMy/Common/vtkmyCommonWin32Header.h +++ b/Examples/Build/vtkMy/Common/vtkmyCommonWin32Header.h @@ -22,7 +22,7 @@ #include -#if defined(WIN32) && !defined(VTKMY_STATIC) +#if defined(_WIN32) && !defined(VTKMY_STATIC) #if defined(vtkmyCommon_EXPORTS) #define VTK_MY_COMMON_EXPORT __declspec( dllexport ) #else diff --git a/Examples/Build/vtkMy/Imaging/vtkmyImagingWin32Header.h b/Examples/Build/vtkMy/Imaging/vtkmyImagingWin32Header.h index fe807bcf298..ded0f9bfce8 100644 --- a/Examples/Build/vtkMy/Imaging/vtkmyImagingWin32Header.h +++ b/Examples/Build/vtkMy/Imaging/vtkmyImagingWin32Header.h @@ -22,7 +22,7 @@ #include -#if defined(WIN32) && !defined(VTKMY_STATIC) +#if defined(_WIN32) && !defined(VTKMY_STATIC) #if defined(vtkmyImaging_EXPORTS) #define VTK_MY_IMAGING_EXPORT __declspec( dllexport ) #else diff --git a/Examples/Build/vtkMy/Unsorted/vtkmyUnsortedWin32Header.h b/Examples/Build/vtkMy/Unsorted/vtkmyUnsortedWin32Header.h index 03e81d70f2f..0e1d1e4ad20 100644 --- a/Examples/Build/vtkMy/Unsorted/vtkmyUnsortedWin32Header.h +++ b/Examples/Build/vtkMy/Unsorted/vtkmyUnsortedWin32Header.h @@ -22,7 +22,7 @@ #include -#if defined(WIN32) && !defined(VTKMY_STATIC) +#if defined(_WIN32) && !defined(VTKMY_STATIC) #if defined(vtkmyUnsorted_EXPORTS) #define VTK_MY_UNSORTED_EXPORT __declspec( dllexport ) #else diff --git a/Examples/Charts/Cxx/vtkGraphItem.h b/Examples/Charts/Cxx/vtkGraphItem.h index ff36c889b71..39cd2d27b04 100644 --- a/Examples/Charts/Cxx/vtkGraphItem.h +++ b/Examples/Charts/Cxx/vtkGraphItem.h @@ -42,7 +42,6 @@ class vtkGraphItem : public vtkContextItem // Paint event for the item. virtual bool Paint(vtkContext2D *painter); -//BTX // Description: // Returns true if the supplied x, y coordinate is inside the item. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -66,11 +65,9 @@ class vtkGraphItem : public vtkContextItem // Description: // Mouse button release event. virtual bool MouseButtonReleaseEvent(const vtkContextMouseEvent &mouse); -//ETX void UpdatePositions(); -//BTX protected: vtkGraphItem(); ~vtkGraphItem(); @@ -89,7 +86,7 @@ class vtkGraphItem : public vtkContextItem private: vtkGraphItem(const vtkGraphItem &); // Not implemented. void operator=(const vtkGraphItem &); // Not implemented. -//ETX + }; #endif //vtkGraphItem_h diff --git a/Examples/GUI/Cocoa/Documentation/Instructions.rtf b/Examples/GUI/Cocoa/Documentation/Instructions.rtf index 86234639482..8d78e8f1b38 100644 --- a/Examples/GUI/Cocoa/Documentation/Instructions.rtf +++ b/Examples/GUI/Cocoa/Documentation/Instructions.rtf @@ -1,11 +1,11 @@ -{\rtf1\ansi\ansicpg1252\cocoartf1348\cocoasubrtf170 +{\rtf1\ansi\ansicpg1252\cocoartf1404\cocoasubrtf340 \cocoascreenfonts1{\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;} \margl1440\margr1440\vieww21440\viewh21120\viewkind0 -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 -\f0\fs38 \cf0 SimpleCocoaVTK 1.9\ -2015-07-27\ +\f0\fs38 \cf0 SimpleCocoaVTK 2.0\ +2016-02-08\ by: Sean McBride and Mike Jackson\ \fs34 \ @@ -14,7 +14,7 @@ by: Sean McBride and Mike Jackson\ 1) you need Mac OS X 10.7 and Xcode 4.x or later installed on your Mac.\ 2) you need CMake 2.8.10 or later.\ 3) you need to know the basics of Xcode, CMake, VTK, and Cocoa already.\ -4) you have to build VTK 6.3 separately. The Xcode project expects VTK to be built with certain options, see below.\ +4) you have to build VTK 7.1 separately. The Xcode project expects VTK to be built with certain options, see below.\ \ \ul Purpose of Example:\ \ulnone \ @@ -38,7 +38,7 @@ The other settings are not so relevant or their defaults are fine. If you've ne \ Next, you have to create two Source Trees in Xcode, named "vtk-debug-include" and "vtk-debug-lib". Do this from Preferences > Locations > Source Trees. Both should point to subfolders of where your installed VTK is. If you install into the default /usr/local/, set them like so:\ \ - vtk-debug-include /usr/local/include/vtk-6.3\ + vtk-debug-include /usr/local/include/vtk-7.1\ vtk-debug-lib /usr/local/lib\ \ Note that the path changes depending on your version of VTK. Basically, you want the source trees to match your CMAKE_INSTALL_PREFIX setting.\ @@ -54,72 +54,79 @@ If you have any problems, please post to the vtkusers mailing list.\ \ \ul \ulc0 Version History:\ \ulnone \ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 + +\i \cf0 Changes in 2.0 (since 1.9)\ +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 + +\i0 \cf0 - updated for VTK 7.1.\ +\ +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i \cf0 Changes in 1.9 (since 1.8)\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i0 \cf0 - updated for VTK 6.3.\ \ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i \cf0 Changes in 1.8 (since 1.7)\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i0 \cf0 - updated for VTK 6 and 10.7+ / Xcode 4+.\ \ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i \cf0 Changes in 1.7 (since 1.6)\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i0 \cf0 - this example can now be built by CMake.\ \ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i \cf0 Changes in 1.6 (since 1.5)\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i0 \cf0 - converted all nibs to xibs.\ - the Xcode project had a reference to a path on my disk, removed.\ \ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i \cf0 Changes in 1.5 (since 1.4)\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i0 \cf0 - now use two source trees instead of one.\ - updated example to better reflect current versions of VTK, Mac OS, and Xcode.\ \ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i \cf0 Changes in 1.4 (since 1.3)\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i0 \cf0 - removed prefix file\ - renamed main.m to main.mm\ - converted tabs to spaces\ \ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i \cf0 Changes in 1.3 (since 1.2)\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i0 \cf0 - switched to using just one Source Tree\ - tested in Mac OS X 10.5 and Xcode 3\ - improved these instructions\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i \cf0 \ Changes in 1.2 (since 1.1)\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i0 \cf0 - using smart pointers\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i \cf0 \ Changes in 1.1 (since 1.0)\ -\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural +\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\tx7380\tx7940\tx8520\pardirnatural\partightenfactor0 \i0 \cf0 - fixed some memory leaks\ - minor code cleanup\ diff --git a/Examples/GUI/Cocoa/PrefixHeader.pch b/Examples/GUI/Cocoa/PrefixHeader.pch index 6835e531878..c36803792c3 100644 --- a/Examples/GUI/Cocoa/PrefixHeader.pch +++ b/Examples/GUI/Cocoa/PrefixHeader.pch @@ -1,10 +1,14 @@ // This header is automatically #included in every source file in the Xcode project. -// VTK 6 factory methods now require "auto-initialization". +// VTK factory methods now require "auto-initialization". // // Match the definitions used to build VTK. // Required for proper object factory initialization. // It happens automatically when building with CMake, // but not when building directly with Xcode. -#define vtkRenderingCore_AUTOINIT 3(vtkInteractionStyle,vtkRenderingFreeType,vtkRenderingOpenGL) -#define vtkRenderingVolume_AUTOINIT 1(vtkRenderingVolumeOpenGL) + +#include "vtkAutoInit.h" + +VTK_MODULE_INIT(vtkInteractionStyle) +VTK_MODULE_INIT(vtkRenderingFreeType) +VTK_MODULE_INIT(vtkRenderingOpenGL2) diff --git a/Examples/GUI/Cocoa/SimpleCocoaVTK.xcodeproj/project.pbxproj b/Examples/GUI/Cocoa/SimpleCocoaVTK.xcodeproj/project.pbxproj index 454d360fd71..2c9265db637 100644 --- a/Examples/GUI/Cocoa/SimpleCocoaVTK.xcodeproj/project.pbxproj +++ b/Examples/GUI/Cocoa/SimpleCocoaVTK.xcodeproj/project.pbxproj @@ -7,8 +7,7 @@ objects = { /* Begin PBXBuildFile section */ - 142CC7EC17133D3600FE6428 /* libvtkfreetype-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 142CC7EB17133D3600FE6428 /* libvtkfreetype-6.3.a */; }; - 142CC7EE17133D4D00FE6428 /* libvtkftgl-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 142CC7ED17133D4D00FE6428 /* libvtkftgl-6.3.a */; }; + 142CC7EC17133D3600FE6428 /* libvtkfreetype-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 142CC7EB17133D3600FE6428 /* libvtkfreetype-7.1.a */; }; 1454C0F1094E266D00F594FE /* MyDocument.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1454C0F0094E266D00F594FE /* MyDocument.mm */; }; 1454C1D6094F306B00F594FE /* OpenGL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1454C1D5094F306B00F594FE /* OpenGL.framework */; }; 1454C4360950A4A800F594FE /* BasicVTKView.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1454C4350950A4A800F594FE /* BasicVTKView.mm */; }; @@ -16,42 +15,43 @@ 14A3028D119E0C3200D75B9A /* MyDocument.xib in Resources */ = {isa = PBXBuildFile; fileRef = 14A3028B119E0C3200D75B9A /* MyDocument.xib */; }; 14B86359113C3E4200C9B42E /* SimpleCocoaVTK.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 14B86358113C3E4200C9B42E /* SimpleCocoaVTK.xcconfig */; }; 14B863A5113C436100C9B42E /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 14B863A4113C436100C9B42E /* IOKit.framework */; }; - 14D951A31B701A690012248C /* libvtkCommonColor-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14D951A21B701A690012248C /* libvtkCommonColor-6.3.a */; }; - 14D951A51B701C9A0012248C /* libvtkzlib-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14D951A41B701C9A0012248C /* libvtkzlib-6.3.a */; }; - 14FC3EAD16C5A02D0092149A /* libvtkRenderingCore-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EAC16C5A02D0092149A /* libvtkRenderingCore-6.3.a */; }; - 14FC3EAF16C5A0460092149A /* libvtkRenderingOpenGL-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EAE16C5A0460092149A /* libvtkRenderingOpenGL-6.3.a */; }; - 14FC3EB616C5A0E30092149A /* libvtkCommonCore-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB016C5A0E30092149A /* libvtkCommonCore-6.3.a */; }; - 14FC3EB716C5A0E30092149A /* libvtkCommonDataModel-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB116C5A0E30092149A /* libvtkCommonDataModel-6.3.a */; }; - 14FC3EB816C5A0E30092149A /* libvtkCommonExecutionModel-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB216C5A0E30092149A /* libvtkCommonExecutionModel-6.3.a */; }; - 14FC3EB916C5A0E30092149A /* libvtkCommonMath-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB316C5A0E30092149A /* libvtkCommonMath-6.3.a */; }; - 14FC3EBA16C5A0E30092149A /* libvtkCommonSystem-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB416C5A0E30092149A /* libvtkCommonSystem-6.3.a */; }; - 14FC3EBB16C5A0E30092149A /* libvtkCommonTransforms-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB516C5A0E30092149A /* libvtkCommonTransforms-6.3.a */; }; - 14FC3EBD16C5A1090092149A /* libvtkCommonMisc-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EBC16C5A1090092149A /* libvtkCommonMisc-6.3.a */; }; - 14FC3EC116C5A1230092149A /* libvtkIOCore-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EBE16C5A1230092149A /* libvtkIOCore-6.3.a */; }; - 14FC3EC216C5A1230092149A /* libvtkIOGeometry-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EBF16C5A1230092149A /* libvtkIOGeometry-6.3.a */; }; - 14FC3EC316C5A1230092149A /* libvtkIOImage-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EC016C5A1230092149A /* libvtkIOImage-6.3.a */; }; - 14FC3EC516C5A15F0092149A /* libvtkImagingCore-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EC416C5A15F0092149A /* libvtkImagingCore-6.3.a */; }; - 14FC3EC816C5A1810092149A /* libvtkImagingMorphological-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EC616C5A1810092149A /* libvtkImagingMorphological-6.3.a */; }; - 14FC3EC916C5A1810092149A /* libvtkImagingStencil-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EC716C5A1810092149A /* libvtkImagingStencil-6.3.a */; }; - 14FC3ECB16C5A1C20092149A /* libvtkRenderingFreeType-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ECA16C5A1C20092149A /* libvtkRenderingFreeType-6.3.a */; }; - 14FC3ECD16C5A8A20092149A /* libvtklibxml2-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ECC16C5A8A20092149A /* libvtklibxml2-6.3.a */; }; - 14FC3ED116C5A8C00092149A /* libvtkjpeg-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ECE16C5A8C00092149A /* libvtkjpeg-6.3.a */; }; - 14FC3ED216C5A8C00092149A /* libvtklibxml2-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ECF16C5A8C00092149A /* libvtklibxml2-6.3.a */; }; - 14FC3ED316C5A8C00092149A /* libvtkpng-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ED016C5A8C00092149A /* libvtkpng-6.3.a */; }; - 14FC3ED616C5A9030092149A /* libvtkIOXML-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ED416C5A9030092149A /* libvtkIOXML-6.3.a */; }; - 14FC3ED716C5A9030092149A /* libvtkIOXMLParser-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ED516C5A9030092149A /* libvtkIOXMLParser-6.3.a */; }; - 14FC3EDD16C5A92E0092149A /* libvtkFiltersCore-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ED816C5A92E0092149A /* libvtkFiltersCore-6.3.a */; }; - 14FC3EDE16C5A92F0092149A /* libvtkFiltersGeneral-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ED916C5A92E0092149A /* libvtkFiltersGeneral-6.3.a */; }; - 14FC3EDF16C5A92F0092149A /* libvtkFiltersGeneric-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EDA16C5A92E0092149A /* libvtkFiltersGeneric-6.3.a */; }; - 14FC3EE016C5A92F0092149A /* libvtkFiltersGeometry-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EDB16C5A92E0092149A /* libvtkFiltersGeometry-6.3.a */; }; - 14FC3EE116C5A92F0092149A /* libvtkFiltersSources-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EDC16C5A92E0092149A /* libvtkFiltersSources-6.3.a */; }; - 14FC3EE316C5A9470092149A /* libvtkexpat-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EE216C5A9470092149A /* libvtkexpat-6.3.a */; }; - 14FC3EE616C5A9690092149A /* libvtkInteractionImage-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EE416C5A9690092149A /* libvtkInteractionImage-6.3.a */; }; - 14FC3EE716C5A9690092149A /* libvtkInteractionStyle-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EE516C5A9690092149A /* libvtkInteractionStyle-6.3.a */; }; - 14FC3EEA16C5A9830092149A /* libvtksys-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EE816C5A9830092149A /* libvtksys-6.3.a */; }; - 14FC3EEB16C5A9830092149A /* libvtktiff-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EE916C5A9830092149A /* libvtktiff-6.3.a */; }; - 14FC3EEE16C5A9A60092149A /* libvtkFiltersExtraction-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EEC16C5A9A60092149A /* libvtkFiltersExtraction-6.3.a */; }; - 14FC3EEF16C5A9A60092149A /* libvtkmetaio-6.3.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EED16C5A9A60092149A /* libvtkmetaio-6.3.a */; }; + 14D589961C69466D00C28521 /* libvtkglew-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14D589951C69466D00C28521 /* libvtkglew-7.1.a */; }; + 14D951A31B701A690012248C /* libvtkCommonColor-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14D951A21B701A690012248C /* libvtkCommonColor-7.1.a */; }; + 14D951A51B701C9A0012248C /* libvtkzlib-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14D951A41B701C9A0012248C /* libvtkzlib-7.1.a */; }; + 14FC3EAD16C5A02D0092149A /* libvtkRenderingCore-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EAC16C5A02D0092149A /* libvtkRenderingCore-7.1.a */; }; + 14FC3EAF16C5A0460092149A /* libvtkRenderingOpenGL2-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EAE16C5A0460092149A /* libvtkRenderingOpenGL2-7.1.a */; }; + 14FC3EB616C5A0E30092149A /* libvtkCommonCore-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB016C5A0E30092149A /* libvtkCommonCore-7.1.a */; }; + 14FC3EB716C5A0E30092149A /* libvtkCommonDataModel-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB116C5A0E30092149A /* libvtkCommonDataModel-7.1.a */; }; + 14FC3EB816C5A0E30092149A /* libvtkCommonExecutionModel-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB216C5A0E30092149A /* libvtkCommonExecutionModel-7.1.a */; }; + 14FC3EB916C5A0E30092149A /* libvtkCommonMath-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB316C5A0E30092149A /* libvtkCommonMath-7.1.a */; }; + 14FC3EBA16C5A0E30092149A /* libvtkCommonSystem-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB416C5A0E30092149A /* libvtkCommonSystem-7.1.a */; }; + 14FC3EBB16C5A0E30092149A /* libvtkCommonTransforms-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EB516C5A0E30092149A /* libvtkCommonTransforms-7.1.a */; }; + 14FC3EBD16C5A1090092149A /* libvtkCommonMisc-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EBC16C5A1090092149A /* libvtkCommonMisc-7.1.a */; }; + 14FC3EC116C5A1230092149A /* libvtkIOCore-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EBE16C5A1230092149A /* libvtkIOCore-7.1.a */; }; + 14FC3EC216C5A1230092149A /* libvtkIOGeometry-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EBF16C5A1230092149A /* libvtkIOGeometry-7.1.a */; }; + 14FC3EC316C5A1230092149A /* libvtkIOImage-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EC016C5A1230092149A /* libvtkIOImage-7.1.a */; }; + 14FC3EC516C5A15F0092149A /* libvtkImagingCore-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EC416C5A15F0092149A /* libvtkImagingCore-7.1.a */; }; + 14FC3EC816C5A1810092149A /* libvtkImagingMorphological-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EC616C5A1810092149A /* libvtkImagingMorphological-7.1.a */; }; + 14FC3EC916C5A1810092149A /* libvtkImagingStencil-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EC716C5A1810092149A /* libvtkImagingStencil-7.1.a */; }; + 14FC3ECB16C5A1C20092149A /* libvtkRenderingFreeType-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ECA16C5A1C20092149A /* libvtkRenderingFreeType-7.1.a */; }; + 14FC3ECD16C5A8A20092149A /* libvtklibxml2-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ECC16C5A8A20092149A /* libvtklibxml2-7.1.a */; }; + 14FC3ED116C5A8C00092149A /* libvtkjpeg-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ECE16C5A8C00092149A /* libvtkjpeg-7.1.a */; }; + 14FC3ED216C5A8C00092149A /* libvtklibxml2-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ECF16C5A8C00092149A /* libvtklibxml2-7.1.a */; }; + 14FC3ED316C5A8C00092149A /* libvtkpng-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ED016C5A8C00092149A /* libvtkpng-7.1.a */; }; + 14FC3ED616C5A9030092149A /* libvtkIOXML-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ED416C5A9030092149A /* libvtkIOXML-7.1.a */; }; + 14FC3ED716C5A9030092149A /* libvtkIOXMLParser-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ED516C5A9030092149A /* libvtkIOXMLParser-7.1.a */; }; + 14FC3EDD16C5A92E0092149A /* libvtkFiltersCore-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ED816C5A92E0092149A /* libvtkFiltersCore-7.1.a */; }; + 14FC3EDE16C5A92F0092149A /* libvtkFiltersGeneral-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3ED916C5A92E0092149A /* libvtkFiltersGeneral-7.1.a */; }; + 14FC3EDF16C5A92F0092149A /* libvtkFiltersGeneric-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EDA16C5A92E0092149A /* libvtkFiltersGeneric-7.1.a */; }; + 14FC3EE016C5A92F0092149A /* libvtkFiltersGeometry-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EDB16C5A92E0092149A /* libvtkFiltersGeometry-7.1.a */; }; + 14FC3EE116C5A92F0092149A /* libvtkFiltersSources-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EDC16C5A92E0092149A /* libvtkFiltersSources-7.1.a */; }; + 14FC3EE316C5A9470092149A /* libvtkexpat-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EE216C5A9470092149A /* libvtkexpat-7.1.a */; }; + 14FC3EE616C5A9690092149A /* libvtkInteractionImage-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EE416C5A9690092149A /* libvtkInteractionImage-7.1.a */; }; + 14FC3EE716C5A9690092149A /* libvtkInteractionStyle-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EE516C5A9690092149A /* libvtkInteractionStyle-7.1.a */; }; + 14FC3EEA16C5A9830092149A /* libvtksys-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EE816C5A9830092149A /* libvtksys-7.1.a */; }; + 14FC3EEB16C5A9830092149A /* libvtktiff-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EE916C5A9830092149A /* libvtktiff-7.1.a */; }; + 14FC3EEE16C5A9A60092149A /* libvtkFiltersExtraction-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EEC16C5A9A60092149A /* libvtkFiltersExtraction-7.1.a */; }; + 14FC3EEF16C5A9A60092149A /* libvtkmetaio-7.1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 14FC3EED16C5A9A60092149A /* libvtkmetaio-7.1.a */; }; 8D15AC320486D014006FF6A4 /* main.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2A37F4B0FDCFA73011CA2CEA /* main.mm */; settings = {ATTRIBUTES = (); }; }; 8D15AC340486D014006FF6A4 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1058C7A7FEA54F5311CA2CBB /* Cocoa.framework */; }; /* End PBXBuildFile section */ @@ -59,8 +59,7 @@ /* Begin PBXFileReference section */ 1058C7A7FEA54F5311CA2CBB /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = /System/Library/Frameworks/Cocoa.framework; sourceTree = ""; }; 142CC7EA17133CB300FE6428 /* PrefixHeader.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PrefixHeader.pch; sourceTree = ""; }; - 142CC7EB17133D3600FE6428 /* libvtkfreetype-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkfreetype-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 142CC7ED17133D4D00FE6428 /* libvtkftgl-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkftgl-6.3.a"; sourceTree = "vtk-debug-lib"; }; + 142CC7EB17133D3600FE6428 /* libvtkfreetype-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkfreetype-7.1.a"; sourceTree = "vtk-debug-lib"; }; 1454C0EF094E266D00F594FE /* MyDocument.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MyDocument.h; sourceTree = SOURCE_ROOT; }; 1454C0F0094E266D00F594FE /* MyDocument.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MyDocument.mm; sourceTree = SOURCE_ROOT; }; 1454C1D5094F306B00F594FE /* OpenGL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGL.framework; path = /System/Library/Frameworks/OpenGL.framework; sourceTree = ""; }; @@ -70,42 +69,43 @@ 14A3028B119E0C3200D75B9A /* MyDocument.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = MyDocument.xib; sourceTree = ""; }; 14B86358113C3E4200C9B42E /* SimpleCocoaVTK.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = SimpleCocoaVTK.xcconfig; sourceTree = ""; }; 14B863A4113C436100C9B42E /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = /System/Library/Frameworks/IOKit.framework; sourceTree = ""; }; - 14D951A21B701A690012248C /* libvtkCommonColor-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonColor-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14D951A41B701C9A0012248C /* libvtkzlib-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkzlib-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EAC16C5A02D0092149A /* libvtkRenderingCore-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkRenderingCore-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EAE16C5A0460092149A /* libvtkRenderingOpenGL-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkRenderingOpenGL-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EB016C5A0E30092149A /* libvtkCommonCore-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonCore-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EB116C5A0E30092149A /* libvtkCommonDataModel-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonDataModel-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EB216C5A0E30092149A /* libvtkCommonExecutionModel-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonExecutionModel-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EB316C5A0E30092149A /* libvtkCommonMath-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonMath-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EB416C5A0E30092149A /* libvtkCommonSystem-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonSystem-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EB516C5A0E30092149A /* libvtkCommonTransforms-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonTransforms-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EBC16C5A1090092149A /* libvtkCommonMisc-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonMisc-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EBE16C5A1230092149A /* libvtkIOCore-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkIOCore-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EBF16C5A1230092149A /* libvtkIOGeometry-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkIOGeometry-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EC016C5A1230092149A /* libvtkIOImage-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkIOImage-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EC416C5A15F0092149A /* libvtkImagingCore-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkImagingCore-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EC616C5A1810092149A /* libvtkImagingMorphological-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkImagingMorphological-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EC716C5A1810092149A /* libvtkImagingStencil-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkImagingStencil-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3ECA16C5A1C20092149A /* libvtkRenderingFreeType-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkRenderingFreeType-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3ECC16C5A8A20092149A /* libvtklibxml2-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtklibxml2-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3ECE16C5A8C00092149A /* libvtkjpeg-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkjpeg-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3ECF16C5A8C00092149A /* libvtklibxml2-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtklibxml2-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3ED016C5A8C00092149A /* libvtkpng-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkpng-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3ED416C5A9030092149A /* libvtkIOXML-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkIOXML-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3ED516C5A9030092149A /* libvtkIOXMLParser-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkIOXMLParser-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3ED816C5A92E0092149A /* libvtkFiltersCore-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersCore-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3ED916C5A92E0092149A /* libvtkFiltersGeneral-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersGeneral-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EDA16C5A92E0092149A /* libvtkFiltersGeneric-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersGeneric-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EDB16C5A92E0092149A /* libvtkFiltersGeometry-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersGeometry-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EDC16C5A92E0092149A /* libvtkFiltersSources-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersSources-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EE216C5A9470092149A /* libvtkexpat-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkexpat-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EE416C5A9690092149A /* libvtkInteractionImage-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkInteractionImage-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EE516C5A9690092149A /* libvtkInteractionStyle-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkInteractionStyle-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EE816C5A9830092149A /* libvtksys-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtksys-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EE916C5A9830092149A /* libvtktiff-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtktiff-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EEC16C5A9A60092149A /* libvtkFiltersExtraction-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersExtraction-6.3.a"; sourceTree = "vtk-debug-lib"; }; - 14FC3EED16C5A9A60092149A /* libvtkmetaio-6.3.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkmetaio-6.3.a"; sourceTree = "vtk-debug-lib"; }; + 14D589951C69466D00C28521 /* libvtkglew-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkglew-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14D951A21B701A690012248C /* libvtkCommonColor-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonColor-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14D951A41B701C9A0012248C /* libvtkzlib-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkzlib-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EAC16C5A02D0092149A /* libvtkRenderingCore-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkRenderingCore-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EAE16C5A0460092149A /* libvtkRenderingOpenGL2-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkRenderingOpenGL2-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EB016C5A0E30092149A /* libvtkCommonCore-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonCore-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EB116C5A0E30092149A /* libvtkCommonDataModel-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonDataModel-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EB216C5A0E30092149A /* libvtkCommonExecutionModel-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonExecutionModel-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EB316C5A0E30092149A /* libvtkCommonMath-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonMath-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EB416C5A0E30092149A /* libvtkCommonSystem-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonSystem-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EB516C5A0E30092149A /* libvtkCommonTransforms-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonTransforms-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EBC16C5A1090092149A /* libvtkCommonMisc-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkCommonMisc-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EBE16C5A1230092149A /* libvtkIOCore-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkIOCore-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EBF16C5A1230092149A /* libvtkIOGeometry-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkIOGeometry-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EC016C5A1230092149A /* libvtkIOImage-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkIOImage-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EC416C5A15F0092149A /* libvtkImagingCore-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkImagingCore-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EC616C5A1810092149A /* libvtkImagingMorphological-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkImagingMorphological-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EC716C5A1810092149A /* libvtkImagingStencil-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkImagingStencil-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3ECA16C5A1C20092149A /* libvtkRenderingFreeType-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkRenderingFreeType-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3ECC16C5A8A20092149A /* libvtklibxml2-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtklibxml2-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3ECE16C5A8C00092149A /* libvtkjpeg-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkjpeg-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3ECF16C5A8C00092149A /* libvtklibxml2-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtklibxml2-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3ED016C5A8C00092149A /* libvtkpng-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkpng-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3ED416C5A9030092149A /* libvtkIOXML-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkIOXML-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3ED516C5A9030092149A /* libvtkIOXMLParser-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkIOXMLParser-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3ED816C5A92E0092149A /* libvtkFiltersCore-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersCore-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3ED916C5A92E0092149A /* libvtkFiltersGeneral-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersGeneral-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EDA16C5A92E0092149A /* libvtkFiltersGeneric-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersGeneric-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EDB16C5A92E0092149A /* libvtkFiltersGeometry-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersGeometry-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EDC16C5A92E0092149A /* libvtkFiltersSources-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersSources-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EE216C5A9470092149A /* libvtkexpat-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkexpat-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EE416C5A9690092149A /* libvtkInteractionImage-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkInteractionImage-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EE516C5A9690092149A /* libvtkInteractionStyle-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkInteractionStyle-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EE816C5A9830092149A /* libvtksys-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtksys-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EE916C5A9830092149A /* libvtktiff-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtktiff-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EEC16C5A9A60092149A /* libvtkFiltersExtraction-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkFiltersExtraction-7.1.a"; sourceTree = "vtk-debug-lib"; }; + 14FC3EED16C5A9A60092149A /* libvtkmetaio-7.1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libvtkmetaio-7.1.a"; sourceTree = "vtk-debug-lib"; }; 2A37F4B0FDCFA73011CA2CEA /* main.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = main.mm; sourceTree = ""; }; 8D15AC360486D014006FF6A4 /* Info-Xcode.plist */ = {isa = PBXFileReference; explicitFileType = text.xml; fileEncoding = 4; path = "Info-Xcode.plist"; sourceTree = ""; }; 8D15AC370486D014006FF6A4 /* SimpleCocoaVTK.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SimpleCocoaVTK.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -119,44 +119,44 @@ 8D15AC340486D014006FF6A4 /* Cocoa.framework in Frameworks */, 1454C1D6094F306B00F594FE /* OpenGL.framework in Frameworks */, 14B863A5113C436100C9B42E /* IOKit.framework in Frameworks */, - 14FC3EAD16C5A02D0092149A /* libvtkRenderingCore-6.3.a in Frameworks */, - 14FC3EAF16C5A0460092149A /* libvtkRenderingOpenGL-6.3.a in Frameworks */, - 14FC3EB616C5A0E30092149A /* libvtkCommonCore-6.3.a in Frameworks */, - 14FC3EB716C5A0E30092149A /* libvtkCommonDataModel-6.3.a in Frameworks */, - 14FC3EB816C5A0E30092149A /* libvtkCommonExecutionModel-6.3.a in Frameworks */, - 14D951A51B701C9A0012248C /* libvtkzlib-6.3.a in Frameworks */, - 14FC3EB916C5A0E30092149A /* libvtkCommonMath-6.3.a in Frameworks */, - 14FC3EBA16C5A0E30092149A /* libvtkCommonSystem-6.3.a in Frameworks */, - 14FC3EBB16C5A0E30092149A /* libvtkCommonTransforms-6.3.a in Frameworks */, - 14FC3EBD16C5A1090092149A /* libvtkCommonMisc-6.3.a in Frameworks */, - 14FC3EC116C5A1230092149A /* libvtkIOCore-6.3.a in Frameworks */, - 14FC3EC216C5A1230092149A /* libvtkIOGeometry-6.3.a in Frameworks */, - 14FC3EC316C5A1230092149A /* libvtkIOImage-6.3.a in Frameworks */, - 14FC3EC516C5A15F0092149A /* libvtkImagingCore-6.3.a in Frameworks */, - 14FC3EC816C5A1810092149A /* libvtkImagingMorphological-6.3.a in Frameworks */, - 14FC3EC916C5A1810092149A /* libvtkImagingStencil-6.3.a in Frameworks */, - 14FC3ECB16C5A1C20092149A /* libvtkRenderingFreeType-6.3.a in Frameworks */, - 14FC3ECD16C5A8A20092149A /* libvtklibxml2-6.3.a in Frameworks */, - 14FC3ED116C5A8C00092149A /* libvtkjpeg-6.3.a in Frameworks */, - 14FC3ED216C5A8C00092149A /* libvtklibxml2-6.3.a in Frameworks */, - 14FC3ED316C5A8C00092149A /* libvtkpng-6.3.a in Frameworks */, - 14FC3ED616C5A9030092149A /* libvtkIOXML-6.3.a in Frameworks */, - 14FC3ED716C5A9030092149A /* libvtkIOXMLParser-6.3.a in Frameworks */, - 14FC3EDD16C5A92E0092149A /* libvtkFiltersCore-6.3.a in Frameworks */, - 14FC3EDE16C5A92F0092149A /* libvtkFiltersGeneral-6.3.a in Frameworks */, - 14FC3EDF16C5A92F0092149A /* libvtkFiltersGeneric-6.3.a in Frameworks */, - 14FC3EE016C5A92F0092149A /* libvtkFiltersGeometry-6.3.a in Frameworks */, - 14FC3EE116C5A92F0092149A /* libvtkFiltersSources-6.3.a in Frameworks */, - 14D951A31B701A690012248C /* libvtkCommonColor-6.3.a in Frameworks */, - 14FC3EE316C5A9470092149A /* libvtkexpat-6.3.a in Frameworks */, - 14FC3EE616C5A9690092149A /* libvtkInteractionImage-6.3.a in Frameworks */, - 14FC3EE716C5A9690092149A /* libvtkInteractionStyle-6.3.a in Frameworks */, - 14FC3EEA16C5A9830092149A /* libvtksys-6.3.a in Frameworks */, - 14FC3EEB16C5A9830092149A /* libvtktiff-6.3.a in Frameworks */, - 14FC3EEE16C5A9A60092149A /* libvtkFiltersExtraction-6.3.a in Frameworks */, - 14FC3EEF16C5A9A60092149A /* libvtkmetaio-6.3.a in Frameworks */, - 142CC7EC17133D3600FE6428 /* libvtkfreetype-6.3.a in Frameworks */, - 142CC7EE17133D4D00FE6428 /* libvtkftgl-6.3.a in Frameworks */, + 14FC3EAD16C5A02D0092149A /* libvtkRenderingCore-7.1.a in Frameworks */, + 14FC3EAF16C5A0460092149A /* libvtkRenderingOpenGL2-7.1.a in Frameworks */, + 14FC3EB616C5A0E30092149A /* libvtkCommonCore-7.1.a in Frameworks */, + 14FC3EB716C5A0E30092149A /* libvtkCommonDataModel-7.1.a in Frameworks */, + 14FC3EB816C5A0E30092149A /* libvtkCommonExecutionModel-7.1.a in Frameworks */, + 14D951A51B701C9A0012248C /* libvtkzlib-7.1.a in Frameworks */, + 14FC3EB916C5A0E30092149A /* libvtkCommonMath-7.1.a in Frameworks */, + 14FC3EBA16C5A0E30092149A /* libvtkCommonSystem-7.1.a in Frameworks */, + 14FC3EBB16C5A0E30092149A /* libvtkCommonTransforms-7.1.a in Frameworks */, + 14D589961C69466D00C28521 /* libvtkglew-7.1.a in Frameworks */, + 14FC3EBD16C5A1090092149A /* libvtkCommonMisc-7.1.a in Frameworks */, + 14FC3EC116C5A1230092149A /* libvtkIOCore-7.1.a in Frameworks */, + 14FC3EC216C5A1230092149A /* libvtkIOGeometry-7.1.a in Frameworks */, + 14FC3EC316C5A1230092149A /* libvtkIOImage-7.1.a in Frameworks */, + 14FC3EC516C5A15F0092149A /* libvtkImagingCore-7.1.a in Frameworks */, + 14FC3EC816C5A1810092149A /* libvtkImagingMorphological-7.1.a in Frameworks */, + 14FC3EC916C5A1810092149A /* libvtkImagingStencil-7.1.a in Frameworks */, + 14FC3ECB16C5A1C20092149A /* libvtkRenderingFreeType-7.1.a in Frameworks */, + 14FC3ECD16C5A8A20092149A /* libvtklibxml2-7.1.a in Frameworks */, + 14FC3ED116C5A8C00092149A /* libvtkjpeg-7.1.a in Frameworks */, + 14FC3ED216C5A8C00092149A /* libvtklibxml2-7.1.a in Frameworks */, + 14FC3ED316C5A8C00092149A /* libvtkpng-7.1.a in Frameworks */, + 14FC3ED616C5A9030092149A /* libvtkIOXML-7.1.a in Frameworks */, + 14FC3ED716C5A9030092149A /* libvtkIOXMLParser-7.1.a in Frameworks */, + 14FC3EDD16C5A92E0092149A /* libvtkFiltersCore-7.1.a in Frameworks */, + 14FC3EDE16C5A92F0092149A /* libvtkFiltersGeneral-7.1.a in Frameworks */, + 14FC3EDF16C5A92F0092149A /* libvtkFiltersGeneric-7.1.a in Frameworks */, + 14FC3EE016C5A92F0092149A /* libvtkFiltersGeometry-7.1.a in Frameworks */, + 14FC3EE116C5A92F0092149A /* libvtkFiltersSources-7.1.a in Frameworks */, + 14D951A31B701A690012248C /* libvtkCommonColor-7.1.a in Frameworks */, + 14FC3EE316C5A9470092149A /* libvtkexpat-7.1.a in Frameworks */, + 14FC3EE616C5A9690092149A /* libvtkInteractionImage-7.1.a in Frameworks */, + 14FC3EE716C5A9690092149A /* libvtkInteractionStyle-7.1.a in Frameworks */, + 14FC3EEA16C5A9830092149A /* libvtksys-7.1.a in Frameworks */, + 14FC3EEB16C5A9830092149A /* libvtktiff-7.1.a in Frameworks */, + 14FC3EEE16C5A9A60092149A /* libvtkFiltersExtraction-7.1.a in Frameworks */, + 14FC3EEF16C5A9A60092149A /* libvtkmetaio-7.1.a in Frameworks */, + 142CC7EC17133D3600FE6428 /* libvtkfreetype-7.1.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -166,44 +166,44 @@ 1454C0F8094E269200F594FE /* vtk libraries */ = { isa = PBXGroup; children = ( - 14D951A21B701A690012248C /* libvtkCommonColor-6.3.a */, - 14FC3EB016C5A0E30092149A /* libvtkCommonCore-6.3.a */, - 14FC3EB116C5A0E30092149A /* libvtkCommonDataModel-6.3.a */, - 14FC3EB216C5A0E30092149A /* libvtkCommonExecutionModel-6.3.a */, - 14FC3EB316C5A0E30092149A /* libvtkCommonMath-6.3.a */, - 14FC3EBC16C5A1090092149A /* libvtkCommonMisc-6.3.a */, - 14FC3EB416C5A0E30092149A /* libvtkCommonSystem-6.3.a */, - 14FC3EB516C5A0E30092149A /* libvtkCommonTransforms-6.3.a */, - 14FC3ED816C5A92E0092149A /* libvtkFiltersCore-6.3.a */, - 14FC3ED916C5A92E0092149A /* libvtkFiltersGeneral-6.3.a */, - 14FC3EDA16C5A92E0092149A /* libvtkFiltersGeneric-6.3.a */, - 14FC3EDB16C5A92E0092149A /* libvtkFiltersGeometry-6.3.a */, - 14FC3EDC16C5A92E0092149A /* libvtkFiltersSources-6.3.a */, - 14FC3EEC16C5A9A60092149A /* libvtkFiltersExtraction-6.3.a */, - 14FC3EE416C5A9690092149A /* libvtkInteractionImage-6.3.a */, - 14FC3EE516C5A9690092149A /* libvtkInteractionStyle-6.3.a */, - 14FC3EC416C5A15F0092149A /* libvtkImagingCore-6.3.a */, - 14FC3EC616C5A1810092149A /* libvtkImagingMorphological-6.3.a */, - 14FC3EC716C5A1810092149A /* libvtkImagingStencil-6.3.a */, - 14FC3EBE16C5A1230092149A /* libvtkIOCore-6.3.a */, - 14FC3EBF16C5A1230092149A /* libvtkIOGeometry-6.3.a */, - 14FC3EC016C5A1230092149A /* libvtkIOImage-6.3.a */, - 14FC3ED416C5A9030092149A /* libvtkIOXML-6.3.a */, - 14FC3ED516C5A9030092149A /* libvtkIOXMLParser-6.3.a */, - 14FC3EAC16C5A02D0092149A /* libvtkRenderingCore-6.3.a */, - 14FC3ECA16C5A1C20092149A /* libvtkRenderingFreeType-6.3.a */, - 14FC3EAE16C5A0460092149A /* libvtkRenderingOpenGL-6.3.a */, - 14FC3EE816C5A9830092149A /* libvtksys-6.3.a */, - 14FC3EE916C5A9830092149A /* libvtktiff-6.3.a */, - 14FC3EE216C5A9470092149A /* libvtkexpat-6.3.a */, - 142CC7EB17133D3600FE6428 /* libvtkfreetype-6.3.a */, - 142CC7ED17133D4D00FE6428 /* libvtkftgl-6.3.a */, - 14FC3ECC16C5A8A20092149A /* libvtklibxml2-6.3.a */, - 14FC3ECE16C5A8C00092149A /* libvtkjpeg-6.3.a */, - 14FC3EED16C5A9A60092149A /* libvtkmetaio-6.3.a */, - 14FC3ECF16C5A8C00092149A /* libvtklibxml2-6.3.a */, - 14FC3ED016C5A8C00092149A /* libvtkpng-6.3.a */, - 14D951A41B701C9A0012248C /* libvtkzlib-6.3.a */, + 14D951A21B701A690012248C /* libvtkCommonColor-7.1.a */, + 14FC3EB016C5A0E30092149A /* libvtkCommonCore-7.1.a */, + 14FC3EB116C5A0E30092149A /* libvtkCommonDataModel-7.1.a */, + 14FC3EB216C5A0E30092149A /* libvtkCommonExecutionModel-7.1.a */, + 14FC3EB316C5A0E30092149A /* libvtkCommonMath-7.1.a */, + 14FC3EBC16C5A1090092149A /* libvtkCommonMisc-7.1.a */, + 14FC3EB416C5A0E30092149A /* libvtkCommonSystem-7.1.a */, + 14FC3EB516C5A0E30092149A /* libvtkCommonTransforms-7.1.a */, + 14FC3ED816C5A92E0092149A /* libvtkFiltersCore-7.1.a */, + 14FC3ED916C5A92E0092149A /* libvtkFiltersGeneral-7.1.a */, + 14FC3EDA16C5A92E0092149A /* libvtkFiltersGeneric-7.1.a */, + 14FC3EDB16C5A92E0092149A /* libvtkFiltersGeometry-7.1.a */, + 14FC3EDC16C5A92E0092149A /* libvtkFiltersSources-7.1.a */, + 14FC3EEC16C5A9A60092149A /* libvtkFiltersExtraction-7.1.a */, + 14FC3EE416C5A9690092149A /* libvtkInteractionImage-7.1.a */, + 14FC3EE516C5A9690092149A /* libvtkInteractionStyle-7.1.a */, + 14D589951C69466D00C28521 /* libvtkglew-7.1.a */, + 14FC3EC416C5A15F0092149A /* libvtkImagingCore-7.1.a */, + 14FC3EC616C5A1810092149A /* libvtkImagingMorphological-7.1.a */, + 14FC3EC716C5A1810092149A /* libvtkImagingStencil-7.1.a */, + 14FC3EBE16C5A1230092149A /* libvtkIOCore-7.1.a */, + 14FC3EBF16C5A1230092149A /* libvtkIOGeometry-7.1.a */, + 14FC3EC016C5A1230092149A /* libvtkIOImage-7.1.a */, + 14FC3ED416C5A9030092149A /* libvtkIOXML-7.1.a */, + 14FC3ED516C5A9030092149A /* libvtkIOXMLParser-7.1.a */, + 14FC3EAC16C5A02D0092149A /* libvtkRenderingCore-7.1.a */, + 14FC3ECA16C5A1C20092149A /* libvtkRenderingFreeType-7.1.a */, + 14FC3EAE16C5A0460092149A /* libvtkRenderingOpenGL2-7.1.a */, + 14FC3EE816C5A9830092149A /* libvtksys-7.1.a */, + 14FC3EE916C5A9830092149A /* libvtktiff-7.1.a */, + 14FC3EE216C5A9470092149A /* libvtkexpat-7.1.a */, + 142CC7EB17133D3600FE6428 /* libvtkfreetype-7.1.a */, + 14FC3ECC16C5A8A20092149A /* libvtklibxml2-7.1.a */, + 14FC3ECE16C5A8C00092149A /* libvtkjpeg-7.1.a */, + 14FC3EED16C5A9A60092149A /* libvtkmetaio-7.1.a */, + 14FC3ECF16C5A8C00092149A /* libvtklibxml2-7.1.a */, + 14FC3ED016C5A8C00092149A /* libvtkpng-7.1.a */, + 14D951A41B701C9A0012248C /* libvtkzlib-7.1.a */, ); name = "vtk libraries"; sourceTree = ""; diff --git a/Examples/ImageProcessing/Cxx/CMakeLists.txt b/Examples/ImageProcessing/Cxx/CMakeLists.txt index 07cdc1e5342..f41a01c8c49 100644 --- a/Examples/ImageProcessing/Cxx/CMakeLists.txt +++ b/Examples/ImageProcessing/Cxx/CMakeLists.txt @@ -9,10 +9,19 @@ endif() PROJECT(ImageProcessing) find_package(VTK COMPONENTS + vtkCommonCore + vtkFiltersCore + vtkFiltersModeling + vtkFiltersSources vtkIOImage vtkImagingCore + vtkImagingGeneral + vtkImagingStatistics + vtkImagingStencil vtkInteractionStyle vtkRendering${VTK_RENDERING_BACKEND} + vtkRenderingCore + vtkTestingCore vtkTestingRendering ) include(${VTK_USE_FILE}) @@ -20,16 +29,25 @@ include(${VTK_USE_FILE}) add_executable(ImageSlicing MACOSX_BUNDLE ImageSlicing.cxx) target_link_libraries(ImageSlicing ${VTK_LIBRARIES}) +add_executable(ImageBenchmark ImageBenchmark.cxx) +target_link_libraries(ImageBenchmark ${VTK_LIBRARIES}) + +add_executable(ImageBenchmarkDriver ImageBenchmarkDriver.cxx) +target_link_libraries(ImageBenchmarkDriver ${VTK_LIBRARIES}) + if(BUILD_TESTING) if(vtkTestingRendering_LOADED) ######## Regression Testing ######## set(vtk-example ImageProcessingExamples) set(TestImageSlicing_ARGS ${VTK_TEST_DATA_DIR}/Data/headsq/quarter) + set(TestImageBenchmark_ARGS + "--threads" "2" "--filter" "resize:kernelsize=4") vtk_add_test_cxx(${vtk-example}CxxTests tests + TestImageBenchmark.cxx,NO_VALID,NO_DATA,NO_OUTPUT TestImageSlicing.cxx ) vtk_test_cxx_executable(${vtk-example}CxxTests tests RENDERING_FACTORY ) - endif() + endif() endif() diff --git a/Examples/ImageProcessing/Cxx/ImageBenchmark.cxx b/Examples/ImageProcessing/Cxx/ImageBenchmark.cxx new file mode 100644 index 00000000000..50fb10d21b9 --- /dev/null +++ b/Examples/ImageProcessing/Cxx/ImageBenchmark.cxx @@ -0,0 +1,1769 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: ImageBenchmark.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +// This program provides benchmarking of several VTK imaging filters. +// See the help text below for instructions on running this program. + +#include "vtkFloatArray.h" +#include "vtkImageBSplineCoefficients.h" +#include "vtkImageBSplineInterpolator.h" +#include "vtkImageCast.h" +#include "vtkImageChangeInformation.h" +#include "vtkImageClip.h" +#include "vtkImageConvolve.h" +#include "vtkImageData.h" +#include "vtkImageFFT.h" +#include "vtkImageGaussianSmooth.h" +#include "vtkImageGaussianSource.h" +#include "vtkImageGridSource.h" +#include "vtkImageHistogram.h" +#include "vtkImageHistogramStatistics.h" +#include "vtkImageInterpolator.h" +#include "vtkImageMandelbrotSource.h" +#include "vtkImageMapToColors.h" +#include "vtkImageMedian3D.h" +#include "vtkImageNoiseSource.h" +#include "vtkImageResize.h" +#include "vtkImageReslice.h" +#include "vtkImageSeparableConvolution.h" +#include "vtkImageShiftScale.h" +#include "vtkImageSincInterpolator.h" +#include "vtkImageStencilData.h" +#include "vtkInformation.h" +#include "vtkInformationVector.h" +#include "vtkLookupTable.h" +#include "vtkMatrix4x4.h" +#include "vtkMultiThreader.h" +#include "vtkPointData.h" +#include "vtkPNGWriter.h" +#include "vtkROIStencilSource.h" +#include "vtkSmartPointer.h" +#include "vtkSMPTools.h" +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkTimerLog.h" +#include "vtkTransform.h" +#include "vtkVersion.h" + +#include + +#include +#include +#include +#include + +// By default, the entry point is "main" (stand-alone program) +#ifndef IMAGE_BENCHMARK_MAIN +#define IMAGE_BENCHMARK_MAIN main +#endif + +const char *HelpText = +"Usage: ImageBenchmark [options]\n" +"\n" +"Options:\n" +" --runs N The number of runs to perform\n" +" --threads N (or N-M or N,M,O) Request a certain number of threads\n" +" --split-mode slab|beam|block Use the specified splitting mode\n" +" --enable-smp on|off Use vtkSMPTools vs. vtkMultiThreader\n" +" --clear-cache MBytes Attempt to clear CPU cache between runs\n" +" --bytes-per-piece N Ask for N bytes per piece [65536]\n" +" --min-piece-size XxYxZ Minimum dimensions per piece [16x1x1]\n" +" --size XxYxZ The image size [256x256x256]\n" +" --type uchar|short|float The data type for the input [short]\n" +" --source Set the data source [gaussian]\n" +" --filter [:options] Set the filter to benchmark [all]\n" +" --output filename.png Output middle slice as a png file.\n" +" --units mvps|mvptps|seconds The output units (see below for details).\n" +" --header Print a header line before the results.\n" +" --verbose Print verbose output to stdout.\n" +" --version Print the VTK version and exit.\n" +" --help Print this message.\n" +"\n" +"This program prints benchmark results to stdout in csv format. The default\n" +"units are megavoxels per second, but the --units option can specify units\n" +"of seconds, megavoxels per second (mvps), or megavoxels per thread per\n" +"second (mvptps).\n" +"\n" +"If more than three runs are done (by use of --runs), then the mean and\n" +"standard deviation over all of the runs except the first will be printed\n" +"(use --header to get the column headings).\n" +"\n" +"Sources: these are how the initial data set is produced.\n" +" gaussian A centered 3D gaussian.\n" +" noise Pseudo-random noise.\n" +" grid A grid, for checking rotations.\n" +" mandelbrot The mandelbrot set.\n" +"\n" +"Filters: these are the algorithms that can be benchmarked.\n" +" median:kernelsize=3 Test vtkImageMedian3D.\n" +" reslice:kernel=nearest Test vtkImageReslice (see below).\n" +" resize:kernelsize=1 Test vtkImageResize.\n" +" convolve:kernelsize=3 Test vtkImageConvolve.\n" +" separable:kernelsize=3 Test vtkImageSeparableConvolution.\n" +" gaussian:kernelsize=3 Test vtkImageGaussianSmooth.\n" +" bspline:degree=3 Test vtkImageBSplineCoefficients.\n" +" fft Test vtkImageFFT.\n" +" histogram:stencil Test vtkImageHistogram.\n" +" colormap:components=3 Test vtkImageMapToColors.\n" +"\n" +"The reslice filter takes the following options:\n" +" stencil Spherical stencil (ignore voxels outside).\n" +" kernel=nearest|linear|cubic|sinc|bspline The interpolator to use.\n" +" kernelsize=4 The kernelsize (sinc, bspline only).\n" +" rotation=0/0/0/0 Rotation angle (degrees) and axis.\n" +"\n" +"The colormap filter takes the following options:\n" +" components=3 Output components (3=RGB, 4=RGBA).\n" +" greyscale Rescale but do not apply a vtkLookupTable.\n" +"\n"; + +const char *DefaultFilters[] = +{ + "colormap:components=3", + "colormap:components=4", + "colormap:components=1:greyscale", + "colormap:components=2:greyscale", + "colormap:components=3:greyscale", + "colormap:components=4:greyscale", + + "resize:kernelsize=1", + "resize:kernelsize=2", + "resize:kernelsize=4", + "resize:kernelsize=6", + + "reslice:kernel=nearest:rotation=0/0/0/1", + "reslice:kernel=nearest:rotation=90/0/0/1", + "reslice:kernel=nearest:rotation=90/0/1/0", + "reslice:kernel=nearest:rotation=45/0/0/1", + "reslice:kernel=nearest:rotation=60/0/1/1", + + "reslice:kernel=linear:rotation=60/0/1/1", + "reslice:kernel=cubic:rotation=60/0/1/1", + "reslice:kernel=bspline:rotation=60/0/1/1", + "reslice:kernel=sinc:rotation=60/0/1/1", + "reslice:kernel=sinc:rotation=60/0/1/1:stencil", + + "gaussian:kernelsize=3", + "convolve:kernelsize=3", + "separable:kernelsize=3", + "resize:kernelsize=3", + "median:kernelsize=3", + + "histogram", + "histogram:stencil", + "bspline:degree=3", + + NULL +}; + +bool Verbose = false; + +// attempt to clear the CPU cache +static VTK_THREAD_RETURN_TYPE ClearOneCPUCache(void *arg) +{ + size_t cacheSize = *static_cast( + static_cast(arg)->UserData); + size_t n = cacheSize/4; + // allocate a cache-sized chunk of memory + unsigned int *bigmem = new unsigned int[n]; + // write random numbers to this memory + unsigned int randNum = 1919872345; + for (size_t i = 0; i < n; i++) + { + randNum = 1664525*randNum + 1013904223; + bigmem[i] = randNum; + } + delete [] bigmem; + + return VTK_THREAD_RETURN_VALUE; +} + +// attempt to clear all CPU caches on a multi-CPU machine +static void ClearCPUCache(size_t cacheSize) +{ + vtkSmartPointer threader = + vtkSmartPointer::New(); + threader->SetSingleMethod(ClearOneCPUCache, &cacheSize); + threader->SingleMethodExecute(); +} + +// verify that everything is set the way that we expect +static void PrintInfo(vtkThreadedImageAlgorithm *filter, std::ostream& os) +{ + os << "EnableSMP: " << filter->GetEnableSMP() << "\n"; + os << "NumberOfThreads: " << (filter->GetEnableSMP() ? + vtkSMPTools::GetEstimatedNumberOfThreads() : + filter->GetNumberOfThreads()) << "\n"; + vtkImageData *data = vtkImageData::SafeDownCast(filter->GetInput()); + os << "ScalarType: " + << data->GetPointData()->GetScalars()->GetDataTypeAsString() << "\n"; + int *imsize = data->GetDimensions(); + os << "Dimensions: " << imsize[0] << "," << imsize[1] << "," << imsize[2] + << "\n"; + int smode = filter->GetSplitMode(); + os << "SplitMode: " + << (smode == 0 ? "Slab" : (smode == 1 ? "Beam" : "Block")) << "\n"; + os << "DesiredBytesPerPiece: " << filter->GetDesiredBytesPerPiece() << "\n"; + imsize = filter->GetMinimumPieceSize(); + os << "MinimumPieceSize: " << imsize[0] << "," << imsize[1] << "," + << imsize[2] << "\n"; + os << "ClassName: " << filter->GetClassName() << "\n"; + vtkImageMedian3D *median = vtkImageMedian3D::SafeDownCast(filter); + if (median) + { + imsize = median->GetKernelSize(); + os << "KernelSize: " << imsize[0] << "," << imsize[1] << "," << imsize[2] + << "\n"; + } + vtkImageReslice *reslice = vtkImageReslice::SafeDownCast(filter); + if (reslice) + { + os << "Stencil: " << reslice->GetStencil() << "\n"; + vtkAbstractImageInterpolator *interp = reslice->GetInterpolator(); + if (vtkImageInterpolator::SafeDownCast(interp)) + { + os << "InterpolationMode: " + << reslice->GetInterpolationModeAsString() << "\n"; + } + else + { + os << "Interpolator: " << interp->GetClassName() << "\n"; + vtkImageBSplineInterpolator *bspline = + vtkImageBSplineInterpolator::SafeDownCast(interp); + if (bspline) + { + os << "SplineDegree: " << bspline->GetSplineDegree() << "\n"; + } + vtkImageSincInterpolator *sinc = + vtkImageSincInterpolator::SafeDownCast(interp); + if (sinc) + { + os << "WindowHalfWidth: " << sinc->GetWindowHalfWidth() << "\n"; + } + } + os << "ResliceAxes:"; + double axes[16] = { 1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, + 0.0,0.0,1.0,0.0, 0.0,0.0,0.0,1.0 }; + if (reslice->GetResliceAxes()) + { + vtkMatrix4x4::DeepCopy(axes, reslice->GetResliceAxes()); + } + for (int k = 0; k < 16; k++) + { + os << ((k % 4 == 0) ? " " : "") << axes[k] + << (k != 15 ? "," : "\n"); + } + } + vtkImageResize *resize = vtkImageResize::SafeDownCast(filter); + if (resize) + { + vtkAbstractImageInterpolator *interp = resize->GetInterpolator(); + os << "Interpolate: " << resize->GetInterpolate() << "\n"; + if (interp) + { + os << "Interpolator: " << interp->GetClassName() << "\n"; + vtkImageBSplineInterpolator *bspline = + vtkImageBSplineInterpolator::SafeDownCast(interp); + if (bspline) + { + os << "SplineDegree: " << bspline->GetSplineDegree() << "\n"; + } + vtkImageSincInterpolator *sinc = + vtkImageSincInterpolator::SafeDownCast(interp); + if (sinc) + { + os << "WindowHalfWidth: " << sinc->GetWindowHalfWidth() << "\n"; + } + } + } + vtkImageConvolve *convolve = vtkImageConvolve::SafeDownCast(filter); + if (convolve) + { + imsize = convolve->GetKernelSize(); + os << "KernelSize: " << imsize[0] << "," << imsize[1] << "," << imsize[2] + << "\n"; + } + vtkImageSeparableConvolution *separable = + vtkImageSeparableConvolution::SafeDownCast(filter); + if (separable) + { + os << "XKernel: " << separable->GetXKernel()->GetNumberOfTuples() << "\n"; + os << "YKernel: " << separable->GetYKernel()->GetNumberOfTuples() << "\n"; + os << "ZKernel: " << separable->GetZKernel()->GetNumberOfTuples() << "\n"; + } + vtkImageGaussianSmooth *gaussian = + vtkImageGaussianSmooth::SafeDownCast(filter); + if (gaussian) + { + double *f = gaussian->GetStandardDeviations(); + os << "StandardDeviations: " << f[0] << "," << f[1] << "," << f[2] << "\n"; + f = gaussian->GetRadiusFactors(); + os << "RadiusFactors: " << f[0] << "," << f[1] << "," << f[2] << "\n"; + } + vtkImageMapToColors *colors = vtkImageMapToColors::SafeDownCast(filter); + if (colors) + { + os << "LookupTable: " + << vtkLookupTable::SafeDownCast(colors->GetLookupTable()) << "\n"; + os << "OutputFormat: " << colors->GetOutputFormat() << "\n"; + } + vtkImageBSplineCoefficients *bspline = + vtkImageBSplineCoefficients::SafeDownCast(filter); + if (bspline) + { + os << "SplineDegree: " << bspline->GetSplineDegree() << "\n"; + } + vtkImageHistogram *histogram = vtkImageHistogram::SafeDownCast(filter); + if (histogram) + { + os << "Stencil : " << histogram->GetStencil() << "\n"; + } + } +// create the filter that will be benchmarked +static vtkThreadedImageAlgorithm *CreateFilter( + const std::string& filterName, const int size[3]) +{ + // filter name may be followed by colon and comma-separated args + std::vector args; + size_t pos = filterName.find(':'); + if (pos == std::string::npos) + { + args.push_back(filterName); + } + else + { + args.push_back(filterName.substr(0, pos)); + do + { + pos++; + size_t endpos = filterName.find(':', pos); + args.push_back(filterName.substr(pos, endpos - pos)); + pos = endpos; + } + while (pos != std::string::npos); + } + + //----- + // all the available filters and their options + //----- + if (args[0] == "median") + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + + int kernelsize = 3; + + if (args.size() > 1) + { + size_t n = args[1].find('='); + if (args[1].substr(0, n) != "kernelsize" || + n == std::string::npos || n + 1 == args[1].size() || + args[1][n+1] < '1' || args[1][n+1] > '9' || + args.size() > 2) + { + std::cerr << "median options: kernelsize=N\n"; + return NULL; + } + std::string num = args[1].substr(n+1); + kernelsize = std::atoi(num.c_str()); + } + + filter->SetKernelSize(kernelsize, kernelsize, kernelsize); + filter->Register(NULL); + return filter; + } + //----- + else if (args[0] == "reslice") + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + + bool mask = false; + std::string kernel; + int kernelsize = 0; + double rotation[4] = { 0.0, 0.0, 0.0, 0.0 }; + + for (size_t k = 1; k < args.size(); k++) + { + size_t n = args[k].find('='); + std::string key = args[k].substr(0, n); + if (key == "stencil") + { + if (n != std::string::npos) + { + std::cerr << "reslice stencil option takes no args\n"; + return NULL; + } + mask = true; + } + else if (key == "kernel") + { + if (n == std::string::npos || n + 1 == args[k].size()) + { + std::cerr << "reslice kernel should be kernel=name\n"; + return NULL; + } + kernel = args[k].substr(n+1); + } + else if (key == "kernelsize") + { + if (n == std::string::npos || n + 1 == args[k].size() || + args[k][n+1] < '0' || args[k][n+1] > '9') + { + std::cerr << "reslice kernelsize should be kernelsize=N\n"; + return NULL; + } + std::string num = args[k].substr(n+1); + kernelsize = std::atoi(num.c_str()); + if (kernelsize < 1 || kernelsize > 10) + { + std::cerr << "reslice kernelsize must be between 1 and 10\n"; + return NULL; + } + } + else if (key == "rotation") + { + int j = 0; + while (n != std::string::npos && j < 4) + { + n++; + size_t endpos = args[k].find('/', n); + std::string num = args[k].substr(n, endpos-n); + rotation[j++] = atof(num.c_str()); + n = endpos; + } + if (n != std::string::npos || j != 4) + { + std::cerr << "reslice rotation format: rotation=degrees/x/y/z\n"; + return NULL; + } + } + else + { + std::cerr << "reslice does not take option " << key << "\n"; + return NULL; + } + } + + // create a spherical mask (or circular for 2D) + if (mask) + { + vtkSmartPointer stencil = + vtkSmartPointer::New(); + stencil->SetOutputWholeExtent(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); + if (size[2] == 1) + { + stencil->SetShapeToCylinderZ(); + } + else if (size[1] == 1) + { + stencil->SetShapeToCylinderY(); + } + else if (size[0] == 1) + { + stencil->SetShapeToCylinderX(); + } + else + { + stencil->SetShapeToEllipsoid(); + } + stencil->SetBounds(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); + stencil->Update(); + filter->SetStencilData(stencil->GetOutput()); + } + + // if kernel not set but kernelsize > 1, default to bspline + if (kernelsize > 1 && kernel.empty()) + { + kernel = "bspline"; + } + + if (kernel == "bspline") + { + if (kernelsize == 0) + { + kernelsize = 4; + } + vtkSmartPointer interpolator = + vtkSmartPointer::New(); + interpolator->SetSplineDegree(kernelsize - 1); + filter->SetInterpolator(interpolator); + } + else if (kernel == "sinc") + { + if (kernelsize % 2 != 0) + { + std::cerr << "reslice sinc kernelsize must be even\n"; + return NULL; + } + if (kernelsize == 0) + { + kernelsize = 6; + } + vtkSmartPointer interpolator = + vtkSmartPointer::New(); + interpolator->SetWindowHalfWidth(kernelsize/2); + filter->SetInterpolator(interpolator); + } + else if (kernel == "cubic") + { + filter->SetInterpolationModeToCubic(); + } + else if (kernel == "linear") + { + filter->SetInterpolationModeToLinear(); + } + else if (kernel != "nearest" && !kernel.empty()) + { + std::cerr << "reslice kernel " << kernel << " not recognized\n"; + return NULL; + } + + // create the transform + if (rotation[1] != 0.0 || rotation[2] != 0.0 || rotation[3] != 0.0) + { + vtkSmartPointer transform = + vtkSmartPointer::New(); + transform->RotateWXYZ(rotation[0], rotation[1], rotation[2], rotation[3]); + vtkSmartPointer matrix = + vtkSmartPointer::New(); + matrix->DeepCopy(transform->GetMatrix()); + for (int i = 0; i < 4; i++) + { + for (int j = 0; j < 4; j++) + { + // clean up numerical error for pure 90 degree rotations + double x = matrix->GetElement(i, j); + if (fabs(x) < 1e-12) + { + x = 0.0; + } + else if (fabs(1.0 - x) < 1e-12) + { + x = 1.0; + } + else if (fabs(1.0 + x) < 1e-12) + { + x = -1.0; + } + matrix->SetElement(i, j, x); + } + } + filter->SetResliceAxes(matrix); + } + + filter->SetOutputExtent(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); + + filter->Register(NULL); + return filter; + } + //----- + else if (args[0] == "resize") + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + + int kernelsize = 1; + + for (size_t k = 1; k < args.size(); k++) + { + size_t n = args[k].find('='); + std::string key = args[k].substr(0, n); + if (key == "kernelsize") + { + if (n == std::string::npos || n + 1 == args[k].size() || + args[k][n+1] < '0' || args[k][n+1] > '9') + { + std::cerr << "resize kernelsize should be kernelsize=N\n"; + return NULL; + } + std::string num = args[k].substr(n+1); + kernelsize = std::atoi(num.c_str()); + if (kernelsize < 1 || kernelsize > 10) + { + std::cerr << "resize kernelsize must be between 1 and 10\n"; + return NULL; + } + } + else + { + std::cerr << "resize does not take option " << key << "\n"; + return NULL; + } + } + + if (kernelsize > 1) + { + vtkSmartPointer interpolator = + vtkSmartPointer::New(); + interpolator->SetSplineDegree(kernelsize - 1); + filter->SetInterpolator(interpolator); + } + else + { + filter->InterpolateOff(); + } + + filter->Register(NULL); + return filter; + } + //----- + else if (args[0] == "convolve") + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + + int kernelsize = 3; + + if (args.size() > 1) + { + size_t n = args[1].find('='); + if (args[1].substr(0, n) != "kernelsize" || + n == std::string::npos || n + 1 == args[1].size() || + args[1][n+1] < '1' || args[1][n+1] > '9' || + args.size() > 2) + { + std::cerr << "convolve options: kernelsize=N\n"; + return NULL; + } + std::string num = args[1].substr(n+1); + kernelsize = std::atoi(num.c_str()); + if (kernelsize != 3 && kernelsize != 5 && kernelsize != 7) + { + std::cerr << "convolve kernelsize must be 3, 5, or 7\n"; + return NULL; + } + } + + int ksize[3] = { kernelsize, kernelsize, kernelsize }; + if (size[2] == 1) + { + ksize[2] = 1; + } + + double kernel[343]; + double sum = 0.0; + for (int z = 0; z < ksize[2]; z++) + { + double dz = z - 0.5*(ksize[2] - 1); + double r = dz*dz; + for (int y = 0; y < ksize[1]; y++) + { + double dy = y - 0.5*(ksize[1] - 1); + r += dy*dy; + for (int x = 0; x < ksize[0]; x++) + { + double dx = x - 0.5*(ksize[0] - 1); + r += dx*dx; + double v = exp(-r/(kernelsize*kernelsize)); + kernel[((z*ksize[1] + y)*ksize[0]) + x] = v; + sum += v; + } + } + } + for (int k = 0; k < ksize[0]*ksize[1]*ksize[2]; k++) + { + kernel[k] /= sum; + } + + if (size[2] == 1) + { + if (kernelsize == 3) + { + filter->SetKernel3x3(kernel); + } + else if (kernelsize == 5) + { + filter->SetKernel5x5(kernel); + } + else + { + filter->SetKernel7x7(kernel); + } + } + else + { + if (kernelsize == 3) + { + filter->SetKernel3x3x3(kernel); + } + else if (kernelsize == 5) + { + filter->SetKernel5x5x5(kernel); + } + else + { + filter->SetKernel7x7x7(kernel); + } + } + + filter->Register(NULL); + return filter; + } + //----- + else if (args[0] == "separable") + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + + int kernelsize = 3; + + if (args.size() > 1) + { + size_t n = args[1].find('='); + if (args[1].substr(0, n) != "kernelsize" || + n == std::string::npos || n + 1 == args[1].size() || + args[1][n+1] < '1' || args[1][n+1] > '9' || + args.size() > 2) + { + std::cerr << "separable options: kernelsize=N\n"; + return NULL; + } + std::string num = args[1].substr(n+1); + kernelsize = std::atoi(num.c_str()); + if (kernelsize % 2 != 1) + { + std::cerr << "separable kernelsize must be odd\n"; + return NULL; + } + } + + vtkSmartPointer kernel = + vtkSmartPointer::New(); + kernel->SetNumberOfValues(kernelsize); + + double sum = 0.0; + for (int k = 0; k < kernelsize; k++) + { + double d = k - 0.5*(kernelsize - 1); + double v = exp(-d*d/(kernelsize*kernelsize)); + kernel->SetValue(k, v); + sum += v; + } + for (vtkIdType k = 0; k < kernelsize; k++) + { + kernel->SetValue(k, kernel->GetValue(k) / sum); + } + + vtkSmartPointer kernel2 = + vtkSmartPointer::New(); + kernel2->SetNumberOfValues(1); + kernel2->SetValue(0, 1.0); + + filter->SetXKernel(kernel); + filter->SetYKernel(kernel); + if (size[2] > 1) + { + filter->SetZKernel(kernel); + } + else + { + filter->SetZKernel(kernel2); + } + + filter->Register(NULL); + return filter; + } + //----- + else if (args[0] == "gaussian") + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + + int kernelsize = 3; + + if (args.size() > 1) + { + size_t n = args[1].find('='); + if (args[1].substr(0, n) != "kernelsize" || + n == std::string::npos || n + 1 == args[1].size() || + args[1][n+1] < '1' || args[1][n+1] > '9' || + args.size() > 2) + { + std::cerr << "gaussian options: kernelsize=N\n"; + return NULL; + } + std::string num = args[1].substr(n+1); + kernelsize = std::atoi(num.c_str()); + if (kernelsize % 2 != 1) + { + std::cerr << "gaussian kernelsize must be odd\n"; + return NULL; + } + } + + double stdev = (kernelsize-1.0)*0.25; + if (size[2] > 1) + { + filter->SetStandardDeviations(stdev, stdev, stdev); + } + else + { + filter->SetStandardDeviations(stdev, stdev, 0.0); + } + filter->SetRadiusFactors(2.0, 2.0, 2.0); + + filter->Register(NULL); + return filter; + } + //----- + else if (args[0] == "colormap") + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + + bool grey = false; + int comps = 4; + + for (size_t k = 1; k < args.size(); k++) + { + size_t n = args[k].find('='); + if (args[k].substr(0, n) == "components") + { + if (n == std::string::npos || n + 1 == args[k].size() || + args[k][n+1] < '1' || args[k][n+1] > '4') + { + std::cerr << "colormap components=N where N = 1, 2, 3, or 4\n"; + return NULL; + } + std::string num = args[k].substr(n+1); + comps = std::atoi(num.c_str()); + } + else if (args[k] == "greyscale") + { + grey = true; + } + else + { + std::cerr << "colormap options: greyscale, components=N\n"; + return NULL; + } + } + + if (grey) + { + vtkSmartPointer table = + vtkSmartPointer::New(); + table->SetRange(0, 255); + filter->SetLookupTable(table); + } + else + { + vtkSmartPointer table = + vtkSmartPointer::New(); + table->SetRange(0, 255); + filter->SetLookupTable(table); + } + filter->SetOutputFormat(comps); + + filter->Register(NULL); + return filter; + } + //----- + else if (args[0] == "bspline") + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + + if (args.size() > 1) + { + size_t n = args[1].find('='); + if (args[1].substr(0, n) != "degree" || + n == std::string::npos || n + 1 == args[1].size() || + args[1][n+1] < '1' || args[1][n+1] > '9' || + args.size() > 2) + { + std::cerr << "bspline options: degree=N\n"; + return NULL; + } + std::string num = args[1].substr(n+1); + filter->SetSplineDegree(std::atoi(num.c_str())); + } + + filter->Register(NULL); + return filter; + } + //----- + else if (args[0] == "fft") + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + + if (args.size() > 1) + { + std::cerr << "fft takes no options\n"; + return NULL; + } + + filter->Register(NULL); + return filter; + } + //----- + else if (args[0] == "histogram") + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + + bool mask = false; + + for (size_t k = 1; k < args.size(); k++) + { + size_t n = args[k].find('='); + std::string key = args[k].substr(0, n); + if (key == "stencil") + { + if (n != std::string::npos) + { + std::cerr << "histogram stencil option takes no args\n"; + return NULL; + } + mask = true; + } + else + { + std::cerr << "histogram options: stencil\n"; + return NULL; + } + } + + // create a spherical mask (or circular for 2D) + if (mask) + { + vtkSmartPointer stencil = + vtkSmartPointer::New(); + stencil->SetOutputWholeExtent(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); + if (size[2] == 1) + { + stencil->SetShapeToCylinderZ(); + } + else if (size[1] == 1) + { + stencil->SetShapeToCylinderY(); + } + else if (size[0] == 1) + { + stencil->SetShapeToCylinderX(); + } + else + { + stencil->SetShapeToEllipsoid(); + } + stencil->SetBounds(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); + stencil->Update(); + filter->SetStencilData(stencil->GetOutput()); + } + + filter->AutomaticBinningOff(); + filter->SetNumberOfBins(256); + filter->SetBinOrigin(0.0); + filter->SetBinSpacing(1.0); + + filter->Register(NULL); + return filter; + } + + cerr << "unrecognized option for --filter\n"; + + return NULL; +} + +// create the source data +static vtkImageData *CreateData( + const std::string& sourceName, const int scalarType, const int size[3]) +{ + vtkImageData *output = NULL; + + if (sourceName == "gaussian") + { + vtkSmartPointer source = + vtkSmartPointer::New(); + source->SetWholeExtent(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); + source->SetCenter(0.5*(size[0]-1), 0.5*(size[1]-1), 0.5*(size[2]-1)); + int maxdim = (size[0] > size[1] ? size[0] : size[1]); + maxdim = (maxdim > size[2] ? maxdim : size[2]); + source->SetStandardDeviation(0.25*(maxdim-1)); + source->SetMaximum(255.0); + + vtkSmartPointer cast = + vtkSmartPointer::New(); + cast->SetInputConnection(source->GetOutputPort()); + cast->SetOutputScalarType(scalarType); + cast->Update(); + + output = cast->GetOutput(); + output->Register(NULL); + } + else if (sourceName == "noise") + { + vtkSmartPointer source = + vtkSmartPointer::New(); + source->SetMinimum(0.0); + source->SetMinimum(255.0); + source->SetWholeExtent(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); + + vtkSmartPointer cast = + vtkSmartPointer::New(); + cast->SetInputConnection(source->GetOutputPort()); + cast->SetOutputScalarType(scalarType); + cast->Update(); + + output = cast->GetOutput(); + output->Register(NULL); + } + else if (sourceName == "mandelbrot") + { + vtkSmartPointer source = + vtkSmartPointer::New(); + source->SetWholeExtent(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); + + vtkSmartPointer cast = + vtkSmartPointer::New(); + cast->SetInputConnection(source->GetOutputPort()); + cast->SetOutputScalarType(scalarType); + cast->Update(); + + output = cast->GetOutput(); + output->Register(NULL); + } + else if (sourceName == "grid") + { + vtkSmartPointer source = + vtkSmartPointer::New(); + source->SetDataExtent(0, size[0]-1, 0, size[1]-1, 0, size[2]-1); + source->SetLineValue(255.0); + source->SetFillValue(0.0); + source->SetDataScalarType(scalarType); + source->Update(); + output = source->GetOutput(); + output->Register(NULL); + } + else + { + cerr << "unrecognized option for --source\n"; + return NULL; + } + + // standardize the geometry of the output + vtkSmartPointer change = + vtkSmartPointer::New(); + change->SetInputData(output); + change->SetOutputSpacing(1.0, 1.0, 1.0); + change->CenterImageOn(); + change->Update(); + output->Delete(); + output = change->GetOutput(); + output->Register(NULL); + + return output; +} + +// Convert a small integer (0 <= i < 1000) to a string +static std::string SmallIntToString(int i) +{ + std::string s; + if (i > 99) + { + s.push_back('0' + (i % 1000)/100); + } + if (i > 9) + { + s.push_back('0' + (i % 100)/10); + } + s.push_back('0' + (i % 10)); + return s; +} + +// get a string parameter from the argument list +bool GetParameter(int argc, char *argv[], int argi, std::string *val) +{ + if (argi+1 >= argc || argv[argi+1][0] == '-') + { + std::cerr << "option " << argv[argi] << " needs an argument.\n"; + return false; + } + + *val = argv[argi+1]; + return true; +} + +// get a boolean parameter from the argument list +bool GetParameter(int argc, char *argv[], int argi, bool *val) +{ + std::string s; + if (!GetParameter(argc, argv, argi, &s)) + { + return false; + } + if (s == "on" || s == "yes" || s == "true") + { + *val = true; + return true; + } + if (s == "off" || s == "no" || s == "false") + { + *val = false; + return true; + } + + std::cerr << "option " << argv[argi] << " needs a boolean argument.\n"; + return false; +} + +// get an integer parameter from the argument list +bool GetParameter(int argc, char *argv[], int argi, int *val, size_t size=1) +{ + std::string s; + if (!GetParameter(argc, argv, argi, &s)) + { + return false; + } + size_t n = 0; + int d = 0; + bool foundDigit = false; + for (size_t i = 0; i < s.size(); i++) + { + if (s[i] >= '0' && s[i] <= '9') + { + foundDigit = true; + d *= 10; + d += s[i] - '0'; + if (i + 1 != s.size()) + { + continue; + } + } + if (foundDigit) + { + foundDigit = false; + if (n < size) + { + val[n] = d; + } + n++; + d = 0; + } + } + + if (n != size) + { + if (size == 1) + { + std::cerr << "option " << argv[argi] << " needs an integer.\n"; + } + else + { + std::cerr << "option " << argv[argi] << " needs " << size << " ints.\n"; + } + return false; + } + + return true; +} + +// get range of positive integers +bool GetParameter(int argc, char *argv[], int argi, + std::vector *value) +{ + std::string s; + if (!GetParameter(argc, argv, argi, &s)) + { + return false; + } + int d = 0; + int prev = 1; + bool foundDigit = false; + char sep = 0; + for (size_t i = 0; i < s.size(); i++) + { + if (s[i] >= '0' && s[i] <= '9') + { + foundDigit = true; + d *= 10; + d += s[i] - '0'; + if (i + 1 != s.size()) + { + continue; + } + } + else if (s[i] != ',' && s[i] != '-') + { + std::cerr << "option " << argv[argi] << " badly formatted.\n"; + return false; + } + if (foundDigit) + { + foundDigit = false; + if (sep == '-') + { + if (prev <= d) + { + while (++prev < d) + { + value->push_back(prev); + } + } + else + { + while (--prev > d) + { + value->push_back(prev); + } + } + } + value->push_back(d); + prev = d; + d = 0; + } + sep = s[i]; + } + + if (value->empty()) + { + std::cerr << "option " << argv[argi] << " needs an integer.\n"; + return false; + } + + return true; +} + +// Run a benchmark on the named filter +static bool RunBenchmark( + const std::string& filterName, + const std::string& sourceName, + const int size[3], + int scalarType, + const std::string& splitMode, + bool useSMP, + vtkIdType bytesPerPiece, + int minPieceSize[3], + int clearCacheSize, + std::vector& threads, + int runs, + const std::string& units, + bool reportFilter, + const std::string& outputFile, + bool slave) +{ + vtkSmartPointer filter; + filter.TakeReference(CreateFilter(filterName, size)); + if (!filter.GetPointer()) + { + return false; + } + + vtkSmartPointer data; + data.TakeReference(CreateData(sourceName, scalarType, size)); + if (!data.GetPointer()) + { + return false; + } + + if (splitMode == "slab") + { + filter->SetSplitModeToSlab(); + } + else if (splitMode == "beam") + { + filter->SetSplitModeToBeam(); + } + else if (splitMode == "block") + { + filter->SetSplitModeToBlock(); + } + + filter->SetEnableSMP(useSMP); + if (useSMP) + { + if (bytesPerPiece) + { + filter->SetDesiredBytesPerPiece(bytesPerPiece); + } + if (minPieceSize[0] > 0 && minPieceSize[1] > 0 && minPieceSize[2] > 0) + { + filter->SetMinimumPieceSize(minPieceSize); + } + } + else + { + if (!threads.empty()) + { + filter->SetNumberOfThreads(threads[0]); + } + } + + filter->SetInputData(data); + + if (Verbose) + { + PrintInfo(filter, std::cout); + } + + // prepare for execution and timing + vtkSmartPointer log = vtkSmartPointer::New(); + + std::vector results; + results.reserve(runs); + + for (int i = 0; i < runs; i++) + { + filter->Modified(); + if (clearCacheSize) + { + ClearCPUCache(clearCacheSize*1024*1024); + } + log->StartTimer(); + filter->Update(); + log->StopTimer(); + double t = log->GetElapsedTime(); + if (!units.empty() && units[0] == 's') + { + results.push_back(t); + } + else + { + double megaVoxels = 0.000001; + megaVoxels *= size[0]; + megaVoxels *= size[1]; + megaVoxels *= size[2]; + if (units == "mvptps") + { + megaVoxels /= (filter->GetEnableSMP() ? + vtkSMPTools::GetEstimatedNumberOfThreads() : + filter->GetNumberOfThreads()); + } + results.push_back(megaVoxels/t); + } + } + + // write the result + if (threads.size() > 1 || (slave && threads.size() == 1)) + { + std::cout << threads[0] << ","; + } + double sum = 0.0; + double sumsq = 0.0; + for (size_t j = 0; j < results.size(); j++) + { + if (j > 0) + { + sum += results[j]; + sumsq += results[j]*results[j]; + } + if (j != 0) + { + std::cout << ","; + } + std::cout << results[j]; + } + // average of all but the first + size_t n = results.size() - 1; + if (n > 1) + { + std::cout << "," << sum/n; + std::cout << "," << sqrt((sumsq - sum*sum/n)/(n - 1)); + } + if (reportFilter) + { + std::cout << "," << filterName; + } + std::cout << std::endl; + + if (!outputFile.empty()) + { + size_t l = outputFile.length(); + for (size_t j = 0; j < outputFile.length(); j++) + { + if (outputFile[j] == '.') + { + l = j; + } + } + std::string pngFile = outputFile.substr(0, l) + ".png"; + + vtkSmartPointer image; + + vtkSmartPointer clip = + vtkSmartPointer::New(); + clip->SetInputData(filter->GetOutput()); + clip->SetOutputWholeExtent(0, size[0], 0, size[1], size[2]/2, size[2]/2); + clip->ClipDataOn(); + clip->Update(); + image = clip->GetOutput(); + + if (image->GetScalarType() != VTK_UNSIGNED_CHAR) + { + // rescale the image to 8-bit + vtkSmartPointer stats = + vtkSmartPointer::New(); + stats->SetInputConnection(clip->GetOutputPort()); + stats->Update(); + + double range[2]; + stats->GetAutoRange(range); + if (range[0] > 0.0) + { + range[0] = 0.0; + } + + vtkSmartPointer scale = + vtkSmartPointer::New(); + scale->SetInputData(image); + scale->SetShift(-range[0]); + scale->SetScale(255.0/(range[1] - range[0])); + scale->ClampOverflowOn(); + scale->SetOutputScalarTypeToUnsignedChar(); + scale->Update(); + image = scale->GetOutput(); + } + + vtkSmartPointer writer = + vtkSmartPointer::New(); + writer->SetInputData(image); + writer->SetFileName(pngFile.c_str()); + writer->Write(); + } + + return true; +} + +// The main() entry point +int IMAGE_BENCHMARK_MAIN(int argc, char *argv[]) +{ + bool slave = false; + bool header = false; + bool reportFilter = false; + bool useSMP = vtkThreadedImageAlgorithm::GetGlobalDefaultEnableSMP(); + int runs = 1; + std::vector threads; + std::string splitMode; + int clearCacheSize = 0; + int bytesPerPiece = 0; + int minPieceSize[3] = { 0, 0, 0 }; + int size[3] = { 256, 256, 256 }; + int scalarType = VTK_SHORT; + std::string sourceName = "gaussian"; + std::string filterName; + std::string units = "mvps"; + std::string outputFile; + + int argi = 1; + while (argi < argc) + { + std::string opt = argv[argi]; + if (opt.compare(0, 1, "-") != 0) + { + std::cerr << "expected an option, got " << opt.c_str() << "\n"; + } + if (opt == "-h" || opt == "-help" || opt == "--help") + { + std::cout << HelpText; + return 0; + } + if (opt == "--version") + { + std::cout << "ImageBenchmark " + << vtkVersion::GetVTKVersion() << "\n"; + return 0; + } + + if (opt == "--runs") + { + if (!GetParameter(argc, argv, argi++, &runs)) + { + return 1; + } + argi++; + } + else if (opt == "--clear-cache") + { + if (!GetParameter(argc, argv, argi++, &clearCacheSize)) + { + return 1; + } + argi++; + } + else if (opt == "--threads") + { + if (!GetParameter(argc, argv, argi++, &threads)) + { + return 1; + } + argi++; + } + else if (opt == "--split-mode") + { + if (!GetParameter(argc, argv, argi++, &splitMode)) + { + return 1; + } + argi++; + if (splitMode != "slab" && splitMode != "beam" && splitMode != "block") + { + std::cerr << "option " << opt << " needs slab, beam, or block\n"; + return 1; + } + } + else if (opt == "--enable-smp") + { + if (!GetParameter(argc, argv, argi++, &useSMP)) + { + return 1; + } + argi++; + } + else if (opt == "--bytes-per-piece") + { + if (!GetParameter(argc, argv, argi++, &bytesPerPiece)) + { + return 1; + } + argi++; + } + else if (opt == "--min-piece-size") + { + if (!GetParameter(argc, argv, argi++, minPieceSize, 3)) + { + return 1; + } + argi++; + } + else if (opt == "--size") + { + if (!GetParameter(argc, argv, argi++, size, 3)) + { + return 1; + } + argi++; + } + else if (opt == "--type") + { + std::string typeString; + if (!GetParameter(argc, argv, argi++, &typeString)) + { + return 1; + } + argi++; + if (typeString == "uchar") + { + scalarType = VTK_UNSIGNED_CHAR; + } + else if (typeString == "short") + { + scalarType = VTK_SHORT; + } + else if (typeString == "float") + { + scalarType = VTK_FLOAT; + } + else + { + std::cerr << "option " << opt << " needs uchar, short, or float\n"; + return 1; + } + } + else if (opt == "--source") + { + if (!GetParameter(argc, argv, argi++, &sourceName)) + { + return 1; + } + argi++; + } + else if (opt == "--filter") + { + if (!GetParameter(argc, argv, argi++, &filterName)) + { + return 1; + } + argi++; + } + else if (opt == "--output") + { + if (!GetParameter(argc, argv, argi++, &outputFile)) + { + return 1; + } + argi++; + } + else if (opt == "--units") + { + if (!GetParameter(argc, argv, argi++, &units)) + { + return 1; + } + argi++; + if (units != "s" && units != "seconds" && + units != "mvps" && units != "mvptps") + { + std::cerr << "option " << opt << " needs mvps, mvptps, or seconds\n"; + return 1; + } + } + else if (opt == "--header") + { + header = true; + argi++; + } + else if (opt == "--slave") + { + slave = true; + argi++; + } + else if (opt == "--verbose" || opt == "-v") + { + Verbose = true; + argi++; + } + else + { + std::cerr << "unrecognized option " << opt << "\n"; + return 1; + } + } + + // add a filter column if filter will vary + if (filterName.empty()) + { + reportFilter = true; + } + + // write the column headers + if (header) + { + if (threads.size() > 1) + { + std::cout << "Threads,"; + } + for (int j = 0; j < runs; j++) + { + if (j != 0) + { + std::cout << ","; + } + if (!units.empty() && units[0] == 's') + { + std::cout << "T" << j; + } + else + { + std::cout << "R" << j; + } + } + if (runs > 2) + { + std::cout << ",Average"; + std::cout << ",StdDev"; + } + if (reportFilter) + { + std::cout << ",Filter"; + } + std::cout << std::endl; + } + + if (threads.size() > 1) + { + // if a list was given for the numbers of threads, re-run the executable + // (vtkSMPTools might only allow one initialization per process) + for (size_t k = 0; k < threads.size(); k++) + { + std::string threadopt = SmallIntToString(threads[k]); + + // create sub-process argument list + std::vector commandLine; + for (int i = 0; i < argc; i++) + { + std::string arg = argv[i]; + + // don't add --header arg to subprocesses + if (arg != "--header") + { + commandLine.push_back(argv[i]); + } + + if (arg == "--threads") + { + // modify the --thread arg so that it specifies just one number + commandLine.push_back(threadopt.c_str()); + i++; + } + } + commandLine.push_back("--slave"); + commandLine.push_back(NULL); + + // create and run the subprocess + vtksysProcess *process = vtksysProcess_New(); + vtksysProcess_SetCommand(process, &commandLine[0]); + vtksysProcess_Execute(process); + + int pipe; + do + { + char *cp; + int length; + pipe = vtksysProcess_WaitForData(process, &cp, &length, NULL); + switch (pipe) + { + case vtksysProcess_Pipe_STDOUT: + std::cout.write(cp, length); + break; + + case vtksysProcess_Pipe_STDERR: + std::cerr.write(cp, length); + break; + } + } + while (pipe != vtksysProcess_Pipe_None); + + vtksysProcess_WaitForExit(process, NULL); + int rval = vtksysProcess_GetExitValue(process); + if (rval != 0) + { + return rval; + } + + vtksysProcess_Delete(process); + } + + return 0; + } + + // set the number of threads + if (useSMP) + { + if (!threads.empty()) + { + vtkSMPTools::Initialize(threads[0]); + } + } + + const char *requestedFilters[] = { + filterName.c_str(), NULL + }; + const char **filters = + (filterName.empty() ? DefaultFilters : requestedFilters); + + for (int k = 0; filters[k] != 0; k++) + { + if (!RunBenchmark(filters[k], sourceName, size, scalarType, + splitMode, useSMP, bytesPerPiece, minPieceSize, + clearCacheSize, threads, runs, units, reportFilter, + outputFile, slave)) + { + return 1; + } + } + + return 0; +} diff --git a/Examples/ImageProcessing/Cxx/ImageBenchmarkDriver.cxx b/Examples/ImageProcessing/Cxx/ImageBenchmarkDriver.cxx new file mode 100644 index 00000000000..caba82c2012 --- /dev/null +++ b/Examples/ImageProcessing/Cxx/ImageBenchmarkDriver.cxx @@ -0,0 +1,293 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: ImageBenchmarkDriver.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +// This program is a driver for the benchmarking tests. +// It runs several benchmarks and writes them to the output directory. + +#include "vtkMultiThreader.h" +#include "vtkThreadedImageAlgorithm.h" +#include "vtkVersion.h" + +#include + +#include +#include +#include + +const char *HelpText = +"Usage: ImageBenchmarkDriver --prefix ...\n" +"\n" +"Options:\n" +" --prefix Prefix for output filenames.\n" +" Any options from ImageBenchmark can also be used.\n" +"\n" +"Details:\n" +"\n" +"This program runs a series of image processing benchmarks,\n" +"by running ImageBenchmark with various parameters:\n" +"\n"; + +// A struct to give a short name to each ImageBenchmark option +struct BenchOption +{ + const char *Name; + const char *Option; +}; + +// A struct to link a range of options to a benchmark parameter +struct BenchParameter +{ + const char *Parameter; + BenchOption *Options; +}; + +static BenchOption FilterList[] = +{ + { "Median3", "median:kernelsize=3" }, + { "Reslice2D", "reslice:kernel=linear:rotation=45/0/0/1" }, + { "Reslice3D", "reslice:kernel=linear:rotation=60/0/1/1" }, + { "Colors4", "colormap:components=4" }, + { NULL, NULL } +}; + +static BenchOption SplitModeList[] = +{ + { "Slab", "slab" }, + { "Beam", "beam" }, + { "Block", "block" }, + { NULL, NULL } +}; + +// These are only for --enable-smp on +static BenchOption BlockByteList[] = +{ + { "1KiB", "1024" }, + { "4KiB", "4096" }, + { "16KiB", "16384" }, + { "64KiB", "65536" }, + { "256KiB", "262144" }, + { "1MiB", "1048576" }, + { "4MiB", "4194304" }, + { "16MiB", "16777216" }, + { NULL, NULL } +}; + +static BenchOption ImageSizeList[] = +{ + { "4096x4096", "4096x4096x1" }, + { "256x256x256", "256x256x256" }, + { NULL, NULL } +}; + +static BenchParameter Parameters[] = +{ + { "--filter", FilterList }, + { "--split-mode", SplitModeList }, + { "--bytes-per-piece", BlockByteList }, + { "--size", ImageSizeList }, + { NULL, NULL } +}; + +int main(int argc, char *argv[]) +{ + // Create the path to the ImageBenchmark executable (assume that + // it is in same directory) + std::string exename = argv[0]; + size_t l = 0; + for (size_t j = 0; j != exename.length(); j++) + { + if (exename[j] == '/' || exename[j] == '\\') + { + l = j + 1; + } + } + exename = exename.substr(0, l) + "ImageBenchmark"; + + // Go through the arguments to create args for ImageBenchmark + bool useSMP = vtkThreadedImageAlgorithm::GetGlobalDefaultEnableSMP(); + std::string prefix; + std::vector args; + args.push_back(exename.c_str()); + int argi = 1; + while (argi < argc) + { + std::string arg = argv[argi]; + if (arg == "-h" || arg == "-help" || arg == "--help") + { + std::cout << HelpText; + for (BenchParameter *p = Parameters; p->Parameter; p++) + { + std::string opt = p->Parameter; + for (BenchOption *o = p->Options; o->Option; o++) + { + std::cout << " " << opt << " " << o->Option << " (" + << o->Name << ")\n"; + } + std::cout << std::endl; + } + return 0; + } + else if (arg == "--version") + { + std::cout << "ImageBenchmarkDriver " + << vtkVersion::GetVTKVersion() << "\n"; + return 0; + } + else if (arg == "--prefix") + { + if (++argi < argc) + { + prefix = argv[argi++]; + } + } + else if (arg == "--enable-smp") + { + args.push_back(argv[argi++]); + if (argi < argc) + { + std::string s = argv[argi]; + if (s == "on" || s == "yes" || s == "true") + { + useSMP = true; + } + else if (s == "off" || s == "no" || s == "false") + { + useSMP = false; + } + args.push_back(argv[argi++]); + } + } + else + { + args.push_back(argv[argi++]); + } + } + + // Count the number of benchmarks to do + int total = 1; + std::vector overrides; + for (BenchParameter *p = Parameters; p->Parameter; p++) + { + // Check if this parameter was overridden on the command line + std::string arg = p->Parameter; + bool overRidden = false; + for (size_t j = 1; j < args.size(); j++) + { + if (arg == args[j] || + (!useSMP && arg == "--bytes-per-piece")) + { + overRidden = true; + break; + } + } + overrides.push_back(overRidden); + if (overRidden) + { + continue; + } + + int count = 0; + for (BenchOption *o = p->Options; o->Option; o++) + { + count++; + } + total *= count; + } + + for (int i = 0; i < total; i++) + { + std::string filename = prefix; + if (prefix.empty() || + prefix[prefix.length()-1] == '/' || + prefix[prefix.length()-1] == '\\') + { + filename += (useSMP ? "SMP" : "MT"); + } + + std::vector commandLine; + commandLine.push_back(args[0]); + for (size_t j = 1; j < args.size(); j++) + { + commandLine.push_back(args[j]); + } + + int part = 1; + std::vector::iterator skip = overrides.begin(); + for (BenchParameter *p = Parameters; p->Parameter; ++p, ++skip) + { + if (*skip) + { + continue; + } + + int count = 0; + for (BenchOption *o = p->Options; o->Option; o++) + { + count++; + } + int k = (i/part) % count; + commandLine.push_back(p->Parameter); + commandLine.push_back(p->Options[k].Option); + filename.push_back('_'); + filename += p->Options[k].Name; + part *= count; + } + + commandLine.push_back("--slave"); + commandLine.push_back(NULL); + + filename += ".csv"; + std::ofstream outfile(filename.c_str()); + + // create and run the subprocess + vtksysProcess *process = vtksysProcess_New(); + vtksysProcess_SetCommand(process, &commandLine[0]); + vtksysProcess_Execute(process); + + int pipe; + do + { + char *cp; + int length; + pipe = vtksysProcess_WaitForData(process, &cp, &length, NULL); + switch (pipe) + { + case vtksysProcess_Pipe_STDOUT: + outfile.write(cp, length); + break; + + case vtksysProcess_Pipe_STDERR: + std::cerr.write(cp, length); + break; + } + } + while (pipe != vtksysProcess_Pipe_None); + + vtksysProcess_WaitForExit(process, NULL); + int rval = vtksysProcess_GetExitValue(process); + if (rval != 0) + { + return rval; + } + + vtksysProcess_Delete(process); + + outfile.close(); + + std::cout << (i + 1) << " of " << total << ": " << filename << std::endl; + } + + return 0; +} diff --git a/Examples/ImageProcessing/Cxx/TestImageBenchmark.cxx b/Examples/ImageProcessing/Cxx/TestImageBenchmark.cxx new file mode 100644 index 00000000000..b0932a9a032 --- /dev/null +++ b/Examples/ImageProcessing/Cxx/TestImageBenchmark.cxx @@ -0,0 +1,2 @@ +#define IMAGE_BENCHMARK_MAIN TestImageBenchmark +#include "ImageBenchmark.cxx" diff --git a/Examples/Infovis/Cxx/TreeLayout.cxx b/Examples/Infovis/Cxx/TreeLayout.cxx index c64ef641737..bdbac6aca8f 100644 --- a/Examples/Infovis/Cxx/TreeLayout.cxx +++ b/Examples/Infovis/Cxx/TreeLayout.cxx @@ -102,7 +102,7 @@ int main(int argc, char* argv[]) return 0; } if (colorArray && - vtkDataArray::SafeDownCast(tree->GetVertexData()->GetAbstractArray(colorArray)) == NULL) + vtkArrayDownCast(tree->GetVertexData()->GetAbstractArray(colorArray)) == NULL) { cerr << "ERROR: The color attribute " << colorArray << " does not have numeric values." << endl; reader->Delete(); @@ -115,7 +115,7 @@ int main(int argc, char* argv[]) double colorRange[2] = {0, 1}; if (colorArray) { - vtkDataArray* color = vtkDataArray::SafeDownCast( + vtkDataArray* color = vtkArrayDownCast( tree->GetVertexData()->GetAbstractArray(colorArray)); color->GetRange(colorRange); } diff --git a/Examples/Medical/Cxx/Baseline/TestMedical4.png.md5 b/Examples/Medical/Cxx/Baseline/TestMedical4.png.md5 index 6d431a5f5b8..a84ec3f8426 100644 --- a/Examples/Medical/Cxx/Baseline/TestMedical4.png.md5 +++ b/Examples/Medical/Cxx/Baseline/TestMedical4.png.md5 @@ -1 +1 @@ -a134cf1237c06936eb2b829b15ae54fa +19228441ae3c8a967205cdc811e5bd4a diff --git a/Examples/Medical/Cxx/CMakeLists.txt b/Examples/Medical/Cxx/CMakeLists.txt index e18f07ee0de..6638f373b2c 100644 --- a/Examples/Medical/Cxx/CMakeLists.txt +++ b/Examples/Medical/Cxx/CMakeLists.txt @@ -24,16 +24,12 @@ include(${VTK_USE_FILE}) add_executable(Medical1 MACOSX_BUNDLE Medical1.cxx) add_executable(Medical2 MACOSX_BUNDLE Medical2.cxx) add_executable(Medical3 MACOSX_BUNDLE Medical3.cxx) -if (NOT VTK_LEGACY_REMOVE) add_executable(Medical4 MACOSX_BUNDLE Medical4.cxx) -endif() target_link_libraries(Medical1 ${VTK_LIBRARIES}) target_link_libraries(Medical2 ${VTK_LIBRARIES}) target_link_libraries(Medical3 ${VTK_LIBRARIES}) -if (NOT VTK_LEGACY_REMOVE) target_link_libraries(Medical4 ${VTK_LIBRARIES}) -endif() add_executable(GenerateModelsFromLabels MACOSX_BUNDLE GenerateModelsFromLabels.cxx) add_executable(GenerateCubesFromLabels MACOSX_BUNDLE GenerateCubesFromLabels.cxx) @@ -47,19 +43,13 @@ if(BUILD_TESTING) set(TestMedical1_ARGS ${VTK_TEST_DATA_DIR}/Data/headsq/quarter) set(TestMedical2_ARGS ${VTK_TEST_DATA_DIR}/Data/headsq/quarter) set(TestMedical3_ARGS ${VTK_TEST_DATA_DIR}/Data/headsq/quarter) -if (NOT VTK_LEGACY_REMOVE) set(TestMedical4_ARGS ${VTK_TEST_DATA_DIR}/Data/headsq/quarter) -endif() vtk_add_test_cxx(${vtk-example}CxxTests tests TestMedical1.cxx TestMedical2.cxx TestMedical3.cxx - ) -if (NOT VTK_LEGACY_REMOVE) - vtk_add_test_cxx(${vtk-example}CxxTests tests TestMedical4.cxx ) -endif() vtk_test_cxx_executable(${vtk-example}CxxTests tests RENDERING_FACTORY ) diff --git a/Examples/Medical/Cxx/Medical4.cxx b/Examples/Medical/Cxx/Medical4.cxx index 3d16fe716d9..419c503b609 100644 --- a/Examples/Medical/Cxx/Medical4.cxx +++ b/Examples/Medical/Cxx/Medical4.cxx @@ -23,8 +23,7 @@ See Copyright.txt or http://www.kitware.com/Copyright.htm for details. #include #include #include -#include -#include +#include #include #include #include @@ -65,15 +64,10 @@ int main (int argc, char *argv[]) v16->SetDataSpacing(3.2, 3.2, 1.5); // The volume will be displayed by ray-cast alpha compositing. - // A ray-cast mapper is needed to do the ray-casting, and a - // compositing function is needed to do the compositing along the ray. - vtkSmartPointer rayCastFunction = - vtkSmartPointer::New(); - - vtkSmartPointer volumeMapper = - vtkSmartPointer::New(); + // A ray-cast mapper is needed to do the ray-casting. + vtkSmartPointer volumeMapper = + vtkSmartPointer::New(); volumeMapper->SetInputConnection(v16->GetOutputPort()); - volumeMapper->SetVolumeRayCastFunction(rayCastFunction); // The color transfer function maps voxel intensities to colors. // It is modality-specific, and often anatomy-specific as well. diff --git a/Examples/Statistics/ExampleDescriptiveStatistics.cxx b/Examples/Statistics/ExampleDescriptiveStatistics.cxx index 72ca249343a..284915311c3 100644 --- a/Examples/Statistics/ExampleDescriptiveStatistics.cxx +++ b/Examples/Statistics/ExampleDescriptiveStatistics.cxx @@ -239,10 +239,10 @@ int main( int, char *[] ) << maxdev << " for metric 1:\n"; - vtkDoubleArray* vals0 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "Metric 0" ) ); - vtkDoubleArray* vals1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "Metric 1" ) ); - vtkDoubleArray* devs0 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "d(Metric 0)" ) ); - vtkDoubleArray* devs1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); + vtkDoubleArray* vals0 = vtkArrayDownCast( outputData1->GetColumnByName( "Metric 0" ) ); + vtkDoubleArray* vals1 = vtkArrayDownCast( outputData1->GetColumnByName( "Metric 1" ) ); + vtkDoubleArray* devs0 = vtkArrayDownCast( outputData1->GetColumnByName( "d(Metric 0)" ) ); + vtkDoubleArray* devs1 = vtkArrayDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); if ( ! devs0 || ! devs1 || ! vals0 || ! vals1 ) { @@ -333,8 +333,8 @@ int main( int, char *[] ) ds1->SetAssessOption( true ); ds1->Update(); - vals1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "Metric 1" ) ); - devs1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); + vals1 = vtkArrayDownCast( outputData1->GetColumnByName( "Metric 1" ) ); + devs1 = vtkArrayDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); if ( ! devs1 || ! vals1 ) { diff --git a/Examples/iOS/CMakeLists.txt b/Examples/iOS/CMakeLists.txt index 2eb49ebf2a5..3a87ee1fdb5 100644 --- a/Examples/iOS/CMakeLists.txt +++ b/Examples/iOS/CMakeLists.txt @@ -1,25 +1,23 @@ # copy the example to the binary tree where they can be built manually using xcode -if (TRUE) - add_custom_target(iOS-examples-rm ALL - COMMAND ${CMAKE_COMMAND} -E remove_directory - "${CMAKE_CURRENT_BINARY_DIR}/GLPaint" - COMMAND ${CMAKE_COMMAND} -E remove_directory - "${CMAKE_CURRENT_BINARY_DIR}/Surfaces") +add_custom_target(iOS-examples-rm ALL + COMMAND ${CMAKE_COMMAND} + -D BIN_DIR="${CMAKE_CURRENT_BINARY_DIR}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/CleanExamples.cmake" + ) - add_custom_target(iOS-examples-copy ALL - COMMAND ${CMAKE_COMMAND} -E copy_directory - "${CMAKE_CURRENT_SOURCE_DIR}/GLPaint" - "${CMAKE_CURRENT_BINARY_DIR}/GLPaint" - COMMAND ${CMAKE_COMMAND} -E copy_directory - "${CMAKE_CURRENT_SOURCE_DIR}/Surfaces" - "${CMAKE_CURRENT_BINARY_DIR}/Surfaces") + add_custom_target(iOS-examples-copy ALL + COMMAND ${CMAKE_COMMAND} -E copy_directory + \"${CMAKE_CURRENT_SOURCE_DIR}/GLPaint\" + \"${CMAKE_CURRENT_BINARY_DIR}/GLPaint\" + COMMAND ${CMAKE_COMMAND} -E copy_directory + \"${CMAKE_CURRENT_SOURCE_DIR}/Surfaces\" + \"${CMAKE_CURRENT_BINARY_DIR}/Surfaces\" + COMMAND ${CMAKE_COMMAND} -E copy_directory + \"${CMAKE_CURRENT_SOURCE_DIR}/VolumeRender\" + \"${CMAKE_CURRENT_BINARY_DIR}/VolumeRender\" + COMMAND ${CMAKE_COMMAND} -E copy_directory + \"${CMAKE_CURRENT_SOURCE_DIR}/PlaneView\" + \"${CMAKE_CURRENT_BINARY_DIR}/PlaneView\") - add_dependencies(iOS-examples-copy iOS-examples-rm) -else () - add_subdirectory(MaceVTK/MaceVTK) - add_custom_target(iOS-examples-copy ALL - COMMAND ${CMAKE_COMMAND} -E copy_directory - "${CMAKE_CURRENT_SOURCE_DIR}/MaceVTK" - "${CMAKE_CURRENT_BINARY_DIR}/MaceVTK") -endif () +add_dependencies(iOS-examples-copy iOS-examples-rm) diff --git a/Examples/iOS/CleanExamples.cmake b/Examples/iOS/CleanExamples.cmake new file mode 100644 index 00000000000..245436bb1bc --- /dev/null +++ b/Examples/iOS/CleanExamples.cmake @@ -0,0 +1,13 @@ + +IF(EXISTS "${BIN_DIR}/GLPaint" AND IS_DIRECTORY "${BIN_DIR}/GLPaint") + FILE(REMOVE_RECURSE "${BIN_DIR}/GLPaint") +ENDIF() +IF(EXISTS "${BIN_DIR}/Surfaces" AND IS_DIRECTORY "${BIN_DIR}/Surfaces") + FILE(REMOVE_RECURSE "${BIN_DIR}/Surfaces") +ENDIF() +IF(EXISTS "${BIN_DIR}/VolumeRender" AND IS_DIRECTORY "${BIN_DIR}/VolumeRender") + FILE(REMOVE_RECURSE "${BIN_DIR}/VolumeRender") +ENDIF() +IF(EXISTS "${BIN_DIR}/PlaneView" AND IS_DIRECTORY "${BIN_DIR}/PlaneView") + FILE(REMOVE_RECURSE "${BIN_DIR}/PlaneView") +ENDIF() diff --git a/Examples/iOS/GLPaint.old/Classes/AppController.h b/Examples/iOS/GLPaint.old/Classes/AppController.h deleted file mode 100644 index 5a215e531ae..00000000000 --- a/Examples/iOS/GLPaint.old/Classes/AppController.h +++ /dev/null @@ -1,22 +0,0 @@ -/*========================================================================= - -Program: Visualization Toolkit - -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#import -#import - -@interface MyGLKViewController : GLKViewController - -@property (nonatomic, strong) UIWindow *window; - -@end diff --git a/Examples/iOS/GLPaint.old/Classes/AppController.mm b/Examples/iOS/GLPaint.old/Classes/AppController.mm deleted file mode 100644 index 246a1f220d8..00000000000 --- a/Examples/iOS/GLPaint.old/Classes/AppController.mm +++ /dev/null @@ -1,126 +0,0 @@ -/*========================================================================= - -Program: Visualization Toolkit - -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#import "MyGLKViewController.h" - -@interface MyGLKViewController () { - - vesKiwiViewerApp::Ptr mKiwiApp; - - MyGestureHandler* mGestureHandler; -} - -@property (strong, nonatomic) EAGLContext *context; - -- (void)tearDownGL; - -@end - -@implementation MyGLKViewController - - -- (void)viewDidLoad -{ - [super viewDidLoad]; - - self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; - - if (!self.context) { - NSLog(@"Failed to create ES context"); - } - - GLKView *view = (GLKView *)self.view; - view.context = self.context; - view.drawableDepthFormat = GLKViewDrawableDepthFormat24; - view.drawableMultisample = GLKViewDrawableMultisample4X; - - [self initializeKiwiApp]; - [self initializeGestureHandler]; -} - --(void) initializeKiwiApp -{ - [EAGLContext setCurrentContext:self.context]; - - std::string dataset = [[[NSBundle mainBundle] pathForResource:@"teapot" ofType:@"vtp"] UTF8String]; - - self->mKiwiApp = vesKiwiViewerApp::Ptr(new vesKiwiViewerApp); - self->mKiwiApp->initGL(); - [self resizeView]; - self->mKiwiApp->loadDataset(dataset); - self->mKiwiApp->resetView(); -} - --(void) initializeGestureHandler -{ - self->mGestureHandler = [[MyGestureHandler alloc] init]; - self->mGestureHandler.view = self.view; - self->mGestureHandler.kiwiApp = self->mKiwiApp; - [self->mGestureHandler createGestureRecognizers]; -} - -- (void)dealloc -{ - [self tearDownGL]; - - if ([EAGLContext currentContext] == self.context) { - [EAGLContext setCurrentContext:nil]; - } -} - -- (void)didReceiveMemoryWarning -{ - [super didReceiveMemoryWarning]; - - if ([self isViewLoaded] && ([[self view] window] == nil)) { - self.view = nil; - - [self tearDownGL]; - - if ([EAGLContext currentContext] == self.context) { - [EAGLContext setCurrentContext:nil]; - } - self.context = nil; - } - - // Dispose of any resources that can be recreated. -} - -- (void)tearDownGL -{ - [EAGLContext setCurrentContext:self.context]; - - // free GL resources - // ... -} - --(void) resizeView -{ - double scale = self.view.contentScaleFactor; - self->mKiwiApp->resizeView(self.view.bounds.size.width*scale, self.view.bounds.size.height*scale); -} - -- (void)viewWillLayoutSubviews -{ - [self resizeView]; -} - -- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect -{ - if (self->mKiwiApp && !self.paused) { - self->mKiwiApp->render(); - } -} - -@end diff --git a/Examples/iOS/GLPaint.old/Classes/AppDelegate.h b/Examples/iOS/GLPaint.old/Classes/AppDelegate.h deleted file mode 100644 index 618bf67f546..00000000000 --- a/Examples/iOS/GLPaint.old/Classes/AppDelegate.h +++ /dev/null @@ -1,20 +0,0 @@ -/*========================================================================= - -Program: Visualization Toolkit - -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#import - -@interface AppDelegate : UIResponder - -@property (strong, nonatomic) UIWindow *window; - -@end diff --git a/Examples/iOS/GLPaint.old/Classes/MyGLKViewController.h b/Examples/iOS/GLPaint.old/Classes/MyGLKViewController.h deleted file mode 100644 index ce82e4e8ff0..00000000000 --- a/Examples/iOS/GLPaint.old/Classes/MyGLKViewController.h +++ /dev/null @@ -1,49 +0,0 @@ -/*========================================================================= - -Program: Visualization Toolkit - -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#import -#import - -// Note: This file should be includable by both pure Objective-C and Objective-C++ source files. -// To achieve this, we use the neat technique below: -#ifdef __cplusplus - // Forward declarations - class vtkIOSRenderWindow; - class vtkIOSRenderWindowInteractor; - - // Type declarations - typedef vtkIOSRenderWindow *vtkIOSRenderWindowRef; - typedef vtkIOSRenderWindowInteractor *vtkIOSRenderWindowInteractorRef; -#else - // Type declarations - typedef void *vtkIOSRenderWindowRef; - typedef void *vtkIOSRenderWindowInteractorRef; -#endif - -@interface MyGLKViewController : GLKViewController -{ - @private - vtkIOSRenderWindowRef _myVTKRenderWindow; -} - -@property (nonatomic, strong) UIWindow *window; - -- (vtkIOSRenderWindowRef)getVTKRenderWindow; -- (void)setVTKRenderWindow:(vtkIOSRenderWindowRef)theVTKRenderWindow; - -- (vtkIOSRenderWindowInteractorRef)getInteractor; - -- (void)setupPipeline; - -@end diff --git a/Examples/iOS/GLPaint.old/Classes/MyGLKViewController.mm b/Examples/iOS/GLPaint.old/Classes/MyGLKViewController.mm deleted file mode 100644 index 0842d61b9c0..00000000000 --- a/Examples/iOS/GLPaint.old/Classes/MyGLKViewController.mm +++ /dev/null @@ -1,193 +0,0 @@ -/*========================================================================= - -Program: Visualization Toolkit - -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#import "MyGLKViewController.h" - -@interface MyGLKViewController () { - - vesKiwiViewerApp::Ptr mKiwiApp; - - MyGestureHandler* mGestureHandler; -} - -@property (strong, nonatomic) EAGLContext *context; - -- (void)tearDownGL; - -@end - -@implementation MyGLKViewController - -//---------------------------------------------------------------------------- -- (vtkIOSRenderWindow *)getVTKRenderWindow -{ - return _myVTKRenderWindow; -} - -//---------------------------------------------------------------------------- -- (void)setVTKRenderWindow:(vtkIOSRenderWindow *)theVTKRenderWindow -{ - _myVTKRenderWindow = theVTKRenderWindow; -} - -//---------------------------------------------------------------------------- -- (vtkIOSRenderWindowInteractor *)getInteractor -{ - if (_myVTKRenderWindow) - { - return (vtkIOSRenderWindowInteractor *)_myVTKRenderWindow->GetInteractor(); - } - else - { - return NULL; - } -} - -- (void)setupPipeline -{ - vtkRenderingOpenGL2ObjectFactory *of = vtkRenderingOpenGL2ObjectFactory::New(); - vtkObjectFactory::RegisterFactory(of); - - vtkIOSRenderWindow *renWin = vtkIOSRenderWindow::New(); - //renWin->DebugOn(); - [self setVTKRenderWindow:renWin]; - - vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); - iren->SetRenderWindow(renWin); - - vtkNew renderer; - renWin->AddRenderer(renderer.Get()); - - vtkInteractorStyleMultiTouchCamera *ismt = vtkInteractorStyleMultiTouchCamera::New(); - iren->SetInteractorStyle(ismt); - ismt->Delete(); - - vtkNew sphere; - sphere->SetThetaResolution(8); - sphere->SetPhiResolution(8); - - vtkNew sphereMapper; - sphereMapper->SetInputConnection(sphere->GetOutputPort()); - vtkNew sphereActor; - sphereActor->SetMapper(sphereMapper.Get()); - - vtkNew cone; - cone->SetResolution(6); - - vtkNew glyph; - glyph->SetInputConnection(sphere->GetOutputPort()); - glyph->SetSourceConnection(cone->GetOutputPort()); - glyph->SetVectorModeToUseNormal(); - glyph->SetScaleModeToScaleByVector(); - glyph->SetScaleFactor(0.25); - - vtkNew spikeMapper; - spikeMapper->SetInputConnection(glyph->GetOutputPort()); - - vtkNew spikeActor; - spikeActor->SetMapper(spikeMapper.Get()); - - renderer->AddActor(sphereActor.Get()); - renderer->AddActor(spikeActor.Get()); - renderer->SetBackground(0.4,0.5,0.6); -} - - -- (void)viewDidLoad -{ - [super viewDidLoad]; - - self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; - - if (!self.context) { - NSLog(@"Failed to create ES context"); - } - - GLKView *view = (GLKView *)self.view; - view.context = self.context; - view.drawableDepthFormat = GLKViewDrawableDepthFormat24; - view.drawableMultisample = GLKViewDrawableMultisample4X; - - // setup the vis pipeline - [self setupPipeline]; - - [self getVTKRenderWindow]->SetSize(backingWidth, backingHeight); - [self getVTKRenderWindow]->Render(); -} - --(void) initializeKiwiApp -{ - [EAGLContext setCurrentContext:self.context]; - - std::string dataset = [[[NSBundle mainBundle] pathForResource:@"teapot" ofType:@"vtp"] UTF8String]; - - self->mKiwiApp = vesKiwiViewerApp::Ptr(new vesKiwiViewerApp); - self->mKiwiApp->initGL(); - [self resizeView]; - self->mKiwiApp->loadDataset(dataset); - self->mKiwiApp->resetView(); -} - -- (void)dealloc -{ - [self tearDownGL]; - - if ([EAGLContext currentContext] == self.context) { - [EAGLContext setCurrentContext:nil]; - } -} - -- (void)didReceiveMemoryWarning -{ - [super didReceiveMemoryWarning]; - - if ([self isViewLoaded] && ([[self view] window] == nil)) { - self.view = nil; - - [self tearDownGL]; - - if ([EAGLContext currentContext] == self.context) { - [EAGLContext setCurrentContext:nil]; - } - self.context = nil; - } - - // Dispose of any resources that can be recreated. -} - -- (void)tearDownGL -{ - [EAGLContext setCurrentContext:self.context]; - - // free GL resources - // ... -} - --(void) resizeView -{ - double scale = self.view.contentScaleFactor; - [self getVTKRenderWindow]->SetSize(self.view.bounds.size.width*scale, self.view.bounds.size.height*scale); -} - -- (void)viewWillLayoutSubviews -{ - [self resizeView]; -} - -- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect -{ - [self getVTKRenderWindow]->Render(); -} - -@end diff --git a/Examples/iOS/GLPaint.old/Classes/PaintingView.h b/Examples/iOS/GLPaint.old/Classes/PaintingView.h deleted file mode 100644 index 32fbee74f6a..00000000000 --- a/Examples/iOS/GLPaint.old/Classes/PaintingView.h +++ /dev/null @@ -1,21 +0,0 @@ -/*========================================================================= - -Program: Visualization Toolkit - -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#import - -//CLASS INTERFACES: - -@interface PaintingView : vtkIOSGLView - -@end diff --git a/Examples/iOS/GLPaint.old/Classes/PaintingView.mm b/Examples/iOS/GLPaint.old/Classes/PaintingView.mm deleted file mode 100644 index 0cdf07f80c4..00000000000 --- a/Examples/iOS/GLPaint.old/Classes/PaintingView.mm +++ /dev/null @@ -1,100 +0,0 @@ -/*========================================================================= - -Program: Visualization Toolkit - -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#import -#import -#import - -#import "PaintingView.h" - -#include "vtkNew.h" -#include "vtkActor.h" -#include "vtkCamera.h" -#include "vtkConeSource.h" -#include "vtkDebugLeaks.h" -#include "vtkGlyph3D.h" -#include "vtkPolyData.h" -#include "vtkPolyDataMapper.h" -#include "vtkIOSRenderWindow.h" -#include "vtkIOSRenderWindowInteractor.h" -#include "vtkRenderer.h" -#include "vtkSphereSource.h" -#include "vtkCommand.h" -#include "vtkInteractorStyleMultiTouchCamera.h" - - -@interface PaintingView() -{ -} - -@end - -@implementation PaintingView - - -- (void)setupPipeline -{ - [super setupPipeline]; - - vtkIOSRenderWindowInteractor *interactor = [self getInteractor]; - if (!interactor) - { - return; - } - - vtkIOSRenderWindow *renWin = [self getVTKRenderWindow]; - if (!renWin) - { - return; - } - - vtkNew renderer; - renWin->AddRenderer(renderer.Get()); - - vtkInteractorStyleMultiTouchCamera *ismt = vtkInteractorStyleMultiTouchCamera::New(); - interactor->SetInteractorStyle(ismt); - ismt->Delete(); - - vtkNew sphere; - sphere->SetThetaResolution(8); - sphere->SetPhiResolution(8); - - vtkNew sphereMapper; - sphereMapper->SetInputConnection(sphere->GetOutputPort()); - vtkNew sphereActor; - sphereActor->SetMapper(sphereMapper.Get()); - - vtkNew cone; - cone->SetResolution(6); - - vtkNew glyph; - glyph->SetInputConnection(sphere->GetOutputPort()); - glyph->SetSourceConnection(cone->GetOutputPort()); - glyph->SetVectorModeToUseNormal(); - glyph->SetScaleModeToScaleByVector(); - glyph->SetScaleFactor(0.25); - - vtkNew spikeMapper; - spikeMapper->SetInputConnection(glyph->GetOutputPort()); - - vtkNew spikeActor; - spikeActor->SetMapper(spikeMapper.Get()); - - renderer->AddActor(sphereActor.Get()); - renderer->AddActor(spikeActor.Get()); - renderer->SetBackground(0.4,0.5,0.6); -} - - -@end diff --git a/Examples/iOS/GLPaint.old/Classes/PaintingViewController.h b/Examples/iOS/GLPaint.old/Classes/PaintingViewController.h deleted file mode 100644 index 096e4a9a91d..00000000000 --- a/Examples/iOS/GLPaint.old/Classes/PaintingViewController.h +++ /dev/null @@ -1,19 +0,0 @@ -/*========================================================================= - -Program: Visualization Toolkit - -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#import - -@interface PaintingViewController : UIViewController - -@end diff --git a/Examples/iOS/GLPaint.old/Classes/PaintingViewController.mm b/Examples/iOS/GLPaint.old/Classes/PaintingViewController.mm deleted file mode 100644 index d432a3af39d..00000000000 --- a/Examples/iOS/GLPaint.old/Classes/PaintingViewController.mm +++ /dev/null @@ -1,56 +0,0 @@ -/*========================================================================= - -Program: Visualization Toolkit - -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#import "PaintingViewController.h" -#import "PaintingView.h" - -//CLASS IMPLEMENTATIONS: - -@interface PaintingViewController() -{ - CFTimeInterval lastTime; -} -@end - -@implementation PaintingViewController - -- (void)viewDidLoad -{ - [super viewDidLoad]; -} - -- (void)viewDidAppear:(BOOL)animated -{ - [super viewDidAppear:animated]; - [self becomeFirstResponder]; -} - -- (BOOL)canBecomeFirstResponder -{ - return YES; -} - -// Release resources when they are no longer needed, -- (void)dealloc -{ -} - -// We do not support auto-rotation in this sample -- (BOOL)shouldAutorotate -{ - return NO; -} - - -@end diff --git a/Examples/iOS/GLPaint.old/Default-568h@2x.png b/Examples/iOS/GLPaint.old/Default-568h@2x.png deleted file mode 100644 index e2b072ce473..00000000000 Binary files a/Examples/iOS/GLPaint.old/Default-568h@2x.png and /dev/null differ diff --git a/Examples/iOS/GLPaint.old/Default.png b/Examples/iOS/GLPaint.old/Default.png deleted file mode 100644 index cfb0fb88f12..00000000000 Binary files a/Examples/iOS/GLPaint.old/Default.png and /dev/null differ diff --git a/Examples/iOS/GLPaint.old/GLPaint-Info.plist b/Examples/iOS/GLPaint.old/GLPaint-Info.plist deleted file mode 100644 index 236440a7408..00000000000 --- a/Examples/iOS/GLPaint.old/GLPaint-Info.plist +++ /dev/null @@ -1,43 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleDisplayName - ${PRODUCT_NAME} - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIconFile - - CFBundleIdentifier - com.example.apple-samplecode.${PRODUCT_NAME:identifier} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - APPL - CFBundleSignature - ???? - CFBundleVersion - 1.13 - LSRequiresIPhoneOS - - NSMainNibFile - MainWindow - UIStatusBarHidden - - UIViewControllerBasedStatusBarAppearance - - CFBundleIconFiles - - Icon.png - Icon@2x.png - Icon-72.png - Icon-Small.png - Icon-Small-50.png - Icon-Small@2x.png - - - diff --git a/Examples/iOS/GLPaint.old/GLPaint.xcodeproj/project.pbxproj b/Examples/iOS/GLPaint.old/GLPaint.xcodeproj/project.pbxproj deleted file mode 100644 index eb516191489..00000000000 --- a/Examples/iOS/GLPaint.old/GLPaint.xcodeproj/project.pbxproj +++ /dev/null @@ -1,376 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 13328B8419C77700006A473C /* vtk.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 13328B8319C77700006A473C /* vtk.framework */; }; - 13328B8619C77938006A473C /* libstdc++.6.0.9.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 13328B8519C77938006A473C /* libstdc++.6.0.9.dylib */; }; - 1B8CA3120DC8E3A4002C657A /* AppController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1B8CA30B0DC8E3A4002C657A /* AppController.mm */; }; - 1B8CA3130DC8E3A4002C657A /* PaintingView.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1B8CA30D0DC8E3A4002C657A /* PaintingView.mm */; }; - 1BD0B6AB0DDCA9B800E538F8 /* Default.png in Resources */ = {isa = PBXBuildFile; fileRef = 1BD0B6AA0DDCA9B800E538F8 /* Default.png */; }; - 1D3623EC0D0F72F000981E51 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D3623EB0D0F72F000981E51 /* CoreGraphics.framework */; }; - 1D60589B0D05DD56006BFB54 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; }; - 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1D30AB110D05D00D00671497 /* Foundation.framework */; }; - 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */; }; - 2D500B940D5A79C200DBA0E3 /* OpenGLES.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2D500B920D5A79C200DBA0E3 /* OpenGLES.framework */; }; - 2D500B9A0D5A79CF00DBA0E3 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2D500B990D5A79CF00DBA0E3 /* QuartzCore.framework */; }; - AF7492AB1728A9E50013253B /* MainWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = AF7492A91728A9E50013253B /* MainWindow.xib */; }; - AF7E20421728A2C600728423 /* PaintingViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = AF7E203F1728A2C600728423 /* PaintingViewController.xib */; }; - AF7E20451728A54000728423 /* PaintingViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = AF7E20441728A53F00728423 /* PaintingViewController.mm */; }; - AF877F8617271F57002D08B8 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = AF877F8517271F57002D08B8 /* Default-568h@2x.png */; }; - AF877F9417272C2F002D08B8 /* GLKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AF877F9317272C2F002D08B8 /* GLKit.framework */; }; - AFCEBA2111D96215001AA22A /* Icon-72.png in Resources */ = {isa = PBXBuildFile; fileRef = AFCEBA1A11D96215001AA22A /* Icon-72.png */; }; - AFCEBA2211D96215001AA22A /* Icon-Small-50.png in Resources */ = {isa = PBXBuildFile; fileRef = AFCEBA1B11D96215001AA22A /* Icon-Small-50.png */; }; - AFCEBA2311D96215001AA22A /* Icon-Small.png in Resources */ = {isa = PBXBuildFile; fileRef = AFCEBA1C11D96215001AA22A /* Icon-Small.png */; }; - AFCEBA2411D96215001AA22A /* Icon-Small@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = AFCEBA1D11D96215001AA22A /* Icon-Small@2x.png */; }; - AFCEBA2511D96215001AA22A /* Icon.png in Resources */ = {isa = PBXBuildFile; fileRef = AFCEBA1E11D96215001AA22A /* Icon.png */; }; - AFCEBA2611D96215001AA22A /* Icon@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = AFCEBA1F11D96215001AA22A /* Icon@2x.png */; }; - AFCEBA2711D96215001AA22A /* iTunesArtwork in Resources */ = {isa = PBXBuildFile; fileRef = AFCEBA2011D96215001AA22A /* iTunesArtwork */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 13328B8319C77700006A473C /* vtk.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = vtk.framework; path = ../../../vtkinstall/frameworks/vtk.framework; sourceTree = ""; }; - 13328B8519C77938006A473C /* libstdc++.6.0.9.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = "libstdc++.6.0.9.dylib"; path = "usr/lib/libstdc++.6.0.9.dylib"; sourceTree = SDKROOT; }; - 1B8CA30A0DC8E3A4002C657A /* AppController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppController.h; path = Classes/AppController.h; sourceTree = ""; }; - 1B8CA30B0DC8E3A4002C657A /* AppController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppController.mm; path = Classes/AppController.mm; sourceTree = ""; }; - 1B8CA30C0DC8E3A4002C657A /* PaintingView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PaintingView.h; path = Classes/PaintingView.h; sourceTree = ""; }; - 1B8CA30D0DC8E3A4002C657A /* PaintingView.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = PaintingView.mm; path = Classes/PaintingView.mm; sourceTree = ""; }; - 1BD0B6AA0DDCA9B800E538F8 /* Default.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Default.png; sourceTree = ""; }; - 1BEB7DB40DA5967E00271C96 /* ReadMe.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ReadMe.txt; sourceTree = ""; }; - 1D30AB110D05D00D00671497 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; - 1D3623EB0D0F72F000981E51 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; - 1D6058910D05DD3D006BFB54 /* GLPaint.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GLPaint.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; - 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; - 2D500B920D5A79C200DBA0E3 /* OpenGLES.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGLES.framework; path = System/Library/Frameworks/OpenGLES.framework; sourceTree = SDKROOT; }; - 2D500B990D5A79CF00DBA0E3 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; - 32CA4F630368D1EE00C91783 /* Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Prefix.pch; sourceTree = ""; }; - 8D1107310486CEB800E47090 /* GLPaint-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GLPaint-Info.plist"; sourceTree = ""; }; - AF7492AA1728A9E50013253B /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/MainWindow.xib; sourceTree = ""; }; - AF7E20401728A2C600728423 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/PaintingViewController.xib; sourceTree = ""; }; - AF7E20431728A53F00728423 /* PaintingViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PaintingViewController.h; path = Classes/PaintingViewController.h; sourceTree = ""; }; - AF7E20441728A53F00728423 /* PaintingViewController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = PaintingViewController.mm; path = Classes/PaintingViewController.mm; sourceTree = ""; }; - AF877F8517271F57002D08B8 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = ""; }; - AF877F9317272C2F002D08B8 /* GLKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GLKit.framework; path = System/Library/Frameworks/GLKit.framework; sourceTree = SDKROOT; }; - AFCEBA1A11D96215001AA22A /* Icon-72.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-72.png"; path = "Images/Icon-72.png"; sourceTree = ""; }; - AFCEBA1B11D96215001AA22A /* Icon-Small-50.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-Small-50.png"; path = "Images/Icon-Small-50.png"; sourceTree = ""; }; - AFCEBA1C11D96215001AA22A /* Icon-Small.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-Small.png"; path = "Images/Icon-Small.png"; sourceTree = ""; }; - AFCEBA1D11D96215001AA22A /* Icon-Small@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon-Small@2x.png"; path = "Images/Icon-Small@2x.png"; sourceTree = ""; }; - AFCEBA1E11D96215001AA22A /* Icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = Icon.png; path = Images/Icon.png; sourceTree = ""; }; - AFCEBA1F11D96215001AA22A /* Icon@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Icon@2x.png"; path = "Images/Icon@2x.png"; sourceTree = ""; }; - AFCEBA2011D96215001AA22A /* iTunesArtwork */ = {isa = PBXFileReference; lastKnownFileType = file; name = iTunesArtwork; path = Images/iTunesArtwork; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 1D60588F0D05DD3D006BFB54 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 13328B8619C77938006A473C /* libstdc++.6.0.9.dylib in Frameworks */, - 13328B8419C77700006A473C /* vtk.framework in Frameworks */, - AF877F9417272C2F002D08B8 /* GLKit.framework in Frameworks */, - 1D60589F0D05DD5A006BFB54 /* Foundation.framework in Frameworks */, - 1DF5F4E00D08C38300B7A737 /* UIKit.framework in Frameworks */, - 1D3623EC0D0F72F000981E51 /* CoreGraphics.framework in Frameworks */, - 2D500B940D5A79C200DBA0E3 /* OpenGLES.framework in Frameworks */, - 2D500B9A0D5A79CF00DBA0E3 /* QuartzCore.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 19C28FACFE9D520D11CA2CBB /* Products */ = { - isa = PBXGroup; - children = ( - 1D6058910D05DD3D006BFB54 /* GLPaint.app */, - ); - name = Products; - sourceTree = ""; - }; - 29B97314FDCFA39411CA2CEA /* CustomTemplate */ = { - isa = PBXGroup; - children = ( - 1BEB7DB40DA5967E00271C96 /* ReadMe.txt */, - 2D500B1D0D5A766B00DBA0E3 /* Classes */, - 29B97315FDCFA39411CA2CEA /* Other Sources */, - 29B97317FDCFA39411CA2CEA /* Resources */, - 29B97323FDCFA39411CA2CEA /* Frameworks */, - 19C28FACFE9D520D11CA2CBB /* Products */, - ); - name = CustomTemplate; - sourceTree = ""; - }; - 29B97315FDCFA39411CA2CEA /* Other Sources */ = { - isa = PBXGroup; - children = ( - 32CA4F630368D1EE00C91783 /* Prefix.pch */, - 29B97316FDCFA39411CA2CEA /* main.m */, - ); - name = "Other Sources"; - sourceTree = ""; - }; - 29B97317FDCFA39411CA2CEA /* Resources */ = { - isa = PBXGroup; - children = ( - AF7492A91728A9E50013253B /* MainWindow.xib */, - AF7E203F1728A2C600728423 /* PaintingViewController.xib */, - AFCEBA1D11D96215001AA22A /* Icon-Small@2x.png */, - AFCEBA1A11D96215001AA22A /* Icon-72.png */, - AFCEBA1B11D96215001AA22A /* Icon-Small-50.png */, - AFCEBA1C11D96215001AA22A /* Icon-Small.png */, - AFCEBA1E11D96215001AA22A /* Icon.png */, - AFCEBA1F11D96215001AA22A /* Icon@2x.png */, - AFCEBA2011D96215001AA22A /* iTunesArtwork */, - 1BD0B6AA0DDCA9B800E538F8 /* Default.png */, - AF877F8517271F57002D08B8 /* Default-568h@2x.png */, - 8D1107310486CEB800E47090 /* GLPaint-Info.plist */, - ); - name = Resources; - sourceTree = ""; - }; - 29B97323FDCFA39411CA2CEA /* Frameworks */ = { - isa = PBXGroup; - children = ( - 13328B8519C77938006A473C /* libstdc++.6.0.9.dylib */, - 13328B8319C77700006A473C /* vtk.framework */, - AF877F9317272C2F002D08B8 /* GLKit.framework */, - 1D3623EB0D0F72F000981E51 /* CoreGraphics.framework */, - 2D500B990D5A79CF00DBA0E3 /* QuartzCore.framework */, - 2D500B920D5A79C200DBA0E3 /* OpenGLES.framework */, - 1DF5F4DF0D08C38300B7A737 /* UIKit.framework */, - 1D30AB110D05D00D00671497 /* Foundation.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 2D500B1D0D5A766B00DBA0E3 /* Classes */ = { - isa = PBXGroup; - children = ( - 1B8CA30A0DC8E3A4002C657A /* AppController.h */, - 1B8CA30B0DC8E3A4002C657A /* AppController.mm */, - AF7E20431728A53F00728423 /* PaintingViewController.h */, - AF7E20441728A53F00728423 /* PaintingViewController.mm */, - 1B8CA30C0DC8E3A4002C657A /* PaintingView.h */, - 1B8CA30D0DC8E3A4002C657A /* PaintingView.mm */, - ); - name = Classes; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 1D6058900D05DD3D006BFB54 /* GLPaint */ = { - isa = PBXNativeTarget; - buildConfigurationList = 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "GLPaint" */; - buildPhases = ( - 1D60588D0D05DD3D006BFB54 /* Resources */, - 1D60588E0D05DD3D006BFB54 /* Sources */, - 1D60588F0D05DD3D006BFB54 /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = GLPaint; - productName = foo; - productReference = 1D6058910D05DD3D006BFB54 /* GLPaint.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 29B97313FDCFA39411CA2CEA /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0510; - }; - buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "GLPaint" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 1; - knownRegions = ( - en, - ); - mainGroup = 29B97314FDCFA39411CA2CEA /* CustomTemplate */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 1D6058900D05DD3D006BFB54 /* GLPaint */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 1D60588D0D05DD3D006BFB54 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 1BD0B6AB0DDCA9B800E538F8 /* Default.png in Resources */, - AFCEBA2111D96215001AA22A /* Icon-72.png in Resources */, - AFCEBA2211D96215001AA22A /* Icon-Small-50.png in Resources */, - AFCEBA2311D96215001AA22A /* Icon-Small.png in Resources */, - AFCEBA2411D96215001AA22A /* Icon-Small@2x.png in Resources */, - AFCEBA2511D96215001AA22A /* Icon.png in Resources */, - AFCEBA2611D96215001AA22A /* Icon@2x.png in Resources */, - AFCEBA2711D96215001AA22A /* iTunesArtwork in Resources */, - AF877F8617271F57002D08B8 /* Default-568h@2x.png in Resources */, - AF7E20421728A2C600728423 /* PaintingViewController.xib in Resources */, - AF7492AB1728A9E50013253B /* MainWindow.xib in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 1D60588E0D05DD3D006BFB54 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 1D60589B0D05DD56006BFB54 /* main.m in Sources */, - 1B8CA3120DC8E3A4002C657A /* AppController.mm in Sources */, - 1B8CA3130DC8E3A4002C657A /* PaintingView.mm in Sources */, - AF7E20451728A54000728423 /* PaintingViewController.mm in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXVariantGroup section */ - AF7492A91728A9E50013253B /* MainWindow.xib */ = { - isa = PBXVariantGroup; - children = ( - AF7492AA1728A9E50013253B /* en */, - ); - name = MainWindow.xib; - sourceTree = ""; - }; - AF7E203F1728A2C600728423 /* PaintingViewController.xib */ = { - isa = PBXVariantGroup; - children = ( - AF7E20401728A2C600728423 /* en */, - ); - name = PaintingViewController.xib; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 1D6058940D05DD3E006BFB54 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ENABLE_OBJC_ARC = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - ../../../vtkinstall/frameworks, - ); - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = Prefix.pch; - HEADER_SEARCH_PATHS = ( - "$(inherited)", - /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, - "../../../vtkinstall/include/vtk-6.2", - ); - INFOPLIST_FILE = "GLPaint-Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; - LIBRARY_SEARCH_PATHS = "$(inherited)"; - ONLY_ACTIVE_ARCH = YES; - PRODUCT_NAME = GLPaint; - TARGETED_DEVICE_FAMILY = 1; - VALID_ARCHS = "armv7 armv7s arm64"; - WARNING_CFLAGS = "-Wall"; - }; - name = Debug; - }; - 1D6058950D05DD3E006BFB54 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ENABLE_OBJC_ARC = YES; - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - ../../../vtkinstall/frameworks, - ); - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = Prefix.pch; - HEADER_SEARCH_PATHS = ( - "$(inherited)", - /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, - "../../../vtkinstall/include/vtk-6.2", - ); - INFOPLIST_FILE = "GLPaint-Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; - LIBRARY_SEARCH_PATHS = "$(inherited)"; - ONLY_ACTIVE_ARCH = YES; - PRODUCT_NAME = GLPaint; - TARGETED_DEVICE_FAMILY = 1; - VALID_ARCHS = "armv7 armv7s arm64"; - WARNING_CFLAGS = "-Wall"; - }; - name = Release; - }; - C01FCF4F08A954540054247B /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_PARAMETER = NO; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - }; - name = Debug; - }; - C01FCF5008A954540054247B /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; - SDKROOT = iphoneos; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 1D6058960D05DD3E006BFB54 /* Build configuration list for PBXNativeTarget "GLPaint" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1D6058940D05DD3E006BFB54 /* Debug */, - 1D6058950D05DD3E006BFB54 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - C01FCF4E08A954540054247B /* Build configuration list for PBXProject "GLPaint" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - C01FCF4F08A954540054247B /* Debug */, - C01FCF5008A954540054247B /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 29B97313FDCFA39411CA2CEA /* Project object */; -} diff --git a/Examples/iOS/GLPaint.old/Images/Icon-72.png b/Examples/iOS/GLPaint.old/Images/Icon-72.png deleted file mode 100644 index 0d5a653ccfb..00000000000 Binary files a/Examples/iOS/GLPaint.old/Images/Icon-72.png and /dev/null differ diff --git a/Examples/iOS/GLPaint.old/Images/Icon-Small-50.png b/Examples/iOS/GLPaint.old/Images/Icon-Small-50.png deleted file mode 100644 index dbc20a572a2..00000000000 Binary files a/Examples/iOS/GLPaint.old/Images/Icon-Small-50.png and /dev/null differ diff --git a/Examples/iOS/GLPaint.old/Images/Icon-Small.png b/Examples/iOS/GLPaint.old/Images/Icon-Small.png deleted file mode 100644 index 5a0701f6a09..00000000000 Binary files a/Examples/iOS/GLPaint.old/Images/Icon-Small.png and /dev/null differ diff --git a/Examples/iOS/GLPaint.old/Images/Icon-Small@2x.png b/Examples/iOS/GLPaint.old/Images/Icon-Small@2x.png deleted file mode 100644 index 50c9b89e709..00000000000 Binary files a/Examples/iOS/GLPaint.old/Images/Icon-Small@2x.png and /dev/null differ diff --git a/Examples/iOS/GLPaint.old/Images/Icon.png b/Examples/iOS/GLPaint.old/Images/Icon.png deleted file mode 100644 index 64af9269728..00000000000 Binary files a/Examples/iOS/GLPaint.old/Images/Icon.png and /dev/null differ diff --git a/Examples/iOS/GLPaint.old/Images/Icon@2x.png b/Examples/iOS/GLPaint.old/Images/Icon@2x.png deleted file mode 100644 index 9b73557834e..00000000000 Binary files a/Examples/iOS/GLPaint.old/Images/Icon@2x.png and /dev/null differ diff --git a/Examples/iOS/GLPaint.old/Images/iTunesArtwork b/Examples/iOS/GLPaint.old/Images/iTunesArtwork deleted file mode 100644 index 6ad7a1ff8fa..00000000000 Binary files a/Examples/iOS/GLPaint.old/Images/iTunesArtwork and /dev/null differ diff --git a/Examples/iOS/GLPaint.old/Prefix.pch b/Examples/iOS/GLPaint.old/Prefix.pch deleted file mode 100644 index bb57e5f8804..00000000000 --- a/Examples/iOS/GLPaint.old/Prefix.pch +++ /dev/null @@ -1,6 +0,0 @@ -#import - - -#ifdef __OBJC__ - #import -#endif diff --git a/Examples/iOS/GLPaint.old/main.m b/Examples/iOS/GLPaint.old/main.m deleted file mode 100644 index a9322aa7d80..00000000000 --- a/Examples/iOS/GLPaint.old/main.m +++ /dev/null @@ -1,23 +0,0 @@ -/*========================================================================= - -Program: Visualization Toolkit - -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#import - -int main(int argc, char *argv[]) -{ - @autoreleasepool { - int retVal = UIApplicationMain(argc, argv, nil, nil); - return retVal; - } -} diff --git a/Examples/iOS/GLPaint/Classes/MyGLKViewController.mm b/Examples/iOS/GLPaint/Classes/MyGLKViewController.mm index 72565d96236..58823010050 100644 --- a/Examples/iOS/GLPaint/Classes/MyGLKViewController.mm +++ b/Examples/iOS/GLPaint/Classes/MyGLKViewController.mm @@ -213,12 +213,6 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event return; } - vtkIOSRenderWindow *renWin = [self getVTKRenderWindow]; - if (!renWin) - { - return; - } - CGRect bounds = [self.view bounds]; // set the position for all contacts @@ -244,7 +238,7 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { int index = interactor->GetPointerIndexForContact((size_t)(__bridge void *)touch); interactor->SetPointerIndex(index); - interactor->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL); + interactor->LeftButtonPressEvent(); NSLog(@"Starting left mouse"); } @@ -261,12 +255,6 @@ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event return; } - vtkIOSRenderWindow *renWin = [self getVTKRenderWindow]; - if (!renWin) - { - return; - } - CGRect bounds = [self.view bounds]; // set the position for all contacts @@ -290,7 +278,7 @@ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event // fire move event on last index interactor->SetPointerIndex(index); - interactor->InvokeEvent(vtkCommand::MouseMoveEvent,NULL); + interactor->MouseMoveEvent(); // NSLog(@"Moved left mouse"); // Display the buffer @@ -306,12 +294,6 @@ - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event return; } - vtkIOSRenderWindow *renWin = [self getVTKRenderWindow]; - if (!renWin) - { - return; - } - CGRect bounds = [self.view bounds]; // set the position for all contacts NSSet *myTouches = [event touchesForView:self.view]; @@ -336,7 +318,7 @@ - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { int index = interactor->GetPointerIndexForContact((size_t)(__bridge void *)touch); interactor->SetPointerIndex(index); - interactor->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL); + interactor->LeftButtonReleaseEvent(); interactor->ClearContact((size_t)(__bridge void *)touch); NSLog(@"lifting left mouse"); } @@ -354,12 +336,6 @@ - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event return; } - vtkIOSRenderWindow *renWin = [self getVTKRenderWindow]; - if (!renWin) - { - return; - } - CGRect bounds = [self.view bounds]; UITouch* touch = [[event touchesForView:self.view] anyObject]; // Convert touch point from UIView referential to OpenGL one (upside-down flip) @@ -370,7 +346,7 @@ - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event (int)round(location.y), 0, 0, 0, 0); - interactor->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL); + interactor->LeftButtonReleaseEvent(); // NSLog(@"Ended left mouse"); // Display the buffer diff --git a/Examples/iOS/PlaneView/PlaneView.xcodeproj/project.pbxproj b/Examples/iOS/PlaneView/PlaneView.xcodeproj/project.pbxproj new file mode 100644 index 00000000000..6d7e440d8d3 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView.xcodeproj/project.pbxproj @@ -0,0 +1,351 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 1312F93D1C65005D0064AA4C /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 1312F93C1C65005D0064AA4C /* main.m */; }; + 1312F9401C65005D0064AA4C /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 1312F93F1C65005D0064AA4C /* AppDelegate.m */; }; + 1312F9471C65005D0064AA4C /* VTKViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1312F9461C65005D0064AA4C /* VTKViewController.mm */; }; + 1312F94A1C65005D0064AA4C /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 1312F9481C65005D0064AA4C /* Main.storyboard */; }; + 1312F94C1C65005D0064AA4C /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 1312F94B1C65005D0064AA4C /* Assets.xcassets */; }; + 1312F94F1C65005D0064AA4C /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 1312F94D1C65005D0064AA4C /* LaunchScreen.storyboard */; }; + 1312F9571C6502270064AA4C /* vtk.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1312F9561C6502270064AA4C /* vtk.framework */; }; + 1312F9591C6503EC0064AA4C /* GLKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1312F9581C6503EC0064AA4C /* GLKit.framework */; }; + 1312F95F1C650B050064AA4C /* SettingsTableViewController.mm in Sources */ = {isa = PBXBuildFile; fileRef = 1312F95E1C650B050064AA4C /* SettingsTableViewController.mm */; }; + 135BC9A11C777D12009C8169 /* iOSapplication.icns in Resources */ = {isa = PBXBuildFile; fileRef = 135BC9A01C777D12009C8169 /* iOSapplication.icns */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 1312F9381C65005D0064AA4C /* PlaneView.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PlaneView.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 1312F93C1C65005D0064AA4C /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + 1312F93E1C65005D0064AA4C /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + 1312F93F1C65005D0064AA4C /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; + 1312F9451C65005D0064AA4C /* VTKViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = VTKViewController.h; sourceTree = ""; }; + 1312F9461C65005D0064AA4C /* VTKViewController.mm */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; path = VTKViewController.mm; sourceTree = ""; }; + 1312F9491C65005D0064AA4C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 1312F94B1C65005D0064AA4C /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 1312F94E1C65005D0064AA4C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 1312F9501C65005D0064AA4C /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 1312F9561C6502270064AA4C /* vtk.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = vtk.framework; path = ../../../../../../install/vtk.framework; sourceTree = ""; }; + 1312F9581C6503EC0064AA4C /* GLKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GLKit.framework; path = System/Library/Frameworks/GLKit.framework; sourceTree = SDKROOT; }; + 1312F95D1C650B050064AA4C /* SettingsTableViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SettingsTableViewController.h; sourceTree = ""; }; + 1312F95E1C650B050064AA4C /* SettingsTableViewController.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = SettingsTableViewController.mm; sourceTree = ""; }; + 1312F9631C68EADF0064AA4C /* PlaneView.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PlaneView.entitlements; sourceTree = ""; }; + 135BC9A01C777D12009C8169 /* iOSapplication.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; name = iOSapplication.icns; path = iOSapplication.icns; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 1312F9351C65005D0064AA4C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1312F9591C6503EC0064AA4C /* GLKit.framework in Frameworks */, + 1312F9571C6502270064AA4C /* vtk.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 1312F92F1C65005D0064AA4C = { + isa = PBXGroup; + children = ( + 1312F9581C6503EC0064AA4C /* GLKit.framework */, + 1312F9561C6502270064AA4C /* vtk.framework */, + 1312F93A1C65005D0064AA4C /* PlaneView */, + 1312F9391C65005D0064AA4C /* Products */, + ); + sourceTree = ""; + }; + 1312F9391C65005D0064AA4C /* Products */ = { + isa = PBXGroup; + children = ( + 1312F9381C65005D0064AA4C /* PlaneView.app */, + ); + name = Products; + sourceTree = ""; + }; + 1312F93A1C65005D0064AA4C /* PlaneView */ = { + isa = PBXGroup; + children = ( + 135BC9A01C777D12009C8169 /* iOSapplication.icns */, + 1312F9631C68EADF0064AA4C /* PlaneView.entitlements */, + 1312F93E1C65005D0064AA4C /* AppDelegate.h */, + 1312F93F1C65005D0064AA4C /* AppDelegate.m */, + 1312F9451C65005D0064AA4C /* VTKViewController.h */, + 1312F9461C65005D0064AA4C /* VTKViewController.mm */, + 1312F9481C65005D0064AA4C /* Main.storyboard */, + 1312F94B1C65005D0064AA4C /* Assets.xcassets */, + 1312F94D1C65005D0064AA4C /* LaunchScreen.storyboard */, + 1312F9501C65005D0064AA4C /* Info.plist */, + 1312F93B1C65005D0064AA4C /* Supporting Files */, + 1312F95D1C650B050064AA4C /* SettingsTableViewController.h */, + 1312F95E1C650B050064AA4C /* SettingsTableViewController.mm */, + ); + path = PlaneView; + sourceTree = ""; + }; + 1312F93B1C65005D0064AA4C /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 1312F93C1C65005D0064AA4C /* main.m */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 1312F9371C65005D0064AA4C /* PlaneView */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1312F9531C65005D0064AA4C /* Build configuration list for PBXNativeTarget "PlaneView" */; + buildPhases = ( + 1312F9341C65005D0064AA4C /* Sources */, + 1312F9351C65005D0064AA4C /* Frameworks */, + 1312F9361C65005D0064AA4C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = PlaneView; + productName = PlaneView; + productReference = 1312F9381C65005D0064AA4C /* PlaneView.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 1312F9301C65005D0064AA4C /* Project object */ = { + isa = PBXProject; + attributes = { + KnownAssetTags = ( + enableProbeSwitch, + ); + LastUpgradeCheck = 0720; + ORGANIZATIONNAME = "Kitware Inc."; + TargetAttributes = { + 1312F9371C65005D0064AA4C = { + CreatedOnToolsVersion = 7.2; + DevelopmentTeam = W38PE5Y733; + SystemCapabilities = { + com.apple.iCloud = { + enabled = 1; + }; + }; + }; + }; + }; + buildConfigurationList = 1312F9331C65005D0064AA4C /* Build configuration list for PBXProject "PlaneView" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 1312F92F1C65005D0064AA4C; + productRefGroup = 1312F9391C65005D0064AA4C /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 1312F9371C65005D0064AA4C /* PlaneView */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 1312F9361C65005D0064AA4C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1312F94A1C65005D0064AA4C /* Main.storyboard in Resources */, + 1312F94C1C65005D0064AA4C /* Assets.xcassets in Resources */, + 135BC9A11C777D12009C8169 /* iOSapplication.icns in Resources */, + 1312F94F1C65005D0064AA4C /* LaunchScreen.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 1312F9341C65005D0064AA4C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1312F95F1C650B050064AA4C /* SettingsTableViewController.mm in Sources */, + 1312F9401C65005D0064AA4C /* AppDelegate.m in Sources */, + 1312F9471C65005D0064AA4C /* VTKViewController.mm in Sources */, + 1312F93D1C65005D0064AA4C /* main.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 1312F9481C65005D0064AA4C /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 1312F9491C65005D0064AA4C /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 1312F94D1C65005D0064AA4C /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 1312F94E1C65005D0064AA4C /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 1312F9511C65005D0064AA4C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_BITCODE = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.1; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 1312F9521C65005D0064AA4C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_BITCODE = NO; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.1; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 1312F9541C65005D0064AA4C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_ENTITLEMENTS = PlaneView/PlaneView.entitlements; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + FRAMEWORK_SEARCH_PATHS = ../../../../../../install; + HEADER_SEARCH_PATHS = ../../../../../../install/vtk.framework/Headers; + INFOPLIST_FILE = PlaneView/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = kitware.com.PlaneView; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; + }; + name = Debug; + }; + 1312F9551C65005D0064AA4C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_ENTITLEMENTS = PlaneView/PlaneView.entitlements; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + FRAMEWORK_SEARCH_PATHS = ../../../../../../install; + HEADER_SEARCH_PATHS = ../../../../../../install/vtk.framework/Headers; + INFOPLIST_FILE = PlaneView/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = kitware.com.PlaneView; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1312F9331C65005D0064AA4C /* Build configuration list for PBXProject "PlaneView" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1312F9511C65005D0064AA4C /* Debug */, + 1312F9521C65005D0064AA4C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 1312F9531C65005D0064AA4C /* Build configuration list for PBXNativeTarget "PlaneView" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1312F9541C65005D0064AA4C /* Debug */, + 1312F9551C65005D0064AA4C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 1312F9301C65005D0064AA4C /* Project object */; +} diff --git a/Examples/iOS/PlaneView/PlaneView.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Examples/iOS/PlaneView/PlaneView.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..4271799eea0 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Common/Core/vtkDataArrayTemplateImplicit.txx b/Examples/iOS/PlaneView/PlaneView/AppDelegate.h similarity index 57% rename from Common/Core/vtkDataArrayTemplateImplicit.txx rename to Examples/iOS/PlaneView/PlaneView/AppDelegate.h index 780942d35a2..2bd4fbabbb0 100644 --- a/Common/Core/vtkDataArrayTemplateImplicit.txx +++ b/Examples/iOS/PlaneView/PlaneView/AppDelegate.h @@ -1,7 +1,6 @@ /*========================================================================= Program: Visualization Toolkit - Module: vtkDataArrayTemplateImplicit.txx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. @@ -12,14 +11,11 @@ PURPOSE. See the above copyright notice for more information. =========================================================================*/ -// This file is used to stop dependency tracking from including a -// dependence on the .txx file from the .h file when implicit -// instantiation is not needed. It just includes the corresponding -// .txx file, so only the name is important. +#import -#ifndef vtkDataArrayTemplateImplicit_txx -#define vtkDataArrayTemplateImplicit_txx +@interface AppDelegate : UIResponder -#include "vtkDataArrayTemplate.txx" +@property (strong, nonatomic) UIWindow *window; -#endif + +@end diff --git a/Examples/iOS/GLPaint.old/Classes/AppDelegate.mm b/Examples/iOS/PlaneView/PlaneView/AppDelegate.m similarity index 71% rename from Examples/iOS/GLPaint.old/Classes/AppDelegate.mm rename to Examples/iOS/PlaneView/PlaneView/AppDelegate.m index c9942063ad4..908340ca42d 100644 --- a/Examples/iOS/GLPaint.old/Classes/AppDelegate.mm +++ b/Examples/iOS/PlaneView/PlaneView/AppDelegate.m @@ -1,49 +1,49 @@ /*========================================================================= -Program: Visualization Toolkit + Program: Visualization Toolkit -Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen -All rights reserved. -See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. -This software is distributed WITHOUT ANY WARRANTY; without even -the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -PURPOSE. See the above copyright notice for more information. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. =========================================================================*/ #import "AppDelegate.h" +@interface AppDelegate () + +@end + @implementation AppDelegate -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions -{ - return YES; + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { + // Override point for customization after application launch. + return YES; } -- (void)applicationWillResignActive:(UIApplication *)application -{ +- (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } -- (void)applicationDidEnterBackground:(UIApplication *)application -{ +- (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } -- (void)applicationWillEnterForeground:(UIApplication *)application -{ +- (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } -- (void)applicationDidBecomeActive:(UIApplication *)application -{ +- (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } -- (void)applicationWillTerminate:(UIApplication *)application -{ +- (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Contents.json b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000000..207c307dba9 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,128 @@ +{ + "images" : [ + { + "size" : "40x40", + "idiom" : "ipad", + "scale" : "1x", + "filename" : "Icon-40.png" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "scale" : "2x", + "filename" : "Icon-40@2x.png" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "scale" : "2x", + "filename" : "Icon-60@2x.png" + }, + { + "size" : "72x72", + "idiom" : "ipad", + "scale" : "1x", + "filename" : "Icon-72.png" + }, + { + "size" : "72x72", + "idiom" : "ipad", + "scale" : "2x", + "filename" : "Icon-72@2x.png" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "scale" : "1x", + "filename" : "Icon-76.png" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "scale" : "2x", + "filename" : "Icon-76@2x.png" + }, + { + "size" : "50x50", + "idiom" : "ipad", + "scale" : "1x", + "filename" : "Icon-Small-50.png" + }, + { + "size" : "50x50", + "idiom" : "ipad", + "scale" : "2x", + "filename" : "Icon-Small-50@2x.png" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "scale" : "1x", + "filename" : "Icon-Small.png" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "scale" : "2x", + "filename" : "Icon-Small@2x.png" + }, + { + "size" : "57x57", + "idiom" : "iphone", + "scale" : "1x", + "filename" : "Icon.png" + }, + { + "size" : "57x57", + "idiom" : "iphone", + "scale" : "2x", + "filename" : "Icon@2x.png" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "scale" : "3x", + "filename" : "Icon-Small@3x.png" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "scale" : "3x", + "filename" : "Icon-40@3x.png" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "scale" : "3x", + "filename" : "Icon-60@3x.png" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "scale" : "2x", + "filename" : "Icon-40@2x.png" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "scale" : "1x", + "filename" : "Icon-Small.png" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "scale" : "2x", + "filename" : "Icon-Small@2x.png" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "scale" : "2x", + "filename" : "Icon-83.5@2x.png" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-40.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-40.png new file mode 100644 index 00000000000..4218047603d Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-40.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-40@2x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-40@2x.png new file mode 100644 index 00000000000..82d3b20201d Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-40@2x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-40@3x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-40@3x.png new file mode 100644 index 00000000000..e339c52d098 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-40@3x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-60@2x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-60@2x.png new file mode 100644 index 00000000000..e339c52d098 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-60@2x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-60@3x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-60@3x.png new file mode 100644 index 00000000000..e53f959df2a Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-60@3x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-72.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-72.png new file mode 100644 index 00000000000..12150e99224 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-72.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-72@2x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-72@2x.png new file mode 100644 index 00000000000..121195a1a9e Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-72@2x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-76.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-76.png new file mode 100644 index 00000000000..a53be6eff24 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-76.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-76@2x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-76@2x.png new file mode 100644 index 00000000000..cff011d5158 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-76@2x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-83.5@2x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-83.5@2x.png new file mode 100644 index 00000000000..e4a68c348cd Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-83.5@2x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small-50.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small-50.png new file mode 100644 index 00000000000..9ea8ffe8224 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small-50.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small-50@2x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small-50@2x.png new file mode 100644 index 00000000000..717771f49d9 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small-50@2x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small.png new file mode 100644 index 00000000000..5c77c75265f Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small@2x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small@2x.png new file mode 100644 index 00000000000..1a87820e047 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small@2x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small@3x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small@3x.png new file mode 100644 index 00000000000..043c031da2d Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon-Small@3x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon.png new file mode 100644 index 00000000000..01d6ade414d Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon@2x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon@2x.png new file mode 100644 index 00000000000..00ac4b89c1f Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/AppIcon.appiconset/Icon@2x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/Contents.json b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/Contents.json new file mode 100644 index 00000000000..da4a164c918 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/Contents.json b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/Contents.json new file mode 100644 index 00000000000..74a9f245824 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "iOSapplication.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "iOSapplication@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "iOSapplication@2x-1.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/iOSapplication.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/iOSapplication.png new file mode 100644 index 00000000000..0fd17430872 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/iOSapplication.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/iOSapplication@2x-1.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/iOSapplication@2x-1.png new file mode 100644 index 00000000000..12334baeeb2 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/iOSapplication@2x-1.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/iOSapplication@2x.png b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/iOSapplication@2x.png new file mode 100644 index 00000000000..12334baeeb2 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/Assets.xcassets/iOSapplication.imageset/iOSapplication@2x.png differ diff --git a/Examples/iOS/PlaneView/PlaneView/Base.lproj/LaunchScreen.storyboard b/Examples/iOS/PlaneView/PlaneView/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000000..80a18d4eb43 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/iOS/PlaneView/PlaneView/Base.lproj/Main.storyboard b/Examples/iOS/PlaneView/PlaneView/Base.lproj/Main.storyboard new file mode 100644 index 00000000000..d71709b93b2 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/Base.lproj/Main.storyboard @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/iOS/PlaneView/PlaneView/Info.plist b/Examples/iOS/PlaneView/PlaneView/Info.plist new file mode 100644 index 00000000000..369568e79da --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/Info.plist @@ -0,0 +1,198 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleDocumentTypes + + + CFBundleTypeIconFiles + + iOSapplication + + CFBundleTypeName + VTK Unstructured Grid + LSItemContentTypes + + com.kitware.vtu + + + + CFBundleTypeIconFiles + + iOSapplication + + CFBundleTypeName + VTK Structured Grid + LSItemContentTypes + + com.kitware.vts + + + + CFBundleTypeIconFiles + + iOSapplication + + CFBundleTypeName + VTK Rectlinear Grid + LSItemContentTypes + + com.kitware.vtr + + + + CFBundleTypeIconFiles + + iOSapplication + + CFBundleTypeName + VTK Image Data + LSItemContentTypes + + com.kitware.vti + + + + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UIFileSharingEnabled + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + opengles-3 + armv7 + + UIStatusBarHidden + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UTImportedTypeDeclarations + + + UTTypeConformsTo + + public.data + + UTTypeDescription + VTK XML Unstructured Grid + UTTypeIdentifier + com.kitware.vtu + UTTypeSize320IconFile + iOSapplication + UTTypeSize64IconFile + iOSapplication + UTTypeTagSpecification + + com.apple.ostype + VTU + public.filename-extension + + vtu + + + + + UTTypeConformsTo + + public.data + + UTTypeDescription + VTK XML Structured Grid + UTTypeIdentifier + com.kitware.vts + UTTypeSize320IconFile + iOSapplication + UTTypeSize64IconFile + iOSapplication + UTTypeTagSpecification + + com.apple.ostype + VTS + public.filename-extension + + vts + + + + + UTTypeConformsTo + + public.data + + UTTypeDescription + VTK XML Rectilinear Grid + UTTypeIdentifier + com.kitware.vtr + UTTypeSize320IconFile + iOSapplication + UTTypeSize64IconFile + iOSapplication + UTTypeTagSpecification + + com.apple.ostype + VTS + public.filename-extension + + vtr + + + + + UTTypeConformsTo + + public.data + + UTTypeDescription + VTK XML Image Data + UTTypeIdentifier + com.kitware.vti + UTTypeSize320IconFile + iOSapplication + UTTypeSize64IconFile + iOSapplication + UTTypeTagSpecification + + com.apple.ostype + VTI + public.filename-extension + + vti + + + + + + diff --git a/Examples/iOS/PlaneView/PlaneView/PlaneView.entitlements b/Examples/iOS/PlaneView/PlaneView/PlaneView.entitlements new file mode 100644 index 00000000000..bb42bb6ead0 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/PlaneView.entitlements @@ -0,0 +1,18 @@ + + + + + com.apple.developer.icloud-container-identifiers + + iCloud.$(CFBundleIdentifier) + + com.apple.developer.icloud-services + + CloudDocuments + + com.apple.developer.ubiquity-container-identifiers + + iCloud.$(CFBundleIdentifier) + + + diff --git a/Examples/iOS/PlaneView/PlaneView/SettingsTableViewController.h b/Examples/iOS/PlaneView/PlaneView/SettingsTableViewController.h new file mode 100644 index 00000000000..629bdb9d981 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/SettingsTableViewController.h @@ -0,0 +1,18 @@ +/*========================================================================= + + Program: Visualization Toolkit + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#import + +@interface SettingsTableViewController : UITableViewController + +@end diff --git a/Examples/iOS/PlaneView/PlaneView/SettingsTableViewController.mm b/Examples/iOS/PlaneView/PlaneView/SettingsTableViewController.mm new file mode 100644 index 00000000000..7dc81e19472 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/SettingsTableViewController.mm @@ -0,0 +1,164 @@ +/*========================================================================= + + Program: Visualization Toolkit + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#import "SettingsTableViewController.h" +#import "VTKViewController.h" + +@interface SettingsTableViewController () + +@property (weak, nonatomic) IBOutlet UISwitch *enableprobeSwitch; + +@end + +@implementation SettingsTableViewController + +- (IBAction)EnableProbeChanged:(id)sender +{ + // Inside another ViewController + VTKViewController *vtkVC = (VTKViewController *) + [self.navigationController.viewControllers firstObject]; + [vtkVC setProbeEnabled:[sender isOn]]; +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + VTKViewController *vtkVC = (VTKViewController *) + [self.navigationController.viewControllers firstObject]; + [self.enableprobeSwitch setOn:[vtkVC getProbeEnabled]]; + + // Uncomment the following line to preserve selection between presentations. + // self.clearsSelectionOnViewWillAppear = NO; + + // Uncomment the following line to display an Edit button in the navigation bar for this view controller. + // self.navigationItem.rightBarButtonItem = self.editButtonItem; +} + +- (void)didReceiveMemoryWarning +{ + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath +{ + [tableView deselectRowAtIndexPath:indexPath animated:NO]; + + if (indexPath.row == 1) + { + UIDocumentPickerViewController *documentPicker = + [[UIDocumentPickerViewController alloc] + initWithDocumentTypes:@[@"com.kitware.vtu",@"com.kitware.vts",@"com.kitware.vtr",@"com.kitware.vti"] + inMode:UIDocumentPickerModeImport]; + documentPicker.delegate = self; + documentPicker.modalPresentationStyle = UIModalPresentationFormSheet; + [self presentViewController:documentPicker animated:NO completion:nil]; + + // UIDocumentMenuViewController *documentPicker = + // [[UIDocumentMenuViewController alloc] + // initWithDocumentTypes:@[@"com.kitware.vtu",@"com.kitware.vts",@"com.kitware.vtr",@"com.kitware.vti"] + // inMode:UIDocumentPickerModeImport]; + // documentPicker.delegate = self; + // documentPicker.modalPresentationStyle = UIModalPresentationFullScreen; + // [self presentViewController:documentPicker animated:NO completion:nil]; + } +} + +- (void)documentMenu:(UIDocumentMenuViewController *)documentMenu + didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker +{ + // documentPicker.delegate = self; + // documentPicker.modalPresentationStyle = UIModalPresentationFormSheet; + // [self presentViewController:documentPicker animated:YES completion:nil]; +} + +- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url +{ + if (controller.documentPickerMode == UIDocumentPickerModeImport) + { + NSString *alertMessage = [NSString stringWithFormat:@"Successfully imported %@", [url lastPathComponent]]; + dispatch_async(dispatch_get_main_queue(), ^{ + UIAlertController *alertController = [UIAlertController + alertControllerWithTitle:@"Import" + message:alertMessage + preferredStyle:UIAlertControllerStyleAlert]; + [alertController addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:nil]]; + [self presentViewController:alertController animated:YES completion:nil]; + }); + + // pass the data to the mapper + VTKViewController *vtkVC = (VTKViewController *) + [self.navigationController.viewControllers firstObject]; + [vtkVC setNewDataFile:url]; + } +} + + +#pragma mark - Table view data source + +/* +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath]; + + // Configure the cell... + + return cell; +} +*/ + +/* +// Override to support conditional editing of the table view. +- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { + // Return NO if you do not want the specified item to be editable. + return YES; +} +*/ + +/* +// Override to support editing the table view. +- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { + if (editingStyle == UITableViewCellEditingStyleDelete) { + // Delete the row from the data source + [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; + } else if (editingStyle == UITableViewCellEditingStyleInsert) { + // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view + } +} +*/ + +/* +// Override to support rearranging the table view. +- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { +} +*/ + +/* +// Override to support conditional rearranging of the table view. +- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { + // Return NO if you do not want the item to be re-orderable. + return YES; +} +*/ + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/Examples/iOS/PlaneView/PlaneView/VTKViewController.h b/Examples/iOS/PlaneView/PlaneView/VTKViewController.h new file mode 100644 index 00000000000..059005d7b9d --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/VTKViewController.h @@ -0,0 +1,48 @@ +/*========================================================================= + + Program: Visualization Toolkit + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#import +#import + +// Forward declarations +class vtkIOSRenderWindow; +class vtkRenderer; +class vtkIOSRenderWindowInteractor; +class vtkPlaneWidget; +class vtkPolyDataMapper; +class vtkProbeFilter; +class vtkTPWCallback; + +@interface VTKViewController : GLKViewController +{ +@private + vtkIOSRenderWindow *RenderWindow; + vtkPlaneWidget *PlaneWidget; + vtkRenderer *Renderer; + vtkProbeFilter *Probe; + vtkPolyDataMapper *OutlineMapper; + vtkPolyDataMapper *ProbeMapper; + vtkTPWCallback *PlaneCallback; +} + +@property (nonatomic, strong) UIWindow *window; + +- (void)setProbeEnabled:(bool)val; +- (bool)getProbeEnabled; + +- (void)setNewDataFile:(NSURL *)url; + +- (vtkIOSRenderWindowInteractor *)getInteractor; + +@end diff --git a/Examples/iOS/PlaneView/PlaneView/VTKViewController.mm b/Examples/iOS/PlaneView/PlaneView/VTKViewController.mm new file mode 100644 index 00000000000..3b52b5c81e2 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/VTKViewController.mm @@ -0,0 +1,484 @@ +/*========================================================================= + + Program: Visualization Toolkit + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#import "VTKViewController.h" + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import + +// This does the actual work: updates the probe. +// Callback for the interaction +class vtkTPWCallback : public vtkCommand +{ +public: + static vtkTPWCallback *New() + { return new vtkTPWCallback; } + virtual void Execute(vtkObject *caller, unsigned long, void*) + { + vtkPlaneWidget *planeWidget = reinterpret_cast(caller); + planeWidget->GetPolyData(this->PolyData); + this->Actor->VisibilityOn(); + } + vtkTPWCallback():PolyData(0),Actor(0) {} + vtkPolyData *PolyData; + vtkActor *Actor; +}; + + +@interface VTKViewController () +{ +} + +@property (strong, nonatomic) EAGLContext *context; + +- (void)tearDownGL; + +@end + +@implementation VTKViewController + +- (void)setProbeEnabled:(bool)val +{ + self->PlaneWidget->SetEnabled(val ? 1 : 0); +} + +- (bool)getProbeEnabled +{ + return (self->PlaneWidget->GetEnabled() ? true : false); +} + +//---------------------------------------------------------------------------- +- (vtkIOSRenderWindowInteractor *)getInteractor +{ + if (self->RenderWindow) + { + return (vtkIOSRenderWindowInteractor *)self->RenderWindow->GetInteractor(); + } + else + { + return NULL; + } +} + +- (void)setupPipeline +{ + vtkRenderingOpenGL2ObjectFactory *of = vtkRenderingOpenGL2ObjectFactory::New(); + vtkObjectFactory::RegisterFactory(of); + + self->RenderWindow = vtkIOSRenderWindow::New(); + self->Renderer = vtkRenderer::New(); + self->RenderWindow->AddRenderer(self->Renderer); + + // this example uses VTK's built in interaction but you could choose + // to use your own instead. + vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); + iren->SetRenderWindow(self->RenderWindow); + + vtkInteractorStyleMultiTouchCamera *ismt = vtkInteractorStyleMultiTouchCamera::New(); + iren->SetInteractorStyle(ismt); + ismt->Delete(); + + vtkNew plane; + vtkNew wavelet; + wavelet->Update(); + + self->Probe = vtkProbeFilter::New(); + self->Probe->SetInputData(plane.Get()); + self->Probe->SetSourceData(wavelet->GetOutput()); + + self->ProbeMapper = vtkPolyDataMapper::New(); + self->ProbeMapper->SetInputConnection(self->Probe->GetOutputPort()); + double tmp[2]; + wavelet->GetOutput()->GetScalarRange(tmp); + self->ProbeMapper->SetScalarRange(tmp[0], tmp[1]); + + vtkNew probeActor; + probeActor->SetMapper(self->ProbeMapper); + probeActor->VisibilityOff(); + + // An outline is shown for context. + vtkNew outline; + outline->SetInputData(wavelet->GetOutput()); + + self->OutlineMapper = vtkPolyDataMapper::New(); + self->OutlineMapper->SetInputConnection(outline->GetOutputPort()); + + vtkNew outlineActor; + outlineActor->SetMapper(self->OutlineMapper); + + // The SetInteractor method is how 3D widgets are associated with the render + // window interactor. Internally, SetInteractor sets up a bunch of callbacks + // using the Command/Observer mechanism (AddObserver()). + self->PlaneCallback = vtkTPWCallback::New(); + self->PlaneCallback->PolyData = plane.Get(); + self->PlaneCallback->Actor = probeActor.Get(); + + // The plane widget is used probe the dataset. + vtkNew planeWidget; + planeWidget->SetInteractor(iren); + planeWidget->SetDefaultRenderer(self->Renderer); + planeWidget->SetInputData(wavelet->GetOutput()); + planeWidget->NormalToXAxisOn(); + planeWidget->SetResolution(30); + planeWidget->SetHandleSize(0.07); + planeWidget->SetRepresentationToOutline(); + planeWidget->PlaceWidget(); + planeWidget->AddObserver(vtkCommand::InteractionEvent,self->PlaneCallback); + planeWidget->On(); + self->PlaneWidget = planeWidget.Get(); + self->PlaneCallback->Execute(self->PlaneWidget,0,NULL); + planeWidget->Register(0); + + self->Renderer->AddActor(outlineActor.Get()); + self->Renderer->AddActor(probeActor.Get()); + self->Renderer->SetBackground(0.3,0.5,0.4); +} + +- (void)setNewDataFile:(NSURL *)url +{ + vtkXMLDataReader *reader = NULL; + vtkPolyDataAlgorithm *outline = NULL; + + // setup the reader and outline filter based + // on data type + if ([url.pathExtension isEqual:@"vtu"]) + { + reader = vtkXMLUnstructuredGridReader::New(); + outline = vtkOutlineFilter::New(); + } + if ([url.pathExtension isEqual:@"vts"]) + { + reader = vtkXMLStructuredGridReader::New(); + outline = vtkStructuredGridOutlineFilter::New(); + } + if ([url.pathExtension isEqual:@"vtr"]) + { + reader = vtkXMLRectilinearGridReader::New(); + outline = vtkOutlineFilter::New(); + } + if ([url.pathExtension isEqual:@"vti"]) + { + reader = vtkXMLImageDataReader::New(); + outline = vtkOutlineFilter::New(); + } + + if (!reader || !outline) + { + return; + } + + reader->SetFileName([url.path cStringUsingEncoding:NSASCIIStringEncoding]); + reader->Update(); + self->Probe->SetSourceData(reader->GetOutputDataObject(0)); + double tmp[2]; + vtkDataSet *ds = vtkDataSet::SafeDownCast(reader->GetOutputDataObject(0)); + ds->GetScalarRange(tmp); + self->ProbeMapper->SetScalarRange(tmp[0], tmp[1]); + outline->SetInputData(ds); + self->OutlineMapper->SetInputConnection(outline->GetOutputPort(0)); + self->PlaneWidget->SetInputData(ds); + self->PlaneWidget->PlaceWidget(ds->GetBounds()); + + self->PlaneCallback->Execute(self->PlaneWidget,0,NULL); + + self->Renderer->ResetCamera(); + self->RenderWindow->Render(); + self->PlaneWidget->PlaceWidget(ds->GetBounds()); + self->RenderWindow->Render(); + reader->Delete(); + outline->Delete(); +} + +- (void)viewDidLoad +{ + [super viewDidLoad]; + + self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3]; + + if (!self.context) + { + NSLog(@"Failed to create ES context"); + return; + } + + UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] + initWithTarget:self action:@selector(handleTap:)]; + tapRecognizer.numberOfTapsRequired = 2; + [self.view addGestureRecognizer:tapRecognizer]; + + + GLKView *view = (GLKView *)self.view; + view.context = self.context; + view.drawableDepthFormat = GLKViewDrawableDepthFormat24; + //view.drawableMultisample = GLKViewDrawableMultisample4X; + + // setup the vis pipeline + [self setupPipeline]; + + [EAGLContext setCurrentContext:self.context]; + [self resizeView]; + self->RenderWindow->Render(); +} + +- (void)dealloc +{ + [self tearDownGL]; + + if ([EAGLContext currentContext] == self.context) + { + [EAGLContext setCurrentContext:nil]; + } +} + +- (void)didReceiveMemoryWarning +{ + [super didReceiveMemoryWarning]; + + if ([self isViewLoaded] && ([[self view] window] == nil)) + { + self.view = nil; + + [self tearDownGL]; + + if ([EAGLContext currentContext] == self.context) + { + [EAGLContext setCurrentContext:nil]; + } + self.context = nil; + } + // Dispose of any resources that can be recreated. +} + +- (void)tearDownGL +{ + [EAGLContext setCurrentContext:self.context]; + + // free GL resources + // ... +} + +-(void) resizeView +{ + double scale = self.view.contentScaleFactor; + self->RenderWindow->SetSize(self.view.bounds.size.width*scale, self.view.bounds.size.height*scale); +} + +- (void)viewWillLayoutSubviews +{ + [self resizeView]; +} + +- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect +{ + self->RenderWindow->Render(); +} + +//================================================================= +// this example uses VTK's built in interaction but you could choose +// to use your own instead. The remaining methods forward touch events +// to VTKs interactor. + +// Handles the start of a touch +- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event +{ + vtkIOSRenderWindowInteractor *interactor = [self getInteractor]; + if (!interactor) + { + return; + } + + CGRect bounds = [self.view bounds]; + double scale = self.view.contentScaleFactor; + + // set the position for all contacts + NSSet *myTouches = [event touchesForView:self.view]; + for (UITouch *touch in myTouches) + { + // Convert touch point from UIView referential to OpenGL one (upside-down flip) + CGPoint location = [touch locationInView:self.view]; + location.y = bounds.size.height - location.y; + + int index = interactor->GetPointerIndexForContact((size_t)(__bridge void *)touch); + if (index < VTKI_MAX_POINTERS) + { + interactor->SetEventInformation((int)round(location.x*scale), + (int)round(location.y*scale), + 0, 0, + 0, 0, 0, index); + } + } + + // handle begin events + for (UITouch *touch in touches) + { + int index = interactor->GetPointerIndexForContact((size_t)(__bridge void *)touch); + interactor->SetPointerIndex(index); + interactor->LeftButtonPressEvent(); + } + + // Display the buffer + [(GLKView *)self.view display]; +} + +// Handles the continuation of a touch. +- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event +{ + vtkIOSRenderWindowInteractor *interactor = [self getInteractor]; + if (!interactor) + { + return; + } + + CGRect bounds = [self.view bounds]; + double scale = self.view.contentScaleFactor; + + // set the position for all contacts + int index = -1; + NSSet *myTouches = [event touchesForView:self.view]; + for (UITouch *touch in myTouches) + { + // Convert touch point from UIView referential to OpenGL one (upside-down flip) + CGPoint location = [touch locationInView:self.view]; + location.y = bounds.size.height - location.y; + + index = interactor->GetPointerIndexForContact((size_t)(__bridge void *)touch); + if (index < VTKI_MAX_POINTERS) + { + interactor->SetEventInformation((int)round(location.x*scale), + (int)round(location.y*scale), + 0, 0, + 0, 0, 0, index); + } + } + + // fire move event on last index + if (index > -1) + { + interactor->SetPointerIndex(index); + interactor->MouseMoveEvent(); + } + + // Display the buffer + [(GLKView *)self.view display]; +} + +// Handles the end of a touch event when the touch is a tap. +- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event +{ + vtkIOSRenderWindowInteractor *interactor = [self getInteractor]; + if (!interactor) + { + return; + } + + CGRect bounds = [self.view bounds]; + double scale = self.view.contentScaleFactor; + + // set the position for all contacts + NSSet *myTouches = [event touchesForView:self.view]; + for (UITouch *touch in myTouches) + { + // Convert touch point from UIView referential to OpenGL one (upside-down flip) + CGPoint location = [touch locationInView:self.view]; + location.y = bounds.size.height - location.y; + + int index = interactor->GetPointerIndexForContact((size_t)(__bridge void *)touch); + if (index < VTKI_MAX_POINTERS) + { + interactor->SetEventInformation((int)round(location.x*scale), + (int)round(location.y*scale), + 0, 0, + 0, 0, 0, index); + } + } + + // handle begin events + for (UITouch *touch in touches) + { + int index = interactor->GetPointerIndexForContact((size_t)(__bridge void *)touch); + interactor->SetPointerIndex(index); + interactor->LeftButtonReleaseEvent(); + interactor->ClearContact((size_t)(__bridge void *)touch); + } + + // Display the buffer + [(GLKView *)self.view display]; +} + +// Handles the end of a touch event. +- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event +{ + vtkIOSRenderWindowInteractor *interactor = [self getInteractor]; + if (!interactor) + { + return; + } + + CGRect bounds = [self.view bounds]; + double scale = self.view.contentScaleFactor; + + for (UITouch *touch in touches) + { + int index = interactor->GetPointerIndexForContact((size_t)(__bridge void *)touch); + interactor->SetPointerIndex(index); + // Convert touch point from UIView referential to OpenGL one (upside-down flip) + CGPoint location = [touch locationInView:self.view]; + location.y = bounds.size.height - location.y; + interactor->SetEventInformation((int)round(location.x*scale), + (int)round(location.y*scale), + 0, 0, + 0, 0); + interactor->LeftButtonReleaseEvent(); + interactor->ClearContact((size_t)(__bridge void *)touch); + } +} + +- (void)handleTap:(UITapGestureRecognizer *)sender +{ + if (sender.state == UIGestureRecognizerStateEnded) + { + vtkIOSRenderWindowInteractor *interactor = [self getInteractor]; + if (!interactor) + { + return; + } + self->Renderer->ResetCamera(); + self->RenderWindow->Render(); + } +} + +@end diff --git a/Examples/iOS/PlaneView/PlaneView/iOSapplication.icns b/Examples/iOS/PlaneView/PlaneView/iOSapplication.icns new file mode 100644 index 00000000000..786e869cbf0 Binary files /dev/null and b/Examples/iOS/PlaneView/PlaneView/iOSapplication.icns differ diff --git a/Examples/iOS/PlaneView/PlaneView/main.m b/Examples/iOS/PlaneView/PlaneView/main.m new file mode 100644 index 00000000000..2239888b4b7 --- /dev/null +++ b/Examples/iOS/PlaneView/PlaneView/main.m @@ -0,0 +1,16 @@ +// +// main.m +// PlaneView +// +// Created by Ken Martin on 2/5/16. +// Copyright © 2016 Kitware Inc. All rights reserved. +// + +#import +#import "AppDelegate.h" + +int main(int argc, char * argv[]) { + @autoreleasepool { + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + } +} diff --git a/Examples/iOS/VolumeRender/Classes/MyGLKViewController.mm b/Examples/iOS/VolumeRender/Classes/MyGLKViewController.mm index 07eee17cc77..a3f90a3ccfe 100644 --- a/Examples/iOS/VolumeRender/Classes/MyGLKViewController.mm +++ b/Examples/iOS/VolumeRender/Classes/MyGLKViewController.mm @@ -289,12 +289,6 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event return; } - vtkIOSRenderWindow *renWin = [self getVTKRenderWindow]; - if (!renWin) - { - return; - } - CGRect bounds = [self.view bounds]; double scale = self.view.contentScaleFactor; @@ -326,7 +320,7 @@ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event int index = interactor->GetPointerIndexForContact((size_t)(__bridge void *)touch); vtkGenericWarningMacro("down touch " << (size_t)(__bridge void *)touch << " index " << index); interactor->SetPointerIndex(index); - interactor->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL); + interactor->LeftButtonPressEvent(); //NSLog(@"Starting left mouse"); } @@ -343,12 +337,6 @@ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event return; } - vtkIOSRenderWindow *renWin = [self getVTKRenderWindow]; - if (!renWin) - { - return; - } - CGRect bounds = [self.view bounds]; double scale = self.view.contentScaleFactor; @@ -377,7 +365,7 @@ - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event // fire move event on last index interactor->SetPointerIndex(index); - interactor->InvokeEvent(vtkCommand::MouseMoveEvent,NULL); + interactor->MouseMoveEvent(); NSLog(@"Moved left mouse"); // Display the buffer @@ -393,12 +381,6 @@ - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event return; } - vtkIOSRenderWindow *renWin = [self getVTKRenderWindow]; - if (!renWin) - { - return; - } - CGRect bounds = [self.view bounds]; double scale = self.view.contentScaleFactor; @@ -430,7 +412,7 @@ - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event int index = interactor->GetPointerIndexForContact((size_t)(__bridge void *)touch); vtkGenericWarningMacro("up touch " << (size_t)(__bridge void *)touch << " index " << index); interactor->SetPointerIndex(index); - interactor->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL); + interactor->LeftButtonReleaseEvent(); interactor->ClearContact((size_t)(__bridge void *)touch); // NSLog(@"lifting left mouse"); } @@ -448,12 +430,6 @@ - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event return; } - vtkIOSRenderWindow *renWin = [self getVTKRenderWindow]; - if (!renWin) - { - return; - } - CGRect bounds = [self.view bounds]; double scale = self.view.contentScaleFactor; @@ -470,7 +446,7 @@ - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event (int)round(location.y), 0, 0, 0, 0); - interactor->InvokeEvent(vtkCommand::LeftButtonReleaseEvent, NULL); + interactor->LeftButtonReleaseEvent(); // NSLog(@"Ended left mouse"); // Display the buffer diff --git a/Examples/iOS/readme.txt b/Examples/iOS/readme.txt index 753e7d53e06..72ad9976b3d 100644 --- a/Examples/iOS/readme.txt +++ b/Examples/iOS/readme.txt @@ -27,7 +27,11 @@ directory in vtkios ala cd vtkios; mkdir install Once the framework is built it will automatically be installed. Now you can try building an iOS application that uses the framework. -* Start up XCode and load an example Xcode project from Examples/iOS. You will +* Start up XCode and load an example Xcode project from Examples/iOS. They will +* be located in + +/CMakeExternals/Build/vtk-ios-device-armv7/Examples/iOS + * likely need to update a couple setting in the project to find the vtk fraework * and its header files. You may also get unresolved link errors related to the * c++ standard libaries. I have had to change the stdlib settings in XCode away @@ -47,6 +51,6 @@ bit twitchy sometimes. The GLPaint example is a modified version of Apple's GLPaint example. So credit to them for the original example file and framework. -The VolumeRender example requires OpenGL ES3 so it will only work on -devices that support ES3, which I believe includes iphone 5s or later and +The VolumeRender and PlaneView examples require OpenGL ES3 so it will only +work on devices that support ES3, which includes iphone 5s or later and ipad Air or later \ No newline at end of file diff --git a/Filters/AMR/Testing/Cxx/TestAMRGhostLayerStripping.cxx b/Filters/AMR/Testing/Cxx/TestAMRGhostLayerStripping.cxx index c454230bece..7aabc6b0ae1 100644 --- a/Filters/AMR/Testing/Cxx/TestAMRGhostLayerStripping.cxx +++ b/Filters/AMR/Testing/Cxx/TestAMRGhostLayerStripping.cxx @@ -313,7 +313,7 @@ bool CheckFields(vtkUniformGrid *grid) } vtkDoubleArray *centroidArray = - vtkDoubleArray::SafeDownCast(CD->GetArray("Centroid")); + vtkArrayDownCast(CD->GetArray("Centroid")); assert("pre: centroid arrays is NULL!" && (centroidArray != NULL) ); if( centroidArray->GetNumberOfComponents() != 3 ) { @@ -322,7 +322,7 @@ bool CheckFields(vtkUniformGrid *grid) double *centers = static_cast(centroidArray->GetVoidPointer(0)); vtkDoubleArray *pulseArray = - vtkDoubleArray::SafeDownCast(CD->GetArray("Gaussian-Pulse")); + vtkArrayDownCast(CD->GetArray("Gaussian-Pulse")); assert("pre: pulse array is NULL!" && (pulseArray != NULL) ); if( pulseArray->GetNumberOfComponents() != 1) { diff --git a/Filters/AMR/Testing/Cxx/TestImageToAMR.cxx b/Filters/AMR/Testing/Cxx/TestImageToAMR.cxx index d7800933b32..d06f724bfd2 100644 --- a/Filters/AMR/Testing/Cxx/TestImageToAMR.cxx +++ b/Filters/AMR/Testing/Cxx/TestImageToAMR.cxx @@ -105,7 +105,7 @@ int TestImageToAMR(int, char *[]) return VTK_FAILURE; } - vtkIdTypeArray* cd = vtkIdTypeArray::SafeDownCast(image->GetCellData()->GetArray("vtkIdFilter_Ids")); + vtkIdTypeArray* cd = vtkArrayDownCast(image->GetCellData()->GetArray("vtkIdFilter_Ids")); assert(cd); for(std::vector::iterator itr=samples.begin(); itr!=samples.end();itr++) { @@ -118,7 +118,7 @@ int TestImageToAMR(int, char *[]) if(amr->FindGrid(x,level,id)) { vtkUniformGrid* grid =amr->GetDataSet(level,id); - vtkIdTypeArray* cd1 = vtkIdTypeArray::SafeDownCast(grid->GetCellData()->GetArray("vtkIdFilter_Ids")); + vtkIdTypeArray* cd1 = vtkArrayDownCast(grid->GetCellData()->GetArray("vtkIdFilter_Ids")); vtkIdType cellId1 = FindCell(grid,x); vtkIdType value1 = cd1->GetValue(cellId1); if(value1!=value) diff --git a/Filters/AMR/vtkAMRCutPlane.h b/Filters/AMR/vtkAMRCutPlane.h index e3dbf2413bc..501812e38aa 100644 --- a/Filters/AMR/vtkAMRCutPlane.h +++ b/Filters/AMR/vtkAMRCutPlane.h @@ -167,9 +167,7 @@ class VTKFILTERSAMR_EXPORT vtkAMRCutPlane : public vtkMultiBlockDataSetAlgorithm bool UseNativeCutter; vtkMultiProcessController *Controller; -// BTX std::vector BlocksToLoad; -// ETX private: vtkAMRCutPlane(const vtkAMRCutPlane& ); // Not implemented diff --git a/Filters/AMR/vtkAMRResampleFilter.h b/Filters/AMR/vtkAMRResampleFilter.h index 10f47b49104..b92bf3be6fa 100644 --- a/Filters/AMR/vtkAMRResampleFilter.h +++ b/Filters/AMR/vtkAMRResampleFilter.h @@ -153,9 +153,8 @@ class VTKFILTERSAMR_EXPORT vtkAMRResampleFilter : public vtkMultiBlockDataSetAlg int NumberOfTimesLevelDown; int NumberOfFailedPoints; double AverageLevel; -// BTX + std::vector< int > BlocksToLoad; // Holds the ids of the blocks to load. -// ETX // Description: // Checks if this filter instance is running on more than one processes diff --git a/Filters/AMR/vtkAMRSliceFilter.cxx b/Filters/AMR/vtkAMRSliceFilter.cxx index d0705e7e674..f4d0f70cc36 100644 --- a/Filters/AMR/vtkAMRSliceFilter.cxx +++ b/Filters/AMR/vtkAMRSliceFilter.cxx @@ -525,7 +525,7 @@ void vtkAMRSliceFilter::GetSliceCellData( sourceCD->GetArray( arrayIdx )->GetNumberOfComponents( ) ); array->SetNumberOfTuples( numCells ); targetCD->AddArray( array ); - vtkUnsignedCharArray* uca = vtkUnsignedCharArray::SafeDownCast(array); + vtkUnsignedCharArray* uca = vtkArrayDownCast(array); if (uca != NULL && uca == slice->GetCellGhostArray()) { // initiallize the ghost array diff --git a/Filters/AMR/vtkAMRSliceFilter.h b/Filters/AMR/vtkAMRSliceFilter.h index 134bff9cdbb..3c0508ec023 100644 --- a/Filters/AMR/vtkAMRSliceFilter.h +++ b/Filters/AMR/vtkAMRSliceFilter.h @@ -157,9 +157,8 @@ class VTKFILTERSAMR_EXPORT vtkAMRSliceFilter : int ForwardUpstream; int EnablePrefetching; - // BTX + std::vector< int > BlocksToLoad; - // ETX private: vtkAMRSliceFilter( const vtkAMRSliceFilter& ); // Not implemented diff --git a/Filters/AMR/vtkImageToAMR.h b/Filters/AMR/vtkImageToAMR.h index f2efbf8ac2a..4eaa69381d5 100644 --- a/Filters/AMR/vtkImageToAMR.h +++ b/Filters/AMR/vtkImageToAMR.h @@ -49,8 +49,6 @@ class VTKFILTERSAMR_EXPORT vtkImageToAMR : public vtkOverlappingAMRAlgorithm vtkSetClampMacro(MaximumNumberOfBlocks, int, 1, VTK_INT_MAX); vtkGetMacro(MaximumNumberOfBlocks, int); - -//BTX protected: vtkImageToAMR(); ~vtkImageToAMR(); @@ -76,7 +74,7 @@ class VTKFILTERSAMR_EXPORT vtkImageToAMR : public vtkOverlappingAMRAlgorithm private: vtkImageToAMR(const vtkImageToAMR&); // Not implemented. void operator=(const vtkImageToAMR&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/Core/Testing/Cxx/TestAppendFilter.cxx b/Filters/Core/Testing/Cxx/TestAppendFilter.cxx index 55bc8046ba9..a804d6ba7a5 100644 --- a/Filters/Core/Testing/Cxx/TestAppendFilter.cxx +++ b/Filters/Core/Testing/Cxx/TestAppendFilter.cxx @@ -139,7 +139,7 @@ int PrintAndCheck(const std::vector& inputs, vtkDataSet* output, for (int arrayIndex = 0; arrayIndex < dataArrays->GetNumberOfArrays(); ++arrayIndex) { - vtkIntArray* outputArray = vtkIntArray::SafeDownCast(dataArrays->GetArray(arrayIndex)); + vtkIntArray* outputArray = vtkArrayDownCast(dataArrays->GetArray(arrayIndex)); const char* outputArrayName = outputArray->GetName(); std::cout << "Array " << arrayIndex << " - "; std::cout << (outputArrayName ? outputArrayName : "(null)") << ": [ "; @@ -162,7 +162,7 @@ int PrintAndCheck(const std::vector& inputs, vtkDataSet* output, // Test the output for (int arrayIndex = 0; arrayIndex < dataArrays->GetNumberOfArrays(); ++arrayIndex) { - vtkIntArray* outputArray = vtkIntArray::SafeDownCast(dataArrays->GetArray(arrayIndex)); + vtkIntArray* outputArray = vtkArrayDownCast(dataArrays->GetArray(arrayIndex)); const char* arrayName = outputArray->GetName(); if (arrayName == NULL) { diff --git a/Filters/Core/Testing/Cxx/TestAppendSelection.cxx b/Filters/Core/Testing/Cxx/TestAppendSelection.cxx index 7dc9622f8ba..f5414194ccd 100644 --- a/Filters/Core/Testing/Cxx/TestAppendSelection.cxx +++ b/Filters/Core/Testing/Cxx/TestAppendSelection.cxx @@ -32,9 +32,9 @@ int SelectionCompare( vtkSelectionNode* b) { int errors = 0; - vtkIdTypeArray* alist = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* alist = vtkArrayDownCast( a->GetSelectionList()); - vtkIdTypeArray* blist = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* blist = vtkArrayDownCast( b->GetSelectionList()); if (a->GetContentType() != b->GetContentType()) { diff --git a/Filters/Core/Testing/Cxx/TestNamedComponents.cxx b/Filters/Core/Testing/Cxx/TestNamedComponents.cxx index 07cb17ab2a8..b626f5698a5 100644 --- a/Filters/Core/Testing/Cxx/TestNamedComponents.cxx +++ b/Filters/Core/Testing/Cxx/TestNamedComponents.cxx @@ -115,7 +115,7 @@ int TestNamedComponents(int , char *[]) { data[j+1] = pts[j]; } - cellPoints->SetTupleValue(i, data); + cellPoints->SetTypedTuple(i, data); } poly->GetCellData()->AddArray(cellPoints); @@ -141,8 +141,8 @@ int TestNamedComponents(int , char *[]) } // the arrays should have been changed so get them again... - cellIndex = vtkIntArray::SafeDownCast(out->GetCellData()->GetArray(ctName)); - cellPoints = vtkIdTypeArray::SafeDownCast(out->GetCellData()->GetArray(cpName)); + cellIndex = vtkArrayDownCast(out->GetCellData()->GetArray(ctName)); + cellPoints = vtkArrayDownCast(out->GetCellData()->GetArray(cpName)); //confirm component names are intact if (strcmp(cellIndex->GetComponentName(0),"index") != 0) diff --git a/Filters/Core/Testing/Cxx/TestResampleToImage.cxx b/Filters/Core/Testing/Cxx/TestResampleToImage.cxx index f8e40079870..e56e7f3bc9b 100644 --- a/Filters/Core/Testing/Cxx/TestResampleToImage.cxx +++ b/Filters/Core/Testing/Cxx/TestResampleToImage.cxx @@ -72,9 +72,9 @@ int TestResampleToImage(int , char *[]) } } - if (numHiddenPoints != 1991) + if (numHiddenPoints != 1855) { - std::cout << "Number of Hidden points: expecting 1991 got " + std::cout << "Number of Hidden points: expecting 1855 got " << numHiddenPoints << std::endl; return 1; } @@ -89,9 +89,9 @@ int TestResampleToImage(int , char *[]) } } - if (numHiddenCells != 2170) + if (numHiddenCells != 2054) { - std::cout << "Number of Hidden points: expecting 2170 got " + std::cout << "Number of Hidden cells: expecting 2054 got " << numHiddenCells << std::endl; return 1; } diff --git a/Filters/Core/Testing/Cxx/TestStructuredGridAppend.cxx b/Filters/Core/Testing/Cxx/TestStructuredGridAppend.cxx index 68a0ef9c9bd..9f45b739e84 100644 --- a/Filters/Core/Testing/Cxx/TestStructuredGridAppend.cxx +++ b/Filters/Core/Testing/Cxx/TestStructuredGridAppend.cxx @@ -69,7 +69,7 @@ namespace for(int i=extent[0];iInsertNextTupleValue(ijk); + cellArray->InsertNextTypedTuple(ijk); } } } @@ -102,7 +102,7 @@ namespace } if(vtkDoubleArray* pointArray = - vtkDoubleArray::SafeDownCast(output->GetPointData()->GetArray(arrayName))) + vtkArrayDownCast(output->GetPointData()->GetArray(arrayName))) { vtkIdType counter = 0; for(int k=extent[4];k<=extent[5];k++) @@ -130,7 +130,7 @@ namespace } if(vtkIntArray* cellArray = - vtkIntArray::SafeDownCast(output->GetCellData()->GetArray(arrayName))) + vtkArrayDownCast(output->GetCellData()->GetArray(arrayName))) { vtkIdType counter = 0; for(int k=extent[4];kGetTupleValue(counter, values); + cellArray->GetTypedTuple(counter, values); if(values[0] != i || values[1] != j || values[2] != k) { vtkGenericWarningMacro("ERROR: Bad cell array tuple value [" diff --git a/Filters/Core/Testing/Data/Baseline/TestFlyingEdges3DWithInterpolation.png.md5 b/Filters/Core/Testing/Data/Baseline/TestFlyingEdges3DWithInterpolation.png.md5 new file mode 100644 index 00000000000..2f1e9ed59b6 --- /dev/null +++ b/Filters/Core/Testing/Data/Baseline/TestFlyingEdges3DWithInterpolation.png.md5 @@ -0,0 +1 @@ +11b30d52f07417d89c088a3d69bb3d7a diff --git a/Filters/Core/Testing/Data/Baseline/TestFlyingEdgesPlaneCutterInterpolation.png.md5 b/Filters/Core/Testing/Data/Baseline/TestFlyingEdgesPlaneCutterInterpolation.png.md5 new file mode 100644 index 00000000000..fb3b4048b1f --- /dev/null +++ b/Filters/Core/Testing/Data/Baseline/TestFlyingEdgesPlaneCutterInterpolation.png.md5 @@ -0,0 +1 @@ +f53474d24af23c6466fd11fb9790d371 diff --git a/Filters/Core/Testing/Python/CMakeLists.txt b/Filters/Core/Testing/Python/CMakeLists.txt index 9eb9c78e453..5689e6cdf65 100644 --- a/Filters/Core/Testing/Python/CMakeLists.txt +++ b/Filters/Core/Testing/Python/CMakeLists.txt @@ -18,8 +18,10 @@ vtk_add_test_python( TestElevationFilter.py TestFlyingEdges2D.py TestFlyingEdges3D.py + TestFlyingEdges3DWithInterpolation.py TestFlyingEdgesExtents.py TestFlyingEdgesPlaneCutter.py + TestFlyingEdgesPlaneCutterInterpolation.py TestGridSynchronizedTemplates3D.py TestMarchingSquares.py TestProbeFilterImageInput.py diff --git a/Filters/Core/Testing/Python/TestFlyingEdges3D.py b/Filters/Core/Testing/Python/TestFlyingEdges3D.py index c6da8d82684..f19b37e48ba 100644 --- a/Filters/Core/Testing/Python/TestFlyingEdges3D.py +++ b/Filters/Core/Testing/Python/TestFlyingEdges3D.py @@ -31,6 +31,8 @@ iso.SetValue(0,0.25) iso.ComputeNormalsOn() iso.ComputeGradientsOn() +iso.ComputeScalarsOn() +iso.InterpolateAttributesOff() isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(iso.GetOutputPort()) diff --git a/Filters/Core/Testing/Python/TestFlyingEdges3DWithInterpolation.py b/Filters/Core/Testing/Python/TestFlyingEdges3DWithInterpolation.py new file mode 100755 index 00000000000..ab5d79f231f --- /dev/null +++ b/Filters/Core/Testing/Python/TestFlyingEdges3DWithInterpolation.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python +import vtk +from vtk.test import Testing +from vtk.util.misc import vtkGetDataRoot +VTK_DATA_ROOT = vtkGetDataRoot() + +# Create the RenderWindow, Renderer and both Actors +# +ren1 = vtk.vtkRenderer() +renWin = vtk.vtkRenderWindow() +renWin.SetMultiSamples(0) +renWin.AddRenderer(ren1) +iren = vtk.vtkRenderWindowInteractor() +iren.SetRenderWindow(renWin) + +# Create a synthetic source +sphere = vtk.vtkSphere() +sphere.SetCenter( 0.0,0.0,0.0) +sphere.SetRadius(0.25) + +# Iso-surface to create geometry. Demonstrate the ability to +# interpolate data attributes. +sample = vtk.vtkSampleFunction() +sample.SetImplicitFunction(sphere) +sample.SetModelBounds(-0.5,0.5, -0.5,0.5, -0.5,0.5) +sample.SetSampleDimensions(100,100,100) + +# Now create some new attributes +cyl = vtk.vtkCylinder() +cyl.SetRadius(0.1) +cyl.SetAxis(1,1,1) + +attr = vtk.vtkSampleImplicitFunctionFilter() +attr.SetInputConnection(sample.GetOutputPort()) +attr.SetImplicitFunction(cyl) +attr.ComputeGradientsOn() +attr.Update() + +iso = vtk.vtkFlyingEdges3D() +iso.SetInputConnection(attr.GetOutputPort()) +iso.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "scalars") +iso.SetValue(0,0.25) +iso.ComputeNormalsOn() +iso.ComputeGradientsOn() +iso.ComputeScalarsOn() +iso.InterpolateAttributesOn() + +# Time execution +timer = vtk.vtkTimerLog() +timer.StartTimer() +iso.Update() +timer.StopTimer() +time = timer.GetElapsedTime() +print("Flying edges with attributes: {0}".format(time)) + +isoMapper = vtk.vtkPolyDataMapper() +isoMapper.SetInputConnection(iso.GetOutputPort()) +isoMapper.ScalarVisibilityOn() +isoMapper.SetScalarModeToUsePointFieldData() +isoMapper.SelectColorArray("Implicit scalars") +isoMapper.SetScalarRange(0,.3) + +isoActor = vtk.vtkActor() +isoActor.SetMapper(isoMapper) +isoActor.GetProperty().SetColor(1,1,1) +isoActor.GetProperty().SetOpacity(1) + +outline = vtk.vtkOutlineFilter() +outline.SetInputConnection(sample.GetOutputPort()) +outlineMapper = vtk.vtkPolyDataMapper() +outlineMapper.SetInputConnection(outline.GetOutputPort()) +outlineActor = vtk.vtkActor() +outlineActor.SetMapper(outlineMapper) +outlineProp = outlineActor.GetProperty() + +# Add the actors to the renderer, set the background and size +# +ren1.AddActor(outlineActor) +ren1.AddActor(isoActor) +ren1.SetBackground(0,0,0) +renWin.SetSize(300,300) +ren1.ResetCamera() +iren.Initialize() + +renWin.Render() +# --- end of script -- diff --git a/Filters/Core/Testing/Python/TestFlyingEdgesPlaneCutterInterpolation.py b/Filters/Core/Testing/Python/TestFlyingEdgesPlaneCutterInterpolation.py new file mode 100755 index 00000000000..0a136c477eb --- /dev/null +++ b/Filters/Core/Testing/Python/TestFlyingEdgesPlaneCutterInterpolation.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +import vtk +from vtk.test import Testing +from vtk.util.misc import vtkGetDataRoot +VTK_DATA_ROOT = vtkGetDataRoot() + +res = 100 + +# Create the RenderWindow, Renderer and both Actors +# +ren1 = vtk.vtkRenderer() +renWin = vtk.vtkRenderWindow() +renWin.SetMultiSamples(0) +renWin.AddRenderer(ren1) +iren = vtk.vtkRenderWindowInteractor() +iren.SetRenderWindow(renWin) + +# Create a synthetic source: sample a sphere across a volume +sphere = vtk.vtkSphere() +sphere.SetCenter( 0.0,0.0,0.0) +sphere.SetRadius(0.25) + +sample = vtk.vtkSampleFunction() +sample.SetImplicitFunction(sphere) +sample.SetModelBounds(-0.5,0.5, -0.5,0.5, -0.5,0.5) +sample.SetSampleDimensions(res,res,res) +sample.ComputeNormalsOff() +sample.Update() + +# Now create some new attributes to interpolate +cyl = vtk.vtkCylinder() +cyl.SetRadius(0.1) +cyl.SetAxis(1,1,1) + +attr = vtk.vtkSampleImplicitFunctionFilter() +attr.SetInputConnection(sample.GetOutputPort()) +attr.SetImplicitFunction(cyl) +attr.ComputeGradientsOn() +attr.Update() + +# The cut plane +plane = vtk.vtkPlane() +plane.SetOrigin(-.2,-.2,-.2) +plane.SetNormal(1,1,1) + +# Perform the cutting on named scalars +cut = vtk.vtkFlyingEdgesPlaneCutter() +cut.SetInputConnection(attr.GetOutputPort()) +cut.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "scalars") +cut.SetPlane(plane) +cut.ComputeNormalsOff() +cut.InterpolateAttributesOn() + +# Time the execution of the filter +timer = vtk.vtkExecutionTimer() +timer.SetFilter(cut) +cut.Update() +CG = timer.GetElapsedWallClockTime() +print ("Cut and interpolate volume:", CG) + +cutMapper = vtk.vtkPolyDataMapper() +cutMapper.SetInputConnection(cut.GetOutputPort()) +cutMapper.SetScalarModeToUsePointFieldData() +cutMapper.SelectColorArray("Implicit scalars") + +cutActor = vtk.vtkActor() +cutActor.SetMapper(cutMapper) +cutActor.GetProperty().SetColor(1,1,1) +cutActor.GetProperty().SetOpacity(1) + +# Look at the vectors +ranPts = vtk.vtkMaskPoints() +ranPts.SetOnRatio(25) +ranPts.SetInputConnection(cut.GetOutputPort()) + +hhog = vtk.vtkHedgeHog() +hhog.SetInputConnection(ranPts.GetOutputPort()) +hhog.SetVectorModeToUseVector() +hhog.SetScaleFactor(0.05) + +hhogMapper = vtk.vtkPolyDataMapper() +hhogMapper.SetInputConnection(hhog.GetOutputPort()) + +hhogActor = vtk.vtkActor() +hhogActor.SetMapper(hhogMapper) +hhogActor.GetProperty().SetColor(1,1,1) +hhogActor.GetProperty().SetOpacity(1) + +# Outline +outline = vtk.vtkOutlineFilter() +outline.SetInputConnection(sample.GetOutputPort()) + +outlineMapper = vtk.vtkPolyDataMapper() +outlineMapper.SetInputConnection(outline.GetOutputPort()) + +outlineActor = vtk.vtkActor() +outlineActor.SetMapper(outlineMapper) +outlineProp = outlineActor.GetProperty() + +# Add the actors to the renderer, set the background and size +# +ren1.AddActor(outlineActor) +ren1.AddActor(cutActor) +ren1.AddActor(hhogActor) +ren1.SetBackground(0,0,0) +renWin.SetSize(400,400) +ren1.ResetCamera() +iren.Initialize() + +renWin.Render() +# --- end of script -- diff --git a/Filters/Core/vtkAppendFilter.cxx b/Filters/Core/vtkAppendFilter.cxx index 0054a2b4fd7..9cc4c6d4e45 100644 --- a/Filters/Core/vtkAppendFilter.cxx +++ b/Filters/Core/vtkAppendFilter.cxx @@ -441,6 +441,7 @@ void vtkAppendFilter::AppendArrays(int attributesType, { vtkAbstractArray* srcArray = firstInputData->GetAbstractArray((*it).c_str()); vtkAbstractArray* dstArray = vtkAbstractArray::CreateArray(srcArray->GetDataType()); + dstArray->CopyInformation(srcArray->GetInformation()); dstArray->SetName(srcArray->GetName()); dstArray->SetNumberOfComponents(srcArray->GetNumberOfComponents()); for (int j = 0; j < srcArray->GetNumberOfComponents(); ++j) diff --git a/Filters/Core/vtkAppendFilter.h b/Filters/Core/vtkAppendFilter.h index 99962bffeeb..c0bfc739b68 100644 --- a/Filters/Core/vtkAppendFilter.h +++ b/Filters/Core/vtkAppendFilter.h @@ -41,13 +41,11 @@ class VTKFILTERSCORE_EXPORT vtkAppendFilter : public vtkUnstructuredGridAlgorith vtkTypeMacro(vtkAppendFilter,vtkUnstructuredGridAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); -//BTX // Description: // Get any input of this filter. vtkDataSet *GetInput(int idx); vtkDataSet *GetInput() {return this->GetInput( 0 );} -//ETX // Description: // Get if the filter should merge coincidental points diff --git a/Filters/Core/vtkAppendPolyData.cxx b/Filters/Core/vtkAppendPolyData.cxx index c5fb5069557..494096450f8 100644 --- a/Filters/Core/vtkAppendPolyData.cxx +++ b/Filters/Core/vtkAppendPolyData.cxx @@ -14,10 +14,12 @@ =========================================================================*/ #include "vtkAppendPolyData.h" +#include "vtkAssume.h" +#include "vtkArrayDispatch.h" #include "vtkAlgorithmOutput.h" #include "vtkCellArray.h" #include "vtkCellData.h" -#include "vtkDataArrayIteratorMacro.h" +#include "vtkDataArrayAccessor.h" #include "vtkDataSetAttributes.h" #include "vtkInformation.h" #include "vtkInformationVector.h" @@ -27,6 +29,9 @@ #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkTrivialProducer.h" +#include +#include + vtkStandardNewMacro(vtkAppendPolyData); //---------------------------------------------------------------------------- @@ -711,62 +716,49 @@ void vtkAppendPolyData::PrintSelf(ostream& os, vtkIndent indent) } //---------------------------------------------------------------------------- -template -size_t vtkAppendPolyDataGetTypeSize(T*) +namespace { +struct AppendDataWorker { - return sizeof(T); -} + vtkIdType Offset; -//---------------------------------------------------------------------------- -void vtkAppendPolyData::AppendData(vtkDataArray *dest, vtkDataArray *src, - vtkIdType offset) -{ - switch (src->GetDataType()) - { - vtkDataArrayIteratorMacro(src, - AppendData(dest, src, offset, vtkDABegin, vtkDAEnd)); - } -} + AppendDataWorker(vtkIdType offset) : Offset(offset) {} -//---------------------------------------------------------------------------- -template -void vtkAppendPolyData::AppendData(vtkDataArray *dest, vtkDataArray *src, - vtkIdType offset, InputIterator srcIt, - InputIterator srcEnd) -{ - switch (dest->GetDataType()) - { - vtkDataArrayIteratorMacro(dest, - AppendData(dest, src, offset, srcIt, srcEnd, vtkDABegin)); - } -} + template + void operator()(Array1T *dest, Array2T *src) + { + vtkDataArrayAccessor d(dest); + vtkDataArrayAccessor s(src); + VTK_ASSUME(src->GetNumberOfComponents() == dest->GetNumberOfComponents()); + const vtkIdType numTuples = src->GetNumberOfTuples(); + const int numComps = src->GetNumberOfComponents(); + + for (vtkIdType t = 0; t < numTuples; ++t) + { + for (int c = 0; c < numComps; ++c) + { + d.Set(t + this->Offset, c, s.Get(t, c)); + } + } + } +}; +} // end anon namespace //---------------------------------------------------------------------------- -template void vtkAppendPolyData::AppendData(vtkDataArray *dest, vtkDataArray *src, - vtkIdType offset, InputIterator srcIt, - InputIterator srcEnd, OutputIterator destIt) + vtkIdType offset) { - if (src->GetNumberOfComponents() != dest->GetNumberOfComponents()) - { - vtkErrorMacro("NumberOfComponents mismatch."); - return; - } - if (src->GetNumberOfTuples() + offset > dest->GetNumberOfTuples()) + assert("Arrays have same number of components." && + src->GetNumberOfComponents() == dest->GetNumberOfComponents()); + assert("Destination array has enough tuples." && + src->GetNumberOfTuples() + offset <= dest->GetNumberOfTuples()); + + AppendDataWorker worker(offset); + if (!vtkArrayDispatch::Dispatch2SameValueType::Execute(dest, src, worker)) { - vtkErrorMacro("Destination not big enough"); - return; + // Use vtkDataArray API when fast-path dispatch fails. + worker(dest, src); } - - // convert from tuples to components. - offset *= src->GetNumberOfComponents(); - - // Position destination iterator - destIt += offset; - - // Copy data, performing implicit conversion if necessary - std::copy(srcIt, srcEnd, destIt); } //---------------------------------------------------------------------------- diff --git a/Filters/Core/vtkAppendPolyData.h b/Filters/Core/vtkAppendPolyData.h index 919d01bbd55..398a3fce42c 100644 --- a/Filters/Core/vtkAppendPolyData.h +++ b/Filters/Core/vtkAppendPolyData.h @@ -63,12 +63,10 @@ class VTKFILTERSCORE_EXPORT vtkAppendPolyData : public vtkPolyDataAlgorithm // used when UserManagedInputs is true, use SetInputByNumber (NULL) instead. void RemoveInputData(vtkPolyData *); -//BTX // Description: // Get any input of this filter. vtkPolyData *GetInput(int idx); vtkPolyData *GetInput() { return this->GetInput( 0 ); }; -//ETX // Description: // Directly set(allocate) number of inputs, should only be used @@ -99,10 +97,9 @@ class VTKFILTERSCORE_EXPORT vtkAppendPolyData : public vtkPolyDataAlgorithm vtkSetMacro(OutputPointsPrecision,int); vtkGetMacro(OutputPointsPrecision,int); -//BTX int ExecuteAppend(vtkPolyData* output, vtkPolyData* inputs[], int numInputs); -//ETX + protected: vtkAppendPolyData(); ~vtkAppendPolyData(); @@ -131,15 +128,6 @@ class VTKFILTERSCORE_EXPORT vtkAppendPolyData : public vtkPolyDataAlgorithm void AddInputData(vtkDataObject *) { vtkErrorMacro( << "AddInput() must be called with a vtkPolyData not a vtkDataObject."); }; - template - void AppendData(vtkDataArray *dest, vtkDataArray *src, vtkIdType offset, - InputIterator srcData, InputIterator srcEnd); - - template - void AppendData(vtkDataArray *dest, vtkDataArray *src, vtkIdType offset, - InputIterator srcData, InputIterator srcEnd, - OutputIterator destData); - int UserManagedInputs; private: diff --git a/Filters/Core/vtkAppendSelection.h b/Filters/Core/vtkAppendSelection.h index 71592cf650b..f4ff7fe18dd 100644 --- a/Filters/Core/vtkAppendSelection.h +++ b/Filters/Core/vtkAppendSelection.h @@ -58,12 +58,10 @@ class VTKFILTERSCORE_EXPORT vtkAppendSelection : public vtkSelectionAlgorithm // used when UserManagedInputs is true, use SetInputByNumber (NULL) instead. void RemoveInputData(vtkSelection *); -//BTX // Description: // Get any input of this filter. vtkSelection *GetInput(int idx); vtkSelection *GetInput() { return this->GetInput( 0 ); }; -//ETX // Description: // Directly set(allocate) number of inputs, should only be used diff --git a/Filters/Core/vtkArrayCalculator.cxx b/Filters/Core/vtkArrayCalculator.cxx index d5f1c126c8a..5eac571247d 100644 --- a/Filters/Core/vtkArrayCalculator.cxx +++ b/Filters/Core/vtkArrayCalculator.cxx @@ -435,7 +435,7 @@ int vtkArrayCalculator::RequestData( else { resultArray= - vtkDataArray::SafeDownCast(vtkAbstractArray::CreateArray(this->ResultArrayType)); + vtkArrayDownCast(vtkAbstractArray::CreateArray(this->ResultArrayType)); } if (resultType == SCALAR_RESULT) @@ -453,12 +453,29 @@ int vtkArrayCalculator::RequestData( resultArray->SetTuple(0, this->FunctionParser->GetVectorResult()); } + // Save array pointers to avoid looking them up for each tuple. + std::vector scalarArrays(this->NumberOfScalarArrays); + std::vector vectorArrays(this->NumberOfVectorArrays); + for (int cc=0; cc < this->NumberOfScalarArrays; cc++) + { + if (this->FunctionParser->GetScalarVariableNeeded(cc)) + { + scalarArrays[cc] = inFD->GetArray(this->ScalarArrayNames[cc]); + } + } + for (int cc=0; cc < this->NumberOfVectorArrays; cc++) + { + if (this->FunctionParser->GetVectorVariableNeeded(cc)) + { + vectorArrays[cc] = inFD->GetArray(this->VectorArrayNames[cc]); + } + } + for (i = 1; i < numTuples; i++) { for (j = 0; j < this->NumberOfScalarArrays; j++) { - currentArray = inFD->GetArray(this->ScalarArrayNames[j]); - if(currentArray) + if ((currentArray = scalarArrays[j])) { this->FunctionParser-> SetScalarVariableValue( @@ -467,13 +484,14 @@ int vtkArrayCalculator::RequestData( } for (j = 0; j < this->NumberOfVectorArrays; j++) { - currentArray = inFD->GetArray(this->VectorArrayNames[j]); - this->FunctionParser-> - SetVectorVariableValue( - j, currentArray->GetComponent(i, this->SelectedVectorComponents[j][0]), - currentArray->GetComponent( - i, this->SelectedVectorComponents[j][1]), - currentArray->GetComponent(i, this->SelectedVectorComponents[j][2])); + if ((currentArray = vectorArrays[j])) + { + this->FunctionParser->SetVectorVariableValue( + j, currentArray->GetComponent(i, this->SelectedVectorComponents[j][0]), + currentArray->GetComponent( + i, this->SelectedVectorComponents[j][1]), + currentArray->GetComponent(i, this->SelectedVectorComponents[j][2])); + } } if(attributeDataType == POINT_DATA) { diff --git a/Filters/Core/vtkAssignAttribute.h b/Filters/Core/vtkAssignAttribute.h index a24fa77b2a4..2c0bb5deb69 100644 --- a/Filters/Core/vtkAssignAttribute.h +++ b/Filters/Core/vtkAssignAttribute.h @@ -85,8 +85,6 @@ class VTKFILTERSCORE_EXPORT vtkAssignAttribute : public vtkPassInputTypeAlgorith void Assign(const char* name, const char* attributeType, const char* attributeLoc); - -//BTX // Always keep NUM_ATTRIBUTE_LOCS as the last entry enum AttributeLocation { @@ -96,17 +94,14 @@ class VTKFILTERSCORE_EXPORT vtkAssignAttribute : public vtkPassInputTypeAlgorith EDGE_DATA=3, NUM_ATTRIBUTE_LOCS }; -//ETX protected: -//BTX enum FieldType { NAME, ATTRIBUTE }; -//ETX vtkAssignAttribute(); virtual ~vtkAssignAttribute(); diff --git a/Filters/Core/vtkClipPolyData.h b/Filters/Core/vtkClipPolyData.h index 18b6c80f5c4..d3adb234485 100644 --- a/Filters/Core/vtkClipPolyData.h +++ b/Filters/Core/vtkClipPolyData.h @@ -51,7 +51,7 @@ // output may consist of different cell types than the input data. // .SECTION See Also -// vtkImplicitFunction vtkCutter vtkClipVolume +// vtkImplicitFunction vtkCutter vtkClipVolume vtkExtractGeometry #ifndef vtkClipPolyData_h #define vtkClipPolyData_h @@ -70,7 +70,8 @@ class VTKFILTERSCORE_EXPORT vtkClipPolyData : public vtkPolyDataAlgorithm // Description: // Construct with user-specified implicit function; InsideOut turned off; - // value set to 0.0; and generate clip scalars turned off. + // value set to 0.0; GenerateClipScalars turned off; GenerateClippedOutput + // turned off. static vtkClipPolyData *New(); // Description: @@ -103,6 +104,7 @@ class VTKFILTERSCORE_EXPORT vtkClipPolyData : public vtkPolyDataAlgorithm // interpolated from the implicit function values, and not the // input scalar data. If you enable this flag but do not provide an // implicit function an error will be reported. + // GenerateClipScalars is off by default. vtkSetMacro(GenerateClipScalars,int); vtkGetMacro(GenerateClipScalars,int); vtkBooleanMacro(GenerateClipScalars,int); @@ -110,6 +112,7 @@ class VTKFILTERSCORE_EXPORT vtkClipPolyData : public vtkPolyDataAlgorithm // Description: // Control whether a second output is generated. The second output // contains the polygonal data that's been clipped away. + // GenerateClippedOutput is off by default. vtkSetMacro(GenerateClippedOutput,int); vtkGetMacro(GenerateClippedOutput,int); vtkBooleanMacro(GenerateClippedOutput,int); @@ -143,7 +146,8 @@ class VTKFILTERSCORE_EXPORT vtkClipPolyData : public vtkPolyDataAlgorithm // Description: // Set/get the desired precision for the output types. See the documentation // for the vtkAlgorithm::DesiredOutputPrecision enum for an explanation of - // the available precision settings. + // the available precision settings. OutputPointsPrecision is DEFAULT_PRECISION + // by default. vtkSetMacro(OutputPointsPrecision,int); vtkGetMacro(OutputPointsPrecision,int); diff --git a/Filters/Core/vtkCompositeDataProbeFilter.cxx b/Filters/Core/vtkCompositeDataProbeFilter.cxx index bd4c144ff93..a6cbde5e879 100644 --- a/Filters/Core/vtkCompositeDataProbeFilter.cxx +++ b/Filters/Core/vtkCompositeDataProbeFilter.cxx @@ -244,7 +244,7 @@ int vtkCompositeDataProbeFilter::BuildFieldList(vtkCompositeDataSet* source) } else { - this->CellList->IntersectFieldList(sourceDS->GetPointData()); + this->CellList->IntersectFieldList(sourceDS->GetCellData()); } } } diff --git a/Filters/Core/vtkCompositeDataProbeFilter.h b/Filters/Core/vtkCompositeDataProbeFilter.h index ea8e1e5c1a8..e643bb214cc 100644 --- a/Filters/Core/vtkCompositeDataProbeFilter.h +++ b/Filters/Core/vtkCompositeDataProbeFilter.h @@ -61,7 +61,6 @@ class VTKFILTERSCORE_EXPORT vtkCompositeDataProbeFilter : public vtkProbeFilter vtkGetMacro(PassPartialArrays, bool); vtkBooleanMacro(PassPartialArrays, bool); -//BTX protected: vtkCompositeDataProbeFilter(); ~vtkCompositeDataProbeFilter(); @@ -92,7 +91,7 @@ class VTKFILTERSCORE_EXPORT vtkCompositeDataProbeFilter : public vtkProbeFilter private: vtkCompositeDataProbeFilter(const vtkCompositeDataProbeFilter&); // Not implemented. void operator=(const vtkCompositeDataProbeFilter&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/Core/vtkContourFilter.h b/Filters/Core/vtkContourFilter.h index 44e36a82c2a..212270bcd38 100644 --- a/Filters/Core/vtkContourFilter.h +++ b/Filters/Core/vtkContourFilter.h @@ -163,7 +163,7 @@ class VTKFILTERSCORE_EXPORT vtkContourFilter : public vtkPolyDataAlgorithm vtkContourFilter(); ~vtkContourFilter(); - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; virtual int RequestData(vtkInformation* request, vtkInformationVector** inputVector, diff --git a/Filters/Core/vtkCutter.cxx b/Filters/Core/vtkCutter.cxx index 0945b473057..4c4408c3aa2 100644 --- a/Filters/Core/vtkCutter.cxx +++ b/Filters/Core/vtkCutter.cxx @@ -14,13 +14,15 @@ =========================================================================*/ #include "vtkCutter.h" +#include "vtkArrayDispatch.h" +#include "vtkAssume.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkCellIterator.h" #include "vtkContourValues.h" +#include "vtkDataArrayAccessor.h" #include "vtkDataSet.h" #include "vtkDoubleArray.h" -#include "vtkDataArrayIteratorMacro.h" #include "vtkFloatArray.h" #include "vtkGenericCell.h" #include "vtkGridSynchronizedTemplates3D.h" @@ -200,19 +202,37 @@ void vtkCutter::StructuredPointsCutter(vtkDataSet *dataSetInput, } namespace { -template -void ExecuteFunction(vtkImplicitFunction* CutFunction, Iterator begin, Iterator end, float *output) +struct CutFunctionWorker +{ + vtkImplicitFunction *CutFunction; + vtkFloatArray *Output; + + CutFunctionWorker(vtkImplicitFunction *cutFunction, vtkFloatArray *output) + : CutFunction(cutFunction), Output(output) {} + + template + void operator()(ArrayT *input) { - for (Iterator input = begin; input < end; std::advance(input,3), std::advance(output,1)) - { + VTK_ASSUME(input->GetNumberOfComponents() == 3); + VTK_ASSUME(this->Output->GetNumberOfComponents() == 1); + + vtkIdType numTuples = input->GetNumberOfTuples(); + assert(numTuples == this->Output->GetNumberOfTuples()); + + vtkDataArrayAccessor src(input); + double in[3]; - in[0] = static_cast(input[0]); - in[1] = static_cast(input[1]); - in[2] = static_cast(input[2]); - *output = static_cast(CutFunction->FunctionValue(in)); - } + for (vtkIdType tIdx = 0; tIdx < numTuples; ++tIdx) + { + in[0] = static_cast(src.Get(tIdx, 0)); + in[1] = static_cast(src.Get(tIdx, 1)); + in[2] = static_cast(src.Get(tIdx, 2)); + this->Output->SetComponent(tIdx, 0, + this->CutFunction->FunctionValue(in)); + } } -} +}; +} // end anon namespace //---------------------------------------------------------------------------- void vtkCutter::StructuredGridCutter(vtkDataSet *dataSetInput, @@ -229,6 +249,7 @@ void vtkCutter::StructuredGridCutter(vtkDataSet *dataSetInput, vtkFloatArray *cutScalars = vtkFloatArray::New(); cutScalars->SetName("cutScalars"); + cutScalars->SetNumberOfTuples(numPts); vtkStructuredGrid *contourData = vtkStructuredGrid::New(); contourData->ShallowCopy(input); @@ -241,12 +262,13 @@ void vtkCutter::StructuredGridCutter(vtkDataSet *dataSetInput, contourData->GetPointData()->AddArray(cutScalars); } - float* ptrCutScalars = cutScalars->WritePointer(0, numPts); vtkDataArray* dataArrayInput = input->GetPoints()->GetData(); - switch(dataArrayInput->GetDataType()) + CutFunctionWorker worker(this->CutFunction, cutScalars); + if (!vtkArrayDispatch::Dispatch::Execute(dataArrayInput, worker)) { - vtkDataArrayIteratorMacro(dataArrayInput,ExecuteFunction(this->CutFunction,vtkDABegin,vtkDAEnd,ptrCutScalars);); + worker(dataArrayInput); // Use vtkDataArray API if dispatch fails. } + int numContours = this->GetNumberOfContours(); this->GridSynchronizedTemplates->SetDebug(this->GetDebug()); diff --git a/Filters/Core/vtkDataSetEdgeSubdivisionCriterion.h b/Filters/Core/vtkDataSetEdgeSubdivisionCriterion.h index 6a0e50fb86c..0b9eb3ffc70 100644 --- a/Filters/Core/vtkDataSetEdgeSubdivisionCriterion.h +++ b/Filters/Core/vtkDataSetEdgeSubdivisionCriterion.h @@ -48,19 +48,17 @@ class VTKFILTERSCORE_EXPORT vtkDataSetEdgeSubdivisionCriterion : public vtkEdgeS virtual void SetMesh( vtkDataSet* ); vtkDataSet* GetMesh(); - //BTX + const vtkDataSet* GetMesh() const; - //ETX virtual void SetCellId( vtkIdType cell ); vtkIdType GetCellId() const; - //BTX + vtkIdType& GetCellId(); - //ETX + vtkCell* GetCell(); - //BTX + const vtkCell* GetCell() const; - //ETX virtual bool EvaluateEdge( const double* p0, double* midpt, const double* p1, int field_start ); @@ -156,8 +154,6 @@ class VTKFILTERSCORE_EXPORT vtkDataSetEdgeSubdivisionCriterion : public vtkEdgeS }; -//BTX - inline vtkIdType& vtkDataSetEdgeSubdivisionCriterion::GetCellId() { return this->CurrentCellId; } inline vtkIdType vtkDataSetEdgeSubdivisionCriterion::GetCellId() const { return this->CurrentCellId; } @@ -167,6 +163,4 @@ inline const vtkDataSet* vtkDataSetEdgeSubdivisionCriterion::GetMesh() const { r inline vtkCell* vtkDataSetEdgeSubdivisionCriterion::GetCell() { return this->CurrentCellData; } inline const vtkCell* vtkDataSetEdgeSubdivisionCriterion::GetCell() const { return this->CurrentCellData; } -//ETX - #endif // vtkDataSetEdgeSubdivisionCriterion_h diff --git a/Filters/Core/vtkDecimatePro.h b/Filters/Core/vtkDecimatePro.h index 53c5f74c9bf..4f2b46b0477 100644 --- a/Filters/Core/vtkDecimatePro.h +++ b/Filters/Core/vtkDecimatePro.h @@ -279,8 +279,6 @@ class VTKFILTERSCORE_EXPORT vtkDecimatePro : public vtkPolyDataAlgorithm // // Special classes for manipulating data // - //BTX - begin tcl exclude - // // Special structures for building loops class LocalVertex { @@ -340,8 +338,6 @@ class VTKFILTERSCORE_EXPORT vtkDecimatePro : public vtkPolyDataAlgorithm LocalTri *Array; // pointer to data vtkIdType MaxId; // maximum index inserted thus far }; - //ETX - end tcl exclude - // private: void InitializeQueue(vtkIdType numPts); diff --git a/Filters/Core/vtkEdgeSubdivisionCriterion.h b/Filters/Core/vtkEdgeSubdivisionCriterion.h index a0011c67d93..f4724b54391 100644 --- a/Filters/Core/vtkEdgeSubdivisionCriterion.h +++ b/Filters/Core/vtkEdgeSubdivisionCriterion.h @@ -165,12 +165,8 @@ class VTKFILTERSCORE_EXPORT vtkEdgeSubdivisionCriterion : public vtkObject void operator = ( const vtkEdgeSubdivisionCriterion& ); // Not implemented. }; -//BTX - inline const int* vtkEdgeSubdivisionCriterion::GetFieldIds() const { return this->FieldIds; } inline const int* vtkEdgeSubdivisionCriterion::GetFieldOffsets() const { return this->FieldOffsets; } inline int vtkEdgeSubdivisionCriterion::GetNumberOfFields() const { return this->NumberOfFields; } -//ETX - #endif // vtkEdgeSubdivisionCriterion_h diff --git a/Filters/Core/vtkFieldDataToAttributeDataFilter.h b/Filters/Core/vtkFieldDataToAttributeDataFilter.h index 2f53ca9447d..b3019257e2b 100644 --- a/Filters/Core/vtkFieldDataToAttributeDataFilter.h +++ b/Filters/Core/vtkFieldDataToAttributeDataFilter.h @@ -212,12 +212,10 @@ class VTKFILTERSCORE_EXPORT vtkFieldDataToAttributeDataFilter : public vtkDataSe // Specify an array name for one of the components. static void SetArrayName(vtkObject *self, char* &name, const char *newName); -//BTX // Description: // Update the maximum and minimum component range values. Returns a flag // indicating whether the range was updated. static int UpdateComponentRange(vtkDataArray *da, vtkIdType compRange[2]); -//ETX // Description: // If output does not need exact extent, the I do not either. diff --git a/Filters/Core/vtkFlyingEdges3D.cxx b/Filters/Core/vtkFlyingEdges3D.cxx index 3ad4df0a3ea..4e7af15cc19 100644 --- a/Filters/Core/vtkFlyingEdges3D.cxx +++ b/Filters/Core/vtkFlyingEdges3D.cxx @@ -14,6 +14,7 @@ =========================================================================*/ #include "vtkFlyingEdges3D.h" +#include "vtkArrayListTemplate.h" // For processing attribute data #include "vtkMath.h" #include "vtkImageData.h" #include "vtkCellArray.h" @@ -33,7 +34,7 @@ vtkStandardNewMacro(vtkFlyingEdges3D); //---------------------------------------------------------------------------- - +namespace { // This templated class implements the heart of the algorithm. // vtkFlyingEdges3D populates the information in this class and // then invokes Contour() to actually initiate execution. @@ -121,6 +122,8 @@ class vtkFlyingEdges3DAlgorithm float *NewGradients; float *NewNormals; bool NeedGradients; + bool InterpolateAttributes; + ArrayList Arrays; // Setup algorithm vtkFlyingEdges3DAlgorithm(); @@ -212,7 +215,8 @@ class vtkFlyingEdges3DAlgorithm const int incs[3], float x1[3], vtkIdType vId, - vtkIdType ijk[3], + vtkIdType ijk0[3], + vtkIdType ijk1[3], float g0[3]) { @@ -224,7 +228,7 @@ class vtkFlyingEdges3DAlgorithm if ( this->NeedGradients ) { float gTmp[3], g1[3]; - this->ComputeGradient(loc,ijk, + this->ComputeGradient(loc,ijk1, s + incs[0], s - incs[0], s + incs[1], s - incs[1], s + incs[2], s - incs[2], @@ -244,6 +248,13 @@ class vtkFlyingEdges3DAlgorithm vtkMath::Normalize(n); } }//if normals or gradients required + + if ( this->InterpolateAttributes ) + { + vtkIdType v0=ijk0[0] + ijk0[1]*incs[1] + ijk0[2]*incs[2]; + vtkIdType v1=ijk1[0] + ijk1[1]*incs[1] + ijk1[2]*incs[2];; + this->Arrays.InterpolateEdge(v0,v1,t,vId); + } } // Compute the gradient on a point which may be on the boundary of the volume. @@ -379,8 +390,9 @@ class vtkFlyingEdges3DAlgorithm // Interface between VTK and templated functions static void Contour(vtkFlyingEdges3D *self, vtkImageData *input, + vtkDataArray *inScalars, int extent[6], vtkIdType *incs, T *scalars, - vtkPoints *newPts, vtkCellArray *newTris, + vtkPolyData *output, vtkPoints *newPts, vtkCellArray *newTris, vtkDataArray *newScalars,vtkFloatArray *newNormals, vtkFloatArray *newGradients); }; @@ -683,6 +695,13 @@ InterpolateEdge(double value, vtkIdType ijk[3], vtkMath::Normalize(n); } }//if normals or gradients required + + if ( this->InterpolateAttributes ) + { + vtkIdType v0=ijk0[0] + ijk0[1]*incs[1] + ijk0[2]*incs[2]; + vtkIdType v1=ijk1[0] + ijk1[1]*incs[1] + ijk1[2]*incs[2];; + this->Arrays.InterpolateEdge(v0,v1,t,vId); + } } //---------------------------------------------------------------------------- @@ -719,7 +738,7 @@ GeneratePoints(double value, unsigned char loc, vtkIdType ijk[3], T const * const sPtr2 = (sPtr+incs[i]); double t = (value - *sPtr) / (*sPtr2 - *sPtr); - this->InterpolateAxesEdge(t, loc, x, sPtr2, incs, x1, eIds[i*4], ijk1, g0); + this->InterpolateAxesEdge(t, loc, x, sPtr2, incs, x1, eIds[i*4], ijk, ijk1, g0); } } @@ -794,15 +813,14 @@ ProcessXEdge(double value, T const* const inPtr, vtkIdType row, vtkIdType slice) vtkIdType nxcells=this->Dims[0]-1; vtkIdType minInt=nxcells, maxInt = 0; vtkIdType *edgeMetaData; - unsigned char *ePtr = this->XCases + slice*this->SliceOffset + row*nxcells; + unsigned char edgeCase, *ePtr=this->XCases+slice*this->SliceOffset+row*nxcells; double s0, s1 = static_cast(*inPtr); + vtkIdType sum = 0; //run along the entire x-edge computing edge cases edgeMetaData = this->EdgeMetaData + (slice*this->Dims[1] + row)*6; std::fill_n(edgeMetaData, 6, 0); - vtkIdType sum = 0; - //pull this out help reduce false sharing vtkIdType inc0 = this->Inc0; @@ -811,11 +829,14 @@ ProcessXEdge(double value, T const* const inPtr, vtkIdType row, vtkIdType slice) s0 = s1; s1 = static_cast(*(inPtr + (i+1)*inc0)); - unsigned char edgeCase = vtkFlyingEdges3DAlgorithm::Below; if (s0 >= value) { edgeCase = vtkFlyingEdges3DAlgorithm::LeftAbove; } + else + { + edgeCase = vtkFlyingEdges3DAlgorithm::Below; + } if( s1 >= value) { edgeCase |= vtkFlyingEdges3DAlgorithm::RightAbove; @@ -828,7 +849,10 @@ ProcessXEdge(double value, T const* const inPtr, vtkIdType row, vtkIdType slice) edgeCase == vtkFlyingEdges3DAlgorithm::RightAbove ) { ++sum; //increment number of intersections along x-edge - minInt = ( i < minInt ? i : minInt); + if ( i < minInt ) + { + minInt = i; + } maxInt = i + 1; }//if contour interacts with this x-edge }//for all x-cell edges along this x-edge @@ -936,6 +960,7 @@ ProcessYZEdges(vtkIdType row, vtkIdType slice) // voxel axes. Also check the number of primitives generated. unsigned char *edgeUses, eCase, numTris; ePtr[0] += xL; ePtr[1] += xL; ePtr[2] += xL; ePtr[3] += xL; + const vtkIdType dim0Wall = this->Dims[0]-2; for (i=xL; i < xR; ++i) //run along the trimmed x-voxels { eCase = this->GetEdgeCase(ePtr); @@ -950,7 +975,7 @@ ProcessYZEdges(vtkIdType row, vtkIdType slice) edgeUses = this->GetEdgeUses(eCase); eMD[0][1] += edgeUses[4]; //y-voxel axes edge always counted eMD[0][2] += edgeUses[8]; //z-voxel axes edge always counted - loc = yzLoc | (i >= (this->Dims[0]-2) ? MaxBoundary : Interior); + loc = yzLoc | (i >= dim0Wall ? MaxBoundary : Interior); if ( loc != 0 ) { this->CountBoundaryYZInts(loc,edgeUses,eMD); @@ -1030,6 +1055,8 @@ GenerateOutput(double value, T* rowPtr, vtkIdType row, vtkIdType slice) //load the inc0/inc1/inc2 into local memory const int incs[3] = { this->Inc0, this->Inc1, this->Inc2 }; const T* sPtr = rowPtr + xL*incs[0]; + const double xSpace = this->Spacing[0]; + const vtkIdType dim0Wall = this->Dims[0]-2; for (i=xL; i < xR; ++i) { @@ -1042,7 +1069,7 @@ GenerateOutput(double value, T* rowPtr, vtkIdType row, vtkIdType slice) // Now generate point(s) along voxel axes if needed. Remember to take // boundary into account. loc = yzLoc | (i < 1 ? MinBoundary : - (i >= (this->Dims[0]-2) ? MaxBoundary : Interior)); + (i >= dim0Wall ? MaxBoundary : Interior)); if ( this->CaseIncludesAxes(eCase) || loc != Interior ) { unsigned char const * const edgeUses = this->GetEdgeUses(eCase); @@ -1059,7 +1086,7 @@ GenerateOutput(double value, T* rowPtr, vtkIdType row, vtkIdType slice) ++ijk[0]; sPtr += incs[0]; - x[0]+= this->Spacing[0]; + x[0] += xSpace; } //for all non-trimmed cells along this x-edge } @@ -1068,10 +1095,10 @@ GenerateOutput(double value, T* rowPtr, vtkIdType row, vtkIdType slice) // interfaces the vtkFlyingEdges3D class with the templated algorithm // class. It also invokes the three passes of the Flying Edges algorithm. template void vtkFlyingEdges3DAlgorithm:: -Contour(vtkFlyingEdges3D *self, vtkImageData *input, int extent[6], - vtkIdType *incs, T *scalars, vtkPoints *newPts, vtkCellArray *newTris, - vtkDataArray *newScalars, vtkFloatArray *newNormals, - vtkFloatArray *newGradients) +Contour(vtkFlyingEdges3D *self, vtkImageData *input, vtkDataArray *inScalars, + int extent[6], vtkIdType *incs, T *scalars, vtkPolyData *output, + vtkPoints *newPts, vtkCellArray *newTris, vtkDataArray *newScalars, + vtkFloatArray *newNormals, vtkFloatArray *newGradients) { double value, *values = self->GetValues(); int numContours = self->GetNumberOfContours(); @@ -1114,6 +1141,12 @@ Contour(vtkFlyingEdges3D *self, vtkImageData *input, int extent[6], // for computational trimming). algo.EdgeMetaData = new vtkIdType [algo.NumberOfEdges*6]; + // Interpolating attributes and other stuff. Interpolate extra attributes only if they + // exist and the user requests it. + algo.NeedGradients = (newGradients || newNormals); + algo.InterpolateAttributes = (self->GetInterpolateAttributes() && + input->GetPointData()->GetNumberOfArrays() > 1) ? true : false; + // Loop across each contour value. This encompasses all three passes. for (vidx = 0; vidx < numContours; vidx++) { @@ -1195,7 +1228,22 @@ Contour(vtkFlyingEdges3D *self, vtkImageData *input, int extent[6], newNormals->WriteVoidPointer(0,3*totalPts); algo.NewNormals = static_cast(newNormals->GetVoidPointer(0)); } - algo.NeedGradients = (algo.NewGradients || algo.NewNormals); + if ( algo.InterpolateAttributes ) + { + if ( vidx == 0 ) //first contour + { + // Make sure we don't interpolate the input scalars twice; or generate scalars + // when ComputeScalars is off. + output->GetPointData()->InterpolateAllocate(input->GetPointData(),totalPts); + output->GetPointData()->RemoveArray(inScalars->GetName()); + algo.Arrays.ExcludeArray(inScalars); + algo.Arrays.AddArrays(totalPts,input->GetPointData(),output->GetPointData()); + } + else + { + algo.Arrays.Realloc(totalPts); + } + } // PASS 4: Fourth and final pass: Process voxel rows and generate output. // Note that we are simultaneously generating triangles and interpolating @@ -1217,6 +1265,8 @@ Contour(vtkFlyingEdges3D *self, vtkImageData *input, int extent[6], delete [] algo.EdgeMetaData; } +}//anonymous namespace + //---------------------------------------------------------------------------- // Here is the VTK class proper. // Construct object with a single contour value of 0.0. @@ -1226,6 +1276,7 @@ vtkFlyingEdges3D::vtkFlyingEdges3D() this->ComputeNormals = 1; this->ComputeGradients = 0; this->ComputeScalars = 1; + this->InterpolateAttributes = 0; this->ArrayComponent = 0; // by default process active point scalars @@ -1278,7 +1329,7 @@ int vtkFlyingEdges3D::RequestData( vtkInformationVector **inputVector, vtkInformationVector *outputVector) { - vtkDebugMacro(<< "Executing 3D structured contour"); + vtkDebugMacro(<< "Executing 3D flying edges"); // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); @@ -1360,12 +1411,12 @@ int vtkFlyingEdges3D::RequestData( } void *ptr = input->GetArrayPointerForExtent(inScalars, exExt); - vtkIdType *incs = input->GetIncrements(); + vtkIdType *incs = input->GetIncrements(inScalars); switch (inScalars->GetDataType()) { vtkTemplateMacro(vtkFlyingEdges3DAlgorithm:: - Contour(this, input, exExt, incs, (VTK_TT *)ptr, - newPts, newTris, newScalars, newNormals, + Contour(this, input, inScalars, exExt, incs, (VTK_TT *)ptr, + output, newPts, newTris, newScalars, newNormals, newGradients)); } @@ -1422,5 +1473,6 @@ void vtkFlyingEdges3D::PrintSelf(ostream& os, vtkIndent indent) os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n"); os << indent << "Compute Gradients: " << (this->ComputeGradients ? "On\n" : "Off\n"); os << indent << "Compute Scalars: " << (this->ComputeScalars ? "On\n" : "Off\n"); + os << indent << "Interpolate Attributes: " << (this->InterpolateAttributes ? "On\n" : "Off\n"); os << indent << "ArrayComponent: " << this->ArrayComponent << endl; } diff --git a/Filters/Core/vtkFlyingEdges3D.h b/Filters/Core/vtkFlyingEdges3D.h index b3ddafa858c..a0cd740d8ad 100644 --- a/Filters/Core/vtkFlyingEdges3D.h +++ b/Filters/Core/vtkFlyingEdges3D.h @@ -100,6 +100,15 @@ class VTKFILTERSCORE_EXPORT vtkFlyingEdges3D : public vtkPolyDataAlgorithm vtkGetMacro(ComputeScalars,int); vtkBooleanMacro(ComputeScalars,int); + // Description: + // Indicate whether to interpolate other attribute data. That is, as the + // isosurface is generated, interpolate all point attribute data across + // the edge. This is independent of scalar interpolation, which is + // controlled by the ComputeScalars flag. + vtkSetMacro(InterpolateAttributes,int); + vtkGetMacro(InterpolateAttributes,int); + vtkBooleanMacro(InterpolateAttributes,int); + // Description: // Set a particular contour value at contour number i. The index i ranges // between 0<=iNewPoints + 3*vId; x[0] = static_cast(x0[0] + t*(x1[0]-x0[0])); @@ -199,17 +204,24 @@ class vtkFlyingEdgesPlaneCutterAlgorithm if ( this->NewNormals ) { float *n = this->NewNormals + 3*vId; - n[0] = this->Normal[0]; - n[1] = this->Normal[1]; - n[2] = this->Normal[2]; + n[0] = -this->Normal[0]; + n[1] = -this->Normal[1]; + n[2] = -this->Normal[2]; }//if normals + + if ( this->InterpolateAttributes ) + { + vtkIdType v0=ijk0[0] + ijk0[1]*incs[1] + ijk0[2]*incs[2]; + vtkIdType v1=ijk1[0] + ijk1[1]*incs[1] + ijk1[2]*incs[2];; + this->Arrays.InterpolateEdge(v0,v1,t,vId); + } } // Interpolate along an arbitrary edge, typically one that may be on the // volume boundary. This means careful computation of stuff requiring // neighborhood information. - void InterpolateEdge(T const * const s, const int incs[3], - double x[3], + void InterpolateEdge(vtkIdType ijk[3], T const * const s, + const int incs[3],double x[3], unsigned char edgeNum, unsigned char const* const edgeUses, vtkIdType *eIds); @@ -335,9 +347,10 @@ class vtkFlyingEdgesPlaneCutterAlgorithm // Interface between VTK and templated functions static void Contour(vtkFlyingEdgesPlaneCutter *self, vtkImageData *input, - int extent[6], vtkIdType *incs, T *scalars, - vtkPoints *newPts, vtkCellArray *newTris, - vtkDataArray *newScalars, vtkDataArray *newNormals); + vtkDataArray *inScalars, int extent[6], vtkIdType *incs, + T *scalars, vtkPolyData *output, vtkPoints *newPts, + vtkCellArray *newTris, vtkDataArray *newScalars, + vtkDataArray *newNormals); }; //---------------------------------------------------------------------------- @@ -509,12 +522,9 @@ CountBoundaryYZInts(unsigned char loc, unsigned char *edgeUses, // Interpolate a new point along a boundary edge. Make sure to consider // proximity to the boundary. template void vtkFlyingEdgesPlaneCutterAlgorithm:: -InterpolateEdge(T const * const s, - const int incs[3], - double x[3], - unsigned char edgeNum, - unsigned char const * const edgeUses, - vtkIdType *eIds) +InterpolateEdge(vtkIdType ijk[3], T const * const s, const int incs[3], + double x[3], unsigned char edgeNum, + unsigned char const * const edgeUses, vtkIdType *eIds) { // if this edge is not used then get out if ( ! edgeUses[edgeNum] ) @@ -528,32 +538,29 @@ InterpolateEdge(T const * const s, const unsigned char *vertMap = this->VertMap[edgeNum]; double x0[3], x1[3]; - vtkIdType vId=eIds[edgeNum]; - int i; - - const unsigned char *offsets = this->VertOffsets[vertMap[0]]; - const T *s0 = s + offsets[0]*incs[0] + - offsets[1]*incs[1] + - offsets[2]*incs[2]; - for (i=0; i<3; ++i) - { - x0[i] = x[i] + offsets[i]*this->Spacing[i]; - } - - offsets = this->VertOffsets[vertMap[1]]; - const T *s1 = s + offsets[0]*incs[0] + - offsets[1]*incs[1] + - offsets[2]*incs[2]; - for (i=0; i<3; ++i) - { - x1[i] = x[i] + offsets[i]*this->Spacing[i]; - } - - double sV = vtkPlane::Evaluate(this->Normal,this->Center,x0); + vtkIdType ijk0[3], ijk1[3], vId=eIds[edgeNum]; + + const unsigned char *offsets0 = this->VertOffsets[vertMap[0]]; + const T *s0 = s + offsets0[0]*incs[0] + + offsets0[1]*incs[1] + + offsets0[2]*incs[2]; + x0[0] = x[0] + offsets0[0]*this->Spacing[0]; + x0[1] = x[1] + offsets0[1]*this->Spacing[1]; + x0[2] = x[2] + offsets0[2]*this->Spacing[2]; + + const unsigned char *offsets1 = this->VertOffsets[vertMap[1]]; + const T *s1 = s + offsets1[0]*incs[0] + + offsets1[1]*incs[1] + + offsets1[2]*incs[2]; + x1[0] = x[0] + offsets1[0]*this->Spacing[0]; + x1[1] = x[1] + offsets1[1]*this->Spacing[1]; + x1[2] = x[2] + offsets1[2]*this->Spacing[2]; + + double sV0 = vtkPlane::Evaluate(this->Normal,this->Center,x0); double sV1 = vtkPlane::Evaluate(this->Normal,this->Center,x1); - // Okay interpolate. Remember the plane value == 0.0. - double t = -(sV) / (sV1 - sV); + // Okay interpolate. Remember the plane value = 0.0. + double t = -(sV0) / (sV1 - sV0); float *xPtr = this->NewPoints + 3*vId; xPtr[0] = static_cast(x0[0] + t*(x1[0]-x0[0])); xPtr[1] = static_cast(x0[1] + t*(x1[1]-x0[1])); @@ -565,10 +572,25 @@ InterpolateEdge(T const * const s, if ( this->NewNormals ) { float *n = this->NewNormals + 3*vId; - n[0] = this->Normal[0]; - n[1] = this->Normal[1]; - n[2] = this->Normal[2]; + n[0] = -this->Normal[0]; + n[1] = -this->Normal[1]; + n[2] = -this->Normal[2]; }//if normals + + if ( this->InterpolateAttributes ) + { + ijk0[0] = ijk[0] + offsets0[0]; + ijk0[1] = ijk[1] + offsets0[1]; + ijk0[2] = ijk[2] + offsets0[2]; + + ijk1[0] = ijk[0] + offsets1[0]; + ijk1[1] = ijk[1] + offsets1[1]; + ijk1[2] = ijk[2] + offsets1[2]; + + vtkIdType v0=ijk0[0] + ijk0[1]*incs[1] + ijk0[2]*incs[2]; + vtkIdType v1=ijk1[0] + ijk1[1]*incs[1] + ijk1[2]*incs[2]; + this->Arrays.InterpolateEdge(v0,v1,t,vId); + } } //---------------------------------------------------------------------------- @@ -576,7 +598,7 @@ InterpolateEdge(T const * const s, template void vtkFlyingEdgesPlaneCutterAlgorithm:: GeneratePoints(unsigned char loc, vtkIdType ijk[3], T const * const sPtr, const int incs[3], - double x[3], const double sV, + double x[3], const double sV0, unsigned char const * const edgeUses, vtkIdType *eIds) { // Interpolate the three x-y-z cell axes edges. @@ -593,8 +615,8 @@ GeneratePoints(unsigned char loc, vtkIdType ijk[3], T const * const sPtr1 = (sPtr+incs[i]); sV1 = vtkPlane::Evaluate(this->Normal,this->Center,x1); - double t = -sV / (sV1 - sV); - this->InterpolateAxesEdge(t, eIds[i*4], x, x1, *sPtr, *sPtr1); + double t = -sV0 / (sV1 - sV0); + this->InterpolateAxesEdge(t, eIds[i*4], incs, x, x1, *sPtr, *sPtr1, ijk, ijk1); } } @@ -609,48 +631,48 @@ GeneratePoints(unsigned char loc, vtkIdType ijk[3], switch (loc) { case 2: case 6: case 18: case 22: //+x - this->InterpolateEdge(sPtr, incs, x, 5, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 9, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 5, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 9, edgeUses, eIds); break; case 8: case 9: case 24: case 25: //+y - this->InterpolateEdge(sPtr, incs, x, 1, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 10, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 1, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 10, edgeUses, eIds); break; case 32: case 33: case 36: case 37: //+z - this->InterpolateEdge(sPtr, incs, x, 2, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 6, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 2, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 6, edgeUses, eIds); break; case 10: case 26: //+x +y - this->InterpolateEdge(sPtr, incs, x, 1, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 5, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 9, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 10, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 11, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 1, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 5, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 9, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 10, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 11, edgeUses, eIds); break; case 34: case 38: //+x +z - this->InterpolateEdge(sPtr, incs, x, 2, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 5, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 9, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 6, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 7, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 2, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 5, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 9, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 6, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 7, edgeUses, eIds); break; case 40: case 41: //+y +z - this->InterpolateEdge(sPtr, incs, x, 1, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 2, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 3, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 6, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 10, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 1, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 2, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 3, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 6, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 10, edgeUses, eIds); break; case 42: //+x +y +z happens no more than once per volume - this->InterpolateEdge(sPtr, incs, x, 1, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 2, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 3, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 5, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 9, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 10, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 11, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 6, edgeUses, eIds); - this->InterpolateEdge(sPtr, incs, x, 7, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 1, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 2, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 3, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 5, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 9, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 10, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 11, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 6, edgeUses, eIds); + this->InterpolateEdge(ijk, sPtr, incs, x, 7, edgeUses, eIds); break; default: //interior, or -x,-y,-z boundaries return; @@ -824,6 +846,7 @@ ProcessYZEdges(vtkIdType row, vtkIdType slice) // voxel axes. Also check the number of primitives generated. unsigned char *edgeUses, eCase, numTris; ePtr[0] += xL; ePtr[1] += xL; ePtr[2] += xL; ePtr[3] += xL; + const vtkIdType dim0Wall = this->Dims[0]-2; for (i=xL; i < xR; ++i) //run along the trimmed x-voxels { eCase = this->GetEdgeCase(ePtr); @@ -838,7 +861,7 @@ ProcessYZEdges(vtkIdType row, vtkIdType slice) edgeUses = this->GetEdgeUses(eCase); eMD[0][1] += edgeUses[4]; //y-voxel axes edge always counted eMD[0][2] += edgeUses[8]; //z-voxel axes edge always counted - loc = yzLoc | (i >= (this->Dims[0]-2) ? MaxBoundary : Interior); + loc = yzLoc | (i >= dim0Wall ? MaxBoundary : Interior); if ( loc != 0 ) { this->CountBoundaryYZInts(loc,edgeUses,eMD); @@ -918,6 +941,8 @@ GenerateOutput(T* rowPtr, vtkIdType row, vtkIdType slice) //load the inc0/inc1/inc2 into local memory const int incs[3] = { this->Inc0, this->Inc1, this->Inc2 }; const T* sPtr = rowPtr + xL*incs[0]; + const double xSpace = this->Spacing[0]; + const vtkIdType dim0Wall = this->Dims[0]-2; for (i=xL; i < xR; ++i) { @@ -930,7 +955,7 @@ GenerateOutput(T* rowPtr, vtkIdType row, vtkIdType slice) // Now generate point(s) along voxel axes if needed. Remember to take // boundary into account. loc = yzLoc | (i < 1 ? MinBoundary : - (i >= (this->Dims[0]-2) ? MaxBoundary : Interior)); + (i >= dim0Wall ? MaxBoundary : Interior)); if ( this->CaseIncludesAxes(eCase) || loc != Interior ) { unsigned char const * const edgeUses = this->GetEdgeUses(eCase); @@ -946,7 +971,7 @@ GenerateOutput(T* rowPtr, vtkIdType row, vtkIdType slice) ++ijk[0]; sPtr += incs[0]; - x[0] += this->Spacing[0]; + x[0] += xSpace; } //for all non-trimmed cells along this x-edge } @@ -955,9 +980,9 @@ GenerateOutput(T* rowPtr, vtkIdType row, vtkIdType slice) // interfaces the vtkFlyingEdgesPlaneCutter class with the templated algorithm // class. It also invokes the three passes of the Flying Edges algorithm. template void vtkFlyingEdgesPlaneCutterAlgorithm:: -Contour(vtkFlyingEdgesPlaneCutter *self, vtkImageData *input, int extent[6], - vtkIdType *incs, T *scalars, vtkPoints *newPts, vtkCellArray *newTris, - vtkDataArray *newScalars, vtkDataArray *newNormals) +Contour(vtkFlyingEdgesPlaneCutter *self, vtkImageData *input, vtkDataArray *inScalars, + int extent[6], vtkIdType *incs, T *scalars, vtkPolyData *output, vtkPoints *newPts, + vtkCellArray *newTris, vtkDataArray *newScalars, vtkDataArray *newNormals) { vtkIdType row, slice, *eMD, zInc; vtkIdType numOutXPts, numOutYPts, numOutZPts, numOutTris; @@ -1006,6 +1031,11 @@ Contour(vtkFlyingEdgesPlaneCutter *self, vtkImageData *input, int extent[6], // for computational trimming). algo.EdgeMetaData = new vtkIdType [algo.NumberOfEdges*6]; + // Configure the interpolation of attribute data. Scalars are required and + // always interpolated, other attributes are optional. + algo.InterpolateAttributes = (self->GetInterpolateAttributes() && + input->GetPointData()->GetNumberOfArrays() > 1) ? true : false; + // PASS 1: Traverse all x-rows building edge cases and counting number of // intersections (i.e., accumulate information necessary for later output // memory allocation, e.g., the number of output points along the x-rows @@ -1076,6 +1106,15 @@ Contour(vtkFlyingEdgesPlaneCutter *self, vtkImageData *input, int extent[6], algo.NewNormals = static_cast(newNormals->GetVoidPointer(0)); } + if ( algo.InterpolateAttributes ) + { + // Make sure we don't interpolate the input scalars twice + output->GetPointData()->InterpolateAllocate(input->GetPointData(),totalPts); + output->GetPointData()->RemoveArray(inScalars->GetName()); + algo.Arrays.ExcludeArray(inScalars); + algo.Arrays.AddArrays(totalPts,input->GetPointData(),output->GetPointData()); + } + // PASS 4: Fourth and final pass: Process voxel rows and generate output. // Note that we are simultaneously generating triangles and interpolating // points. These could be split into separate, parallel operations for @@ -1089,6 +1128,8 @@ Contour(vtkFlyingEdgesPlaneCutter *self, vtkImageData *input, int extent[6], delete [] algo.EdgeMetaData; } +}//anonymous namespace + //---------------------------------------------------------------------------- // Here is the VTK class proper. // Construct object with a single contour value of 0.0. @@ -1096,6 +1137,7 @@ vtkFlyingEdgesPlaneCutter::vtkFlyingEdgesPlaneCutter() { this->Plane = vtkPlane::New(); this->ComputeNormals = 0; + this->InterpolateAttributes = 0; this->ArrayComponent = 0; // by default process active point scalars @@ -1221,12 +1263,12 @@ int vtkFlyingEdgesPlaneCutter::RequestData( } void *ptr = input->GetArrayPointerForExtent(inScalars, exExt); - vtkIdType *incs = input->GetIncrements(); + vtkIdType *incs = input->GetIncrements(inScalars); switch (inScalars->GetDataType()) { vtkTemplateMacro(vtkFlyingEdgesPlaneCutterAlgorithm:: - Contour(this, input, exExt, incs, (VTK_TT *)ptr, newPts, - newTris, newScalars, newNormals)); + Contour(this, input, inScalars, exExt, incs, (VTK_TT *)ptr, + output, newPts, newTris, newScalars, newNormals)); } vtkDebugMacro(<<"Created: " @@ -1268,5 +1310,6 @@ void vtkFlyingEdgesPlaneCutter::PrintSelf(ostream& os, vtkIndent indent) os << indent << "Plane: " << this->Plane << "\n"; os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n"); + os << indent << "Interpolate Attributes: " << (this->InterpolateAttributes ? "On\n" : "Off\n"); os << indent << "ArrayComponent: " << this->ArrayComponent << endl; } diff --git a/Filters/Core/vtkFlyingEdgesPlaneCutter.h b/Filters/Core/vtkFlyingEdgesPlaneCutter.h index 88cb5f27ace..32a9130f893 100644 --- a/Filters/Core/vtkFlyingEdgesPlaneCutter.h +++ b/Filters/Core/vtkFlyingEdgesPlaneCutter.h @@ -78,6 +78,14 @@ class VTKFILTERSCORE_EXPORT vtkFlyingEdgesPlaneCutter : public vtkPolyDataAlgori vtkGetMacro(ComputeNormals,int); vtkBooleanMacro(ComputeNormals,int); + // Description: + // Indicate whether to interpolate other attribute data besides the input + // scalars (which are required). That is, as the isosurface is generated, + // interpolate all other point attribute data across intersected edges. + vtkSetMacro(InterpolateAttributes,int); + vtkGetMacro(InterpolateAttributes,int); + vtkBooleanMacro(InterpolateAttributes,int); + // Description: // Set/get which component of the scalar array to contour on; defaults to 0. vtkSetMacro(ArrayComponent, int); @@ -89,6 +97,7 @@ class VTKFILTERSCORE_EXPORT vtkFlyingEdgesPlaneCutter : public vtkPolyDataAlgori vtkPlane *Plane; int ComputeNormals; + int InterpolateAttributes; int ArrayComponent; virtual int RequestData(vtkInformation *, vtkInformationVector **, diff --git a/Filters/Core/vtkMaskFields.h b/Filters/Core/vtkMaskFields.h index 6fd52a8dba8..e0f1cff9367 100644 --- a/Filters/Core/vtkMaskFields.h +++ b/Filters/Core/vtkMaskFields.h @@ -120,14 +120,12 @@ class VTKFILTERSCORE_EXPORT vtkMaskFields : public vtkDataSetAlgorithm // If CopyAllOff is set, do not copy the array virtual void CopyAllOff(); -//BTX enum FieldLocation { OBJECT_DATA=0, POINT_DATA=1, CELL_DATA=2 }; -//ETX protected: vtkMaskFields(); @@ -135,7 +133,6 @@ class VTKFILTERSCORE_EXPORT vtkMaskFields : public vtkDataSetAlgorithm virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); -//BTX struct CopyFieldFlag { char* Name; @@ -143,7 +140,6 @@ class VTKFILTERSCORE_EXPORT vtkMaskFields : public vtkDataSetAlgorithm int Location; int IsCopied; }; -//ETX CopyFieldFlag* CopyFieldFlags; // the names of fields not to be copied int NumberOfFieldFlags; // the number of fields not to be copied diff --git a/Filters/Core/vtkMergeFields.h b/Filters/Core/vtkMergeFields.h index 3d2b0f2b14c..00d38a46f19 100644 --- a/Filters/Core/vtkMergeFields.h +++ b/Filters/Core/vtkMergeFields.h @@ -79,16 +79,13 @@ class VTKFILTERSCORE_EXPORT vtkMergeFields : public vtkDataSetAlgorithm vtkSetMacro(NumberOfComponents, int); vtkGetMacro(NumberOfComponents, int); -//BTX enum FieldLocations { DATA_OBJECT=0, POINT_DATA=1, CELL_DATA=2 }; -//ETX -//BTX struct Component { int Index; @@ -109,17 +106,14 @@ class VTKFILTERSCORE_EXPORT vtkMergeFields : public vtkDataSetAlgorithm Component() { FieldName = 0; } ~Component() { delete[] FieldName; } }; -//ETX protected: -//BTX enum FieldType { NAME, ATTRIBUTE }; -//ETX vtkMergeFields(); virtual ~vtkMergeFields(); diff --git a/Filters/Core/vtkPolyDataConnectivityFilter.cxx b/Filters/Core/vtkPolyDataConnectivityFilter.cxx index ec48b886d89..21542aa0d2b 100644 --- a/Filters/Core/vtkPolyDataConnectivityFilter.cxx +++ b/Filters/Core/vtkPolyDataConnectivityFilter.cxx @@ -473,7 +473,7 @@ void vtkPolyDataConnectivityFilter::TraverseAndMark () if ( this->PointMap[ptId=pts[j]] < 0 ) { this->PointMap[ptId] = this->PointNumber++; - vtkIdTypeArray::SafeDownCast(this->NewScalars)->SetValue( + vtkArrayDownCast(this->NewScalars)->SetValue( this->PointMap[ptId], this->RegionNumber); this->Mesh->GetPointCells(ptId,ncells,cells); diff --git a/Filters/Core/vtkPolyDataNormals.h b/Filters/Core/vtkPolyDataNormals.h index fb26364ed1f..aa550ea189b 100644 --- a/Filters/Core/vtkPolyDataNormals.h +++ b/Filters/Core/vtkPolyDataNormals.h @@ -23,9 +23,9 @@ // (using SetNormals()) of the PointData and/or the CellData (respectively) // of the output PolyData. The name of these arrays is "Normals", so they // can be retrieved either with -// vtkFloatArray::SafeDownCast(output->GetPointData()->GetNormals()) +// vtkArrayDownCast(output->GetPointData()->GetNormals()) // or with -// vtkFloatArray::SafeDownCast(output->GetPointData()->GetArray("Normals")) +// vtkArrayDownCast(output->GetPointData()->GetArray("Normals")) // // The filter can reorder polygons to insure consistent // orientation across polygon neighbors. Sharp edges can be split and points diff --git a/Filters/Core/vtkProbeFilter.cxx b/Filters/Core/vtkProbeFilter.cxx index 3512705a9f9..e12eebacbe1 100644 --- a/Filters/Core/vtkProbeFilter.cxx +++ b/Filters/Core/vtkProbeFilter.cxx @@ -30,6 +30,8 @@ vtkStandardNewMacro(vtkProbeFilter); +#define CELL_TOLERANCE_FACTOR_SQR 1e-6 + class vtkProbeFilter::vtkVectorOfArrays : public std::vector { @@ -321,37 +323,8 @@ void vtkProbeFilter::ProbeEmptyPoints(vtkDataSet *input, char* maskArray = this->MaskPoints->GetPointer(0); - if (this->ComputeTolerance) - { - // Use tolerance as a function of size of source data - // - tol2 = source->GetLength(); - tol2 = (tol2 != 0.0) ? tol2*tol2 / 1000.0 : 0.001; - - // the actual sampling rate needs to be considered for a - // more appropriate / accurate selection of the tolerance. - // Otherwise the tolerance simply determined above might be - // so large as to cause incorrect cell location - double bounds[6]; - source->GetBounds(bounds); - double minRes = 10000000000.0; - double axisRes[3]; - for ( int i = 0; i < 3; i ++ ) - { - axisRes[i] = ( bounds[i * 2 + 1] - bounds[i * 2] ) / numPts; - if ( (axisRes[i] > 0.0) && (axisRes[i] < minRes) ) - minRes = axisRes[i]; - } - double minRes2 = minRes * minRes; - tol2 = tol2 > minRes2 ? minRes2 : tol2; - - // Don't go below epsilon for a double - tol2 = (tol2 < VTK_DBL_EPSILON) ? VTK_DBL_EPSILON : tol2; - } - else - { - tol2 = this->Tolerance * this->Tolerance; - } + tol2 = this->ComputeTolerance ? VTK_DOUBLE_MAX : + (this->Tolerance * this->Tolerance); // Loop over all input points, interpolating source data // @@ -380,27 +353,24 @@ void vtkProbeFilter::ProbeEmptyPoints(vtkDataSet *input, if (cellId >= 0) { cell = source->GetCell(cellId); - // If we found a cell, let's make sure that the point is within - // a certain size of the cell when it is slightly outside. - // The tolerance check above is based on the bounds of the whole - // dataset which may be significantly larger than the cell. When - // that happens, even a small tolerance may lead to finding a cell - // when the point is significantly outside that cell. This check - // is based on the cell's size. The tolerance here is significantly - // larger, 1/10 the size of the cell. - double dist2; - double closestPoint[3]; - cell->EvaluatePosition(x, closestPoint, subId, - pcoords, dist2, weights); - if (dist2 > cell->GetLength2() * 0.01) + if (this->ComputeTolerance) { - cell = 0; + // If ComputeTolerance is set, compute a tolerance proportional to the + // cell length. + double dist2; + double closestPoint[3]; + cell->EvaluatePosition(x, closestPoint, subId, pcoords, dist2, weights); + if (dist2 > (cell->GetLength2() * CELL_TOLERANCE_FACTOR_SQR)) + { + cell = 0; + } } } else { cell = 0; } + if (cell) { // Interpolate the point data @@ -532,6 +502,7 @@ void vtkProbeFilter::ProbePointsImageData(vtkImageData *input, continue; } + double userTol2 = this->Tolerance * this->Tolerance; for (int iz=idxBounds[4]; iz<=idxBounds[5]; iz++) { double p[3]; @@ -548,19 +519,15 @@ void vtkProbeFilter::ProbePointsImageData(vtkImageData *input, double dist2; int subId; int inside = cell->EvaluatePosition(p, closestPoint, subId, pcoords, - dist2, weights); + dist2, weights); - // Ensure the point really falls in the cell. Prevents extrapolation. - for (int k=0; kGetNumberOfPoints(); k++) - { - if (weights[k]<0) - { - inside=0; - break; - } - } + // If ComputeTolerance is set, compute a tolerance proportional to the + // cell length. Otherwise, use the user specified absolute tolerance. + double tol2 = this->ComputeTolerance ? + (CELL_TOLERANCE_FACTOR_SQR * cell->GetLength2()) : + userTol2; - if (inside && (dist2==0)) // ensure it's inside the cell + if ((inside == 1) && (dist2 <= tol2)) { vtkIdType ptId = ix + dim[0]*(iy + dim[1]*iz); diff --git a/Filters/Core/vtkProbeFilter.h b/Filters/Core/vtkProbeFilter.h index 06fa7117c33..8d8f7002f96 100644 --- a/Filters/Core/vtkProbeFilter.h +++ b/Filters/Core/vtkProbeFilter.h @@ -127,7 +127,6 @@ class VTKFILTERSCORE_EXPORT vtkProbeFilter : public vtkDataSetAlgorithm vtkBooleanMacro(ComputeTolerance, bool); vtkGetMacro(ComputeTolerance, bool); -//BTX protected: vtkProbeFilter(); ~vtkProbeFilter(); @@ -200,7 +199,7 @@ class VTKFILTERSCORE_EXPORT vtkProbeFilter : public vtkDataSetAlgorithm class vtkVectorOfArrays; vtkVectorOfArrays* CellArrays; -//ETX + }; #endif diff --git a/Filters/Core/vtkQuadricClustering.h b/Filters/Core/vtkQuadricClustering.h index a7614a68f40..55b3efe3fde 100644 --- a/Filters/Core/vtkQuadricClustering.h +++ b/Filters/Core/vtkQuadricClustering.h @@ -320,7 +320,6 @@ class VTKFILTERSCORE_EXPORT vtkQuadricClustering : public vtkPolyDataAlgorithm double ZBinStep; vtkIdType SliceSize; //eliminate one multiplication - //BTX struct PointQuadric { PointQuadric():VertexId(-1),Dimension(255) {} @@ -332,7 +331,6 @@ class VTKFILTERSCORE_EXPORT vtkQuadricClustering : public vtkPolyDataAlgorithm unsigned char Dimension; double Quadric[9]; }; - //ETX PointQuadric* QuadricArray; vtkIdType NumberOfBinsUsed; diff --git a/Filters/Core/vtkQuadricDecimation.h b/Filters/Core/vtkQuadricDecimation.h index 2c562a738f1..2cf2ef7fef5 100644 --- a/Filters/Core/vtkQuadricDecimation.h +++ b/Filters/Core/vtkQuadricDecimation.h @@ -210,12 +210,10 @@ class VTKFILTERSCORE_EXPORT vtkQuadricDecimation : public vtkPolyDataAlgorithm int NumberOfComponents; vtkPolyData *Mesh; - //BTX struct ErrorQuadric { double *Quadric; }; - //ETX ErrorQuadric *ErrorQuadrics; int AttributeComponents[6]; diff --git a/Filters/Core/vtkRearrangeFields.h b/Filters/Core/vtkRearrangeFields.h index 899c657aa1b..0823f501838 100644 --- a/Filters/Core/vtkRearrangeFields.h +++ b/Filters/Core/vtkRearrangeFields.h @@ -72,7 +72,6 @@ class VTKFILTERSCORE_EXPORT vtkRearrangeFields : public vtkDataSetAlgorithm // Create a new vtkRearrangeFields with an empty operation list. static vtkRearrangeFields *New(); -//BTX enum OperationType { COPY=0, @@ -84,7 +83,6 @@ class VTKFILTERSCORE_EXPORT vtkRearrangeFields : public vtkDataSetAlgorithm POINT_DATA=1, CELL_DATA=2 }; -//ETX // Description: // Add an operation which copies an attribute's field (data array) from @@ -133,7 +131,6 @@ class VTKFILTERSCORE_EXPORT vtkRearrangeFields : public vtkDataSetAlgorithm this->DeleteAllOperations(); } -//BTX enum FieldType { NAME, @@ -153,7 +150,6 @@ class VTKFILTERSCORE_EXPORT vtkRearrangeFields : public vtkDataSetAlgorithm Operation() { FieldName = 0; } ~Operation() { delete[] FieldName; } }; -//ETX protected: diff --git a/Filters/Core/vtkRectilinearSynchronizedTemplates.h b/Filters/Core/vtkRectilinearSynchronizedTemplates.h index f95ba03b136..ff318bd0138 100644 --- a/Filters/Core/vtkRectilinearSynchronizedTemplates.h +++ b/Filters/Core/vtkRectilinearSynchronizedTemplates.h @@ -162,11 +162,8 @@ class VTKFILTERSCORE_EXPORT vtkRectilinearSynchronizedTemplates : public vtkPoly }; // template table. -//BTX extern int VTK_RECTILINEAR_SYNCHONIZED_TEMPLATES_TABLE_1[]; extern int VTK_RECTILINEAR_SYNCHONIZED_TEMPLATES_TABLE_2[]; -//ETX - #endif diff --git a/Filters/Core/vtkResampleToImage.cxx b/Filters/Core/vtkResampleToImage.cxx index 850057b7631..3c34df68e68 100644 --- a/Filters/Core/vtkResampleToImage.cxx +++ b/Filters/Core/vtkResampleToImage.cxx @@ -15,14 +15,16 @@ #include "vtkResampleToImage.h" #include "vtkCharArray.h" +#include "vtkCompositeDataProbeFilter.h" +#include "vtkCompositeDataIterator.h" +#include "vtkCompositeDataSet.h" #include "vtkIdList.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" -#include "vtkNew.h" +#include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" -#include "vtkProbeFilter.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkUnsignedCharArray.h" @@ -49,6 +51,26 @@ vtkResampleToImage::~vtkResampleToImage() { } +//---------------------------------------------------------------------------- +void vtkResampleToImage::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "UseInputBounds " << this->UseInputBounds << endl; + os << indent << "SamplingBounds [" + << this->SamplingBounds[0] << ", " + << this->SamplingBounds[1] << ", " + << this->SamplingBounds[2] << ", " + << this->SamplingBounds[3] << ", " + << this->SamplingBounds[4] << ", " + << this->SamplingBounds[5] << "]" + << endl; + os << indent << "SamplingDimensions " + << this->SamplingDimensions[0] << " x " + << this->SamplingDimensions[1] << " x " + << this->SamplingDimensions[2] << endl; + this->Prober->PrintSelf(os, indent); +} + //---------------------------------------------------------------------------- vtkImageData* vtkResampleToImage::GetOutput() { @@ -120,6 +142,7 @@ int vtkResampleToImage::FillInputPortInformation(int vtkNotUsed(port), vtkInformation *info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet"); + info->Append(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkCompositeDataSet"); return 1; } @@ -132,19 +155,113 @@ int vtkResampleToImage::FillOutputPortInformation(int vtkNotUsed(port), } //---------------------------------------------------------------------------- -void vtkResampleToImage::SetBlankPointsAndCells(vtkImageData *data, - const char *maskArrayName) +const char* vtkResampleToImage::GetMaskArrayName() const +{ + return this->Prober->GetValidPointMaskArrayName(); +} + +//---------------------------------------------------------------------------- +namespace +{ + +inline void ComputeBoundingExtent(const double origin[3], const double spacing[3], + const double bounds[6], int extent[6]) +{ + for (int i = 0; i < 3; ++i) + { + if (spacing[i] != 0.0) + { + extent[2*i] = + static_cast(vtkMath::Floor((bounds[2*i] - origin[i])/spacing[i])); + extent[2*i + 1] = + static_cast(vtkMath::Ceil((bounds[2*i + 1] - origin[i])/spacing[i])); + } + else + { + extent[2*i] = extent[2*i + 1] = 0; + } + } +} + +} // anonymous namespace + +void vtkResampleToImage::PerformResampling(vtkDataObject *input, + const double samplingBounds[6], + bool computeProbingExtent, + const double inputBounds[6], + vtkImageData *output) { + if (this->SamplingDimensions[0] <= 0 || + this->SamplingDimensions[1] <= 0 || + this->SamplingDimensions[2] <= 0) + { + return; + } + + // compute bounds and extent where probing should be performed + double origin[3] = { samplingBounds[0], samplingBounds[2], samplingBounds[4] }; + double spacing[3]; + for (int i = 0; i < 3; ++i) + { + spacing[i] = (this->SamplingDimensions[i] == 1) ? 0 : + ((samplingBounds[i*2 + 1] - samplingBounds[i*2]) / + static_cast(this->SamplingDimensions[i] - 1)); + } + + int *updateExtent = this->GetUpdateExtent(); + int probingExtent[6]; + if (computeProbingExtent) + { + ComputeBoundingExtent(origin, spacing, inputBounds, probingExtent); + for (int i = 0; i < 3; ++i) + { + probingExtent[2*i] = vtkMath::Max(probingExtent[2*i], updateExtent[2*i]); + probingExtent[2*i + 1] = vtkMath::Min(probingExtent[2*i + 1], updateExtent[2*i + 1]); + if (probingExtent[2*i] > probingExtent[2*i + 1]) // no overlap + { + probingExtent[0] = probingExtent[2] = probingExtent[4] = 0; + probingExtent[1] = probingExtent[3] = probingExtent[5] = -1; + break; + } + } + } + else + { + std::copy(updateExtent, updateExtent + 6, probingExtent); + } + + // perform probing + vtkNew structure; + structure->SetOrigin(origin); + structure->SetSpacing(spacing); + structure->SetExtent(probingExtent); + + this->Prober->SetInputData(structure.GetPointer()); + this->Prober->SetSourceData(input); + this->Prober->Update(); + + output->ShallowCopy(this->Prober->GetOutput()); +} + +//---------------------------------------------------------------------------- +void vtkResampleToImage::SetBlankPointsAndCells(vtkImageData *data) +{ + if (data->GetNumberOfPoints() <= 0) + { + return; + } + + vtkPointData *pd = data->GetPointData(); + vtkCharArray *maskArray = vtkArrayDownCast( + pd->GetArray(this->GetMaskArrayName())); + char *mask = maskArray->GetPointer(0); + data->AllocatePointGhostArray(); vtkUnsignedCharArray *pointGhostArray = data->GetPointGhostArray(); data->AllocateCellGhostArray(); vtkUnsignedCharArray *cellGhostArray = data->GetCellGhostArray(); - vtkPointData *pd = data->GetPointData(); - vtkCharArray *maskArray = vtkCharArray::SafeDownCast(pd->GetArray(maskArrayName)); - char *mask = maskArray->GetPointer(0); - vtkNew pointCells; pointCells->Allocate(8); @@ -178,78 +295,57 @@ int vtkResampleToImage::RequestData(vtkInformation *vtkNotUsed(request), vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and output - vtkDataSet *input = vtkDataSet::SafeDownCast( - inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkDataObject *input = inInfo->Get(vtkDataObject::DATA_OBJECT()); vtkImageData *output = vtkImageData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); - if (this->SamplingDimensions[0] <= 0 || - this->SamplingDimensions[1] <= 0 || - this->SamplingDimensions[2] <= 0) - { - return 1; - } - - double inputBounds[6]; - input->GetBounds(inputBounds); - - // compute bounds and extent where probing should be performed - double *wholeBounds = this->UseInputBounds ? inputBounds : this->SamplingBounds; - double origin[3] = { wholeBounds[0], wholeBounds[2], wholeBounds[4] }; - double spacing[3]; - for (int i = 0; i < 3; ++i) - { - spacing[i] = (this->SamplingDimensions[i] == 1) ? 0 : - ((wholeBounds[i*2 + 1] - wholeBounds[i*2]) / - static_cast(this->SamplingDimensions[i] - 1)); - } - - int extent[6]; - if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT())) + double samplingBounds[6]; + if (this->UseInputBounds) { - int *updateExtent = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()); - std::copy(updateExtent, updateExtent + 6, extent); + ComputeDataBounds(input, samplingBounds); } else { - extent[0] = extent[2] = extent[4] = 0; - extent[1] = this->SamplingDimensions[0] - 1; - extent[3] = this->SamplingDimensions[1] - 1; - extent[5] = this->SamplingDimensions[2] - 1; + std::copy(this->SamplingBounds, this->SamplingBounds + 6, samplingBounds); } - // perform probing - vtkNew structure; - structure->SetOrigin(origin); - structure->SetSpacing(spacing); - structure->SetExtent(extent); + this->PerformResampling(input, samplingBounds, false, NULL, output); + this->SetBlankPointsAndCells(output); - vtkNew prober; - prober->SetInputData(structure.GetPointer()); - prober->SetSourceData(input); - prober->Update(); - - const char *maskArrayName = prober->GetValidPointMaskArrayName(); - output->ShallowCopy(prober->GetOutput()); - vtkResampleToImage::SetBlankPointsAndCells(output, maskArrayName); return 1; } + //---------------------------------------------------------------------------- -void vtkResampleToImage::PrintSelf(ostream& os, vtkIndent indent) +void vtkResampleToImage::ComputeDataBounds(vtkDataObject* data, double bounds[6]) { - this->Superclass::PrintSelf(os, indent); - os << indent << "UseInputBounds " << this->UseInputBounds << endl; - os << indent << "SamplingBounds [" - << this->SamplingBounds[0] << ", " - << this->SamplingBounds[1] << ", " - << this->SamplingBounds[2] << ", " - << this->SamplingBounds[3] << ", " - << this->SamplingBounds[4] << ", " - << this->SamplingBounds[5] << "]" - << endl; - os << indent << "SamplingDimensions " - << this->SamplingDimensions[0] << " x " - << this->SamplingDimensions[1] << " x " - << this->SamplingDimensions[2] << endl; + if (vtkDataSet::SafeDownCast(data)) + { + vtkDataSet::SafeDownCast(data)->GetBounds(bounds); + } + else + { + vtkCompositeDataSet *cdata = vtkCompositeDataSet::SafeDownCast(data); + bounds[0] = bounds[2] = bounds[4] = VTK_DOUBLE_MAX; + bounds[1] = bounds[3] = bounds[5] = -VTK_DOUBLE_MAX; + + vtkCompositeDataIterator *iter = cdata->NewIterator(); + for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) + { + vtkDataSet *ds = vtkDataSet::SafeDownCast(iter->GetCurrentDataObject()); + if (!ds) + { + vtkGenericWarningMacro("vtkCompositeDataSet leaf not vtkDataSet. Skipping."); + continue; + } + double b[6]; + ds->GetBounds(b); + for (int i = 0; i < 3; ++i) + { + bounds[2*i] = vtkMath::Min(bounds[2*i], b[2*i]); + bounds[2*i + 1] = vtkMath::Max(bounds[2*i + 1], b[2*i + 1]); + } + } + iter->Delete(); + } } diff --git a/Filters/Core/vtkResampleToImage.h b/Filters/Core/vtkResampleToImage.h index b2a0cdfab30..d422d8bf65d 100644 --- a/Filters/Core/vtkResampleToImage.h +++ b/Filters/Core/vtkResampleToImage.h @@ -24,9 +24,12 @@ #include "vtkAlgorithm.h" #include "vtkFiltersCoreModule.h" // For export macro +#include "vtkNew.h" // For vtkCompositeDataProbeFilter member variable -class vtkDataSet; + +class vtkDataObject; class vtkImageData; +class vtkCompositeDataProbeFilter; class VTKFILTERSCORE_EXPORT vtkResampleToImage : public vtkAlgorithm { @@ -74,12 +77,31 @@ class VTKFILTERSCORE_EXPORT vtkResampleToImage : public vtkAlgorithm virtual int FillInputPortInformation(int, vtkInformation *); virtual int FillOutputPortInformation(int, vtkInformation *); - static void SetBlankPointsAndCells(vtkImageData *data, - const char *maskArrayName); + // Description: + // Get the name of the valid-points mask array. + const char* GetMaskArrayName() const; + + // Description: + // Resample input vtkDataObject to a vtkImageData with the specified bounds + // and extent. + void PerformResampling(vtkDataObject *input, const double samplingBounds[6], + bool computeProbingExtent, const double inputBounds[6], + vtkImageData *output); + + // Description: + // Mark invalid points and cells of vtkImageData as hidden + void SetBlankPointsAndCells(vtkImageData *data); + + // Description: + // Helper function to compute the bounds of the given vtkDataSet or + // vtkCompositeDataSet + static void ComputeDataBounds(vtkDataObject *data, double bounds[6]); + bool UseInputBounds; double SamplingBounds[6]; int SamplingDimensions[3]; + vtkNew Prober; private: vtkResampleToImage(const vtkResampleToImage&); // Not implemented. diff --git a/Filters/Core/vtkStreamingTessellator.h b/Filters/Core/vtkStreamingTessellator.h index b84cfc5f619..f56bb138bba 100644 --- a/Filters/Core/vtkStreamingTessellator.h +++ b/Filters/Core/vtkStreamingTessellator.h @@ -86,7 +86,6 @@ class VTKFILTERSCORE_EXPORT vtkStreamingTessellator : public vtkObject static vtkStreamingTessellator* New(); virtual void PrintSelf( ostream& os, vtkIndent indent ); - //BTX typedef void (*VertexProcessorFunction)( const double*, vtkEdgeSubdivisionCriterion*, void*, const void* ); typedef void (*EdgeProcessorFunction)( const double*, const double*, vtkEdgeSubdivisionCriterion*, void*, const void* ); typedef void (*TriangleProcessorFunction)( const double*, const double*, const double*, vtkEdgeSubdivisionCriterion*, void*, const void* ); @@ -113,7 +112,6 @@ class VTKFILTERSCORE_EXPORT vtkStreamingTessellator : public vtkObject // Get/Set the function called for each output line segment (1-facet). virtual void SetVertexCallback( VertexProcessorFunction ); virtual VertexProcessorFunction GetVertexCallback() const; - //ETX // Description: // Get/Set a void pointer passed to the triangle and edge output functions. @@ -121,12 +119,11 @@ class VTKFILTERSCORE_EXPORT vtkStreamingTessellator : public vtkObject virtual void* GetPrivateData() const; // can't wrap const private data because python wrapper will try to cast it to void*, not const void* - //BTX + // Description: // Get/Set a constant void pointer passed to the simplex output functions. virtual void SetConstPrivateData( const void* ConstPrivate ); virtual const void* GetConstPrivateData() const; - //ETX // Description: // Get/Set the algorithm used to determine whether an edge should be @@ -136,9 +133,8 @@ class VTKFILTERSCORE_EXPORT vtkStreamingTessellator : public vtkObject // each call to AdaptivelySample2Facet (also recursive). virtual void SetSubdivisionAlgorithm( vtkEdgeSubdivisionCriterion* ); virtual vtkEdgeSubdivisionCriterion* GetSubdivisionAlgorithm() ; - //BTX + virtual const vtkEdgeSubdivisionCriterion* GetSubdivisionAlgorithm() const; - //ETX // Description: // Get/Set the number of parameter-space coordinates associated with each input and output point. @@ -256,16 +252,15 @@ class VTKFILTERSCORE_EXPORT vtkStreamingTessellator : public vtkObject } protected: - //BTX + static int EdgeCodesToCaseCodesPlusPermutation[64][2]; static vtkIdType PermutationsFromIndex[24][14]; static vtkIdType TetrahedralDecompositions[]; - //ETX void* PrivateData; const void* ConstPrivateData; vtkEdgeSubdivisionCriterion* Algorithm; - //BTX + VertexProcessorFunction Callback0; EdgeProcessorFunction Callback1; TriangleProcessorFunction Callback2; @@ -274,7 +269,6 @@ class VTKFILTERSCORE_EXPORT vtkStreamingTessellator : public vtkObject mutable vtkIdType CaseCounts[11]; mutable vtkIdType SubcaseCounts[11][51]; #endif // PARAVIEW_DEBUG_TESSELLATOR - //ETX // Description: // PointDimension is the length of each \p double* array associated with @@ -309,8 +303,6 @@ class VTKFILTERSCORE_EXPORT vtkStreamingTessellator : public vtkObject void operator = ( const vtkStreamingTessellator& ); // Not implemented. }; -//BTX - inline void vtkStreamingTessellator::AdaptivelySample3Facet( double* v1, double* v2, double* v3, double* v4 ) const { this->AdaptivelySample3Facet( v1, v2, v3, v4, this->MaximumNumberOfSubdivisions ); } inline void vtkStreamingTessellator::AdaptivelySample2Facet( double* v1, double* v2, double* v3 ) const @@ -326,6 +318,4 @@ inline int vtkStreamingTessellator::GetFieldSize( int k ) const inline int vtkStreamingTessellator::GetMaximumNumberOfSubdivisions() {return this->MaximumNumberOfSubdivisions;} -//ETX - #endif // vtkStreamingTessellator_h diff --git a/Filters/Core/vtkSynchronizedTemplates3D.h b/Filters/Core/vtkSynchronizedTemplates3D.h index 0d17f77cb77..f785aece85f 100644 --- a/Filters/Core/vtkSynchronizedTemplates3D.h +++ b/Filters/Core/vtkSynchronizedTemplates3D.h @@ -165,12 +165,9 @@ class VTKFILTERSCORE_EXPORT vtkSynchronizedTemplates3D : public vtkPolyDataAlgor // template table. -//BTX extern int VTKFILTERSCORE_EXPORT VTK_SYNCHRONIZED_TEMPLATES_3D_TABLE_1[]; extern int VTKFILTERSCORE_EXPORT VTK_SYNCHRONIZED_TEMPLATES_3D_TABLE_2[]; -//ETX - #endif diff --git a/Filters/Core/vtkSynchronizedTemplatesCutter3D.cxx b/Filters/Core/vtkSynchronizedTemplatesCutter3D.cxx index 9afde2f2a13..b24e85e537f 100644 --- a/Filters/Core/vtkSynchronizedTemplatesCutter3D.cxx +++ b/Filters/Core/vtkSynchronizedTemplatesCutter3D.cxx @@ -126,30 +126,31 @@ void ContourImage(vtkSynchronizedTemplatesCutter3D *self, int *exExt, vtkImageData *data, vtkPolyData *output, T *ptr, bool outputTriangles) { int *inExt = data->GetExtent(); - int xdim = exExt[1] - exExt[0] + 1; - int ydim = exExt[3] - exExt[2] + 1; + vtkIdType xdim = exExt[1] - exExt[0] + 1; + vtkIdType ydim = exExt[3] - exExt[2] + 1; double *values = self->GetValues(); int numContours = self->GetNumberOfContours(); T *inPtrX, *inPtrY, *inPtrZ; T *s0, *s1, *s2, *s3; int xMin, xMax, yMin, yMax, zMin, zMax; - int xInc, yInc, zInc; + vtkIdType xInc, yInc, zInc; int xIncFunc, yIncFunc, zIncFunc, scalarZIncFunc; double *origin = data->GetOrigin(); double *spacing = data->GetSpacing(); - int *isect1Ptr, *isect2Ptr; + vtkIdType *isect1Ptr, *isect2Ptr; double y, z, t; int i, j, k; - int zstep, yisectstep; - int offsets[12]; + vtkIdType zstep, yisectstep; + vtkIdType offsets[12]; int *tablePtr; - int idx, vidx; + vtkIdType idx; + int vidx; double x[3], xz[3]; - int v0, v1, v2, v3; + vtkIdType v0, v1, v2, v3; vtkIdType ptIds[3]; double value; // We need to know the edgePointId's for interpolating attributes. - int edgePtId, inCellId, outCellId; + vtkIdType edgePtId, inCellId, outCellId; vtkPointData *inPD = data->GetPointData(); vtkCellData *inCD = data->GetCellData(); vtkPointData *outPD = output->GetPointData(); @@ -183,7 +184,7 @@ void ContourImage(vtkSynchronizedTemplatesCutter3D *self, int *exExt, yInc = xInc*(inExt[1]-inExt[0]+1); zInc = yInc*(inExt[3]-inExt[2]+1); - // Note that the implicit functions are specified + // Note that the implicit functions are specified //over exExt so we need to compute the steps differently xIncFunc = 1; yIncFunc = xIncFunc*xdim; @@ -208,7 +209,7 @@ void ContourImage(vtkSynchronizedTemplatesCutter3D *self, int *exExt, offsets[11] = zstep*3; // allocate storage array - int *isect1 = new int [xdim*ydim*3*2]; + vtkIdType *isect1 = new vtkIdType [xdim*ydim*3*2]; // set impossible edges to -1 for (i = 0; i < ydim; i++) { diff --git a/Filters/Core/vtkTensorGlyph.h b/Filters/Core/vtkTensorGlyph.h index 7dde2e09639..33a4fdba678 100644 --- a/Filters/Core/vtkTensorGlyph.h +++ b/Filters/Core/vtkTensorGlyph.h @@ -153,13 +153,11 @@ class VTKFILTERSCORE_EXPORT vtkTensorGlyph : public vtkPolyDataAlgorithm vtkGetMacro(ColorGlyphs,int); vtkBooleanMacro(ColorGlyphs,int); -//BTX enum { COLOR_BY_SCALARS, COLOR_BY_EIGENVALUES }; -//ETX // Description: // Set the color mode to be used for the glyphs. This can be set to diff --git a/Filters/Core/vtkThreshold.h b/Filters/Core/vtkThreshold.h index 098dd0e3a04..fff71e8c7b5 100644 --- a/Filters/Core/vtkThreshold.h +++ b/Filters/Core/vtkThreshold.h @@ -172,9 +172,7 @@ class VTKFILTERSCORE_EXPORT vtkThreshold : public vtkUnstructuredGridAlgorithm int OutputPointsPrecision; int UseContinuousCellRange; - //BTX int (vtkThreshold::*ThresholdFunction)(double s); - //ETX int Lower(double s) {return ( s <= this->LowerThreshold ? 1 : 0 );}; int Upper(double s) {return ( s >= this->UpperThreshold ? 1 : 0 );}; diff --git a/Filters/Core/vtkThresholdPoints.h b/Filters/Core/vtkThresholdPoints.h index 7d63896a017..5e93b486fa5 100644 --- a/Filters/Core/vtkThresholdPoints.h +++ b/Filters/Core/vtkThresholdPoints.h @@ -77,9 +77,7 @@ class VTKFILTERSCORE_EXPORT vtkThresholdPoints : public vtkPolyDataAlgorithm double UpperThreshold; int OutputPointsPrecision; - //BTX int (vtkThresholdPoints::*ThresholdFunction)(double s); - //ETX int Lower(double s) {return ( s <= this->LowerThreshold ? 1 : 0 );}; int Upper(double s) {return ( s >= this->UpperThreshold ? 1 : 0 );}; diff --git a/Filters/Extraction/Testing/Cxx/TestExtractRectilinearGrid.cxx b/Filters/Extraction/Testing/Cxx/TestExtractRectilinearGrid.cxx index c443c02df98..191406d42fb 100644 --- a/Filters/Extraction/Testing/Cxx/TestExtractRectilinearGrid.cxx +++ b/Filters/Extraction/Testing/Cxx/TestExtractRectilinearGrid.cxx @@ -65,7 +65,7 @@ int CheckGrid( vtkRectilinearGrid* grid ) return( rc ); } - vtkDoubleArray* xyz_data = vtkDoubleArray::SafeDownCast(PD->GetArray("xyz")); + vtkDoubleArray* xyz_data = vtkArrayDownCast(PD->GetArray("xyz")); double* xyz = static_cast( xyz_data->GetVoidPointer(0)); vtkIdType npoints = grid->GetNumberOfPoints(); diff --git a/Filters/Extraction/vtkConvertSelection.cxx b/Filters/Extraction/vtkConvertSelection.cxx index b76710fc8fb..02568b7fd21 100644 --- a/Filters/Extraction/vtkConvertSelection.cxx +++ b/Filters/Extraction/vtkConvertSelection.cxx @@ -21,7 +21,6 @@ #include "vtkCellData.h" #include "vtkCommand.h" #include "vtkCompositeDataSet.h" -#include "vtkDataArrayTemplate.h" #include "vtkDataSet.h" #include "vtkDoubleArray.h" #include "vtkExtractSelectedThresholds.h" @@ -192,12 +191,12 @@ int vtkConvertSelection::ConvertToIndexSelection( vtkSignedCharArray* insidedness = 0; if (type == vtkSelectionNode::CELL) { - insidedness = vtkSignedCharArray::SafeDownCast( + insidedness = vtkArrayDownCast( extracted->GetCellData()->GetAbstractArray("vtkInsidedness")); } else if (type == vtkSelectionNode::POINT) { - insidedness = vtkSignedCharArray::SafeDownCast( + insidedness = vtkArrayDownCast( extracted->GetPointData()->GetAbstractArray("vtkInsidedness")); } else @@ -572,7 +571,7 @@ int vtkConvertSelection::Convert( } else if (inputNode->GetContentType() == vtkSelectionNode::THRESHOLDS) { - vtkDoubleArray *lims = vtkDoubleArray::SafeDownCast(inputNode->GetSelectionList()); + vtkDoubleArray *lims = vtkArrayDownCast(inputNode->GetSelectionList()); if (!lims) { vtkErrorMacro("Thresholds selection requires vtkDoubleArray selection list."); @@ -581,11 +580,11 @@ int vtkConvertSelection::Convert( vtkDataArray *dataArr = 0; if (dsa) { - dataArr = vtkDataArray::SafeDownCast(dsa->GetAbstractArray(lims->GetName())); + dataArr = vtkArrayDownCast(dsa->GetAbstractArray(lims->GetName())); } else if (fd) { - dataArr = vtkDataArray::SafeDownCast(fd->GetAbstractArray(lims->GetName())); + dataArr = vtkArrayDownCast(fd->GetAbstractArray(lims->GetName())); } if (!dataArr) { @@ -669,7 +668,7 @@ int vtkConvertSelection::Convert( } // Handle the special case where we have a domain array. - vtkStringArray* domainArr = dsa ? vtkStringArray::SafeDownCast(dsa->GetAbstractArray("domain")) : 0; + vtkStringArray* domainArr = dsa ? vtkArrayDownCast(dsa->GetAbstractArray("domain")) : 0; if (inputNode->GetContentType() == vtkSelectionNode::PEDIGREEIDS && domainArr && selArr->GetName()) { @@ -736,7 +735,7 @@ int vtkConvertSelection::Convert( } // Handle the special case where we have a pedigree id selection with a domain array. - vtkStringArray* outputDomainArr = dsa ? vtkStringArray::SafeDownCast( + vtkStringArray* outputDomainArr = dsa ? vtkArrayDownCast( dsa->GetAbstractArray("domain")) : 0; if (this->OutputType == vtkSelectionNode::PEDIGREEIDS && outputDomainArr) { @@ -951,7 +950,7 @@ void vtkConvertSelection::GetSelectedItems( for (unsigned int n = 0; n < indexSel->GetNumberOfNodes(); ++n) { vtkSelectionNode* node = indexSel->GetNode(n); - vtkIdTypeArray* list = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkIdTypeArray* list = vtkArrayDownCast(node->GetSelectionList()); if (node->GetFieldType() == fieldType && node->GetContentType() == vtkSelectionNode::INDICES && list) { for (vtkIdType i = 0; i < list->GetNumberOfTuples(); ++i) diff --git a/Filters/Extraction/vtkExtractArraysOverTime.cxx b/Filters/Extraction/vtkExtractArraysOverTime.cxx index 5c7fb33db40..5ddf3c4812d 100644 --- a/Filters/Extraction/vtkExtractArraysOverTime.cxx +++ b/Filters/Extraction/vtkExtractArraysOverTime.cxx @@ -264,7 +264,7 @@ void vtkExtractArraysOverTime::vtkInternal::AddTimeStepInternalForLocations( } vtkDataSetAttributes* inDSA = input->GetPointData(); - vtkCharArray* validMask = vtkCharArray::SafeDownCast( + vtkCharArray* validMask = vtkArrayDownCast( inDSA->GetArray("vtkValidPointMask")); if (!validMask) @@ -493,7 +493,7 @@ void vtkExtractArraysOverTime::vtkInternal::AddTimeStepInternalForQuery( vtkExtractArraysAddColumnValue( statSummary.GetPointer(), maxName.str(), cType, model->GetValue(4, 1)); } - if (vtkDataArray::SafeDownCast(col)) + if (vtkArrayDownCast(col)) { descrStats->ResetRequests(); descrStats->AddColumn(cname); @@ -601,11 +601,11 @@ void vtkExtractArraysOverTime::vtkInternal::AddTimeStepInternal( } vtkIdTypeArray* idsArray = - vtkIdTypeArray::SafeDownCast(inDSA->GetArray(idarrayname)); + vtkArrayDownCast(inDSA->GetArray(idarrayname)); if (this->ContentType == vtkSelectionNode::GLOBALIDS) { - idsArray = vtkIdTypeArray::SafeDownCast(inDSA->GetGlobalIds()); + idsArray = vtkArrayDownCast(inDSA->GetGlobalIds()); } if (!idsArray) @@ -647,7 +647,7 @@ void vtkExtractArraysOverTime::vtkInternal::AddTimeStepInternal( std::ostringstream stream; if (this->ContentType == vtkSelectionNode::GLOBALIDS) { - vtkIdTypeArray* gidsArray = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* gidsArray = vtkArrayDownCast( inDSA->GetGlobalIds()); if (gidsArray) { diff --git a/Filters/Extraction/vtkExtractArraysOverTime.h b/Filters/Extraction/vtkExtractArraysOverTime.h index 44713329724..30b2838e339 100644 --- a/Filters/Extraction/vtkExtractArraysOverTime.h +++ b/Filters/Extraction/vtkExtractArraysOverTime.h @@ -86,7 +86,6 @@ class VTKFILTERSEXTRACTION_EXPORT vtkExtractArraysOverTime : public vtkMultiBloc vtkGetMacro(ReportStatisticsOnly,int); vtkBooleanMacro(ReportStatisticsOnly,int); -//BTX protected: vtkExtractArraysOverTime(); ~vtkExtractArraysOverTime(); @@ -147,7 +146,6 @@ class VTKFILTERSEXTRACTION_EXPORT vtkExtractArraysOverTime : public vtkMultiBloc class vtkInternal; vtkInternal *Internal; -//ETX }; #endif diff --git a/Filters/Extraction/vtkExtractBlock.h b/Filters/Extraction/vtkExtractBlock.h index de472219cb9..ece446cbe8a 100644 --- a/Filters/Extraction/vtkExtractBlock.h +++ b/Filters/Extraction/vtkExtractBlock.h @@ -64,7 +64,6 @@ class VTKFILTERSEXTRACTION_EXPORT vtkExtractBlock : public vtkMultiBlockDataSetA vtkGetMacro(MaintainStructure, int); vtkBooleanMacro(MaintainStructure, int); -//BTX protected: vtkExtractBlock(); ~vtkExtractBlock(); @@ -95,7 +94,7 @@ class VTKFILTERSEXTRACTION_EXPORT vtkExtractBlock : public vtkMultiBlockDataSetA class vtkSet; vtkSet *Indices; vtkSet *ActiveIndices; -//ETX + }; #endif diff --git a/Filters/Extraction/vtkExtractDataSets.h b/Filters/Extraction/vtkExtractDataSets.h index ad3f2d3a2fc..2f6a2f9b302 100644 --- a/Filters/Extraction/vtkExtractDataSets.h +++ b/Filters/Extraction/vtkExtractDataSets.h @@ -45,7 +45,6 @@ class VTKFILTERSEXTRACTION_EXPORT vtkExtractDataSets : // Remove all entries from the list of datasets to be extracted. void ClearDataSetList(); -//BTX protected: vtkExtractDataSets(); ~vtkExtractDataSets(); @@ -62,7 +61,7 @@ class VTKFILTERSEXTRACTION_EXPORT vtkExtractDataSets : class vtkInternals; vtkInternals* Internals; -//ETX + }; #endif diff --git a/Filters/Extraction/vtkExtractLevel.h b/Filters/Extraction/vtkExtractLevel.h index 788a6cb9150..749ea4c6390 100644 --- a/Filters/Extraction/vtkExtractLevel.h +++ b/Filters/Extraction/vtkExtractLevel.h @@ -40,7 +40,6 @@ class VTKFILTERSEXTRACTION_EXPORT vtkExtractLevel : void RemoveLevel(unsigned int level); void RemoveAllLevels(); -//BTX protected: vtkExtractLevel(); ~vtkExtractLevel(); @@ -61,7 +60,7 @@ class VTKFILTERSEXTRACTION_EXPORT vtkExtractLevel : class vtkSet; vtkSet* Levels; -//ETX + }; #endif diff --git a/Filters/Extraction/vtkExtractSelectedBlock.cxx b/Filters/Extraction/vtkExtractSelectedBlock.cxx index 8bbe5d29a97..bbdd90543f8 100644 --- a/Filters/Extraction/vtkExtractSelectedBlock.cxx +++ b/Filters/Extraction/vtkExtractSelectedBlock.cxx @@ -124,7 +124,7 @@ int vtkExtractSelectedBlock::RequestData( node->GetProperties()->Get(vtkSelectionNode::INVERSE()) == 1); output->CopyStructure(cd); - vtkDataArray* selectionList = vtkDataArray::SafeDownCast( + vtkDataArray* selectionList = vtkArrayDownCast( node->GetSelectionList()); std::set blocks; if (selectionList) diff --git a/Filters/Extraction/vtkExtractSelectedBlock.h b/Filters/Extraction/vtkExtractSelectedBlock.h index 9a282add847..fa8a42dd49a 100644 --- a/Filters/Extraction/vtkExtractSelectedBlock.h +++ b/Filters/Extraction/vtkExtractSelectedBlock.h @@ -28,7 +28,6 @@ class VTKFILTERSEXTRACTION_EXPORT vtkExtractSelectedBlock : public vtkExtractSel vtkTypeMacro(vtkExtractSelectedBlock, vtkExtractSelectionBase); void PrintSelf(ostream& os, vtkIndent indent); -//BTX protected: vtkExtractSelectedBlock(); ~vtkExtractSelectedBlock(); @@ -47,7 +46,7 @@ class VTKFILTERSEXTRACTION_EXPORT vtkExtractSelectedBlock : public vtkExtractSel private: vtkExtractSelectedBlock(const vtkExtractSelectedBlock&); // Not implemented. void operator=(const vtkExtractSelectedBlock&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/Extraction/vtkExtractSelectedIds.cxx b/Filters/Extraction/vtkExtractSelectedIds.cxx index 0cb22a522aa..cde3f76dd1e 100644 --- a/Filters/Extraction/vtkExtractSelectedIds.cxx +++ b/Filters/Extraction/vtkExtractSelectedIds.cxx @@ -644,7 +644,7 @@ int vtkExtractSelectedIds::ExtractCells( int selType = sel->GetProperties()->Get(vtkSelectionNode::CONTENT_TYPE()); if (selType == vtkSelectionNode::GLOBALIDS) { - labelArray = vtkIdTypeArray::SafeDownCast( + labelArray = vtkArrayDownCast( input->GetCellData()->GetGlobalIds()); } else if (selType == vtkSelectionNode::PEDIGREEIDS) @@ -718,8 +718,8 @@ int vtkExtractSelectedIds::ExtractCells( } // Array types must match if they are string arrays. - if (vtkStringArray::SafeDownCast(labelArray) && - vtkStringArray::SafeDownCast(idArray) == NULL) + if (vtkArrayDownCast(labelArray) && + vtkArrayDownCast(idArray) == NULL) { labelArray->Delete(); idxArray->Delete(); @@ -847,7 +847,7 @@ int vtkExtractSelectedIds::ExtractPoints( int selType = sel->GetProperties()->Get(vtkSelectionNode::CONTENT_TYPE()); if (selType == vtkSelectionNode::GLOBALIDS) { - labelArray = vtkIdTypeArray::SafeDownCast( + labelArray = vtkArrayDownCast( input->GetPointData()->GetGlobalIds()); } else if (selType == vtkSelectionNode::PEDIGREEIDS) @@ -910,8 +910,8 @@ int vtkExtractSelectedIds::ExtractPoints( } // Array types must match if they are string arrays. - if (vtkStringArray::SafeDownCast(labelArray) && - vtkStringArray::SafeDownCast(idArray) == NULL) + if (vtkArrayDownCast(labelArray) && + vtkArrayDownCast(idArray) == NULL) { vtkWarningMacro( "Array types don't match. They must match for vtkStringArray."); diff --git a/Filters/Extraction/vtkExtractSelectedLocations.cxx b/Filters/Extraction/vtkExtractSelectedLocations.cxx index bb96e0a5345..09ff90098a7 100644 --- a/Filters/Extraction/vtkExtractSelectedLocations.cxx +++ b/Filters/Extraction/vtkExtractSelectedLocations.cxx @@ -206,7 +206,7 @@ int vtkExtractSelectedLocations::ExtractCells( { //get a hold of input data structures and allocate output data structures vtkDoubleArray *locArray = - vtkDoubleArray::SafeDownCast(sel->GetSelectionList()); + vtkArrayDownCast(sel->GetSelectionList()); if (!locArray) { @@ -358,7 +358,7 @@ int vtkExtractSelectedLocations::ExtractPoints( { //get a hold of input data structures and allocate output data structures vtkDoubleArray *locArray = - vtkDoubleArray::SafeDownCast(sel->GetSelectionList()); + vtkArrayDownCast(sel->GetSelectionList()); if (!locArray) { return 1; diff --git a/Filters/Extraction/vtkExtractSelectedPolyDataIds.cxx b/Filters/Extraction/vtkExtractSelectedPolyDataIds.cxx index 6f8ac3de203..fcf146cc5fb 100644 --- a/Filters/Extraction/vtkExtractSelectedPolyDataIds.cxx +++ b/Filters/Extraction/vtkExtractSelectedPolyDataIds.cxx @@ -90,7 +90,7 @@ int vtkExtractSelectedPolyDataIds::RequestData( } vtkIdTypeArray* idArray = - vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkArrayDownCast(node->GetSelectionList()); if (!idArray) { diff --git a/Filters/Extraction/vtkExtractSelectedThresholds.cxx b/Filters/Extraction/vtkExtractSelectedThresholds.cxx index c8b7e663f9c..ece39b8cee3 100644 --- a/Filters/Extraction/vtkExtractSelectedThresholds.cxx +++ b/Filters/Extraction/vtkExtractSelectedThresholds.cxx @@ -142,7 +142,7 @@ int vtkExtractSelectedThresholds::ExtractCells( int usePointScalars) { //find the values to threshold within - vtkDataArray *lims = vtkDataArray::SafeDownCast(sel->GetSelectionList()); + vtkDataArray *lims = vtkArrayDownCast(sel->GetSelectionList()); if (lims == NULL) { vtkErrorMacro(<<"No values to threshold with"); @@ -412,7 +412,7 @@ int vtkExtractSelectedThresholds::ExtractPoints( vtkDataSet *output) { //find the values to threshold within - vtkDataArray *lims = vtkDataArray::SafeDownCast(sel->GetSelectionList()); + vtkDataArray *lims = vtkArrayDownCast(sel->GetSelectionList()); if (lims == NULL) { vtkErrorMacro(<<"No values to threshold with"); @@ -552,7 +552,7 @@ int vtkExtractSelectedThresholds::ExtractRows( vtkSelectionNode* sel, vtkTable* input, vtkTable* output) { //find the values to threshold within - vtkDataArray *lims = vtkDataArray::SafeDownCast(sel->GetSelectionList()); + vtkDataArray *lims = vtkArrayDownCast(sel->GetSelectionList()); if (lims == NULL) { vtkErrorMacro(<<"No values to threshold with"); diff --git a/Filters/Extraction/vtkHierarchicalDataExtractDataSets.h b/Filters/Extraction/vtkHierarchicalDataExtractDataSets.h index 219824e01b1..b3c87ce6698 100644 --- a/Filters/Extraction/vtkHierarchicalDataExtractDataSets.h +++ b/Filters/Extraction/vtkHierarchicalDataExtractDataSets.h @@ -25,9 +25,7 @@ #include "vtkFiltersExtractionModule.h" // For export macro #include "vtkExtractDataSets.h" -//BTX struct vtkHierarchicalDataExtractDataSetsInternals; -//ETX class VTKFILTERSEXTRACTION_EXPORT vtkHierarchicalDataExtractDataSets : public vtkExtractDataSets diff --git a/Filters/Extraction/vtkProbeSelectedLocations.cxx b/Filters/Extraction/vtkProbeSelectedLocations.cxx index 93dadf328da..948a9c80ca6 100644 --- a/Filters/Extraction/vtkProbeSelectedLocations.cxx +++ b/Filters/Extraction/vtkProbeSelectedLocations.cxx @@ -96,7 +96,7 @@ int vtkProbeSelectedLocations::RequestData(vtkInformation *vtkNotUsed(request), tempInput->SetPoints(points); points->Delete(); - vtkDataArray* dA = vtkDataArray::SafeDownCast( + vtkDataArray* dA = vtkArrayDownCast( node->GetSelectionList()); if (!dA) { diff --git a/Filters/Extraction/vtkProbeSelectedLocations.h b/Filters/Extraction/vtkProbeSelectedLocations.h index 4a72908c676..bc3c138ae68 100644 --- a/Filters/Extraction/vtkProbeSelectedLocations.h +++ b/Filters/Extraction/vtkProbeSelectedLocations.h @@ -35,7 +35,6 @@ class VTKFILTERSEXTRACTION_EXPORT vtkProbeSelectedLocations : public vtkExtractS vtkTypeMacro(vtkProbeSelectedLocations, vtkExtractSelectionBase); void PrintSelf(ostream& os, vtkIndent indent); -//BTX protected: vtkProbeSelectedLocations(); ~vtkProbeSelectedLocations(); @@ -52,7 +51,7 @@ class VTKFILTERSEXTRACTION_EXPORT vtkProbeSelectedLocations : public vtkExtractS private: vtkProbeSelectedLocations(const vtkProbeSelectedLocations&); // Not implemented. void operator=(const vtkProbeSelectedLocations&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/FlowPaths/Testing/Cxx/TestParticleTracers.cxx b/Filters/FlowPaths/Testing/Cxx/TestParticleTracers.cxx index e586f5dcab4..6dd70f251b0 100644 --- a/Filters/FlowPaths/Testing/Cxx/TestParticleTracers.cxx +++ b/Filters/FlowPaths/Testing/Cxx/TestParticleTracers.cxx @@ -177,7 +177,7 @@ class TestTimeSource : public vtkAlgorithm return 0 ; } - vtkDataArray* outArray = vtkDataArray::SafeDownCast(vtkAbstractArray::CreateArray(VTK_FLOAT)); + vtkDataArray* outArray = vtkArrayDownCast(vtkAbstractArray::CreateArray(VTK_FLOAT)); outArray->SetName("Gradients"); outArray->SetNumberOfComponents(3); outArray->SetNumberOfTuples(outImage->GetNumberOfPoints()); @@ -269,7 +269,7 @@ int TestParticlePathFilter() vtkPolyData* out = filter->GetOutput(); vtkCellArray* lines = out->GetLines(); vtkNew polyLine; -// vtkIntArray* particleIds = vtkIntArray::SafeDownCast(out->GetPointData()->GetArray("ParticleId")); +// vtkIntArray* particleIds = vtkArrayDownCast(out->GetPointData()->GetArray("ParticleId")); @@ -358,7 +358,7 @@ int TestStreaklineFilter() vtkCellArray* lines = out->GetLines(); vtkNew polyLine; - vtkFloatArray* particleAge = vtkFloatArray::SafeDownCast(out->GetPointData()->GetArray("ParticleAge")); + vtkFloatArray* particleAge = vtkArrayDownCast(out->GetPointData()->GetArray("ParticleAge")); lines->InitTraversal(); while(lines->GetNextCell(polyLine.GetPointer())) diff --git a/Filters/FlowPaths/vtkAbstractInterpolatedVelocityField.h b/Filters/FlowPaths/vtkAbstractInterpolatedVelocityField.h index a9c7060fbab..3d5458dc123 100644 --- a/Filters/FlowPaths/vtkAbstractInterpolatedVelocityField.h +++ b/Filters/FlowPaths/vtkAbstractInterpolatedVelocityField.h @@ -65,14 +65,13 @@ #define vtkAbstractInterpolatedVelocityField_h #include "vtkFunctionSet.h" -//BTX + #include // STL Header; Required for vector -//ETX class vtkDataSet; -//BTX + class vtkDataArray; -//ETX + class vtkPointData; class vtkGenericCell; class vtkAbstractInterpolatedVelocityFieldDataSetsType; @@ -226,7 +225,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkAbstractInterpolatedVelocityField : public v // using FindPoint and comparing distance with tolerance virtual bool FindAndUpdateCell(vtkDataSet* ds, double* x); -//BTX friend class vtkTemporalInterpolatedVelocityField; // Description: // If all weights have been computed (parametric coords etc all valid), a @@ -237,7 +235,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkAbstractInterpolatedVelocityField : public v bool InterpolatePoint( vtkPointData * outPD, vtkIdType outIndex ); vtkGenericCell * GetLastCell() { return ( this->LastCellId != -1 ) ? this->GenCell : NULL; } -//ETX private: vtkAbstractInterpolatedVelocityField diff --git a/Filters/FlowPaths/vtkCachingInterpolatedVelocityField.cxx b/Filters/FlowPaths/vtkCachingInterpolatedVelocityField.cxx index 23724b7a769..d21bb2a826c 100644 --- a/Filters/FlowPaths/vtkCachingInterpolatedVelocityField.cxx +++ b/Filters/FlowPaths/vtkCachingInterpolatedVelocityField.cxx @@ -68,13 +68,13 @@ void IVFDataSetInfo::SetDataSet(vtkDataSet *data, char *velocity, bool staticdat this->DataSet->GetLength() * IVFDataSetInfo::TOLERANCE_SCALE; // vtkDataArray *vectors = this->DataSet->GetPointData()->GetArray(velocity); - if (vtkFloatArray::SafeDownCast(vectors)) + if (vtkArrayDownCast(vectors)) { - this->VelocityFloat = vtkFloatArray::SafeDownCast(vectors)->GetPointer(0); + this->VelocityFloat = vtkArrayDownCast(vectors)->GetPointer(0); } - else if (vtkDoubleArray::SafeDownCast(vectors)) + else if (vtkArrayDownCast(vectors)) { - this->VelocityDouble = vtkDoubleArray::SafeDownCast(vectors)->GetPointer(0); + this->VelocityDouble = vtkArrayDownCast(vectors)->GetPointer(0); } else { diff --git a/Filters/FlowPaths/vtkCachingInterpolatedVelocityField.h b/Filters/FlowPaths/vtkCachingInterpolatedVelocityField.h index e0ba1262d1a..bdee5c77740 100644 --- a/Filters/FlowPaths/vtkCachingInterpolatedVelocityField.h +++ b/Filters/FlowPaths/vtkCachingInterpolatedVelocityField.h @@ -44,22 +44,21 @@ #include "vtkFiltersFlowPathsModule.h" // For export macro #include "vtkFunctionSet.h" #include "vtkSmartPointer.h" // this is allowed -//BTX + #include // we need them -//ETX class vtkDataSet; class vtkDataArray; class vtkPointData; class vtkGenericCell; class vtkAbstractCellLocator; -//BTX + //--------------------------------------------------------------------------- class IVFDataSetInfo; //--------------------------------------------------------------------------- class IVFCacheList : public std::vector< IVFDataSetInfo > {}; //--------------------------------------------------------------------------- -//ETX + class VTKFILTERSFLOWPATHS_EXPORT vtkCachingInterpolatedVelocityField : public vtkFunctionSet { public: @@ -126,9 +125,8 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkCachingInterpolatedVelocityField : public vt IVFDataSetInfo *Cache; IVFCacheList CacheList; char *VectorsSelection; -//BTX + std::vector Weights; -//ETX vtkSetStringMacro(VectorsSelection); @@ -137,7 +135,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkCachingInterpolatedVelocityField : public vt int FunctionValues(IVFDataSetInfo *cache, double *x, double *f); int InsideTest(IVFDataSetInfo *cache, double* x); -//BTX friend class vtkTemporalInterpolatedVelocityField; // Description: // If all weights have been computed (parametric coords etc all valid) @@ -150,7 +147,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkCachingInterpolatedVelocityField : public vt bool InterpolatePoint(vtkCachingInterpolatedVelocityField *inCIVF, vtkPointData *outPD, vtkIdType outIndex); vtkGenericCell *GetLastCell(); -//ETX private: vtkCachingInterpolatedVelocityField(const vtkCachingInterpolatedVelocityField&); // Not implemented. @@ -164,7 +160,7 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkCachingInterpolatedVelocityField : public vt /////////////////////////////////////////////////////////////////////////////// #ifndef DOXYGEN_SHOULD_SKIP_THIS // -//BTX + // class IVFDataSetInfo { @@ -186,7 +182,7 @@ class IVFDataSetInfo }; // -//ETX + // #endif /* DOXYGEN_SHOULD_SKIP_THIS */ diff --git a/Filters/FlowPaths/vtkCompositeInterpolatedVelocityField.h b/Filters/FlowPaths/vtkCompositeInterpolatedVelocityField.h index c6f3fd6df2f..3c36a3cb5a3 100644 --- a/Filters/FlowPaths/vtkCompositeInterpolatedVelocityField.h +++ b/Filters/FlowPaths/vtkCompositeInterpolatedVelocityField.h @@ -67,14 +67,12 @@ #include "vtkFiltersFlowPathsModule.h" // For export macro #include "vtkAbstractInterpolatedVelocityField.h" -//BTX #include // STL Header; Required for vector -//ETX class vtkDataSet; -//BTX + class vtkDataArray; -//ETX + class vtkPointData; class vtkGenericCell; class vtkCompositeInterpolatedVelocityFieldDataSetsType; @@ -119,9 +117,7 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkCompositeInterpolatedVelocityField : public void operator = ( const vtkCompositeInterpolatedVelocityField & ); // Not implemented. }; -//BTX typedef std::vector< vtkDataSet * > DataSetsTypeBase; class vtkCompositeInterpolatedVelocityFieldDataSetsType: public DataSetsTypeBase { }; -//ETX #endif diff --git a/Filters/FlowPaths/vtkModifiedBSPTree.h b/Filters/FlowPaths/vtkModifiedBSPTree.h index 5db1b6fd1bf..181800aafaa 100644 --- a/Filters/FlowPaths/vtkModifiedBSPTree.h +++ b/Filters/FlowPaths/vtkModifiedBSPTree.h @@ -144,13 +144,11 @@ #include "vtkAbstractCellLocator.h" #include "vtkSmartPointer.h" // required because it is nice -//BTX class Sorted_cell_extents_Lists; class BSPNode; class vtkGenericCell; class vtkIdList; class vtkIdListCollection; -//ETX class VTKFILTERSFLOWPATHS_EXPORT vtkModifiedBSPTree : public vtkAbstractCellLocator { public: @@ -175,7 +173,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkModifiedBSPTree : public vtkAbstractCellLoca // Build Tree void BuildLocator(); -//BTX // Description: // Generate BBox representation of Nth level virtual void GenerateRepresentation(int level, vtkPolyData *pd); @@ -223,7 +220,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkModifiedBSPTree : public vtkAbstractCellLoca // which holds a cell Id list for each leaf node. vtkIdListCollection *GetLeafNodeCellInformation(); -//ETX protected: vtkModifiedBSPTree(); ~vtkModifiedBSPTree(); @@ -232,7 +228,7 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkModifiedBSPTree : public vtkAbstractCellLoca int npn; int nln; int tot_depth; -//BTX + // // The main subdivision routine void Subdivide(BSPNode *node, Sorted_cell_extents_Lists *lists, vtkDataSet *dataSet, @@ -245,7 +241,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkModifiedBSPTree : public vtkAbstractCellLoca virtual int IntersectCellInternal(vtkIdType cell_ID, const double p1[3], const double p2[3], const double tol, double &t, double ipt[3], double pcoords[3], int &subId); -//ETX void BuildLocatorIfNeeded(); void ForceBuildLocator(); void BuildLocatorInternal(); @@ -254,8 +249,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkModifiedBSPTree : public vtkAbstractCellLoca void operator=(const vtkModifiedBSPTree&); // Not implemented. }; -//BTX - /////////////////////////////////////////////////////////////////////////////// // BSP Node // A BSP Node is a BBox - axis aligned etc etc @@ -315,6 +308,4 @@ class BSPNode { #endif /* DOXYGEN_SHOULD_SKIP_THIS */ -//ETX - #endif diff --git a/Filters/FlowPaths/vtkParticlePathFilter.cxx b/Filters/FlowPaths/vtkParticlePathFilter.cxx index 1aa2fe14d8b..2c040c9dc71 100644 --- a/Filters/FlowPaths/vtkParticlePathFilter.cxx +++ b/Filters/FlowPaths/vtkParticlePathFilter.cxx @@ -68,7 +68,7 @@ int ParticlePathFilterInternal::OutputParticles(vtkPolyData* particles) //Get the input arrays vtkPointData* pd = particles->GetPointData(); - vtkIntArray* particleIds = vtkIntArray::SafeDownCast(pd->GetArray("ParticleId")); + vtkIntArray* particleIds = vtkArrayDownCast(pd->GetArray("ParticleId")); //Append the input arrays to the output arrays int begin = outPoints->GetNumberOfPoints(); @@ -99,7 +99,7 @@ int ParticlePathFilterInternal::OutputParticles(vtkPolyData* particles) #ifdef DEBUG if(path->GetNumberOfIds()>0) { - vtkFloatArray* outParticleAge = vtkFloatArray::SafeDownCast(outPd->GetArray("ParticleAge")); + vtkFloatArray* outParticleAge = vtkArrayDownCast(outPd->GetArray("ParticleAge")); if(outParticleAge->GetValue(outId) < outParticleAge->GetValue(path->GetId(path->GetNumberOfIds()-1))) { vtkOStrStreamWrapper vtkmsg; diff --git a/Filters/FlowPaths/vtkParticleTracerBase.cxx b/Filters/FlowPaths/vtkParticleTracerBase.cxx index f1b96a7187c..aafb3cd6b27 100644 --- a/Filters/FlowPaths/vtkParticleTracerBase.cxx +++ b/Filters/FlowPaths/vtkParticleTracerBase.cxx @@ -133,7 +133,7 @@ vtkParticleTracerBase::vtkParticleTracerBase() this->SetNumberOfInputPorts(2); #ifdef JB_H5PART_PARTICLE_OUTPUT -#ifdef WIN32 +#ifdef _WIN32 vtkDebugMacro(<<"Setting vtkH5PartWriter"); vtkH5PartWriter *writer = vtkH5PartWriter::New(); #else @@ -1647,55 +1647,55 @@ void vtkParticleTracerBase::GetPointDataArrayNames( //--------------------------------------------------------------------------- vtkFloatArray* vtkParticleTracerBase::GetParticleAge(vtkPointData* pd) { - return vtkFloatArray::SafeDownCast(pd->GetArray("ParticleAge")); + return vtkArrayDownCast(pd->GetArray("ParticleAge")); } //--------------------------------------------------------------------------- vtkIntArray* vtkParticleTracerBase::GetParticleIds(vtkPointData* pd) { - return vtkIntArray::SafeDownCast(pd->GetArray("ParticleId")); + return vtkArrayDownCast(pd->GetArray("ParticleId")); } //--------------------------------------------------------------------------- vtkCharArray* vtkParticleTracerBase::GetParticleSourceIds(vtkPointData* pd) { - return vtkCharArray::SafeDownCast(pd->GetArray("ParticleSourceId")); + return vtkArrayDownCast(pd->GetArray("ParticleSourceId")); } //--------------------------------------------------------------------------- vtkIntArray* vtkParticleTracerBase::GetInjectedPointIds(vtkPointData* pd) { - return vtkIntArray::SafeDownCast(pd->GetArray("InjectedPointId")); + return vtkArrayDownCast(pd->GetArray("InjectedPointId")); } //--------------------------------------------------------------------------- vtkIntArray* vtkParticleTracerBase::GetInjectedStepIds(vtkPointData* pd) { - return vtkIntArray::SafeDownCast(pd->GetArray("InjectionStepId")); + return vtkArrayDownCast(pd->GetArray("InjectionStepId")); } //--------------------------------------------------------------------------- vtkIntArray* vtkParticleTracerBase::GetErrorCodeArr(vtkPointData* pd) { - return vtkIntArray::SafeDownCast(pd->GetArray("ErrorCode")); + return vtkArrayDownCast(pd->GetArray("ErrorCode")); } //--------------------------------------------------------------------------- vtkFloatArray* vtkParticleTracerBase::GetParticleVorticity(vtkPointData* pd) { - return vtkFloatArray::SafeDownCast(pd->GetArray("Vorticity")); + return vtkArrayDownCast(pd->GetArray("Vorticity")); } //--------------------------------------------------------------------------- vtkFloatArray* vtkParticleTracerBase::GetParticleRotation(vtkPointData* pd) { - return vtkFloatArray::SafeDownCast(pd->GetArray("Rotation")); + return vtkArrayDownCast(pd->GetArray("Rotation")); } //--------------------------------------------------------------------------- vtkFloatArray* vtkParticleTracerBase::GetParticleAngularVel(vtkPointData* pd) { - return vtkFloatArray::SafeDownCast(pd->GetArray("AngularVelocity")); + return vtkArrayDownCast(pd->GetArray("AngularVelocity")); } //--------------------------------------------------------------------------- diff --git a/Filters/FlowPaths/vtkParticleTracerBase.h b/Filters/FlowPaths/vtkParticleTracerBase.h index 5be006ea999..df9746d979e 100644 --- a/Filters/FlowPaths/vtkParticleTracerBase.h +++ b/Filters/FlowPaths/vtkParticleTracerBase.h @@ -28,10 +28,9 @@ #include "vtkFiltersFlowPathsModule.h" // For export macro #include "vtkSmartPointer.h" // For protected ivars. #include "vtkPolyDataAlgorithm.h" -//BTX + #include // STL Header #include // STL Header -//ETX class vtkAbstractInterpolatedVelocityField; class vtkAbstractParticleWriter; @@ -52,7 +51,6 @@ class vtkPoints; class vtkPolyData; class vtkTemporalInterpolatedVelocityField; -//BTX namespace vtkParticleTracerBaseNamespace { typedef struct { double x[4]; } Position; @@ -90,7 +88,6 @@ namespace vtkParticleTracerBaseNamespace typedef std::list ParticleDataList; typedef ParticleDataList::iterator ParticleListIterator; }; -//ETX class VTKFILTERSFLOWPATHS_EXPORT vtkParticleTracerBase : public vtkPolyDataAlgorithm { diff --git a/Filters/FlowPaths/vtkStreaklineFilter.cxx b/Filters/FlowPaths/vtkStreaklineFilter.cxx index b4dd8226c62..2bf5ff1c69e 100644 --- a/Filters/FlowPaths/vtkStreaklineFilter.cxx +++ b/Filters/FlowPaths/vtkStreaklineFilter.cxx @@ -82,9 +82,9 @@ void StreaklineFilterInternal::Finalize() vtkPointData* pd = this->Filter->Output->GetPointData(); Assert(pd); - vtkFloatArray* particleAge = vtkFloatArray::SafeDownCast(pd->GetArray("ParticleAge")); + vtkFloatArray* particleAge = vtkArrayDownCast(pd->GetArray("ParticleAge")); Assert(particleAge); - vtkIntArray* seedIds = vtkIntArray::SafeDownCast(pd->GetArray("InjectedPointId")); + vtkIntArray* seedIds = vtkArrayDownCast(pd->GetArray("InjectedPointId")); Assert(seedIds); if(seedIds) diff --git a/Filters/FlowPaths/vtkStreamTracer.cxx b/Filters/FlowPaths/vtkStreamTracer.cxx index fe79740ba25..29d3afbfa21 100644 --- a/Filters/FlowPaths/vtkStreamTracer.cxx +++ b/Filters/FlowPaths/vtkStreamTracer.cxx @@ -425,12 +425,9 @@ int vtkStreamTracer::SetupOutput(vtkInformation* inInfo, } else if (dsInput) { - vtkDataSet* copy = dsInput->NewInstance(); - copy->ShallowCopy(dsInput); vtkMultiBlockDataSet* mb = vtkMultiBlockDataSet::New(); mb->SetNumberOfBlocks(numPieces); - mb->SetBlock(piece, copy); - copy->Delete(); + mb->SetBlock(piece, dsInput); this->InputData = mb; mb->Register(this); mb->Delete(); diff --git a/Filters/FlowPaths/vtkStreamTracer.h b/Filters/FlowPaths/vtkStreamTracer.h index 43959fe1c9e..7ecb3cd45fb 100644 --- a/Filters/FlowPaths/vtkStreamTracer.h +++ b/Filters/FlowPaths/vtkStreamTracer.h @@ -125,7 +125,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkStreamTracer : public vtkPolyDataAlgorithm // New style. void SetSourceConnection(vtkAlgorithmOutput* algOutput); -//BTX // The previously-supported TIME_UNIT is excluded in this current // enumeration definition because the underlying step size is ALWAYS in // arc length unit (LENGTH_UNIT) while the 'real' time interval (virtual @@ -159,7 +158,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkStreamTracer : public vtkPolyDataAlgorithm OUT_OF_STEPS = 5, STAGNATION = 6 }; -//ETX // Description: // Set/get the integrator type to be used for streamline generation. @@ -250,7 +248,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkStreamTracer : public vtkPolyDataAlgorithm vtkSetMacro(SurfaceStreamlines, bool); vtkBooleanMacro(SurfaceStreamlines, bool); -//BTX enum { FORWARD, @@ -263,7 +260,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkStreamTracer : public vtkPolyDataAlgorithm INTERPOLATOR_WITH_DATASET_POINT_LOCATOR, INTERPOLATOR_WITH_CELL_LOCATOR }; -//ETX // Description: // Specify whether the streamline is integrated in the upstream or @@ -353,7 +349,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkStreamTracer : public vtkPolyDataAlgorithm double LastUsedStepSize; -//BTX struct IntervalInformation { double Interval; @@ -370,8 +365,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkStreamTracer : public vtkPolyDataAlgorithm static double ConvertToLength( double interval, int unit, double cellLength ); static double ConvertToLength( IntervalInformation& interval, double cellLength ); -//ETX - int SetupOutput(vtkInformation* inInfo, vtkInformation* outInfo); void InitializeSeeds(vtkDataArray*& seeds, diff --git a/Filters/FlowPaths/vtkStreamer.h b/Filters/FlowPaths/vtkStreamer.h index 5473c617913..89481f815f5 100644 --- a/Filters/FlowPaths/vtkStreamer.h +++ b/Filters/FlowPaths/vtkStreamer.h @@ -212,8 +212,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkStreamer : public vtkPolyDataAlgorithm // // Special classes for manipulating data // - //BTX - begin tcl exclude - // class StreamPoint { public: double x[3]; // position @@ -257,7 +255,7 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkStreamer : public vtkPolyDataAlgorithm vtkIdType Extend; // grow array by this amount double Direction; // integration direction }; - //ETX + // //array of streamers diff --git a/Filters/FlowPaths/vtkTemporalInterpolatedVelocityField.h b/Filters/FlowPaths/vtkTemporalInterpolatedVelocityField.h index 4e4f99946d1..8cb7686be42 100644 --- a/Filters/FlowPaths/vtkTemporalInterpolatedVelocityField.h +++ b/Filters/FlowPaths/vtkTemporalInterpolatedVelocityField.h @@ -46,9 +46,8 @@ #include "vtkFiltersFlowPathsModule.h" // For export macro #include "vtkFunctionSet.h" #include "vtkSmartPointer.h" // because it is good -//BTX + #include // Because they are good -//ETX #define ID_INSIDE_ALL 00 #define ID_OUTSIDE_ALL 01 @@ -152,11 +151,11 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkTemporalInterpolatedVelocityField : public v double OneMinusWeight; // A scaling factor used when calculating the CurrentWeight { 1.0/(T2-T1) } double ScaleCoeff; -//BTX + vtkSmartPointer IVF[2]; // we want to keep track of static datasets so we can optimize caching std::vector StaticDataSets; -//ETX + private: // Hide this since we need multiple time steps and are using a different // function prototype diff --git a/Filters/FlowPaths/vtkTemporalStreamTracer.cxx b/Filters/FlowPaths/vtkTemporalStreamTracer.cxx index 2b6873fd369..fb194a57c09 100644 --- a/Filters/FlowPaths/vtkTemporalStreamTracer.cxx +++ b/Filters/FlowPaths/vtkTemporalStreamTracer.cxx @@ -46,7 +46,7 @@ PURPOSE. See the above copyright notice for more information. #include "vtkToolkits.h" // For VTK_USE_MPI #include -#ifdef WIN32 +#ifdef _WIN32 #undef JB_H5PART_PARTICLE_OUTPUT #else // #define JB_H5PART_PARTICLE_OUTPUT @@ -66,7 +66,7 @@ using namespace vtkTemporalStreamTracerNamespace; //---------------------------------------------------------------------------- //#define JB_DEBUG__ #if defined JB_DEBUG__ - #ifdef WIN32 + #ifdef _WIN32 #define OUTPUTTEXT(a) vtkOutputWindowDisplayText(a); #else #endif @@ -132,7 +132,7 @@ vtkTemporalStreamTracer::vtkTemporalStreamTracer() this->SetNumberOfInputPorts(2); #ifdef JB_H5PART_PARTICLE_OUTPUT -#ifdef WIN32 +#ifdef _WIN32 vtkDebugMacro(<<"Setting vtkH5PartWriter"); vtkH5PartWriter *writer = vtkH5PartWriter::New(); #else diff --git a/Filters/FlowPaths/vtkTemporalStreamTracer.h b/Filters/FlowPaths/vtkTemporalStreamTracer.h index 1de45e095c6..3148a24b6d4 100644 --- a/Filters/FlowPaths/vtkTemporalStreamTracer.h +++ b/Filters/FlowPaths/vtkTemporalStreamTracer.h @@ -28,10 +28,8 @@ #include "vtkSmartPointer.h" // For protected ivars. #include "vtkStreamTracer.h" -//BTX #include // STL Header #include // STL Header -//ETX class vtkMultiProcessController; @@ -49,7 +47,6 @@ class vtkIntArray; class vtkCharArray; class vtkAbstractParticleWriter; -//BTX namespace vtkTemporalStreamTracerNamespace { typedef struct { double x[4]; } Position; @@ -80,7 +77,6 @@ namespace vtkTemporalStreamTracerNamespace typedef std::list ParticleDataList; typedef ParticleDataList::iterator ParticleListIterator; }; -//ETX class VTKFILTERSFLOWPATHS_EXPORT vtkTemporalStreamTracer : public vtkStreamTracer { @@ -127,13 +123,11 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkTemporalStreamTracer : public vtkStreamTrace vtkSetMacro(ForceReinjectionEveryNSteps,int); vtkGetMacro(ForceReinjectionEveryNSteps,int); -//BTX enum Units { TERMINATION_TIME_UNIT, TERMINATION_STEP_UNIT }; -//ETX // Description: // Setting TerminationTime to a positive value will cause particles @@ -254,7 +248,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkTemporalStreamTracer : public vtkStreamTrace int InitializeInterpolator(); int SetTemporalInput(vtkDataObject *td, int index); -//BTX // // Description : Test the list of particles to see if they are @@ -329,7 +322,7 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkTemporalStreamTracer : public vtkStreamTrace vtkGenericCell *cell); // -//ETX + // //Track internally which round of RequestData it is--between 0 and 2 int RequestIndex; @@ -348,10 +341,9 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkTemporalStreamTracer : public vtkStreamTrace unsigned int ActualTimeStep; int IgnorePipelineTime; unsigned int NumberOfInputTimeSteps; -//BTX + std::vector InputTimeValues; std::vector OutputTimeValues; -//ETX // more time management double EarliestTime; @@ -373,14 +365,11 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkTemporalStreamTracer : public vtkStreamTrace char *ParticleFileName; int EnableParticleWriting; -//BTX // The main lists which are held during operation- between time step updates unsigned int NumberOfParticles; vtkTemporalStreamTracerNamespace::ParticleDataList ParticleHistories; vtkTemporalStreamTracerNamespace::ParticleVector LocalSeeds; -//ETX -//BTX // // Scalar arrays that are generated as each particle is updated // @@ -420,8 +409,6 @@ class VTKFILTERSFLOWPATHS_EXPORT vtkTemporalStreamTracer : public vtkStreamTrace // utility function we use to test if a point is inside any of our local datasets bool InsideBounds(double point[]); -//ETX - // global Id counter used to give particles a stamp vtkIdType UniqueIdCounter; vtkIdType UniqueIdCounterMPI; diff --git a/Filters/General/Testing/Cxx/BoxClipTetrahedra.cxx b/Filters/General/Testing/Cxx/BoxClipTetrahedra.cxx index 97d145e90ce..d8721d83d79 100644 --- a/Filters/General/Testing/Cxx/BoxClipTetrahedra.cxx +++ b/Filters/General/Testing/Cxx/BoxClipTetrahedra.cxx @@ -104,10 +104,11 @@ class BadWinding this->Data = bw.Data; this->Data->Register(NULL); } - void operator=(const BadWinding &bw) { + BadWinding& operator=(const BadWinding &bw) { this->Data->UnRegister(NULL); this->Data = bw.Data; this->Data->Register(NULL); + return *this; } vtkUnstructuredGrid *Data; diff --git a/Filters/General/Testing/Cxx/TestGradientAndVorticity.cxx b/Filters/General/Testing/Cxx/TestGradientAndVorticity.cxx index 28e5e61323d..9672891da5f 100644 --- a/Filters/General/Testing/Cxx/TestGradientAndVorticity.cxx +++ b/Filters/General/Testing/Cxx/TestGradientAndVorticity.cxx @@ -84,7 +84,7 @@ namespace {// +offset makes the curl/vorticity nonzero tupleValues[j] = point[(j+offset)%3]; } - array->SetTupleValue(i, &tupleValues[0]); + array->SetTypedTuple(i, &tupleValues[0]); } array->SetName(arrayName); grid->GetCellData()->AddArray(array); @@ -107,7 +107,7 @@ namespace {// +offset makes the curl/vorticity nonzero tupleValues[j] = point[(j+offset)%3]; } - array->SetTupleValue(i, &tupleValues[0]); + array->SetTypedTuple(i, &tupleValues[0]); } array->SetName(arrayName); grid->GetPointData()->AddArray(array); @@ -277,7 +277,7 @@ namespace cellGradients->Update(); pointGradients->Update(); - vtkDoubleArray* gradCellArray = vtkDoubleArray::SafeDownCast( + vtkDoubleArray* gradCellArray = vtkArrayDownCast( vtkDataSet::SafeDownCast( cellGradients->GetOutput())->GetCellData()->GetArray(resultName)); @@ -291,7 +291,7 @@ namespace } } - vtkDoubleArray* gradPointArray = vtkDoubleArray::SafeDownCast( + vtkDoubleArray* gradPointArray = vtkArrayDownCast( vtkDataSet::SafeDownCast( pointGradients->GetOutput())->GetPointData()->GetArray(resultName)); @@ -320,7 +320,7 @@ namespace pointVorticity->Update(); // cell stuff - vtkDoubleArray* vorticityCellArray = vtkDoubleArray::SafeDownCast( + vtkDoubleArray* vorticityCellArray = vtkArrayDownCast( vtkDataSet::SafeDownCast( cellVorticity->GetOutput())->GetCellData()->GetArray("Vorticity")); @@ -330,7 +330,7 @@ namespace } // point stuff - vtkDoubleArray* vorticityPointArray = vtkDoubleArray::SafeDownCast( + vtkDoubleArray* vorticityPointArray = vtkArrayDownCast( vtkDataSet::SafeDownCast( pointVorticity->GetOutput())->GetPointData()->GetArray("Vorticity")); @@ -338,7 +338,7 @@ namespace { return EXIT_FAILURE; } - vtkDoubleArray* divergencePointArray = vtkDoubleArray::SafeDownCast( + vtkDoubleArray* divergencePointArray = vtkArrayDownCast( vtkDataSet::SafeDownCast( pointVorticity->GetOutput())->GetPointData()->GetArray("Divergence")); @@ -346,7 +346,7 @@ namespace { return EXIT_FAILURE; } - vtkDoubleArray* qCriterionPointArray = vtkDoubleArray::SafeDownCast( + vtkDoubleArray* qCriterionPointArray = vtkArrayDownCast( vtkDataSet::SafeDownCast( pointVorticity->GetOutput())->GetPointData()->GetArray("Q-criterion")); if(!IsQCriterionCorrect(gradPointArray, qCriterionPointArray)) diff --git a/Filters/General/Testing/Cxx/TestGraphWeightEuclideanDistanceFilter.cxx b/Filters/General/Testing/Cxx/TestGraphWeightEuclideanDistanceFilter.cxx index bdb8980e3a4..7d7659c7e05 100644 --- a/Filters/General/Testing/Cxx/TestGraphWeightEuclideanDistanceFilter.cxx +++ b/Filters/General/Testing/Cxx/TestGraphWeightEuclideanDistanceFilter.cxx @@ -42,7 +42,7 @@ int TestGraphWeightEuclideanDistanceFilter(int, char *[]) weightFilter->SetInputData(g); weightFilter->Update(); - vtkFloatArray* weights = vtkFloatArray::SafeDownCast(weightFilter->GetOutput()->GetEdgeData()->GetArray("Weights")); + vtkFloatArray* weights = vtkArrayDownCast(weightFilter->GetOutput()->GetEdgeData()->GetArray("Weights")); std::vector correctWeights; correctWeights.push_back(1.0f); diff --git a/Filters/General/Testing/Cxx/TestPassArrays.cxx b/Filters/General/Testing/Cxx/TestPassArrays.cxx index 4afff193170..cb7220fb52a 100644 --- a/Filters/General/Testing/Cxx/TestPassArrays.cxx +++ b/Filters/General/Testing/Cxx/TestPassArrays.cxx @@ -93,8 +93,8 @@ int TestPassArrays(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) std::cerr << "Checking output ..." << std::endl; vtkFieldData* outAttrib = out->GetAttributesAsFieldData(type); - vtkIntArray* out1 = vtkIntArray::SafeDownCast(outAttrib->GetAbstractArray("column1")); - vtkIntArray* out2 = vtkIntArray::SafeDownCast(outAttrib->GetAbstractArray("column2")); + vtkIntArray* out1 = vtkArrayDownCast(outAttrib->GetAbstractArray("column1")); + vtkIntArray* out2 = vtkArrayDownCast(outAttrib->GetAbstractArray("column2")); if (useFieldTypes) { if (!out1 || !out2) diff --git a/Filters/General/Testing/Cxx/TestQuadraturePoints.cxx b/Filters/General/Testing/Cxx/TestQuadraturePoints.cxx index 42cdd3a372f..d52ec00b70d 100644 --- a/Filters/General/Testing/Cxx/TestQuadraturePoints.cxx +++ b/Filters/General/Testing/Cxx/TestQuadraturePoints.cxx @@ -264,7 +264,7 @@ int TestQuadraturePoints(int argc,char *argv[]) int GenerateWarpVector(vtkUnstructuredGrid *usg) { vtkDoubleArray *pts - = vtkDoubleArray::SafeDownCast(usg->GetPoints()->GetData()); + = vtkArrayDownCast(usg->GetPoints()->GetData()); vtkIdType nTups = usg->GetPointData()->GetArray(0)->GetNumberOfTuples(); @@ -306,7 +306,7 @@ int GenerateWarpVector(vtkUnstructuredGrid *usg) int GenerateThresholdScalar(vtkUnstructuredGrid *usg) { vtkDoubleArray *pts - = vtkDoubleArray::SafeDownCast(usg->GetPoints()->GetData()); + = vtkArrayDownCast(usg->GetPoints()->GetData()); vtkIdType nTups = usg->GetPointData()->GetArray(0)->GetNumberOfTuples(); diff --git a/Filters/General/Testing/Cxx/TestTableSplitColumnComponents.cxx b/Filters/General/Testing/Cxx/TestTableSplitColumnComponents.cxx index a869b18cc73..c8c6f2af586 100644 --- a/Filters/General/Testing/Cxx/TestTableSplitColumnComponents.cxx +++ b/Filters/General/Testing/Cxx/TestTableSplitColumnComponents.cxx @@ -38,7 +38,7 @@ int TestTableSplitColumnComponents(int, char*[]) { single->InsertValue(i, i); int ints[] = { i+1, 2 * (i+1), 3 * (i+1) }; - multi->InsertTupleValue(i, ints); + multi->InsertTypedTuple(i, ints); } VTK_CREATE(vtkTable, table); @@ -58,10 +58,10 @@ int TestTableSplitColumnComponents(int, char*[]) return EXIT_FAILURE; } vtkIntArray* arrays[4]; - arrays[0] = vtkIntArray::SafeDownCast(out->GetColumn(0)); - arrays[1] = vtkIntArray::SafeDownCast(out->GetColumn(1)); - arrays[2] = vtkIntArray::SafeDownCast(out->GetColumn(2)); - arrays[3] = vtkIntArray::SafeDownCast(out->GetColumn(3)); + arrays[0] = vtkArrayDownCast(out->GetColumn(0)); + arrays[1] = vtkArrayDownCast(out->GetColumn(1)); + arrays[2] = vtkArrayDownCast(out->GetColumn(2)); + arrays[3] = vtkArrayDownCast(out->GetColumn(3)); if (arrays[0] == 0 || arrays[1] == 0 || arrays[2] == 0 || arrays[3] == 0) { vtkGenericWarningMacro(<< "One of the output arrays was zero - type change?"); @@ -90,7 +90,7 @@ int TestTableSplitColumnComponents(int, char*[]) split->SetNamingModeToNumberWithUnderscores(); split->Update(); out = split->GetOutput(0); - arrays[1] = vtkIntArray::SafeDownCast(out->GetColumn(1)); + arrays[1] = vtkArrayDownCast(out->GetColumn(1)); if (strcmp(arrays[1]->GetName(), "Multi_0") != 0) { vtkGenericWarningMacro("Incorrect name. NamingMode not being respected correctly."); @@ -100,7 +100,7 @@ int TestTableSplitColumnComponents(int, char*[]) split->SetNamingModeToNamesWithParens(); split->Update(); out = split->GetOutput(0); - arrays[1] = vtkIntArray::SafeDownCast(out->GetColumn(1)); + arrays[1] = vtkArrayDownCast(out->GetColumn(1)); if (strcmp(arrays[1]->GetName(), "Multi (X)") != 0) { vtkGenericWarningMacro("Incorrect name. NamingMode not being respected correctly."); @@ -110,7 +110,7 @@ int TestTableSplitColumnComponents(int, char*[]) split->SetNamingModeToNamesWithUnderscores(); split->Update(); out = split->GetOutput(0); - arrays[1] = vtkIntArray::SafeDownCast(out->GetColumn(1)); + arrays[1] = vtkArrayDownCast(out->GetColumn(1)); if (strcmp(arrays[1]->GetName(), "Multi_X") != 0) { vtkGenericWarningMacro("Incorrect name. NamingMode not being respected correctly."); diff --git a/Filters/General/Testing/Data/Baseline/streamTracer.png.md5 b/Filters/General/Testing/Data/Baseline/streamTracer.png.md5 index af646f8fe51..b11fa87ec86 100644 --- a/Filters/General/Testing/Data/Baseline/streamTracer.png.md5 +++ b/Filters/General/Testing/Data/Baseline/streamTracer.png.md5 @@ -1 +1 @@ -f9f85a937c6f3733cce439f0a15ecb7f +945a036811d5fee165d41f21905e2768 diff --git a/Filters/General/vtkAnnotationLink.h b/Filters/General/vtkAnnotationLink.h index b7eb67cde1f..090d43fb0c6 100644 --- a/Filters/General/vtkAnnotationLink.h +++ b/Filters/General/vtkAnnotationLink.h @@ -124,11 +124,10 @@ class VTKFILTERSGENERAL_EXPORT vtkAnnotationLink : public vtkAnnotationLayersAlg vtkAnnotationLink(const vtkAnnotationLink&); // Not implemented. void operator=(const vtkAnnotationLink&); // Not implemented. - //BTX class Command; friend class Command; Command* Observer; - //ETX + }; #endif diff --git a/Filters/General/vtkAreaContourSpectrumFilter.cxx b/Filters/General/vtkAreaContourSpectrumFilter.cxx index 52b9e015c1b..5a671d53ef6 100644 --- a/Filters/General/vtkAreaContourSpectrumFilter.cxx +++ b/Filters/General/vtkAreaContourSpectrumFilter.cxx @@ -112,14 +112,14 @@ int vtkAreaContourSpectrumFilter::RequestData(vtkInformation* vtkNotUsed(request { // Retrieve the arc given by ArcId - vtkVariantArray *edgeInfo = vtkVariantArray::SafeDownCast( + vtkVariantArray *edgeInfo = vtkArrayDownCast( inputGraph->GetEdgeData()->GetAbstractArray("Vertex Ids")); // Invalid Reeb graph (no information associated to the edges) if(!edgeInfo) return 0; // Retrieve the information to get the critical vertices Ids - vtkDataArray *criticalPointIds = vtkDataArray::SafeDownCast( + vtkDataArray *criticalPointIds = vtkArrayDownCast( inputGraph->GetVertexData()->GetAbstractArray("Vertex Ids")); // Invalid Reeb graph (no information associated to the vertices) if(!criticalPointIds) diff --git a/Filters/General/vtkBlockIdScalars.h b/Filters/General/vtkBlockIdScalars.h index 976f58f09ca..1a3a98f3ed9 100644 --- a/Filters/General/vtkBlockIdScalars.h +++ b/Filters/General/vtkBlockIdScalars.h @@ -31,7 +31,6 @@ class VTKFILTERSGENERAL_EXPORT vtkBlockIdScalars : public vtkMultiBlockDataSetAl vtkTypeMacro(vtkBlockIdScalars, vtkMultiBlockDataSetAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); -//BTX protected: vtkBlockIdScalars(); ~vtkBlockIdScalars(); @@ -45,7 +44,7 @@ class VTKFILTERSGENERAL_EXPORT vtkBlockIdScalars : public vtkMultiBlockDataSetAl private: vtkBlockIdScalars(const vtkBlockIdScalars&); // Not implemented. void operator=(const vtkBlockIdScalars&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/General/vtkBooleanOperationPolyDataFilter.cxx b/Filters/General/vtkBooleanOperationPolyDataFilter.cxx index 34d5b07410d..08cd53230ec 100644 --- a/Filters/General/vtkBooleanOperationPolyDataFilter.cxx +++ b/Filters/General/vtkBooleanOperationPolyDataFilter.cxx @@ -53,7 +53,7 @@ void vtkBooleanOperationPolyDataFilter::SortPolyData(vtkPolyData* input, { int numCells = input->GetNumberOfCells(); - vtkDoubleArray *distArray = vtkDoubleArray::SafeDownCast + vtkDoubleArray *distArray = vtkArrayDownCast ( input->GetCellData()->GetArray("Distance") ); for (int cid = 0; cid < numCells; cid++) @@ -290,7 +290,7 @@ ::CopyCells(vtkPolyData* in, vtkPolyData* out, int idx, vtkFloatArray *outNormals = NULL; if ( reverseCells ) { - outNormals = vtkFloatArray::SafeDownCast( outPD->GetArray("Normals") ); + outNormals = vtkArrayDownCast( outPD->GetArray("Normals") ); } vtkIdType numPts = in->GetNumberOfPoints(); @@ -336,11 +336,11 @@ ::CopyCells(vtkPolyData* in, vtkPolyData* out, int idx, if ( reverseCells && outNormals ) { float normal[3]; - outNormals->GetTupleValue( newId, normal ); + outNormals->GetTypedTuple( newId, normal ); normal[0] *= -1.0; normal[1] *= -1.0; normal[2] *= -1.0; - outNormals->SetTupleValue( newId, normal ); + outNormals->SetTypedTuple( newId, normal ); } } diff --git a/Filters/General/vtkCellTreeLocator.cxx b/Filters/General/vtkCellTreeLocator.cxx index d78e22dfb03..0222f513f2d 100644 --- a/Filters/General/vtkCellTreeLocator.cxx +++ b/Filters/General/vtkCellTreeLocator.cxx @@ -1265,7 +1265,7 @@ static void AddBox(vtkPolyData *pd, double *bounds, int level) { vtkPoints *pts = pd->GetPoints(); vtkCellArray *lines = pd->GetLines(); - vtkIntArray *levels = vtkIntArray::SafeDownCast(pd->GetPointData()->GetArray(0)); + vtkIntArray *levels = vtkArrayDownCast(pd->GetPointData()->GetArray(0)); double x[3]; vtkIdType cells[8], ids[2]; // diff --git a/Filters/General/vtkCellTreeLocator.h b/Filters/General/vtkCellTreeLocator.h index 02b71b59680..4c83f98c111 100644 --- a/Filters/General/vtkCellTreeLocator.h +++ b/Filters/General/vtkCellTreeLocator.h @@ -78,7 +78,6 @@ class VTKFILTERSGENERAL_EXPORT vtkCellTreeLocator : public vtkAbstractCellLocato // only after the locator has been built. virtual void FindCellsWithinBounds(double *bbox, vtkIdList *cells); - //BTX /* if the borland compiler is ever removed, we can use these declarations instead of reimplementaing the calls in this subclass @@ -86,7 +85,7 @@ class VTKFILTERSGENERAL_EXPORT vtkCellTreeLocator : public vtkAbstractCellLocato using vtkAbstractCellLocator::FindClosestPoint; using vtkAbstractCellLocator::FindClosestPointWithinRadius; */ - //ETX + // Description: // reimplemented from vtkAbstractCellLocator to support bad compilers virtual int IntersectWithLine( @@ -128,8 +127,6 @@ class VTKFILTERSGENERAL_EXPORT vtkCellTreeLocator : public vtkAbstractCellLocato virtual void ForceBuildLocator(); virtual void BuildLocator(); - -//BTX // Description: // Internal classes made public to allow subclasses to create // customized some traversal algorithms @@ -185,7 +182,6 @@ class VTKFILTERSGENERAL_EXPORT vtkCellTreeLocator : public vtkAbstractCellLocato unsigned int Start() const; unsigned int Size() const; }; -//ETX protected: vtkCellTreeLocator(); diff --git a/Filters/General/vtkClipClosedSurface.cxx b/Filters/General/vtkClipClosedSurface.cxx index 79376afd143..7415bb996d7 100644 --- a/Filters/General/vtkClipClosedSurface.cxx +++ b/Filters/General/vtkClipClosedSurface.cxx @@ -586,7 +586,7 @@ int vtkClipClosedSurface::RequestData( // Add scalars for the newly-created contour lines vtkUnsignedCharArray *scalars = - vtkUnsignedCharArray::SafeDownCast(outLineData->GetScalars()); + vtkArrayDownCast(outLineData->GetScalars()); if (scalars) { @@ -598,13 +598,13 @@ int vtkClipClosedSurface::RequestData( for (vtkIdType lineId = numClipLines; lineId < numLines; lineId++) { unsigned char oldColor[3]; - scalars->GetTupleValue(lineId, oldColor); + scalars->GetTypedTuple(lineId, oldColor); if (numberOfScalarComponents != 3 || oldColor[0] != activeColor[0] || oldColor[1] != activeColor[1] || oldColor[2] != activeColor[2]) { - scalars->SetTupleValue(lineId, color); + scalars->SetTypedTuple(lineId, color); } } } @@ -623,7 +623,7 @@ int vtkClipClosedSurface::RequestData( newPolys, pc); // Add scalars for the newly-created polys - scalars = vtkUnsignedCharArray::SafeDownCast(outPolyData->GetScalars()); + scalars = vtkArrayDownCast(outPolyData->GetScalars()); if (scalars) { @@ -633,17 +633,17 @@ int vtkClipClosedSurface::RequestData( if (numCells > cellId) { // The insert allocates space up to numCells-1 - scalars->InsertTupleValue(numCells-1, color); + scalars->InsertTypedTuple(numCells-1, color); for (;cellId < numCells; cellId++) { - scalars->SetTupleValue(cellId, color); + scalars->SetTypedTuple(cellId, color); } } } // Add scalars to any diagnostic lines that added by // TriangulateContours(). In usual operation, no lines are added. - scalars = vtkUnsignedCharArray::SafeDownCast(outLineData->GetScalars()); + scalars = vtkArrayDownCast(outLineData->GetScalars()); if (scalars) { @@ -653,11 +653,11 @@ int vtkClipClosedSurface::RequestData( if (numCells > numClipAndContourLines) { // The insert allocates space up to numCells-1 - scalars->InsertTupleValue(numCells-1, color); + scalars->InsertTypedTuple(numCells-1, color); for (vtkIdType lineCellId = numClipAndContourLines; lineCellId < numCells; lineCellId++) { - scalars->SetTupleValue(lineCellId, color); + scalars->SetTypedTuple(lineCellId, color); } } } @@ -699,7 +699,7 @@ int vtkClipClosedSurface::RequestData( // Get the line scalars vtkUnsignedCharArray *scalars = - vtkUnsignedCharArray::SafeDownCast(inLineData->GetScalars()); + vtkArrayDownCast(inLineData->GetScalars()); if (this->GenerateOutline) { @@ -718,7 +718,7 @@ int vtkClipClosedSurface::RequestData( if (polys && scalars) { vtkUnsignedCharArray *pScalars = - vtkUnsignedCharArray::SafeDownCast(inPolyData->GetScalars()); + vtkArrayDownCast(inPolyData->GetScalars()); vtkIdType m = scalars->GetNumberOfTuples(); vtkIdType n = pScalars->GetNumberOfTuples(); @@ -729,13 +729,13 @@ int vtkClipClosedSurface::RequestData( color[0] = color[1] = color[2] = 0; // This is just to expand the array - scalars->InsertTupleValue(n+m-1, color); + scalars->InsertTypedTuple(n+m-1, color); // Fill in the poly scalars for (vtkIdType i = 0; i < n; i++) { - pScalars->GetTupleValue(i, color); - scalars->SetTupleValue(i+m, color); + pScalars->GetTypedTuple(i, color); + scalars->SetTypedTuple(i+m, color); } } } @@ -1188,7 +1188,7 @@ void vtkClipClosedSurface::BreakPolylines( { if (inputScalars) { - inputScalars->GetTupleValue(firstLineScalar + cellId++, cellColor); + inputScalars->GetTypedTuple(firstLineScalar + cellId++, cellColor); } for (vtkIdType i = 1; i < npts; i++) @@ -1199,7 +1199,7 @@ void vtkClipClosedSurface::BreakPolylines( if (scalars) { - scalars->InsertNextTupleValue(cellColor); + scalars->InsertNextTypedTuple(cellColor); } } } @@ -1232,15 +1232,15 @@ void vtkClipClosedSurface::CopyPolygons( { for (vtkIdType i = 0; i < n; i++) { - inputScalars->GetTupleValue(i + firstPolyScalar, scalarValue); - polyScalars->SetTupleValue(i, scalarValue); + inputScalars->GetTypedTuple(i + firstPolyScalar, scalarValue); + polyScalars->SetTypedTuple(i, scalarValue); } } else { for (vtkIdType i = 0; i < n; i++) { - polyScalars->SetTupleValue(i, scalarValue); + polyScalars->SetTypedTuple(i, scalarValue); } } } @@ -1278,7 +1278,7 @@ void vtkClipClosedSurface::BreakTriangleStrips( if (inputScalars) { // If there are input scalars, use them instead of "color" - inputScalars->GetTupleValue(cellId, scalarValue); + inputScalars->GetTypedTuple(cellId, scalarValue); } vtkIdType n = npts - 3; @@ -1286,11 +1286,11 @@ void vtkClipClosedSurface::BreakTriangleStrips( if (n >= 0) { // First insert is just to allocate space - polyScalars->InsertTupleValue(m+n, scalarValue); + polyScalars->InsertTypedTuple(m+n, scalarValue); for (vtkIdType i = 0; i < n; i++) { - polyScalars->SetTupleValue(m+i, scalarValue); + polyScalars->SetTypedTuple(m+i, scalarValue); } } } diff --git a/Filters/General/vtkClipVolume.cxx b/Filters/General/vtkClipVolume.cxx index f0285bfeb7e..f281f93a351 100644 --- a/Filters/General/vtkClipVolume.cxx +++ b/Filters/General/vtkClipVolume.cxx @@ -311,7 +311,7 @@ int vtkClipVolume::RequestData( { above = 1; } - else if ( s < value ) + else { below = 1; } diff --git a/Filters/General/vtkClipVolume.h b/Filters/General/vtkClipVolume.h index 1dc3b30ab17..497cbb6460e 100644 --- a/Filters/General/vtkClipVolume.h +++ b/Filters/General/vtkClipVolume.h @@ -167,7 +167,7 @@ class VTKFILTERSGENERAL_EXPORT vtkClipVolume : public vtkUnstructuredGridAlgorit vtkClipVolume(vtkImplicitFunction *cf=NULL); ~vtkClipVolume(); - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); virtual int FillInputPortInformation(int port, vtkInformation *info); diff --git a/Filters/General/vtkCoincidentPoints.h b/Filters/General/vtkCoincidentPoints.h index 0164bc99e47..80071b0d38b 100644 --- a/Filters/General/vtkCoincidentPoints.h +++ b/Filters/General/vtkCoincidentPoints.h @@ -72,10 +72,8 @@ class VTKFILTERSGENERAL_EXPORT vtkCoincidentPoints : public vtkObject // might reuse this class (another executive pass for instance). void Clear(); - //BTX class implementation; implementation * GetImplementation() { return this->Implementation; } - //ETX // Description: // Calculate \a num points, at a regular interval, along a parametric @@ -91,11 +89,10 @@ class VTKFILTERSGENERAL_EXPORT vtkCoincidentPoints : public vtkObject vtkCoincidentPoints( const vtkCoincidentPoints& ); // Not implemented. void operator = ( const vtkCoincidentPoints& ); // Not implemented. - //BTX implementation* Implementation; friend class implementation; - //ETX + }; #endif // vtkCoincidentPoints_h diff --git a/Filters/General/vtkEdgePoints.cxx b/Filters/General/vtkEdgePoints.cxx index 0223940085e..df5dc02dca8 100644 --- a/Filters/General/vtkEdgePoints.cxx +++ b/Filters/General/vtkEdgePoints.cxx @@ -142,7 +142,7 @@ int vtkEdgePoints::RequestData( { above = 1; } - else if ( cellScalars->GetComponent(ptId,0) < this->Value ) + else { below = 1; } diff --git a/Filters/General/vtkExtractSelectedFrustum.cxx b/Filters/General/vtkExtractSelectedFrustum.cxx index c58d212a7ce..83dc575d73a 100644 --- a/Filters/General/vtkExtractSelectedFrustum.cxx +++ b/Filters/General/vtkExtractSelectedFrustum.cxx @@ -220,7 +220,7 @@ int vtkExtractSelectedFrustum::RequestData( } if (node && node->GetContentType() == vtkSelectionNode::FRUSTUM) { - vtkDoubleArray *corners = vtkDoubleArray::SafeDownCast( + vtkDoubleArray *corners = vtkArrayDownCast( node->GetSelectionList()); this->CreateFrustum(corners->GetPointer(0)); if (node->GetProperties()->Has(vtkSelectionNode::INVERSE())) diff --git a/Filters/General/vtkExtractSelectionBase.h b/Filters/General/vtkExtractSelectionBase.h index 69848bbb80b..cf3c4d4473c 100644 --- a/Filters/General/vtkExtractSelectionBase.h +++ b/Filters/General/vtkExtractSelectionBase.h @@ -46,7 +46,6 @@ class VTKFILTERSGENERAL_EXPORT vtkExtractSelectionBase : public vtkDataObjectAlg vtkGetMacro(PreserveTopology, int); vtkBooleanMacro(PreserveTopology, int); -//BTX protected: vtkExtractSelectionBase(); ~vtkExtractSelectionBase(); @@ -63,7 +62,7 @@ class VTKFILTERSGENERAL_EXPORT vtkExtractSelectionBase : public vtkDataObjectAlg private: vtkExtractSelectionBase(const vtkExtractSelectionBase&); // Not implemented. void operator=(const vtkExtractSelectionBase&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/General/vtkHyperStreamline.cxx b/Filters/General/vtkHyperStreamline.cxx index 031c41182fa..2e9df92bfea 100644 --- a/Filters/General/vtkHyperStreamline.cxx +++ b/Filters/General/vtkHyperStreamline.cxx @@ -28,7 +28,7 @@ vtkStandardNewMacro(vtkHyperStreamline); // // Special classes for manipulating data -//BTX +// class vtkHyperPoint { //;prevent man page generation public: vtkHyperPoint(); // method sets up storage @@ -46,7 +46,6 @@ class vtkHyperPoint { //;prevent man page generation double S; // scalar value double D; // distance travelled so far }; -//ETX class vtkHyperArray { //;prevent man page generation public: diff --git a/Filters/General/vtkIconGlyphFilter.cxx b/Filters/General/vtkIconGlyphFilter.cxx index 86e53632dc9..acfe86cca89 100644 --- a/Filters/General/vtkIconGlyphFilter.cxx +++ b/Filters/General/vtkIconGlyphFilter.cxx @@ -95,7 +95,7 @@ int vtkIconGlyphFilter::RequestData(vtkInformation *vtkNotUsed(request), return 1; } - vtkIntArray* scalars = vtkIntArray::SafeDownCast( + vtkIntArray* scalars = vtkArrayDownCast( this->GetInputArrayToProcess(0, inputVector)); if (!scalars) { diff --git a/Filters/General/vtkInterpolateDataSetAttributes.h b/Filters/General/vtkInterpolateDataSetAttributes.h index cd0ac79b323..0db8fda157f 100644 --- a/Filters/General/vtkInterpolateDataSetAttributes.h +++ b/Filters/General/vtkInterpolateDataSetAttributes.h @@ -55,7 +55,7 @@ class VTKFILTERSGENERAL_EXPORT vtkInterpolateDataSetAttributes : public vtkDataS vtkInterpolateDataSetAttributes(); ~vtkInterpolateDataSetAttributes(); - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); int FillInputPortInformation(int port, vtkInformation *info); diff --git a/Filters/General/vtkLinkEdgels.cxx b/Filters/General/vtkLinkEdgels.cxx index 1df904d2e97..2c236db959b 100644 --- a/Filters/General/vtkLinkEdgels.cxx +++ b/Filters/General/vtkLinkEdgels.cxx @@ -65,7 +65,7 @@ int vtkLinkEdgels::RequestData( pd = input->GetPointData(); dimensions = input->GetDimensions(); - inScalars = vtkDoubleArray::SafeDownCast(pd->GetScalars()); + inScalars = vtkArrayDownCast(pd->GetScalars()); inVectors = pd->GetVectors(); if ((input->GetNumberOfPoints()) < 2 || inScalars == NULL) { diff --git a/Filters/General/vtkMatricizeArray.h b/Filters/General/vtkMatricizeArray.h index d107f21d2b7..1dcef8f25f0 100644 --- a/Filters/General/vtkMatricizeArray.h +++ b/Filters/General/vtkMatricizeArray.h @@ -64,9 +64,7 @@ class VTKFILTERSGENERAL_EXPORT vtkMatricizeArray : public vtkArrayDataAlgorithm vtkMatricizeArray(const vtkMatricizeArray&); // Not implemented void operator=(const vtkMatricizeArray&); // Not implemented -//BTX class Generator; -//ETX vtkIdType SliceDimension; }; diff --git a/Filters/General/vtkMergeCells.h b/Filters/General/vtkMergeCells.h index 0804b15f1cf..d28d0ae1f7c 100644 --- a/Filters/General/vtkMergeCells.h +++ b/Filters/General/vtkMergeCells.h @@ -185,10 +185,8 @@ class VTKFILTERSGENERAL_EXPORT vtkMergeCells : public vtkObject vtkMergeCellsSTLCloak *GlobalIdMap; vtkMergeCellsSTLCloak *GlobalCellIdMap; -//BTX vtkDataSetAttributes::FieldList *ptList; vtkDataSetAttributes::FieldList *cellList; -//ETX vtkUnstructuredGrid *UnstructuredGrid; diff --git a/Filters/General/vtkMultiThreshold.h b/Filters/General/vtkMultiThreshold.h index 411d61c942d..d88816ad9d6 100644 --- a/Filters/General/vtkMultiThreshold.h +++ b/Filters/General/vtkMultiThreshold.h @@ -121,7 +121,6 @@ class VTKFILTERSGENERAL_EXPORT vtkMultiThreshold : public vtkMultiBlockDataSetAl static vtkMultiThreshold* New(); virtual void PrintSelf( ostream& os, vtkIndent indent ); - //BTX /// Whether the endpoint value of an interval should be included or excluded. enum Closure { OPEN=0, //!< Specify an open interval @@ -141,7 +140,6 @@ class VTKFILTERSGENERAL_EXPORT vtkMultiThreshold : public vtkMultiBlockDataSetAl WOR, //!< Include elements that belong to an odd number of input sets (a kind of "winding XOR") NAND //!< Only include elements that don't belong to any input set }; - //ETX // Description: // Add a mesh subset to be computed by thresholding an attribute of the input mesh. @@ -212,7 +210,6 @@ class VTKFILTERSGENERAL_EXPORT vtkMultiThreshold : public vtkMultiBlockDataSetAl // Remove all the intervals currently defined. void Reset(); - //BTX /// A pointer to a function that returns a norm (or a single component) of a tuple with 1 or more components. typedef double (*TupleNorm)( vtkDataArray* arr, vtkIdType tuple, int component ); @@ -331,14 +328,12 @@ class VTKFILTERSGENERAL_EXPORT vtkMultiThreshold : public vtkMultiBlockDataSetAl virtual void PrintNode( ostream& os ); virtual BooleanSet* GetBooleanSetPointer(); }; - //ETX protected: vtkMultiThreshold(); virtual ~vtkMultiThreshold(); - //BTX // Description: // When an interval is evaluated, its value is used to update a truth table. // If its value allows the output of the truth table to be determined, then @@ -357,7 +352,6 @@ class VTKFILTERSGENERAL_EXPORT vtkMultiThreshold : public vtkMultiBlockDataSetAl INCLUDE=-2, EXCLUDE=-3 }; - //ETX // Description: // This function performs the actual thresholding. @@ -379,7 +373,6 @@ class VTKFILTERSGENERAL_EXPORT vtkMultiThreshold : public vtkMultiBlockDataSetAl // The number of output datasets. int NumberOfOutputs; - //BTX /// A list of pointers to IntervalSets. typedef std::vector IntervalList; /// A map describing the IntervalSets that share a common attribute and norm. @@ -414,8 +407,6 @@ class VTKFILTERSGENERAL_EXPORT vtkMultiThreshold : public vtkMultiBlockDataSetAl // A utility method called by the public AddInterval members. int AddIntervalSet( NormKey& nk, double xmin, double xmax, int omin, int omax ); - //ETX - // Description: // Print out a graphviz-formatted text description of all the sets. void PrintGraph( ostream& os ); diff --git a/Filters/General/vtkNonOverlappingAMRLevelIdScalars.h b/Filters/General/vtkNonOverlappingAMRLevelIdScalars.h index f2dceef4aff..aa80a4ca7a0 100644 --- a/Filters/General/vtkNonOverlappingAMRLevelIdScalars.h +++ b/Filters/General/vtkNonOverlappingAMRLevelIdScalars.h @@ -35,7 +35,6 @@ class VTKFILTERSGENERAL_EXPORT vtkNonOverlappingAMRLevelIdScalars : vtkTypeMacro(vtkNonOverlappingAMRLevelIdScalars,vtkNonOverlappingAMRAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); -//BTX protected: vtkNonOverlappingAMRLevelIdScalars(); ~vtkNonOverlappingAMRLevelIdScalars(); @@ -50,7 +49,7 @@ class VTKFILTERSGENERAL_EXPORT vtkNonOverlappingAMRLevelIdScalars : private: vtkNonOverlappingAMRLevelIdScalars(const vtkNonOverlappingAMRLevelIdScalars&); // Not implemented. void operator=(const vtkNonOverlappingAMRLevelIdScalars&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/General/vtkOBBTree.h b/Filters/General/vtkOBBTree.h index 12b658ec724..6a6531173f7 100644 --- a/Filters/General/vtkOBBTree.h +++ b/Filters/General/vtkOBBTree.h @@ -56,7 +56,7 @@ class vtkMatrix4x4; // Special class defines node for the OBB tree // -//BTX + // class VTKFILTERSGENERAL_EXPORT vtkOBBNode { //;prevent man page generation public: @@ -75,7 +75,7 @@ class VTKFILTERSGENERAL_EXPORT vtkOBBNode { //;prevent man page generation vtkOBBNode(const vtkOBBNode& other); // no copy constructor vtkOBBNode& operator=(const vtkOBBNode& rhs); // no copy assignment }; -//ETX + // class VTKFILTERSGENERAL_EXPORT vtkOBBTree : public vtkAbstractCellLocator @@ -134,8 +134,6 @@ class VTKFILTERSGENERAL_EXPORT vtkOBBTree : public vtkAbstractCellLocator // The return value is +1 if outside, -1 if inside, and 0 if undecided. int InsideOrOutside(const double point[3]); - //BTX - // Description: // Returns true if nodeB and nodeA are disjoint after optional // transformation of nodeB with matrix XformBtoA @@ -161,7 +159,6 @@ class VTKFILTERSGENERAL_EXPORT vtkOBBTree : public vtkAbstractCellLocator vtkMatrix4x4 *Xform, void *arg ), void *data_arg ); - //ETX // Description: // Satisfy locator's abstract interface, see vtkLocator. @@ -178,7 +175,6 @@ class VTKFILTERSGENERAL_EXPORT vtkOBBTree : public vtkAbstractCellLocator // the relative diameter of the OBB compared to the diameter (d). void GenerateRepresentation(int level, vtkPolyData *pd); - //BTX protected: vtkOBBTree(); ~vtkOBBTree(); @@ -199,7 +195,6 @@ class VTKFILTERSGENERAL_EXPORT vtkOBBTree : public vtkAbstractCellLocator void GeneratePolygons(vtkOBBNode *OBBptr, int level, int repLevel, vtkPoints* pts, vtkCellArray *polys); - //ETX private: vtkOBBTree(const vtkOBBTree&); // Not implemented. void operator=(const vtkOBBTree&); // Not implemented. diff --git a/Filters/General/vtkOverlappingAMRLevelIdScalars.h b/Filters/General/vtkOverlappingAMRLevelIdScalars.h index b124cb169cb..d73f844dd6d 100644 --- a/Filters/General/vtkOverlappingAMRLevelIdScalars.h +++ b/Filters/General/vtkOverlappingAMRLevelIdScalars.h @@ -35,7 +35,6 @@ class VTKFILTERSGENERAL_EXPORT vtkOverlappingAMRLevelIdScalars : vtkTypeMacro(vtkOverlappingAMRLevelIdScalars,vtkOverlappingAMRAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); -//BTX protected: vtkOverlappingAMRLevelIdScalars(); ~vtkOverlappingAMRLevelIdScalars(); @@ -50,7 +49,7 @@ class VTKFILTERSGENERAL_EXPORT vtkOverlappingAMRLevelIdScalars : private: vtkOverlappingAMRLevelIdScalars(const vtkOverlappingAMRLevelIdScalars&); // Not implemented. void operator=(const vtkOverlappingAMRLevelIdScalars&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/General/vtkPassArrays.h b/Filters/General/vtkPassArrays.h index 58ca73ea493..45252ccab82 100644 --- a/Filters/General/vtkPassArrays.h +++ b/Filters/General/vtkPassArrays.h @@ -147,10 +147,8 @@ class VTKFILTERSGENERAL_EXPORT vtkPassArrays : public vtkDataObjectAlgorithm bool RemoveArrays; bool UseFieldTypes; - //BTX class Internals; Internals* Implementation; - //ETX private: vtkPassArrays(const vtkPassArrays&); // Not implemented diff --git a/Filters/General/vtkRectilinearGridToTetrahedra.h b/Filters/General/vtkRectilinearGridToTetrahedra.h index dbd39ba0a6d..3fbca4a58b8 100644 --- a/Filters/General/vtkRectilinearGridToTetrahedra.h +++ b/Filters/General/vtkRectilinearGridToTetrahedra.h @@ -118,7 +118,6 @@ class VTKFILTERSGENERAL_EXPORT vtkRectilinearGridToTetrahedra : public vtkUnstru void operator=(const vtkRectilinearGridToTetrahedra&); // Not implemented. -//BTX // Description: // Determine how to Divide each cell (voxel) in the RectilinearGrid // Overwrites VoxelSubdivisionType with flipping information for forming the mesh @@ -149,7 +148,7 @@ class VTKFILTERSGENERAL_EXPORT vtkRectilinearGridToTetrahedra : public vtkUnstru // Adds a center point in the middle of the voxel static inline void TetrahedralizeAddCenterPoint(vtkIdList *VoxelCorners, vtkPoints *NodeList); -//ETX + }; #endif /* vtkRectilinearGridToTetrahedra_h */ diff --git a/Filters/General/vtkRecursiveDividingCubes.cxx b/Filters/General/vtkRecursiveDividingCubes.cxx index fad2ec64d93..74758570b60 100644 --- a/Filters/General/vtkRecursiveDividingCubes.cxx +++ b/Filters/General/vtkRecursiveDividingCubes.cxx @@ -154,7 +154,7 @@ int vtkRecursiveDividingCubes::RequestData( { above = 1; } - else if ( voxelScalars->GetComponent(vertNum,0) < this->Value ) + else { below = 1; } @@ -315,7 +315,7 @@ void vtkRecursiveDividingCubes::SubDivide(double origin[3], double h[3], { above = 1; } - else if ( scalar < this->Value ) + else { below = 1; } diff --git a/Filters/General/vtkReflectionFilter.h b/Filters/General/vtkReflectionFilter.h index 8d13d54acd4..c949581340a 100644 --- a/Filters/General/vtkReflectionFilter.h +++ b/Filters/General/vtkReflectionFilter.h @@ -35,7 +35,6 @@ class VTKFILTERSGENERAL_EXPORT vtkReflectionFilter : public vtkDataObjectAlgorit vtkTypeMacro(vtkReflectionFilter, vtkDataObjectAlgorithm); void PrintSelf(ostream &os, vtkIndent indent); -//BTX enum ReflectionPlane { USE_X_MIN = 0, @@ -48,7 +47,6 @@ class VTKFILTERSGENERAL_EXPORT vtkReflectionFilter : public vtkDataObjectAlgorit USE_Y = 7, USE_Z = 8 }; -//ETX // Description: // Set the normal of the plane to use as mirror. diff --git a/Filters/General/vtkRotationFilter.h b/Filters/General/vtkRotationFilter.h index 81571fb9e04..86018683241 100644 --- a/Filters/General/vtkRotationFilter.h +++ b/Filters/General/vtkRotationFilter.h @@ -36,14 +36,12 @@ class VTKFILTERSGENERAL_EXPORT vtkRotationFilter : public vtkUnstructuredGridAlg vtkTypeMacro(vtkRotationFilter, vtkUnstructuredGridAlgorithm); void PrintSelf(ostream &os, vtkIndent indent); -//BTX enum RotationAxis { USE_X = 0, USE_Y = 1, USE_Z = 2 }; -//ETX // Description: // Set the axis of rotation to use. It is set by default to Z. diff --git a/Filters/General/vtkSampleImplicitFunctionFilter.h b/Filters/General/vtkSampleImplicitFunctionFilter.h index 299deeda76a..c22a18fd29b 100644 --- a/Filters/General/vtkSampleImplicitFunctionFilter.h +++ b/Filters/General/vtkSampleImplicitFunctionFilter.h @@ -83,7 +83,7 @@ class VTKFILTERSGENERAL_EXPORT vtkSampleImplicitFunctionFilter : public vtkDataS char *ScalarArrayName; char *GradientArrayName; - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); diff --git a/Filters/General/vtkSpatialRepresentationFilter.h b/Filters/General/vtkSpatialRepresentationFilter.h index a36b7becc63..5b23a30d3ff 100644 --- a/Filters/General/vtkSpatialRepresentationFilter.h +++ b/Filters/General/vtkSpatialRepresentationFilter.h @@ -95,7 +95,7 @@ class VTKFILTERSGENERAL_EXPORT vtkSpatialRepresentationFilter : public vtkMultiB vtkLocator *SpatialRepresentation; - virtual void ReportReferences(vtkGarbageCollector*); + virtual void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; virtual int FillInputPortInformation(int, vtkInformation*); private: vtkSpatialRepresentationFilter(const vtkSpatialRepresentationFilter&); // Not implemented. diff --git a/Filters/General/vtkSplitField.h b/Filters/General/vtkSplitField.h index 7ba257f79fd..6086e01445a 100644 --- a/Filters/General/vtkSplitField.h +++ b/Filters/General/vtkSplitField.h @@ -87,16 +87,13 @@ class VTKFILTERSGENERAL_EXPORT vtkSplitField : public vtkDataSetAlgorithm // Create a new array with the given component. void Split(int component, const char* arrayName); -//BTX enum FieldLocations { DATA_OBJECT=0, POINT_DATA=1, CELL_DATA=2 }; -//ETX -//BTX struct Component { int Index; @@ -116,17 +113,14 @@ class VTKFILTERSGENERAL_EXPORT vtkSplitField : public vtkDataSetAlgorithm Component() { FieldName = 0; } ~Component() { delete[] FieldName; } }; -//ETX protected: -//BTX enum FieldTypes { NAME, ATTRIBUTE }; -//ETX vtkSplitField(); virtual ~vtkSplitField(); diff --git a/Filters/General/vtkSubPixelPositionEdgels.cxx b/Filters/General/vtkSubPixelPositionEdgels.cxx index de77b2a6ea0..ecf7a379db8 100644 --- a/Filters/General/vtkSubPixelPositionEdgels.cxx +++ b/Filters/General/vtkSubPixelPositionEdgels.cxx @@ -85,14 +85,14 @@ int vtkSubPixelPositionEdgels::RequestData( dimensions = gradMaps->GetDimensions(); spacing = gradMaps->GetSpacing(); origin = gradMaps->GetOrigin(); - if (vtkDoubleArray::SafeDownCast(gradMaps->GetPointData()->GetScalars())) + if (vtkArrayDownCast(gradMaps->GetPointData()->GetScalars())) { - DMapData = vtkDoubleArray::SafeDownCast(gradMaps->GetPointData() + DMapData = vtkArrayDownCast(gradMaps->GetPointData() ->GetScalars())->GetPointer(0); } - else if (vtkFloatArray::SafeDownCast(gradMaps->GetPointData()->GetScalars())) + else if (vtkArrayDownCast(gradMaps->GetPointData()->GetScalars())) { - MapData = vtkFloatArray::SafeDownCast(gradMaps->GetPointData() + MapData = vtkArrayDownCast(gradMaps->GetPointData() ->GetScalars())->GetPointer(0); } else diff --git a/Filters/General/vtkTableBasedClipDataSet.cxx b/Filters/General/vtkTableBasedClipDataSet.cxx index d0c0f679058..39a7f6b7bbe 100644 --- a/Filters/General/vtkTableBasedClipDataSet.cxx +++ b/Filters/General/vtkTableBasedClipDataSet.cxx @@ -1237,7 +1237,7 @@ void vtkTableBasedClipperVolumeFromVolume:: vtkCellData * outCD = output->GetCellData(); vtkIntArray * newOrigNodes = NULL; - vtkIntArray * origNodes = vtkIntArray::SafeDownCast + vtkIntArray * origNodes = vtkArrayDownCast ( inPD->GetArray( "avtOriginalNodeNumbers" ) ); // // If the isovolume only affects a small part of the dataset, we can save diff --git a/Filters/General/vtkTableToPolyData.cxx b/Filters/General/vtkTableToPolyData.cxx index f556b21b350..8f17a985d59 100644 --- a/Filters/General/vtkTableToPolyData.cxx +++ b/Filters/General/vtkTableToPolyData.cxx @@ -76,20 +76,20 @@ int vtkTableToPolyData::RequestData(vtkInformation* vtkNotUsed(request), if(this->XColumn && this->YColumn) { - xarray = vtkDataArray::SafeDownCast( + xarray = vtkArrayDownCast( input->GetColumnByName(this->XColumn)); - yarray = vtkDataArray::SafeDownCast( + yarray = vtkArrayDownCast( input->GetColumnByName(this->YColumn)); - zarray = vtkDataArray::SafeDownCast( + zarray = vtkArrayDownCast( input->GetColumnByName(this->ZColumn)); } else if(this->XColumnIndex >= 0) { - xarray = vtkDataArray::SafeDownCast( + xarray = vtkArrayDownCast( input->GetColumn(this->XColumnIndex)); - yarray = vtkDataArray::SafeDownCast( + yarray = vtkArrayDownCast( input->GetColumn(this->YColumnIndex)); - zarray = vtkDataArray::SafeDownCast( + zarray = vtkArrayDownCast( input->GetColumn(this->ZColumnIndex)); } diff --git a/Filters/General/vtkTableToPolyData.h b/Filters/General/vtkTableToPolyData.h index 2199dd0369a..b1017c180e6 100644 --- a/Filters/General/vtkTableToPolyData.h +++ b/Filters/General/vtkTableToPolyData.h @@ -97,7 +97,6 @@ class VTKFILTERSGENERAL_EXPORT vtkTableToPolyData : public vtkPolyDataAlgorithm vtkGetMacro(PreserveCoordinateColumnsAsDataArrays, bool); vtkBooleanMacro(PreserveCoordinateColumnsAsDataArrays, bool); -//BTX protected: vtkTableToPolyData(); ~vtkTableToPolyData(); @@ -125,7 +124,7 @@ class VTKFILTERSGENERAL_EXPORT vtkTableToPolyData : public vtkPolyDataAlgorithm private: vtkTableToPolyData(const vtkTableToPolyData&); // Not implemented. void operator=(const vtkTableToPolyData&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/General/vtkTableToStructuredGrid.cxx b/Filters/General/vtkTableToStructuredGrid.cxx index ab284d3526d..d930453d34a 100644 --- a/Filters/General/vtkTableToStructuredGrid.cxx +++ b/Filters/General/vtkTableToStructuredGrid.cxx @@ -99,11 +99,11 @@ int vtkTableToStructuredGrid::Convert(vtkTable* input, return 0; } - vtkDataArray* xarray = vtkDataArray::SafeDownCast( + vtkDataArray* xarray = vtkArrayDownCast( input->GetColumnByName(this->XColumn)); - vtkDataArray* yarray = vtkDataArray::SafeDownCast( + vtkDataArray* yarray = vtkArrayDownCast( input->GetColumnByName(this->YColumn)); - vtkDataArray* zarray = vtkDataArray::SafeDownCast( + vtkDataArray* zarray = vtkArrayDownCast( input->GetColumnByName(this->ZColumn)); if (!xarray || !yarray || !zarray) { diff --git a/Filters/General/vtkTableToStructuredGrid.h b/Filters/General/vtkTableToStructuredGrid.h index 3d0eabc2c45..0697a67bd82 100644 --- a/Filters/General/vtkTableToStructuredGrid.h +++ b/Filters/General/vtkTableToStructuredGrid.h @@ -77,7 +77,6 @@ class VTKFILTERSGENERAL_EXPORT vtkTableToStructuredGrid : public vtkStructuredGr vtkSetClampMacro(ZComponent, int, 0, VTK_INT_MAX); vtkGetMacro(ZComponent, int); -//BTX protected: vtkTableToStructuredGrid(); ~vtkTableToStructuredGrid(); @@ -110,7 +109,7 @@ class VTKFILTERSGENERAL_EXPORT vtkTableToStructuredGrid : public vtkStructuredGr private: vtkTableToStructuredGrid(const vtkTableToStructuredGrid&); // Not implemented. void operator=(const vtkTableToStructuredGrid&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/General/vtkTemporalPathLineFilter.h b/Filters/General/vtkTemporalPathLineFilter.h index 88f6622ccf4..e93b8622cef 100644 --- a/Filters/General/vtkTemporalPathLineFilter.h +++ b/Filters/General/vtkTemporalPathLineFilter.h @@ -41,13 +41,11 @@ class vtkCellArray; class vtkMergePoints; class vtkFloatArray; -//BTX #include "vtkSmartPointer.h" // for memory safety #include // Because we want to use it class ParticleTrail; class vtkTemporalPathLineFilterInternals; typedef vtkSmartPointer TrailPointer; -//ETX class VTKFILTERSGENERAL_EXPORT vtkTemporalPathLineFilter : public vtkPolyDataAlgorithm { @@ -139,11 +137,10 @@ class VTKFILTERSGENERAL_EXPORT vtkTemporalPathLineFilter : public vtkPolyDataAlg vtkInformationVector** inputVector, vtkInformationVector* outputVector); -//BTX TrailPointer GetTrail(vtkIdType i); void IncrementTrail( TrailPointer trail, vtkDataSet *input, vtkIdType i); -//ETX + // internal data variables int NumberOfTimeSteps; int MaskPoints; @@ -156,7 +153,7 @@ class VTKFILTERSGENERAL_EXPORT vtkTemporalPathLineFilter : public vtkPolyDataAlg int KeepDeadTrails; int UsingSelection; // -//BTX + vtkSmartPointer PolyLines; vtkSmartPointer Vertices; vtkSmartPointer LineCoordinates; @@ -164,7 +161,7 @@ class VTKFILTERSGENERAL_EXPORT vtkTemporalPathLineFilter : public vtkPolyDataAlg vtkSmartPointer TrailId; vtkSmartPointer Internals; std::set SelectionIds; -//ETX + // private: vtkTemporalPathLineFilter(const vtkTemporalPathLineFilter&); // Not implemented. diff --git a/Filters/General/vtkTemporalStatistics.cxx b/Filters/General/vtkTemporalStatistics.cxx index cc34d897144..939683deccc 100644 --- a/Filters/General/vtkTemporalStatistics.cxx +++ b/Filters/General/vtkTemporalStatistics.cxx @@ -402,7 +402,7 @@ void vtkTemporalStatistics::InitializeArray(vtkDataArray *array, if (this->ComputeAverage || this->ComputeStandardDeviation) { vtkSmartPointer newArray; - newArray.TakeReference(vtkDataArray::SafeDownCast( + newArray.TakeReference(vtkArrayDownCast( vtkAbstractArray::CreateArray(array->GetDataType()))); newArray->DeepCopy(array); newArray->SetName(vtkTemporalStatisticsMangleName(array->GetName(), @@ -419,7 +419,7 @@ void vtkTemporalStatistics::InitializeArray(vtkDataArray *array, if (this->ComputeMinimum) { vtkSmartPointer newArray; - newArray.TakeReference(vtkDataArray::SafeDownCast( + newArray.TakeReference(vtkArrayDownCast( vtkAbstractArray::CreateArray(array->GetDataType()))); newArray->DeepCopy(array); newArray->SetName(vtkTemporalStatisticsMangleName(array->GetName(), @@ -430,7 +430,7 @@ void vtkTemporalStatistics::InitializeArray(vtkDataArray *array, if (this->ComputeMaximum) { vtkSmartPointer newArray; - newArray.TakeReference(vtkDataArray::SafeDownCast( + newArray.TakeReference(vtkArrayDownCast( vtkAbstractArray::CreateArray(array->GetDataType()))); newArray->DeepCopy(array); newArray->SetName(vtkTemporalStatisticsMangleName(array->GetName(), @@ -441,7 +441,7 @@ void vtkTemporalStatistics::InitializeArray(vtkDataArray *array, if (this->ComputeStandardDeviation) { vtkSmartPointer newArray; - newArray.TakeReference(vtkDataArray::SafeDownCast( + newArray.TakeReference(vtkArrayDownCast( vtkAbstractArray::CreateArray(array->GetDataType()))); newArray->SetName(vtkTemporalStatisticsMangleName(array->GetName(), STANDARD_DEVIATION_SUFFIX)); diff --git a/Filters/General/vtkTessellatorFilter.h b/Filters/General/vtkTessellatorFilter.h index 643ea78bb4f..8fc200b5b6e 100644 --- a/Filters/General/vtkTessellatorFilter.h +++ b/Filters/General/vtkTessellatorFilter.h @@ -87,9 +87,8 @@ class VTKFILTERSGENERAL_EXPORT vtkTessellatorFilter : public vtkUnstructuredGrid // interior. vtkSetClampMacro(OutputDimension,int,1,3); vtkGetMacro(OutputDimension,int); - //BTX + int GetOutputDimension() const; - //ETX // Description: // These are convenience routines for setting properties maintained by the @@ -140,7 +139,6 @@ class VTKFILTERSGENERAL_EXPORT vtkTessellatorFilter : public vtkUnstructuredGrid vtkInformationVector** inputVector, vtkInformationVector* outputVector); - //BTX vtkStreamingTessellator* Tessellator; vtkDataSetEdgeSubdivisionCriterion* Subdivider; int OutputDimension; @@ -184,18 +182,15 @@ class VTKFILTERSGENERAL_EXPORT vtkTessellatorFilter : public vtkUnstructuredGrid const double*, const double*, const double* ); - //ETX private: vtkTessellatorFilter( const vtkTessellatorFilter& ); // Not implemented. void operator = ( const vtkTessellatorFilter& ); // Not implemented. }; -//BTX inline int vtkTessellatorFilter::GetOutputDimension() const { return this->OutputDimension; } -//ETX #endif // vtkTessellatorFilter_h diff --git a/Filters/General/vtkUncertaintyTubeFilter.cxx b/Filters/General/vtkUncertaintyTubeFilter.cxx index 2ce3d7b1923..df171fe9dee 100644 --- a/Filters/General/vtkUncertaintyTubeFilter.cxx +++ b/Filters/General/vtkUncertaintyTubeFilter.cxx @@ -31,7 +31,7 @@ vtkStandardNewMacro(vtkUncertaintyTubeFilter); // // Special classes for manipulating data -//BTX +// class vtkTubePoint { //;prevent man page generation public: vtkTubePoint(); // method sets up storage @@ -44,7 +44,6 @@ class vtkTubePoint { //;prevent man page generation double V2[3]; // another, orthogonal normal to the line double Vector[3];//local uncertainty vector }; -//ETX class vtkTubeArray { //;prevent man page generation public: diff --git a/Filters/General/vtkVolumeContourSpectrumFilter.cxx b/Filters/General/vtkVolumeContourSpectrumFilter.cxx index 4fd7d7f88f1..7f0b41b8e01 100644 --- a/Filters/General/vtkVolumeContourSpectrumFilter.cxx +++ b/Filters/General/vtkVolumeContourSpectrumFilter.cxx @@ -114,14 +114,14 @@ int vtkVolumeContourSpectrumFilter::RequestData(vtkInformation* vtkNotUsed(reque { // Retrieve the arc given by ArcId - vtkVariantArray *edgeInfo = vtkVariantArray::SafeDownCast( + vtkVariantArray *edgeInfo = vtkArrayDownCast( inputGraph->GetEdgeData()->GetAbstractArray("Vertex Ids")); // Invalid Reeb graph (no information associated to the edges) if(!edgeInfo) return 0; // Retrieve the information to get the critical vertices Ids - vtkDataArray *criticalPointIds = vtkDataArray::SafeDownCast( + vtkDataArray *criticalPointIds = vtkArrayDownCast( inputGraph->GetVertexData()->GetAbstractArray("Vertex Ids")); // Invalid Reeb graph (no information associated to the vertices) if(!criticalPointIds) diff --git a/Filters/General/vtkWarpScalar.h b/Filters/General/vtkWarpScalar.h index 889a76343f2..a268adfe7a1 100644 --- a/Filters/General/vtkWarpScalar.h +++ b/Filters/General/vtkWarpScalar.h @@ -92,12 +92,10 @@ class VTKFILTERSGENERAL_EXPORT vtkWarpScalar : public vtkPointSetAlgorithm double Normal[3]; int XYPlane; - //BTX double *(vtkWarpScalar::*PointNormal)(vtkIdType id, vtkDataArray *normals); double *DataNormal(vtkIdType id, vtkDataArray *normals=NULL); double *InstanceNormal(vtkIdType id, vtkDataArray *normals=NULL); double *ZNormal(vtkIdType id, vtkDataArray *normals=NULL); - //ETX private: vtkWarpScalar(const vtkWarpScalar&); // Not implemented. diff --git a/Filters/General/vtkWarpVector.cxx b/Filters/General/vtkWarpVector.cxx index 4c4c6602299..ba87af1c8f0 100644 --- a/Filters/General/vtkWarpVector.cxx +++ b/Filters/General/vtkWarpVector.cxx @@ -14,8 +14,8 @@ =========================================================================*/ #include "vtkWarpVector.h" +#include "vtkArrayDispatch.h" #include "vtkCellData.h" -#include "vtkDataArrayIteratorMacro.h" #include "vtkImageData.h" #include "vtkImageDataToPointSet.h" #include "vtkInformation.h" @@ -31,6 +31,8 @@ #include "vtkNew.h" #include "vtkSmartPointer.h" +#include + vtkStandardNewMacro(vtkWarpVector); //---------------------------------------------------------------------------- @@ -87,53 +89,75 @@ int vtkWarpVector::RequestDataObject(vtkInformation *request, } //---------------------------------------------------------------------------- -template -void vtkWarpVectorExecute2(vtkWarpVector *self, - InputIterator begin, InputIterator end, - OutputType *outPts, VectorIterator inVec) +namespace { +// Used by the WarpVectorDispatch1Vector worker, defined below: +template +struct WarpVectorDispatch2Points { - OutputType scaleFactor = static_cast(self->GetScaleFactor()); + vtkWarpVector *Self; + VectorArrayT *Vectors; - // Loop over all points, adjusting locations - vtkIdType counter = 0; - vtkIdType numPts = static_cast(end - begin); - while (begin != end) - { - if (!(counter & 0xfff)) + WarpVectorDispatch2Points(vtkWarpVector *self, VectorArrayT *vectors) + : Self(self), Vectors(vectors) + {} + + template + void operator()(InPointArrayT *inPtArray, OutPointArrayT *outPtArray) + { + typedef typename OutPointArrayT::ValueType PointValueT; + const vtkIdType numTuples = inPtArray->GetNumberOfTuples(); + const double scaleFactor = this->Self->GetScaleFactor(); + + assert(this->Vectors->GetNumberOfComponents() == 3); + assert(inPtArray->GetNumberOfComponents() == 3); + assert(outPtArray->GetNumberOfComponents() == 3); + + for (vtkIdType t = 0; t < numTuples; ++t) { - self->UpdateProgress(static_cast(counter) / - static_cast(numPts+1)); - if (self->GetAbortExecute()) + if (!(t & 0xfff)) { - break; + this->Self->UpdateProgress(t / static_cast(numTuples)); + if (this->Self->GetAbortExecute()) + { + return; + } } - } - - *outPts++ = *begin++ + scaleFactor * static_cast(*inVec++); - *outPts++ = *begin++ + scaleFactor * static_cast(*inVec++); - *outPts++ = *begin++ + scaleFactor * static_cast(*inVec++); - counter++; - } -} + for (int c = 0; c < 3; ++c) + { + PointValueT val = inPtArray->GetTypedComponent(t, c) + + scaleFactor * this->Vectors->GetTypedComponent(t, c); + outPtArray->SetTypedComponent(t, c, val); + } + } + } +}; -//---------------------------------------------------------------------------- -template -void vtkWarpVectorExecute(vtkWarpVector *self, - InputIterator begin, - InputIterator end, - OutputType *outPts, - vtkDataArray *vectors) +// Dispatch just the vector array first, we can cut out some generated code +// since the point arrays will have the same type. +struct WarpVectorDispatch1Vector { - // call templated function - switch (vectors->GetDataType()) - { - vtkDataArrayIteratorMacro(vectors, - vtkWarpVectorExecute2(self, begin, end, outPts, vtkDABegin)); - default: - break; - } -} + vtkWarpVector *Self; + vtkDataArray *InPoints; + vtkDataArray *OutPoints; + + WarpVectorDispatch1Vector(vtkWarpVector *self, + vtkDataArray *inPoints, vtkDataArray *outPoints) + : Self(self), InPoints(inPoints), OutPoints(outPoints) + {} + + template + void operator()(VectorArrayT *vectors) + { + WarpVectorDispatch2Points worker(this->Self, vectors); + if (!vtkArrayDispatch::Dispatch2SameValueType::Execute( + this->InPoints, this->OutPoints, worker)) + { + vtkGenericWarningMacro("Error dispatching point arrays."); + } + } +}; +} // end anon namespace //---------------------------------------------------------------------------- int vtkWarpVector::RequestData( @@ -205,18 +229,15 @@ int vtkWarpVector::RequestData( output->SetPoints(points); points->Delete(); - // We know that this array has a standard memory layout, as we just created - // it above. - void *outPtr = output->GetPoints()->GetVoidPointer(0); - - // call templated function - switch (input->GetPoints()->GetDataType()) + // call templated function. + // We use two dispatches since we need to dispatch 3 arrays and two share a + // value type. Implementating a second type-restricted dispatch reduces + // the amount of generated templated code. + WarpVectorDispatch1Vector worker(this, input->GetPoints()->GetData(), + output->GetPoints()->GetData()); + if (!vtkArrayDispatch::Dispatch::Execute(vectors, worker)) { - vtkDataArrayIteratorMacro(input->GetPoints()->GetData(), - vtkWarpVectorExecute(this, vtkDABegin, vtkDAEnd, - static_cast(outPtr), vectors)); - default: - break; + vtkWarningMacro("Dispatch failed for vector array."); } // now pass the data. diff --git a/Filters/General/vtkYoungsMaterialInterface.h b/Filters/General/vtkYoungsMaterialInterface.h index 134c809c400..c1d41866cd2 100644 --- a/Filters/General/vtkYoungsMaterialInterface.h +++ b/Filters/General/vtkYoungsMaterialInterface.h @@ -136,13 +136,10 @@ class VTKFILTERSGENERAL_EXPORT vtkYoungsMaterialInterface : public vtkMultiBlock virtual void RemoveAllMaterialBlockMappings(); virtual void AddMaterialBlockMapping(int b); - -//BTX enum { MAX_CELL_POINTS=256 }; -//ETX protected: vtkYoungsMaterialInterface (); @@ -170,9 +167,9 @@ class VTKFILTERSGENERAL_EXPORT vtkYoungsMaterialInterface : public vtkMultiBlock int ReverseMaterialOrder; int UseFractionAsDistance; double VolumeFractionRange[2]; -//BTX + vtkSmartPointer MaterialBlockMapping; -//ETX + bool UseAllBlocks; // Description: diff --git a/Filters/Generic/Testing/Cxx/CMakeLists.txt b/Filters/Generic/Testing/Cxx/CMakeLists.txt index 6535d723d5e..576ef65564a 100644 --- a/Filters/Generic/Testing/Cxx/CMakeLists.txt +++ b/Filters/Generic/Testing/Cxx/CMakeLists.txt @@ -8,6 +8,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestGenericGlyph3DFilter.cxx TestGenericProbeFilter.cxx otherCreation.cxx,NO_VALID + UnitTestGenericGeometryFilter.cxx,NO_VALID,NO_DATA ) vtk_test_cxx_executable(${vtk-module}CxxTests tests) diff --git a/Filters/Generic/Testing/Cxx/UnitTestGenericGeometryFilter.cxx b/Filters/Generic/Testing/Cxx/UnitTestGenericGeometryFilter.cxx new file mode 100644 index 00000000000..ef1e60dbd20 --- /dev/null +++ b/Filters/Generic/Testing/Cxx/UnitTestGenericGeometryFilter.cxx @@ -0,0 +1,352 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: UnitTestGenericGeometryFilter.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkSmartPointer.h" + +#include "vtkGenericGeometryFilter.h" +#include "vtkBridgeDataSet.h" +#include "vtkPlaneSource.h" +#include "vtkVertex.h" +#include "vtkTetra.h" +#include "vtkPolyData.h" +#include "vtkUnstructuredGrid.h" +#include "vtkPointData.h" +#include "vtkCellData.h" +#include "vtkPointLocator.h" + +#include "vtkTestErrorObserver.h" + +#include + +static vtkSmartPointer CreatePolyData(const int xres, const int yres); +static vtkSmartPointer CreateVertexData(); +static vtkSmartPointer CreateTetraData(); + +#define CHECK_ERROR_MSG(errorObserver, msg, status) \ + { \ + std::string expectedMsg(msg); \ + if (!errorObserver->GetError()) \ + { \ + std::cout << "Failed to catch any error. Expected the error message to contain \"" << expectedMsg << std::endl; \ + status++; \ + } \ + else \ + { \ + std::string gotMsg(errorObserver->GetErrorMessage()); \ + if (gotMsg.find(expectedMsg) == std::string::npos) \ + { \ + std::cout << "Error message does not contain \"" << expectedMsg << "\" got \n\"" << gotMsg << std::endl; \ + status++; \ + } \ + } \ + } \ + errorObserver->Clear() + +int UnitTestGenericGeometryFilter(int, char*[]) +{ + const int xres = 20, yres = 10; + int status = EXIT_SUCCESS; + { + std::cout << "Testing empty print..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + filter->Print(emptyPrint); + std::cout << "PASSED." << std::endl; + } + { + std::cout << "Testing default settings..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreatePolyData(xres, yres)); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << "# of cells: " << got; + int expected = xres * yres; + if (expected != got) + { + std::cout << " Expected " << expected << " cells" + << " but got " << got << " cells." + << " FAILED." << std::endl; + status++; + } + else + { + std::cout << " PASSED." << std::endl; + } + } + { + std::cout << "Testing PointClippingOn()..."; + vtkSmartPointer locator = + vtkSmartPointer::New(); + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreatePolyData(xres, yres)); + filter->SetLocator(locator); + filter->MergingOff(); + filter->PointClippingOn(); + filter->CellClippingOff(); + filter->ExtentClippingOff(); + filter->SetPointMinimum(0); + filter->SetPointMaximum((xres+1)*(yres+1)-1); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << "# of cells: " << got; + int expected = xres * yres; + if (expected != got) + { + std::cout << " Expected " << expected << " cells" + << " but got " << got << " cells." + << " FAILED." << std::endl; + status++; + } + else + { + std::cout << " PASSED." << std::endl; + } + std::ostringstream fullPrint; + filter->Print(fullPrint); + + } + { + std::cout << "Testing CellClippingOn()..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreatePolyData(xres, yres)); + filter->PointClippingOff(); + filter->CellClippingOn(); + filter->ExtentClippingOff(); + filter->SetCellMinimum(xres); + filter->SetCellMaximum(xres + 9); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << "# of cells: " << got; + int expected = filter->GetCellMaximum() - filter->GetCellMinimum() + 1; + if (expected != got) + { + std::cout << " Expected " << expected << " cells" + << " but got " << got << " cells." + << " FAILED" << std::endl; + status++; + } + else + { + std::cout << " PASSED." << std::endl; + } + } + { + std::cout << "Testing ExtentClippingOn()..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->MergingOn(); + filter->SetInputData (CreatePolyData(xres, yres)); + filter->PointClippingOff(); + filter->CellClippingOff(); + filter->ExtentClippingOn(); + filter->PassThroughCellIdsOn(); + filter->SetExtent(.4, -.4, .4, -.4, .4, -.4); + filter->SetExtent(-.499, .499, -.499, .499, 0.0, 0.0); + filter->SetExtent(-.499, .499, -.499, .499, 0.0, 0.0); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << "# of cells: " << got; + int expected = (xres * yres) - 2 * xres - 2 * (yres - 2); + if (expected != got) + { + std::cout << " Expected " << expected << " cells" + << " but got " << got << " cells." + << " FAILED." << std::endl; + status++; + } + else if (filter->GetOutput()->GetCellData()->GetArray("vtkOriginalCellIds") == NULL) + { + std::cout << " PassThroughCellIdsOn should produce vtkOriginalCellIds, but did not." << std::endl; + std::cout << " FAILED." << std::endl; + status++; + } + else + { + std::cout << " PASSED." << std::endl; + } + } + { + std::cout << "Testing with TetraData..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateTetraData()); + filter->PointClippingOff(); + filter->CellClippingOff(); + filter->ExtentClippingOff(); + filter->PassThroughCellIdsOn(); + filter->Update(); + + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << "# of cells: " << got; + int expected = 4; + if (expected != got) + { + std::cout << " Expected " << expected << " cells" + << " but got " << got << " cells." + << " FAILED." << std::endl; + status++; + } + else + { + std::cout << " PASSED." << std::endl; + } + } + { + std::cout << "Testing errors..."; + vtkSmartPointer errorObserver = + vtkSmartPointer::New(); + + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->AddObserver(vtkCommand::ErrorEvent, errorObserver); + filter->SetInputData (vtkSmartPointer::New()); + filter->Update(); + CHECK_ERROR_MSG(errorObserver, "Number of cells is zero, no data to process.", status); + + filter->SetInputData (CreateVertexData()); + filter->Update(); + CHECK_ERROR_MSG(errorObserver, "Cell of dimension 0 not handled yet.", status); + + if (status) + { + std::cout << "FAILED." << std::endl; + } + else + { + std::cout << "PASSED." << std::endl; + } + } + return status; +} + +vtkSmartPointer CreatePolyData(const int xres, const int yres) +{ + vtkSmartPointer plane = + vtkSmartPointer::New(); + plane->SetXResolution(xres); + plane->SetYResolution(yres); + plane->Update(); + vtkSmartPointer cellData = + vtkSmartPointer::New(); + cellData->SetNumberOfTuples(xres * yres); + cellData->SetName("CellDataTestArray"); + vtkIdType c = 0; + for (int j = 0; j < yres; ++j) + { + for (int i = 0; i SetTuple1(c++, i); + } + } + vtkSmartPointer pointData = + vtkSmartPointer::New(); + pointData->SetNumberOfTuples((xres + 1) * (yres + 1)); + pointData->SetName("PointDataTestArray"); + c = 0; + for (int j = 0; j < yres + 1; ++j) + { + for (int i = 0; i SetTuple1(c++, i); + } + } + + vtkSmartPointer pd = + vtkSmartPointer::New(); + pd = plane->GetOutput(); + pd->GetPointData()->SetScalars(pointData); + pd->GetCellData()->SetScalars(cellData); + + vtkSmartPointer bridge = + vtkSmartPointer::New(); + bridge->SetDataSet(plane->GetOutput()); + + return bridge; +} +vtkSmartPointer CreateVertexData() +{ + vtkSmartPointer points = + vtkSmartPointer::New(); + points->InsertNextPoint(0,0,0); + + vtkSmartPointer vertex = + vtkSmartPointer::New(); + vertex->GetPointIds()->SetId(0, 0); + + vtkSmartPointer vertices = + vtkSmartPointer::New(); + vertices->InsertNextCell(vertex); + + vtkSmartPointer polydata = + vtkSmartPointer::New(); + polydata->SetPoints(points); + polydata->SetVerts(vertices); + + vtkSmartPointer bridge = + vtkSmartPointer::New(); + bridge->SetDataSet(polydata); + + return bridge; +} + +vtkSmartPointer CreateTetraData() +{ + vtkSmartPointer points = + vtkSmartPointer:: New(); + points->InsertNextPoint(0, 0, 0); + points->InsertNextPoint(1, 0, 0); + points->InsertNextPoint(1, 1, 0); + points->InsertNextPoint(0, 1, 1); + points->InsertNextPoint(5, 5, 5); + points->InsertNextPoint(6, 5, 5); + points->InsertNextPoint(6, 6, 5); + points->InsertNextPoint(5, 6, 6); + + vtkSmartPointer unstructuredGrid = + vtkSmartPointer::New(); + unstructuredGrid->SetPoints(points); + + vtkSmartPointer tetra = + vtkSmartPointer::New(); + tetra->GetPointIds()->SetId(0, 4); + tetra->GetPointIds()->SetId(1, 5); + tetra->GetPointIds()->SetId(2, 6); + tetra->GetPointIds()->SetId(3, 7); + + vtkSmartPointer cellArray = + vtkSmartPointer::New(); + cellArray->InsertNextCell(tetra); + unstructuredGrid->SetCells(VTK_TETRA, cellArray); + + vtkSmartPointer pointData = + vtkSmartPointer::New(); + pointData->SetNumberOfTuples(unstructuredGrid->GetNumberOfPoints()); + pointData->SetName("PointDataTestArray"); + int c = 0; + for (vtkIdType id = 0; id < tetra->GetNumberOfPoints(); ++id) + { + pointData->SetTuple1(c++, id); + } + unstructuredGrid->GetPointData()->SetScalars(pointData); + + vtkSmartPointer bridge = + vtkSmartPointer::New(); + bridge->SetDataSet(unstructuredGrid); + + return bridge; +} diff --git a/Filters/Generic/vtkGenericContourFilter.h b/Filters/Generic/vtkGenericContourFilter.h index e2f5cc646c4..0b373d01ad7 100644 --- a/Filters/Generic/vtkGenericContourFilter.h +++ b/Filters/Generic/vtkGenericContourFilter.h @@ -61,9 +61,7 @@ class VTKFILTERSGENERIC_EXPORT vtkGenericContourFilter : public vtkPolyDataAlgor // of 0.0. static vtkGenericContourFilter *New(); - //BTX typedef double PointType[3]; // Arbitrary definition of a point - //ETX // Description: // Methods to set / get contour values. diff --git a/Filters/Generic/vtkGenericGeometryFilter.cxx b/Filters/Generic/vtkGenericGeometryFilter.cxx index 2e3f8c19659..cf19ca4ee0d 100644 --- a/Filters/Generic/vtkGenericGeometryFilter.cxx +++ b/Filters/Generic/vtkGenericGeometryFilter.cxx @@ -33,6 +33,7 @@ #include "vtkWedge.h" #include "vtkDoubleArray.h" #include "vtkGenericCellIterator.h" +#include "vtkGenericPointIterator.h" #include "vtkGenericAdaptorCell.h" #include "vtkGenericDataSet.h" #include "vtkGenericAttributeCollection.h" @@ -140,26 +141,21 @@ int vtkGenericGeometryFilter::RequestData( vtkIdType cellId; int i, j; -// vtkGenericDataSet *input= this->GetInput(); vtkIdType numPts = input->GetNumberOfPoints(); vtkIdType numCells = input->GetNumberOfCells(); char *cellVis; vtkGenericAdaptorCell *cell; double x[3]={0,0,0}; - //vtkIdList *ptIds; vtkIdType ptIds[4]; vtkIdType ptId; - //int npts; - //vtkIdType pt=0; int allVisible; -// vtkPolyData *output = this->GetOutput(); vtkPointData *outputPD = output->GetPointData(); vtkCellData *outputCD = output->GetCellData(); if (numCells == 0) { - vtkErrorMacro(<<"No data to clip"); + vtkErrorMacro(<<"Number of cells is zero, no data to process."); return 1; } @@ -193,19 +189,25 @@ int vtkGenericGeometryFilter::RequestData( } else { - //ptIds = cell->GetPointIds(); + vtkGenericPointIterator *pointIt = input->NewPointIterator(); + cell->GetPointIterator(pointIt); + pointIt->Begin(); + cell->GetPointIds( ptIds ); for (i=0; i < cell->GetNumberOfPoints(); i++) { ptId = ptIds[i]; - //input->GetPoint(ptId, x); + + // Get point coordinate + pointIt->GetPosition(x); + pointIt->Next(); if ( (this->PointClipping && (ptId < this->PointMinimum || ptId > this->PointMaximum) ) || (this->ExtentClipping && (x[0] < this->Extent[0] || x[0] > this->Extent[1] || - x[1] < this->Extent[2] || x[1] > this->Extent[3] || - x[2] < this->Extent[4] || x[2] > this->Extent[5] )) ) + x[1] < this->Extent[2] || x[1] > this->Extent[3] || + x[2] < this->Extent[4] || x[2] > this->Extent[5] )) ) { cellVis[cellId] = 0; break; @@ -215,6 +217,7 @@ int vtkGenericGeometryFilter::RequestData( { cellVis[cellId] = 1; } + pointIt->Delete(); } } } @@ -230,11 +233,9 @@ int vtkGenericGeometryFilter::RequestData( output->Allocate(numCells); vtkPoints *newPts = vtkPoints::New(); -//FB vtkDoubleArray *newScalars = vtkDoubleArray::New(); vtkCellArray *cellArray = vtkCellArray::New(); newPts->Allocate(estimatedSize,numPts); -//FB newScalars->Allocate(estimatedSize, 5*numPts); cellArray->Allocate(numCells); @@ -337,7 +338,7 @@ int vtkGenericGeometryFilter::RequestData( { // create new points and then cell case 0: case 1: - vtkErrorMacro( "Cell not handled yet" ); + vtkErrorMacro( "Cell of dimension " << cell->GetDimension() << " not handled yet." ); break; case 2: if ( cell->IsOnBoundary() ) @@ -392,12 +393,9 @@ int vtkGenericGeometryFilter::RequestData( // output->SetPoints(newPts); output->SetPolys(cellArray); -//FB newScalars->SetNumberOfTuples( newPts->GetNumberOfPoints() ); -//FB outputPD->SetScalars(newScalars); cellArray->Delete(); newPts->Delete(); -//FB newScalars->Delete(); faceList->Delete(); //free storage @@ -440,32 +438,32 @@ void vtkGenericGeometryFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); - os << indent << "Point Minimum : " << this->PointMinimum << "\n"; - os << indent << "Point Maximum : " << this->PointMaximum << "\n"; + os << indent << "Point Minimum : " << this->GetPointMinimum() << "\n"; + os << indent << "Point Maximum : " << this->GetPointMaximum() << "\n"; - os << indent << "Cell Minimum : " << this->CellMinimum << "\n"; - os << indent << "Cell Maximum : " << this->CellMaximum << "\n"; + os << indent << "Cell Minimum : " << this->GetCellMinimum() << "\n"; + os << indent << "Cell Maximum : " << this->GetCellMaximum() << "\n"; os << indent << "Extent: \n"; os << indent << " Xmin,Xmax: (" << this->Extent[0] << ", " << this->Extent[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->Extent[2] << ", " << this->Extent[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->Extent[4] << ", " << this->Extent[5] << ")\n"; - os << indent << "PointClipping: " << (this->PointClipping ? "On\n" : "Off\n"); - os << indent << "CellClipping: " << (this->CellClipping ? "On\n" : "Off\n"); - os << indent << "ExtentClipping: " << (this->ExtentClipping ? "On\n" : "Off\n"); + os << indent << "PointClipping: " << (this->GetPointClipping() ? "On\n" : "Off\n"); + os << indent << "CellClipping: " << (this->GetCellClipping() ? "On\n" : "Off\n"); + os << indent << "ExtentClipping: " << (this->GetExtentClipping() ? "On\n" : "Off\n"); - os << indent << "Merging: " << (this->Merging ? "On\n" : "Off\n"); - if ( this->Locator ) + os << indent << "Merging: " << (this->GetMerging() ? "On\n" : "Off\n"); + if ( this->GetLocator() ) { - os << indent << "Locator: " << this->Locator << "\n"; + os << indent << "Locator: " << this->GetLocator() << "\n"; } else { os << indent << "Locator: (none)\n"; } - os << indent << "PassThroughCellIds: " << (this->PassThroughCellIds ? "On\n" : "Off\n"); + os << indent << "PassThroughCellIds: " << (this->GetPassThroughCellIds() ? "On\n" : "Off\n"); } @@ -516,21 +514,3 @@ int vtkGenericGeometryFilter::RequestUpdateExtent( return 1; } - -//---------------------------------------------------------------------------- -int vtkGenericGeometryFilter::RequestInformation( - vtkInformation *vtkNotUsed(request), - vtkInformationVector **vtkNotUsed(inputVector), - vtkInformationVector *vtkNotUsed(outputVector)) -{ - // get the info objects -// vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); -// vtkInformation *outInfo = outputVector->GetInformationObject(0); - - if (this->GetInput() == NULL) - { - vtkErrorMacro("No Input"); - return 1; - } - return 1; -} diff --git a/Filters/Generic/vtkGenericGeometryFilter.h b/Filters/Generic/vtkGenericGeometryFilter.h index e6bb2aa2a47..b7a8ce922cf 100644 --- a/Filters/Generic/vtkGenericGeometryFilter.h +++ b/Filters/Generic/vtkGenericGeometryFilter.h @@ -145,7 +145,6 @@ class VTKFILTERSGENERIC_EXPORT vtkGenericGeometryFilter : public vtkPolyDataAlgo void UnstructuredGridExecute(); void StructuredGridExecute(); int RequestUpdateExtent(vtkInformation *, vtkInformationVector **, vtkInformationVector *); - int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *); int FillInputPortInformation(int, vtkInformation*); diff --git a/Filters/Generic/vtkGenericStreamTracer.h b/Filters/Generic/vtkGenericStreamTracer.h index 63f76a76f28..70ba603ca25 100644 --- a/Filters/Generic/vtkGenericStreamTracer.h +++ b/Filters/Generic/vtkGenericStreamTracer.h @@ -109,7 +109,6 @@ class VTKFILTERSGENERIC_EXPORT vtkGenericStreamTracer : public vtkPolyDataAlgori int FillInputPortInformation(int port, vtkInformation* info); -//BTX enum Units { TIME_UNIT, @@ -135,7 +134,6 @@ class VTKFILTERSGENERIC_EXPORT vtkGenericStreamTracer : public vtkPolyDataAlgori OUT_OF_STEPS = 5, STAGNATION = 6 }; -//ETX // Description: // Set/get the integrator type to be used in the stream line @@ -261,14 +259,12 @@ class VTKFILTERSGENERIC_EXPORT vtkGenericStreamTracer : public vtkPolyDataAlgori this->SetMaximumIntegrationStepUnit(unit); } -//BTX enum { FORWARD, BACKWARD, BOTH }; -//ETX // Description: // Specify whether the streamtrace will be generated in the @@ -363,7 +359,6 @@ class VTKFILTERSGENERIC_EXPORT vtkGenericStreamTracer : public vtkPolyDataAlgori double LastUsedTimeStep; -//BTX struct IntervalInformation { double Interval; @@ -388,7 +383,6 @@ class VTKFILTERSGENERIC_EXPORT vtkGenericStreamTracer : public vtkPolyDataAlgori double cellLength, double speed); void ConvertIntervals(double& step, double& minStep, double& maxStep, int direction, double cellLength, double speed); -//ETX void InitializeSeeds(vtkDataArray*& seeds, vtkIdList*& seedIds, diff --git a/Filters/Geometry/Testing/Cxx/CMakeLists.txt b/Filters/Geometry/Testing/Cxx/CMakeLists.txt index 813cc13c38b..35cf6024cb8 100644 --- a/Filters/Geometry/Testing/Cxx/CMakeLists.txt +++ b/Filters/Geometry/Testing/Cxx/CMakeLists.txt @@ -13,6 +13,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests no_data_tests TestStructuredAMRGridConnectivity.cxx TestStructuredGridConnectivity.cxx TestStructuredGridGhostDataGenerator.cxx + UnitTestDataSetSurfaceFilter.cxx ) set(all_tests diff --git a/Filters/Geometry/Testing/Cxx/TestDataSetSurfaceFieldData.cxx b/Filters/Geometry/Testing/Cxx/TestDataSetSurfaceFieldData.cxx index 516934de277..7ad1c482184 100644 --- a/Filters/Geometry/Testing/Cxx/TestDataSetSurfaceFieldData.cxx +++ b/Filters/Geometry/Testing/Cxx/TestDataSetSurfaceFieldData.cxx @@ -53,7 +53,7 @@ int TestDataSet(vtkDataSet* ds, int expectedValue) { std::cout << "Have field data for surface from data set type " << className << "\n"; - vtkIntArray* array = vtkIntArray::SafeDownCast(fieldData->GetArray(0)); + vtkIntArray* array = vtkArrayDownCast(fieldData->GetArray(0)); if (!array) { std::cerr << "Field data array was not of type vtkIntArray for data set type" @@ -69,7 +69,7 @@ int TestDataSet(vtkDataSet* ds, int expectedValue) else { int value = 0; - array->GetTupleValue(0, &value); + array->GetTypedTuple(0, &value); std::cout << "Block value " << value << "\n"; if (value != expectedValue) @@ -92,7 +92,7 @@ void AddFieldData(vtkDataSet* ds, int id) array->SetName("ID"); array->SetNumberOfComponents(1); array->SetNumberOfTuples(1); - array->SetTupleValue(0, &id); + array->SetTypedTuple(0, &id); ds->GetFieldData()->AddArray(array.GetPointer()); } diff --git a/Filters/Geometry/Testing/Cxx/TestGeometryFilterCellData.cxx b/Filters/Geometry/Testing/Cxx/TestGeometryFilterCellData.cxx index 1fedbd5d56e..6970ea4937c 100644 --- a/Filters/Geometry/Testing/Cxx/TestGeometryFilterCellData.cxx +++ b/Filters/Geometry/Testing/Cxx/TestGeometryFilterCellData.cxx @@ -142,7 +142,7 @@ vtkUnstructuredGrid* GridFactory::Get() for ( int i = 0; i < num; ++i ) { vtkIdType value = i+100; - pointDataArray->InsertNextTupleValue( &value ); + pointDataArray->InsertNextTypedTuple( &value ); } this->Grid->GetPointData()->AddArray( pointDataArray ); @@ -156,7 +156,7 @@ vtkUnstructuredGrid* GridFactory::Get() for ( int i = 0; i < num; ++i ) { vtkIdType value = i+200; - cellDataArray->InsertNextTupleValue( &value ); + cellDataArray->InsertNextTypedTuple( &value ); } this->Grid->GetCellData()->AddArray( cellDataArray ); diff --git a/Filters/Geometry/Testing/Cxx/TestStructuredGridConnectivity.cxx b/Filters/Geometry/Testing/Cxx/TestStructuredGridConnectivity.cxx index 20852114982..37492cb953b 100644 --- a/Filters/Geometry/Testing/Cxx/TestStructuredGridConnectivity.cxx +++ b/Filters/Geometry/Testing/Cxx/TestStructuredGridConnectivity.cxx @@ -699,12 +699,12 @@ bool CompareFieldsForGrid( vtkUniformGrid *grid ) grid->GetPointData()->HasArray( "EXPECTED-NodeXYZ" ) ); vtkDoubleArray *computedCellData = - vtkDoubleArray::SafeDownCast( + vtkArrayDownCast( grid->GetCellData()->GetArray( "COMPUTED-CellXYZ" ) ); assert( "pre: computedCellData is NULL" && (computedCellData != NULL) ); vtkDoubleArray *expectedCellData = - vtkDoubleArray::SafeDownCast( + vtkArrayDownCast( grid->GetCellData()->GetArray( "EXPECTED-CellXYZ" ) ); assert( "pre: expectedCellData is NULL" && (expectedCellData != NULL) ); @@ -715,12 +715,12 @@ bool CompareFieldsForGrid( vtkUniformGrid *grid ) } vtkDoubleArray *computedPointData = - vtkDoubleArray::SafeDownCast( + vtkArrayDownCast( grid->GetPointData()->GetArray( "COMPUTED-NodeXYZ" ) ); assert( "pre: computePointData is NULL" && (computedPointData != NULL) ); vtkDoubleArray *expectedPointData = - vtkDoubleArray::SafeDownCast( + vtkArrayDownCast( grid->GetPointData()->GetArray( "EXPECTED-NodeXYZ" ) ); assert( "pre: expectedPointData is NULL" && (expectedPointData != NULL) ); diff --git a/Filters/Geometry/Testing/Cxx/TestStructuredGridGhostDataGenerator.cxx b/Filters/Geometry/Testing/Cxx/TestStructuredGridGhostDataGenerator.cxx index b05985ff84d..56b20e88317 100644 --- a/Filters/Geometry/Testing/Cxx/TestStructuredGridGhostDataGenerator.cxx +++ b/Filters/Geometry/Testing/Cxx/TestStructuredGridGhostDataGenerator.cxx @@ -84,7 +84,7 @@ bool CheckNodeFieldsForGrid( vtkStructuredGrid *grid ) double xyz[3]; vtkDoubleArray *array = - vtkDoubleArray::SafeDownCast( grid->GetPointData()->GetArray("NODE-XYZ") ); + vtkArrayDownCast( grid->GetPointData()->GetArray("NODE-XYZ") ); assert("pre: num tuples must match number of nodes" && (array->GetNumberOfTuples() == grid->GetNumberOfPoints()) ); assert("pre: num components must be 3" && @@ -119,7 +119,7 @@ bool CheckCellFieldsForGrid( vtkStructuredGrid *grid ) double centroid[3]; double xyz[3]; vtkDoubleArray *array = - vtkDoubleArray::SafeDownCast(grid->GetCellData()->GetArray("CELL-XYZ") ); + vtkArrayDownCast(grid->GetCellData()->GetArray("CELL-XYZ") ); assert("pre: num tuples must match number of nodes" && (array->GetNumberOfTuples() == grid->GetNumberOfCells()) ); assert("pre: num components must be 3" && diff --git a/Filters/Geometry/Testing/Cxx/TestUniformGridGhostDataGenerator.cxx b/Filters/Geometry/Testing/Cxx/TestUniformGridGhostDataGenerator.cxx index d34cb59d61f..c302c62b22c 100644 --- a/Filters/Geometry/Testing/Cxx/TestUniformGridGhostDataGenerator.cxx +++ b/Filters/Geometry/Testing/Cxx/TestUniformGridGhostDataGenerator.cxx @@ -58,7 +58,7 @@ bool CheckNodeFieldsForGrid( vtkUniformGrid *grid ) double xyz[3]; vtkDoubleArray *array = - vtkDoubleArray::SafeDownCast( grid->GetPointData()->GetArray("NODE-XYZ") ); + vtkArrayDownCast( grid->GetPointData()->GetArray("NODE-XYZ") ); assert("pre: num tuples must match number of nodes" && (array->GetNumberOfTuples() == grid->GetNumberOfPoints()) ); assert("pre: num components must be 3" && @@ -89,7 +89,7 @@ bool CheckCellFieldsForGrid( vtkUniformGrid *grid ) double centroid[3]; double xyz[3]; vtkDoubleArray *array = - vtkDoubleArray::SafeDownCast(grid->GetCellData()->GetArray("CELL-XYZ") ); + vtkArrayDownCast(grid->GetCellData()->GetArray("CELL-XYZ") ); assert("pre: num tuples must match number of nodes" && (array->GetNumberOfTuples() == grid->GetNumberOfCells()) ); assert("pre: num components must be 3" && diff --git a/Filters/Geometry/Testing/Cxx/UnitTestDataSetSurfaceFilter.cxx b/Filters/Geometry/Testing/Cxx/UnitTestDataSetSurfaceFilter.cxx new file mode 100644 index 00000000000..4ffc8d0ea7a --- /dev/null +++ b/Filters/Geometry/Testing/Cxx/UnitTestDataSetSurfaceFilter.cxx @@ -0,0 +1,873 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: UnitTestDataSetSurfaceFilter.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkSmartPointer.h" + +#include "vtkDataSetSurfaceFilter.h" + +#include "vtkAppendFilter.h" +#include "vtkPlaneSource.h" +#include "vtkRegularPolygonSource.h" +#include "vtkTriangleFilter.h" +#include "vtkStripper.h" + +#include "vtkUnstructuredGrid.h" +#include "vtkRectilinearGrid.h" +#include "vtkUniformGrid.h" +#include "vtkStructuredGrid.h" + +#include "vtkPoints.h" +#include "vtkPointData.h" +#include "vtkCellData.h" +#include "vtkPointLocator.h" +#include "vtkDoubleArray.h" + +#include "vtkTetra.h" +#include "vtkHexahedron.h" +#include "vtkPolyData.h" +#include "vtkPolyLine.h" +#include "vtkQuadraticWedge.h" +#include "vtkGenericCell.h" + +#include "vtkCommand.h" +#include "vtkTestErrorObserver.h" + +#include +#include + +static vtkSmartPointer CreatePolyData(const int xres, const int yres); +static vtkSmartPointer CreateTriangleStripData(const int xres, const int yres); +static vtkSmartPointer CreateTetraData(); +static vtkSmartPointer CreatePolygonData(int sides = 6); +static vtkSmartPointer CreateQuadraticWedgeData(); +static vtkSmartPointer CreateUniformGrid(unsigned int, unsigned int, unsigned int); +static vtkSmartPointer CreateRectilinearGrid(); +static vtkSmartPointer CreateStructuredGrid(bool blank = false); +static vtkSmartPointer CreateBadAttributes(); +static vtkSmartPointer CreateGenericCellData(int cellType); + +#define CHECK_ERROR_MSG(errorObserver, msg, status) \ + { \ + std::string expectedMsg(msg); \ + if (!errorObserver->GetError()) \ + { \ + std::cout << "Failed to catch any error. Expected the error message to contain \"" << expectedMsg << std::endl; \ + status++; \ + } \ + else \ + { \ + std::string gotMsg(errorObserver->GetErrorMessage()); \ + if (gotMsg.find(expectedMsg) == std::string::npos) \ + { \ + std::cout << "Error message does not contain \"" << expectedMsg << "\" got \n\"" << gotMsg << std::endl; \ + status++; \ + } \ + } \ + } \ + errorObserver->Clear() + +#define CHECK_WARNING_MSG(warningObserver, msg, status) \ + { \ + std::string expectedMsg(msg); \ + if (!warningObserver->GetWarning()) \ + { \ + std::cout << "Failed to catch any warning. Expected the warning message to contain \"" << expectedMsg << std::endl; \ + status++; \ + } \ + else \ + { \ + std::string gotMsg(warningObserver->GetWarningMessage()); \ + if (gotMsg.find(expectedMsg) == std::string::npos) \ + { \ + std::cout << "Warning message does not contain \"" << expectedMsg << "\" got \n\"" << gotMsg << std::endl; \ + status++; \ + } \ + } \ + } \ + warningObserver->Clear() + +namespace test +{ +// What to expect for a cell +class CellDescription + { + public: + CellDescription (int cellType, int numCells) + { + this->Type = cellType; + this->Cells = numCells; + } + CellDescription(const CellDescription &cell) + { + this->Type = cell.Type; + this->Cells = cell.Cells; + } + CellDescription() : Type(0), Cells(0) + {} + int Type; + int Cells; +}; +} +int UnitTestDataSetSurfaceFilter(int, char*[]) +{ + int status = EXIT_SUCCESS; + { + std::cout << "Testing empty print..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + filter->Print(emptyPrint); + std::cout << "PASSED." << std::endl; + } + { + std::map typesToProcess; + typesToProcess["Vertex"] = test::CellDescription(VTK_VERTEX, 1); + typesToProcess["Line"] = test::CellDescription(VTK_LINE, 1); + typesToProcess["Triangle"] = test::CellDescription(VTK_TRIANGLE, 1); + typesToProcess["Pixel"] = test::CellDescription(VTK_PIXEL, 1); + typesToProcess["Quad"] = test::CellDescription(VTK_QUAD, 1); + typesToProcess["Tetra"] = test::CellDescription(VTK_TETRA, 4); + typesToProcess["Voxel"] = test::CellDescription(VTK_VOXEL, 6); + typesToProcess["Hexahedron"] = test::CellDescription(VTK_HEXAHEDRON, 6); + typesToProcess["Wedge"] = test::CellDescription(VTK_WEDGE, 5); + typesToProcess["Pyramid"] = test::CellDescription(VTK_PYRAMID, 5); + typesToProcess["PentagonalPrism"] = test::CellDescription(VTK_PENTAGONAL_PRISM, 7); + typesToProcess["HexagonalPrism"] = test::CellDescription(VTK_HEXAGONAL_PRISM, 8); + typesToProcess["QuadraticEdge"] = test::CellDescription(VTK_QUADRATIC_EDGE, 2); + typesToProcess["QuadraticTriangle"] = test::CellDescription(VTK_QUADRATIC_TRIANGLE, 1); + typesToProcess["QuadraticQuad"] = test::CellDescription(VTK_QUADRATIC_QUAD, 1); + typesToProcess["QuadraticTetra"] = test::CellDescription(VTK_QUADRATIC_TETRA, 16); + typesToProcess["QuadraticHexahedron"] = test::CellDescription(VTK_QUADRATIC_HEXAHEDRON, 36); + typesToProcess["QuadraticWedge"] = test::CellDescription(VTK_QUADRATIC_WEDGE, 26); + typesToProcess["QuadraticPyramid"] = test::CellDescription(VTK_QUADRATIC_PYRAMID, 22); + typesToProcess["BiQuadraticQuad"] = test::CellDescription(VTK_BIQUADRATIC_QUAD, 8); + typesToProcess["TriQuadraticHexahedron"] = test::CellDescription(VTK_TRIQUADRATIC_HEXAHEDRON, 768); + typesToProcess["QuadraticLinearQuad"] = test::CellDescription(VTK_QUADRATIC_LINEAR_QUAD, 4); + typesToProcess["QuadraticLinearWedge"] = test::CellDescription(VTK_QUADRATIC_LINEAR_WEDGE, 20); + typesToProcess["BiQuadraticQuadraticWedge"] = test::CellDescription(VTK_BIQUADRATIC_QUADRATIC_WEDGE, 32); + + std::map ::iterator it; + for (it = typesToProcess.begin(); it != typesToProcess.end(); ++it) + { + std::cout << "Testing (" << it->first << ")..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateGenericCellData(it->second.Type)); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + if (it->first == "QuadraticTriangle" || it->first == "QuadraticQuad") + { + filter->SetNonlinearSubdivisionLevel(0); + } + if (it->first == "TriQuadraticHexahedron") + { + filter->SetNonlinearSubdivisionLevel(3); + } + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + int expected = it->second.Cells; + if (got != expected) + { + std::cout << " got " << got << " cells but expected " << expected; + std::cout << " FAILED." << std::endl; + status++; + } + else + { + std::cout << " # of cells: " << got; + std::cout << " PASSED." << std::endl; + } + std::cout.flush(); + } + } + { + std::cout << "Testing default settings (PolyData)..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreatePolyData(10, 20)); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing (TriangleStrips)..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateTriangleStripData(10, 20)); + filter->PassThroughCellIdsOff(); + filter->PassThroughPointIdsOff(); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing (PolyData Polygons)..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreatePolygonData(9)); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing (UnstructuredGrid, QuadraticWedge, Tetra, PassThroughCellIds, PassThroughPointIds)..."; + vtkSmartPointer append = + vtkSmartPointer::New(); + append->AddInputData(CreateTetraData()); + append->AddInputData(CreateQuadraticWedgeData()); + + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputConnection(append->GetOutputPort()); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing (UniformGrid(5,10,1), UseStripsOn, PassThroughCellIds, PassThroughPointIds)..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateUniformGrid(5, 10, 1)); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + filter->UseStripsOn(); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + std::ostringstream fullPrint; + filter->Print(fullPrint); + + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing (UniformGrid(1,5,10), UseStripsOn, PassThroughCellIds, PassThroughPointIds)..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateUniformGrid(1, 5, 10)); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + filter->UseStripsOn(); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + std::ostringstream fullPrint; + filter->Print(fullPrint); + + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing (UniformGrid(5,1,10), UseStripsOn, PassThroughCellIds, PassThroughPointIds)..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateUniformGrid(5, 1, 10)); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + filter->UseStripsOn(); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + std::ostringstream fullPrint; + filter->Print(fullPrint); + + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing (UniformGrid, UseStripsOff, PassThroughCellIds, PassThroughPointIds)..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateUniformGrid(10, 5, 1)); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + filter->UseStripsOff(); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing DataSetExecute..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + + vtkSmartPointer ugrid = CreateUniformGrid(10, 5, 1); + + vtkSmartPointer polyData = + vtkSmartPointer::New(); + filter->DataSetExecute(ugrid, polyData); + + int got = polyData->GetNumberOfCells(); + std::cout << " # of cells: " << got; + + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing UniformGridExecute all faces..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + + vtkSmartPointer ugrid = CreateUniformGrid(10, 5, 1); + + vtkSmartPointer polyData = + vtkSmartPointer::New(); + vtkUniformGrid *grid = vtkUniformGrid::SafeDownCast(ugrid); + int* tmpext = grid->GetExtent(); + vtkIdType ext[6]; + ext[0] = tmpext[0]; ext[1] = tmpext[1]; + ext[2] = tmpext[2]; ext[3] = tmpext[3]; + ext[4] = tmpext[4]; ext[5] = tmpext[5]; + bool faces[6] = {true, true, true, true, true, true}; + filter->UniformGridExecute(ugrid, polyData, ext, ext, faces); + + int got = polyData->GetNumberOfCells(); + std::cout << " # of cells: " << got; + + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing UniformGridExecute three faces..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + + vtkSmartPointer ugrid = CreateUniformGrid(10, 5, 2); + + vtkSmartPointer polyData = + vtkSmartPointer::New(); + vtkUniformGrid *grid = vtkUniformGrid::SafeDownCast(ugrid); + int* tmpext = grid->GetExtent(); + vtkIdType ext[6]; + ext[0] = tmpext[0]; ext[1] = tmpext[1]; + ext[2] = tmpext[2]; ext[3] = tmpext[3]; + ext[4] = tmpext[4]; ext[5] = tmpext[5]; + bool faces[6] = {true, false, true, false, true, false}; + filter->UniformGridExecute(ugrid, polyData, ext, ext, faces); + + int got = polyData->GetNumberOfCells(); + std::cout << " # of cells: " << got; + + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing (RectilinearGrid, PassThroughCellIds, PassThroughPointIds)..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateRectilinearGrid()); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + filter->Update(); + + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing (StructuredGrid, PassThroughCellIds, PassThroughPointIds)..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateStructuredGrid()); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + + std::cout << " PASSED." << std::endl; + } + { + std::cout << "Testing (StructuredGrid, Blanking, PassThroughCellIds, PassThroughPointIds)..."; + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateStructuredGrid(true)); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + filter->Update(); + int got = filter->GetOutput()->GetNumberOfCells(); + std::cout << " # of cells: " << got; + + std::cout << " PASSED." << std::endl; + } + // Error and warnings + { + std::cout << "Testing UniformGridExecute strips not supported error..."; + vtkSmartPointer errorObserver = + vtkSmartPointer::New(); + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->UseStripsOn(); + filter->AddObserver(vtkCommand::ErrorEvent, errorObserver); + vtkSmartPointer ugrid = CreateUniformGrid(10, 5, 1); + + vtkSmartPointer polyData = + vtkSmartPointer::New(); + vtkUniformGrid *grid = vtkUniformGrid::SafeDownCast(ugrid); + int* tmpext = grid->GetExtent(); + vtkIdType ext[6]; + ext[0] = tmpext[0]; ext[1] = tmpext[1]; + ext[2] = tmpext[2]; ext[3] = tmpext[3]; + ext[4] = tmpext[4]; ext[5] = tmpext[5]; + bool faces[6] = {true, true, true, true, true, true}; + filter->UniformGridExecute(ugrid, polyData, ext, ext, faces); + int status1 = 0; + CHECK_ERROR_MSG(errorObserver, "Strips are not supported for uniform grid!", status1); + if (status1) + { + std::cout << " FAILED." << std::endl; + status++; + } + else + { + std::cout << " PASSED." << std::endl; + } + } + { + std::cout << "Testing cells == 0 warning..."; + vtkSmartPointer warningObserver = + vtkSmartPointer::New(); + + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (vtkSmartPointer::New()); + filter->AddObserver(vtkCommand::WarningEvent, warningObserver); + filter->Update(); + + int status1 = 0; + CHECK_WARNING_MSG(warningObserver, "Number of cells is zero, no data to process.", status1); + if (status1) + { + std::cout << " FAILED." << std::endl; + status++; + } + else + { + std::cout << " PASSED." << std::endl; + } + } + { + std::cout << "Testing DataSetExecute cells == 0 warning..."; + vtkSmartPointer warningObserver = + vtkSmartPointer::New(); + + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->AddObserver(vtkCommand::WarningEvent, warningObserver); + + vtkSmartPointer ugrid = + vtkSmartPointer::New(); + + vtkSmartPointer polyData = + vtkSmartPointer::New(); + filter->DataSetExecute(ugrid, polyData); + + int status1 = 0; + CHECK_WARNING_MSG(warningObserver, "Number of cells is zero, no data to process.", status1); + if (status1) + { + std::cout << " FAILED." << std::endl; + status++; + } + else + { + std::cout << " PASSED." << std::endl; + } + } + { + std::cout << "Testing StructuredExecute invalid dataset error..."; + vtkSmartPointer errorObserver = + vtkSmartPointer::New(); + + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->AddObserver(vtkCommand::ErrorEvent, errorObserver); + + vtkSmartPointer ugrid = + vtkSmartPointer::New(); + + vtkSmartPointer polyData = + vtkSmartPointer::New(); + vtkIdType ext[6]; + ext[0] = 0; ext[1] = 1; + ext[2] = 0; ext[3] = 1; + ext[4] = 0; ext[5] = 1; + + filter->StructuredExecute(ugrid, polyData, ext, ext); + + int status1 = 0; + CHECK_ERROR_MSG(errorObserver, "Invalid data set type: 4", status1); + if (status1) + { + std::cout << " FAILED." << std::endl; + status++; + } + else + { + std::cout << " PASSED." << std::endl; + } + } + { + std::cout << "Testing BadAttributes error..."; + vtkSmartPointer errorObserver = + vtkSmartPointer::New(); + + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData (CreateBadAttributes()); + filter->PassThroughCellIdsOn(); + filter->PassThroughPointIdsOn(); + filter->GetInput()->AddObserver(vtkCommand::ErrorEvent, errorObserver); + filter->Update(); + + int status1 = 0; + CHECK_ERROR_MSG(errorObserver, "Point array PointDataTestArray with 1 components, only has 2 tuples but there are 3 points", status1); + if (status1) + { + std::cout << " FAILED." << std::endl; + status++; + } + else + { + std::cout << " PASSED." << std::endl; + } + } + return status; +} + +vtkSmartPointer CreateTriangleStripData(const int xres, const int yres) +{ + vtkSmartPointer plane = + vtkSmartPointer::New(); + plane->SetXResolution(xres); + plane->SetYResolution(yres); + plane->Update(); + + vtkSmartPointer tris = + vtkSmartPointer::New(); + tris->SetInputConnection(plane->GetOutputPort()); + vtkSmartPointer stripper = + vtkSmartPointer::New(); + stripper->SetInputConnection(tris->GetOutputPort()); + stripper->Update(); + + vtkSmartPointer unstructuredGrid = + vtkSmartPointer::New(); + unstructuredGrid->SetPoints(stripper->GetOutput()->GetPoints()); + unstructuredGrid->SetCells(VTK_TRIANGLE_STRIP, stripper->GetOutput()->GetStrips()); + return unstructuredGrid; +} + +vtkSmartPointer CreatePolyData(const int xres, const int yres) +{ + vtkSmartPointer plane = + vtkSmartPointer::New(); + plane->SetXResolution(xres); + plane->SetYResolution(yres); + plane->Update(); + + vtkSmartPointer tris = + vtkSmartPointer::New(); + tris->SetInputConnection(plane->GetOutputPort()); + vtkSmartPointer stripper = + vtkSmartPointer::New(); + stripper->SetInputConnection(tris->GetOutputPort()); + stripper->Update(); + + vtkSmartPointer pd = + vtkSmartPointer::New(); + pd = plane->GetOutput(); + return pd; +} + +vtkSmartPointer CreatePolygonData(int sides) +{ + vtkSmartPointer polygon = + vtkSmartPointer::New(); + polygon->SetNumberOfSides(sides); + polygon->Update(); + vtkSmartPointer cellData = + vtkSmartPointer::New(); + cellData->SetNumberOfTuples(polygon->GetOutput()->GetNumberOfCells()); + cellData->SetName("CellDataTestArray"); + vtkIdType c = 0; + for (vtkIdType i = 0; i < polygon->GetOutput()->GetNumberOfCells(); ++i) + { + cellData->SetTuple1(c++, i); + } + vtkSmartPointer pointData = + vtkSmartPointer::New(); + pointData->SetNumberOfTuples(polygon->GetOutput()->GetNumberOfPoints()); + pointData->SetName("PointDataTestArray"); + c = 0; + for (int i = 0; i < polygon->GetOutput()->GetNumberOfPoints(); ++i) + { + pointData->SetTuple1(c++, i); + } + + vtkSmartPointer pd = + vtkSmartPointer::New(); + pd = polygon->GetOutput(); + pd->GetPointData()->SetScalars(pointData); + pd->GetCellData()->SetScalars(cellData); + + return pd; +} + +vtkSmartPointer CreateTetraData() +{ + vtkSmartPointer points = + vtkSmartPointer:: New(); + points->InsertNextPoint(0, 0, 0); + points->InsertNextPoint(1, 0, 0); + points->InsertNextPoint(1, 1, 0); + points->InsertNextPoint(0, 1, 1); + points->InsertNextPoint(5, 5, 5); + points->InsertNextPoint(6, 5, 5); + points->InsertNextPoint(6, 6, 5); + points->InsertNextPoint(5, 6, 6); + + vtkSmartPointer unstructuredGrid = + vtkSmartPointer::New(); + unstructuredGrid->SetPoints(points); + + vtkSmartPointer tetra = + vtkSmartPointer::New(); + tetra->GetPointIds()->SetId(0, 4); + tetra->GetPointIds()->SetId(1, 5); + tetra->GetPointIds()->SetId(2, 6); + tetra->GetPointIds()->SetId(3, 7); + + vtkSmartPointer cellArray = + vtkSmartPointer::New(); + cellArray->InsertNextCell(tetra); + unstructuredGrid->SetCells(VTK_TETRA, cellArray); + + vtkSmartPointer pointData = + vtkSmartPointer::New(); + pointData->SetNumberOfTuples(unstructuredGrid->GetNumberOfPoints()); + pointData->SetName("PointDataTestArray"); + int c = 0; + for (vtkIdType id = 0; id < tetra->GetNumberOfPoints(); ++id) + { + pointData->SetTuple1(c++, id); + } + unstructuredGrid->GetPointData()->SetScalars(pointData); + + return unstructuredGrid; +} +vtkSmartPointer CreateQuadraticWedgeData() +{ + vtkSmartPointer aWedge = + vtkSmartPointer::New(); + double *pcoords = aWedge->GetParametricCoords(); + for (int i = 0; i < aWedge->GetNumberOfPoints(); ++i) + { + aWedge->GetPointIds()->SetId(i, i); + aWedge->GetPoints()->SetPoint(i, + *(pcoords + 3 * i), + *(pcoords + 3 * i + 1), + *(pcoords + 3 * i + 2)); + } + + vtkSmartPointer unstructuredGrid = + vtkSmartPointer::New(); + unstructuredGrid->SetPoints(aWedge->GetPoints()); + + vtkSmartPointer cellArray = + vtkSmartPointer::New(); + cellArray->InsertNextCell(aWedge); + unstructuredGrid->SetCells(VTK_QUADRATIC_WEDGE, cellArray); + return unstructuredGrid; +} +vtkSmartPointer CreateUniformGrid( + unsigned int dimx, unsigned int dimy, unsigned int dimz) +{ + vtkSmartPointer image = + vtkSmartPointer::New(); + + image->SetDimensions(dimx, dimy, dimz); + + image->AllocateScalars(VTK_UNSIGNED_CHAR,1); + + for(unsigned int x = 0; x < dimx; x++) + { + for(unsigned int y = 0; y < dimy; y++) + { + for(unsigned int z = 0; z < dimz; z++) + { + unsigned char* pixel = static_cast(image->GetScalarPointer(x,y,0)); + if(x < dimx/2) + { + pixel[0] = 50; + } + else + { + pixel[0] = 150; + } + } + } + } + return image; +} + +vtkSmartPointer CreateGenericCellData(int cellType) +{ + vtkSmartPointer aCell = + vtkSmartPointer::New(); + aCell->SetCellType(cellType); + if (aCell->RequiresInitialization()) + { + aCell->Initialize(); + } + + int numPts = aCell->GetNumberOfPoints(); + double *pcoords = aCell->GetParametricCoords(); + for(int j=0; jGetPointIds()->SetId(j,j); + aCell->GetPoints()->SetPoint(j, pcoords + 3*j); + } + + vtkSmartPointer pointData = + vtkSmartPointer::New(); + pointData->SetNumberOfTuples(numPts); + pointData->SetName("PointDataTestArray"); + for(int j=0; jSetTuple1(j, j); + } + + vtkSmartPointer unstructuredGrid = + vtkSmartPointer::New(); + unstructuredGrid->SetPoints(aCell->GetPoints()); + unstructuredGrid->GetPointData()->SetScalars(pointData); + + vtkSmartPointer cellArray = + vtkSmartPointer::New(); + cellArray->InsertNextCell(aCell); + unstructuredGrid->SetCells(cellType, cellArray); + return unstructuredGrid; +} + +vtkSmartPointer CreateRectilinearGrid() +{ + vtkSmartPointer grid = + vtkSmartPointer::New(); + grid->SetDimensions(2,3,1); + + vtkSmartPointer xArray = + vtkSmartPointer::New(); + xArray->InsertNextValue(0.0); + xArray->InsertNextValue(2.0); + + vtkSmartPointer yArray = + vtkSmartPointer::New(); + yArray->InsertNextValue(0.0); + yArray->InsertNextValue(1.0); + yArray->InsertNextValue(2.0); + + vtkSmartPointer zArray = + vtkSmartPointer::New(); + zArray->InsertNextValue(0.0); + + grid->SetXCoordinates(xArray); + grid->SetYCoordinates(yArray); + grid->SetZCoordinates(zArray); + + return grid; +} + +vtkSmartPointer CreateStructuredGrid(bool blank) +{ + vtkSmartPointer grid = + vtkSmartPointer::New(); + + vtkSmartPointer points = + vtkSmartPointer::New(); + double x, y, z; + + x = 0.0; + y = 0.0; + z = 0.0; + + for(unsigned int k = 0; k < 2; k++) + { + z += 2.0; + for(unsigned int j = 0; j < 3; j++) + { + y += 1.0; + for(unsigned int i = 0; i < 2; i++) + { + x += .5; + points->InsertNextPoint(x, y, z); + } + } + } + + // Specify the dimensions of the grid + grid->SetDimensions(2,3,2); + grid->SetPoints(points); + + if (blank) + { + grid->BlankPoint(points->GetNumberOfPoints() / 2); + } + return grid; +} + +vtkSmartPointer CreateBadAttributes() +{ + vtkSmartPointer aPolyLine = + vtkSmartPointer::New(); + aPolyLine->GetPointIds()->SetNumberOfIds(3); + aPolyLine->GetPointIds()->SetId(0,0); + aPolyLine->GetPointIds()->SetId(1,1); + aPolyLine->GetPointIds()->SetId(2,2); + + aPolyLine->GetPoints()->SetNumberOfPoints(3); + aPolyLine->GetPoints()->SetPoint (0, 10.0, 20.0, 30.0); + aPolyLine->GetPoints()->SetPoint (1, 10.0, 30.0, 30.0); + aPolyLine->GetPoints()->SetPoint (2, 10.0, 30.0, 40.0); + + vtkSmartPointer unstructuredGrid = + vtkSmartPointer::New(); + unstructuredGrid->SetPoints(aPolyLine->GetPoints()); + + vtkSmartPointer pointData = + vtkSmartPointer::New(); + pointData->SetNumberOfTuples(2); + pointData->SetName("PointDataTestArray"); + for(int j=0; j<2; ++j) + { + pointData->SetTuple1(j, j); + } + + vtkSmartPointer cellArray = + vtkSmartPointer::New(); + cellArray->InsertNextCell(aPolyLine); + unstructuredGrid->SetCells(VTK_POLY_LINE, cellArray); + unstructuredGrid->GetPointData()->SetScalars(pointData); + + return unstructuredGrid; +} diff --git a/Filters/Geometry/vtkAbstractGridConnectivity.h b/Filters/Geometry/vtkAbstractGridConnectivity.h index 82207801352..6e03ee3cb43 100644 --- a/Filters/Geometry/vtkAbstractGridConnectivity.h +++ b/Filters/Geometry/vtkAbstractGridConnectivity.h @@ -170,7 +170,6 @@ class VTKFILTERSGEOMETRY_EXPORT vtkAbstractGridConnectivity : public vtkObject unsigned int NumberOfGrids; unsigned int NumberOfGhostLayers; - // BTX // Arrays registered by the user for each grid std::vector< vtkUnsignedCharArray* > GridPointGhostArrays; std::vector< vtkUnsignedCharArray* > GridCellGhostArrays; @@ -185,7 +184,6 @@ class VTKFILTERSGEOMETRY_EXPORT vtkAbstractGridConnectivity : public vtkObject std::vector< vtkUnsignedCharArray* > GhostedPointGhostArray; std::vector< vtkUnsignedCharArray* > GhostedCellGhostArray; std::vector< vtkPoints* > GhostedGridPoints; - // ETX private: vtkAbstractGridConnectivity(const vtkAbstractGridConnectivity&);// Not implemented diff --git a/Filters/Geometry/vtkDataSetSurfaceFilter.cxx b/Filters/Geometry/vtkDataSetSurfaceFilter.cxx index c5547df924f..2f7eb359ce2 100644 --- a/Filters/Geometry/vtkDataSetSurfaceFilter.cxx +++ b/Filters/Geometry/vtkDataSetSurfaceFilter.cxx @@ -133,15 +133,6 @@ vtkDataSetSurfaceFilter::vtkDataSetSurfaceFilter() //---------------------------------------------------------------------------- vtkDataSetSurfaceFilter::~vtkDataSetSurfaceFilter() { - if (this->QuadHash) - { - this->DeleteQuadHash(); - } - if (this->OriginalCellIds != NULL) - { - this->OriginalCellIds->Delete(); - this->OriginalCellIds = NULL; - } this->SetOriginalCellIdsName(NULL); this->SetOriginalPointIdsName(NULL); } @@ -172,6 +163,7 @@ int vtkDataSetSurfaceFilter::RequestData( if (numCells == 0) { + vtkWarningMacro(<<"Number of cells is zero, no data to process."); return 1; } @@ -192,10 +184,7 @@ int vtkDataSetSurfaceFilter::RequestData( case VTK_UNSTRUCTURED_GRID: case VTK_UNSTRUCTURED_GRID_BASE: { - if (!this->UnstructuredGridExecute(input, output)) - { - return 1; - } + this->UnstructuredGridExecute(input, output); output->CheckAttributes(); return 1; } @@ -341,8 +330,8 @@ int vtkDataSetSurfaceFilter::UniformGridExecute( if( this->UseStrips ) { - vtkWarningMacro( "Strips are not supported for uniform grid!" ); - return 0; + vtkErrorMacro( "Strips are not supported for uniform grid!" ); + return 0; } vtkIdType numPoints,numCells; @@ -410,18 +399,18 @@ int vtkDataSetSurfaceFilter::UniformGridExecute( this->ExecuteFaceQuads(input, output, 1, ext, 2,1,0, wholeExt, true ); output->Squeeze(); - if (this->OriginalCellIds != NULL) - { - this->OriginalCellIds->Delete(); - this->OriginalCellIds = NULL; - } - if (this->OriginalPointIds != NULL) - { - this->OriginalPointIds->Delete(); - this->OriginalPointIds = NULL; - } this->PassThroughCellIds = originalPassThroughCellIds; + if (this->OriginalPointIds) + { + this->OriginalPointIds->Delete(); + this->OriginalPointIds = NULL; + } + if (this->OriginalCellIds) + { + this->OriginalCellIds->Delete(); + this->OriginalPointIds = NULL; + } return 1; } @@ -525,8 +514,9 @@ int vtkDataSetSurfaceFilter::StructuredExecute(vtkDataSet *input, } default: dataType = VTK_DOUBLE; - vtkWarningMacro("Invalid data set type."); - break; + vtkErrorMacro("Invalid data set type: " << input->GetDataObjectType()); + outPoints->Delete(); + return 1; } outPoints->SetDataType(dataType); @@ -1069,6 +1059,7 @@ int vtkDataSetSurfaceFilter::DataSetExecute(vtkDataSet *input, vtkCellData *outputCD = output->GetCellData(); if (numCells == 0) { + vtkWarningMacro(<<"Number of cells is zero, no data to process."); return 1; } @@ -1273,7 +1264,7 @@ void vtkDataSetSurfaceFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); - if (this->UseStrips) + if (this->GetUseStrips()) { os << indent << "UseStripsOn\n"; } @@ -1282,15 +1273,15 @@ void vtkDataSetSurfaceFilter::PrintSelf(ostream& os, vtkIndent indent) os << indent << "UseStripsOff\n"; } - os << indent << "PieceInvariant: " << this->PieceInvariant << endl; - os << indent << "PassThroughCellIds: " << (this->PassThroughCellIds ? "On\n" : "Off\n"); - os << indent << "PassThroughPointIds: " << (this->PassThroughPointIds ? "On\n" : "Off\n"); + os << indent << "PieceInvariant: " << this->GetPieceInvariant() << endl; + os << indent << "PassThroughCellIds: " << (this->GetPassThroughCellIds() ? "On\n" : "Off\n"); + os << indent << "PassThroughPointIds: " << (this->GetPassThroughPointIds() ? "On\n" : "Off\n"); os << indent << "OriginalCellIdsName: " << this->GetOriginalCellIdsName() << endl; os << indent << "OriginalPointIdsName: " << this->GetOriginalPointIdsName() << endl; os << indent << "NonlinearSubdivisionLevel: " - << this->NonlinearSubdivisionLevel << endl; + << this->GetNonlinearSubdivisionLevel() << endl; } //======================================================================== @@ -1851,7 +1842,7 @@ int vtkDataSetSurfaceFilter::UnstructuredGridExecute(vtkDataSet *dataSetInput, for (cellPtId = 0; cell->GetPointId(cellPtId) != ptId; cellPtId++) { } - parametricCoords->InsertNextTupleValue(pc + 3*cellPtId); + parametricCoords->InsertNextTypedTuple(pc + 3*cellPtId); } // Subdivide these triangles as many more times as necessary. Remember // that we have already done the first subdivision. @@ -1873,7 +1864,7 @@ int vtkDataSetSurfaceFilter::UnstructuredGridExecute(vtkDataSet *dataSetInput, for (k = 0; k < 3; k++) { inPts[k] = outPts->GetId(i+k); - parametricCoords->GetTupleValue(i+k, inParamCoords[k]); + parametricCoords->GetTypedTuple(i+k, inParamCoords[k]); } for (k = 3; k < 6; k++) { @@ -1900,7 +1891,7 @@ int vtkDataSetSurfaceFilter::UnstructuredGridExecute(vtkDataSet *dataSetInput, { int localId = subtriangles[k]; outPts2->InsertNextId(inPts[localId]); - parametricCoords2->InsertNextTupleValue(inParamCoords[localId]); + parametricCoords2->InsertNextTypedTuple(inParamCoords[localId]); } } // Iterate over triangles // Now that we have recorded the subdivided triangles in outPts2 and @@ -2090,7 +2081,7 @@ void vtkDataSetSurfaceFilter::InsertQuadInHash(vtkIdType a, vtkIdType b, // c should be independent of point order. if (quad->numPts == 4 && c == quad->ptArray[2]) { - // Check boh orders for b and d. + // Check both orders for b and d. if ((b == quad->ptArray[1] && d == quad->ptArray[3]) || (b == quad->ptArray[3] && d == quad->ptArray[1])) { // We have a match. diff --git a/Filters/Geometry/vtkDataSetSurfaceFilter.h b/Filters/Geometry/vtkDataSetSurfaceFilter.h index 4b775697fbc..6560a7b0e50 100644 --- a/Filters/Geometry/vtkDataSetSurfaceFilter.h +++ b/Filters/Geometry/vtkDataSetSurfaceFilter.h @@ -33,7 +33,6 @@ class vtkPointData; class vtkPoints; class vtkIdTypeArray; -//BTX // Helper structure for hashing faces. struct vtkFastGeomQuadStruct { @@ -43,7 +42,6 @@ struct vtkFastGeomQuadStruct vtkIdType* ptArray; }; typedef struct vtkFastGeomQuadStruct vtkFastGeomQuad; -//ETX class VTKFILTERSGEOMETRY_EXPORT vtkDataSetSurfaceFilter : public vtkPolyDataAlgorithm { @@ -207,9 +205,9 @@ class VTKFILTERSGEOMETRY_EXPORT vtkDataSetSurfaceFilter : public vtkPolyDataAlgo vtkIdType *PointMap; vtkIdType GetOutputPointId(vtkIdType inPtId, vtkDataSet *input, vtkPoints *outPts, vtkPointData *outPD); -//BTX + class vtkEdgeInterpolationMap; -//ETX + vtkEdgeInterpolationMap *EdgeMap; vtkIdType GetInterpolatedPointId(vtkIdType edgePtA, vtkIdType edgePtB, vtkDataSet *input, vtkCell *cell, diff --git a/Filters/Geometry/vtkGeometryFilter.cxx b/Filters/Geometry/vtkGeometryFilter.cxx index eb353a43a07..1d98d3091a2 100644 --- a/Filters/Geometry/vtkGeometryFilter.cxx +++ b/Filters/Geometry/vtkGeometryFilter.cxx @@ -755,6 +755,13 @@ void vtkGeometryFilter::UnstructuredGridExecute(vtkDataSet *dataSetInput, case VTK_PIXEL: polys->InsertNextCell(npts); + // pixelConvert (in the following loop) is an int[4]. GCC 5.1.1 + // warns about pixelConvert[4] being uninitialized due to loop + // unrolling -- forcibly restricting npts <= 4 prevents this warning. + if (npts > 4) + { + npts = 4; + } for ( int i=0; i < npts; i++) { polys->InsertCellPoint(pts[pixelConvert[i]]); diff --git a/Filters/Geometry/vtkStructuredAMRGridConnectivity.h b/Filters/Geometry/vtkStructuredAMRGridConnectivity.h index b8690987c69..49c457a899c 100644 --- a/Filters/Geometry/vtkStructuredAMRGridConnectivity.h +++ b/Filters/Geometry/vtkStructuredAMRGridConnectivity.h @@ -478,7 +478,6 @@ class VTKFILTERSGEOMETRY_EXPORT vtkStructuredAMRGridConnectivity : // grids in the hierarchy can only differ by one // level. - // BTX // AMRHierarchy stores the the set of grid Ids in [0,N] for each level std::map< int, std::set > AMRHierarchy; @@ -498,7 +497,6 @@ class VTKFILTERSGEOMETRY_EXPORT vtkStructuredAMRGridConnectivity : // RefinementRatios stores the refinement ratio at each level, this vector // is used only when the refinement ratio varies across levels std::vector< int > RefinementRatios; - // ETX private: vtkStructuredAMRGridConnectivity(const vtkStructuredAMRGridConnectivity&); // Not implemented diff --git a/Filters/Geometry/vtkStructuredGridConnectivity.h b/Filters/Geometry/vtkStructuredGridConnectivity.h index e85b3e1446e..9b420fa0b93 100644 --- a/Filters/Geometry/vtkStructuredGridConnectivity.h +++ b/Filters/Geometry/vtkStructuredGridConnectivity.h @@ -551,13 +551,11 @@ class VTKFILTERSGEOMETRY_EXPORT vtkStructuredGridConnectivity : int DataDescription; int WholeExtent[6]; - // BTX std::vector< int > GridExtents; std::vector< int > GhostedExtents; std::vector< unsigned char > BlockTopology; std::vector< std::vector > Neighbors; std::map< std::pair< int,int >, int > NeighborPair2NeighborListIndex; - // ETX private: vtkStructuredGridConnectivity( const vtkStructuredGridConnectivity& ); // Not implemented diff --git a/Filters/Hybrid/Testing/Cxx/TestTemporalCacheSimple.cxx b/Filters/Hybrid/Testing/Cxx/TestTemporalCacheSimple.cxx index 1ccfbe89082..676e2d107c1 100644 --- a/Filters/Hybrid/Testing/Cxx/TestTemporalCacheSimple.cxx +++ b/Filters/Hybrid/Testing/Cxx/TestTemporalCacheSimple.cxx @@ -60,9 +60,7 @@ class vtkTemporalSphereSource : public vtkSphereSource { // Save the range of valid timestep index values. vtkGetVector2Macro(TimeStepRange, int); - //BTX // void GetTimeStepValues(std::vector &steps); - //ETX protected: vtkTemporalSphereSource(); diff --git a/Filters/Hybrid/vtkBSplineTransform.h b/Filters/Hybrid/vtkBSplineTransform.h index 09c29b8c4e6..7b9d23e371d 100644 --- a/Filters/Hybrid/vtkBSplineTransform.h +++ b/Filters/Hybrid/vtkBSplineTransform.h @@ -122,12 +122,10 @@ class VTKFILTERSHYBRID_EXPORT vtkBSplineTransform : public vtkWarpTransform void InverseTransformDerivative(const double in[3], double out[3], double derivative[3][3]); -//BTX void (*CalculateSpline)(const double point[3], double displacement[3], double derivatives[3][3], void *gridPtr, int inExt[6], vtkIdType inInc[3], int borderMode); -//ETX double DisplacementScale; int BorderMode; diff --git a/Filters/Hybrid/vtkDepthSortPolyData.cxx b/Filters/Hybrid/vtkDepthSortPolyData.cxx index 7e5b88dca6a..6c566418ed9 100644 --- a/Filters/Hybrid/vtkDepthSortPolyData.cxx +++ b/Filters/Hybrid/vtkDepthSortPolyData.cxx @@ -88,10 +88,7 @@ void getCellCenterDepth(vtkPolyData *pds, vtkDataArray *gpts, return; } - vtkDataArrayTemplate *pts - = static_cast*>(gpts); - - T *ppts = pts->GetPointer(0); + T *ppts = static_cast(gpts->GetVoidPointer(0)); T *px = ppts; T *py = ppts + 1; T *pz = ppts + 2; @@ -148,10 +145,7 @@ void getCellPoint0Depth(vtkPolyData *pds, vtkDataArray *gpts, return; } - vtkDataArrayTemplate *pts - = static_cast*>(gpts); - - T *ppts = pts->GetPointer(0); + T *ppts = static_cast(gpts->GetVoidPointer(0)); T *px = ppts; T *py = ppts + 1; T *pz = ppts + 2; diff --git a/Filters/Hybrid/vtkFacetReader.cxx b/Filters/Hybrid/vtkFacetReader.cxx index 0cb71096fd3..67fa4cdb87a 100644 --- a/Filters/Hybrid/vtkFacetReader.cxx +++ b/Filters/Hybrid/vtkFacetReader.cxx @@ -56,7 +56,7 @@ static bool GetLineFromStream(istream& is, // If no characters are read from the stream, the end of file has // been reached. - while((is.getline(buffer, bufferSize), is.gcount() > 0)) + while(((void)(is.getline(buffer, bufferSize)), (is.gcount() > 0))) { haveData = true; line.append(buffer); diff --git a/Filters/Hybrid/vtkGridTransform.h b/Filters/Hybrid/vtkGridTransform.h index 8b2f2acdbeb..b4f5e720ee2 100644 --- a/Filters/Hybrid/vtkGridTransform.h +++ b/Filters/Hybrid/vtkGridTransform.h @@ -120,12 +120,11 @@ class VTKFILTERSHYBRID_EXPORT vtkGridTransform : public vtkWarpTransform void InverseTransformDerivative(const double in[3], double out[3], double derivative[3][3]); -//BTX void (*InterpolationFunction)(double point[3], double displacement[3], double derivatives[3][3], void *gridPtr, int gridType, int inExt[6], vtkIdType inInc[3]); -//ETX + int InterpolationMode; double DisplacementScale; double DisplacementShift; @@ -144,8 +143,6 @@ class VTKFILTERSHYBRID_EXPORT vtkGridTransform : public vtkWarpTransform vtkGridTransformConnectionHolder* ConnectionHolder; }; -//BTX - //---------------------------------------------------------------------------- inline const char *vtkGridTransform::GetInterpolationModeAsString() { @@ -161,7 +158,6 @@ inline const char *vtkGridTransform::GetInterpolationModeAsString() return ""; } } -//ETX #endif diff --git a/Filters/Hybrid/vtkProjectedTerrainPath.h b/Filters/Hybrid/vtkProjectedTerrainPath.h index 3d9441e4f7b..7229e47d409 100644 --- a/Filters/Hybrid/vtkProjectedTerrainPath.h +++ b/Filters/Hybrid/vtkProjectedTerrainPath.h @@ -96,9 +96,7 @@ class VTKFILTERSHYBRID_EXPORT vtkProjectedTerrainPath : public vtkPolyDataAlgori // Note: vtkImageData* is required void SetSourceConnection(vtkAlgorithmOutput* algOutput); -//BTX enum {SIMPLE_PROJECTION=0,NONOCCLUDED_PROJECTION,HUG_PROJECTION}; -//ETX // Description: // Determine how to control the projection process. Simple projection diff --git a/Filters/Hybrid/vtkTemporalDataSetCache.h b/Filters/Hybrid/vtkTemporalDataSetCache.h index 11c439a18e1..00fee206123 100644 --- a/Filters/Hybrid/vtkTemporalDataSetCache.h +++ b/Filters/Hybrid/vtkTemporalDataSetCache.h @@ -52,12 +52,9 @@ class VTKFILTERSHYBRID_EXPORT vtkTemporalDataSetCache : public vtkAlgorithm int CacheSize; -//BTX typedef std::map > CacheType; CacheType Cache; -//ETX - // Description: // see vtkAlgorithm for details diff --git a/Filters/Hybrid/vtkTemporalInterpolator.cxx b/Filters/Hybrid/vtkTemporalInterpolator.cxx index 6b506847d1b..463abe1ea89 100644 --- a/Filters/Hybrid/vtkTemporalInterpolator.cxx +++ b/Filters/Hybrid/vtkTemporalInterpolator.cxx @@ -459,7 +459,7 @@ ::InterpolateDataSet(vtkDataSet *in1, vtkDataSet *in2, double ratio) outPointSet->SetPoints(outpoints); } - if (vtkDoubleArray::SafeDownCast(outarray)) + if (vtkArrayDownCast(outarray)) { outpoints->SetDataTypeToDouble(); } @@ -626,7 +626,7 @@ ::InterpolateDataArray(double ratio, vtkDataArray **arrays, vtkIdType N) // Create the output // vtkAbstractArray *aa = arrays[0]->CreateArray(arrays[0]->GetDataType()); - vtkDataArray *output = vtkDataArray::SafeDownCast(aa); + vtkDataArray *output = vtkArrayDownCast(aa); int Nc = arrays[0]->GetNumberOfComponents(); diff --git a/Filters/Hybrid/vtkTemporalSnapToTimeStep.h b/Filters/Hybrid/vtkTemporalSnapToTimeStep.h index 9dd3abc8261..27cd91be764 100644 --- a/Filters/Hybrid/vtkTemporalSnapToTimeStep.h +++ b/Filters/Hybrid/vtkTemporalSnapToTimeStep.h @@ -32,9 +32,7 @@ #include "vtkFiltersHybridModule.h" // For export macro #include "vtkAlgorithm.h" -//BTX #include // used because I am a bad boy. So there. -//ETX class VTKFILTERSHYBRID_EXPORT vtkTemporalSnapToTimeStep : public vtkAlgorithm { @@ -43,13 +41,12 @@ class VTKFILTERSHYBRID_EXPORT vtkTemporalSnapToTimeStep : public vtkAlgorithm vtkTypeMacro(vtkTemporalSnapToTimeStep, vtkAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); -//BTX enum { VTK_SNAP_NEAREST=0, VTK_SNAP_NEXTBELOW_OR_EQUAL, VTK_SNAP_NEXTABOVE_OR_EQUAL }; -//ETX + vtkSetMacro(SnapMode,int); vtkGetMacro(SnapMode,int); void SetSnapModeToNearest() { this->SetSnapMode(VTK_SNAP_NEAREST); } @@ -80,11 +77,9 @@ class VTKFILTERSHYBRID_EXPORT vtkTemporalSnapToTimeStep : public vtkAlgorithm vtkInformationVector **, vtkInformationVector *); -//BTX std::vector InputTimeValues; int HasDiscrete; int SnapMode; -//ETX private: vtkTemporalSnapToTimeStep(const vtkTemporalSnapToTimeStep&); // Not implemented. diff --git a/Filters/HyperTree/vtkHyperOctreeContourFilter.h b/Filters/HyperTree/vtkHyperOctreeContourFilter.h index a807bfebce8..8c447ff8727 100644 --- a/Filters/HyperTree/vtkHyperOctreeContourFilter.h +++ b/Filters/HyperTree/vtkHyperOctreeContourFilter.h @@ -225,9 +225,8 @@ class VTKFILTERSHYPERTREE_EXPORT vtkHyperOctreeContourFilter : public vtkPolyDat double LeftValue; double LeftCoord; - //BTX friend class vtkHyperOctreeContourPointsGrabber; - //ETX + private: vtkHyperOctreeContourFilter(const vtkHyperOctreeContourFilter&); // Not implemented. void operator=(const vtkHyperOctreeContourFilter&); // Not implemented. diff --git a/Filters/Imaging/vtkComputeHistogram2DOutliers.cxx b/Filters/Imaging/vtkComputeHistogram2DOutliers.cxx index 2668c078d22..baf1a98be50 100644 --- a/Filters/Imaging/vtkComputeHistogram2DOutliers.cxx +++ b/Filters/Imaging/vtkComputeHistogram2DOutliers.cxx @@ -363,8 +363,8 @@ int vtkComputeHistogram2DOutliers::FillOutlierIds(vtkTable* data, vtkCollection* vtkSmartPointer uniqueRowIds = vtkSmartPointer::New(); for (int i=0; iGetColumn(i)); - vtkDataArray* col2 = vtkDataArray::SafeDownCast(data->GetColumn(i+1)); + vtkDataArray* col1 = vtkArrayDownCast(data->GetColumn(i)); + vtkDataArray* col2 = vtkArrayDownCast(data->GetColumn(i+1)); vtkDoubleArray* currThresholds = vtkDoubleArray::SafeDownCast(thresholds->GetItemAsObject(i)); for (int j=0; jGetNumberOfTuples(); j++) diff --git a/Filters/Imaging/vtkComputeHistogram2DOutliers.h b/Filters/Imaging/vtkComputeHistogram2DOutliers.h index 6885029098c..192335dc910 100644 --- a/Filters/Imaging/vtkComputeHistogram2DOutliers.h +++ b/Filters/Imaging/vtkComputeHistogram2DOutliers.h @@ -67,7 +67,7 @@ class VTKFILTERSIMAGING_EXPORT vtkComputeHistogram2DOutliers : public vtkSelecti // vtkTable* GetOutputTable(); -//BTX + enum InputPorts { INPUT_TABLE_DATA=0, @@ -79,7 +79,6 @@ class VTKFILTERSIMAGING_EXPORT vtkComputeHistogram2DOutliers : public vtkSelecti OUTPUT_SELECTED_ROWS=0, OUTPUT_SELECTED_TABLE_DATA }; -//ETX // Description: // Set the source table data, from which data will be filtered. diff --git a/Filters/Imaging/vtkExtractHistogram2D.cxx b/Filters/Imaging/vtkExtractHistogram2D.cxx index 259e95b15a9..eb22a42a122 100644 --- a/Filters/Imaging/vtkExtractHistogram2D.cxx +++ b/Filters/Imaging/vtkExtractHistogram2D.cxx @@ -255,15 +255,15 @@ int vtkExtractHistogram2D::GetInputArrays(vtkDataArray*& col1, vtkDataArray*& co vtkStdString colName; this->Internals->GetColumnForRequest( 0, (this->SwapColumns != 0), colName ); - col1 = vtkDataArray::SafeDownCast( inData->GetColumnByName( colName ) ); + col1 = vtkArrayDownCast( inData->GetColumnByName( colName ) ); this->Internals->GetColumnForRequest( 0, (this->SwapColumns == 0), colName ); - col2 = vtkDataArray::SafeDownCast( inData->GetColumnByName( colName ) ); + col2 = vtkArrayDownCast( inData->GetColumnByName( colName ) ); } else { - col1 = vtkDataArray::SafeDownCast( inData->GetColumn( 0 ) ); - col2 = vtkDataArray::SafeDownCast( inData->GetColumn( 1 ) ); + col1 = vtkArrayDownCast( inData->GetColumn( 0 ) ); + col2 = vtkArrayDownCast( inData->GetColumn( 1 ) ); } if (!col2) diff --git a/Filters/Imaging/vtkExtractHistogram2D.h b/Filters/Imaging/vtkExtractHistogram2D.h index 5acaf0f3143..9ce54a26c9f 100644 --- a/Filters/Imaging/vtkExtractHistogram2D.h +++ b/Filters/Imaging/vtkExtractHistogram2D.h @@ -58,12 +58,10 @@ class VTKFILTERSIMAGING_EXPORT vtkExtractHistogram2D : public vtkStatisticsAlgor vtkTypeMacro(vtkExtractHistogram2D, vtkStatisticsAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); -//BTX enum OutputIndices { HISTOGRAM_IMAGE=3 }; -//ETX // Description: // Set/get the number of bins to be used per dimension (x,y) diff --git a/Filters/Imaging/vtkPairwiseExtractHistogram2D.cxx b/Filters/Imaging/vtkPairwiseExtractHistogram2D.cxx index 1ad75f6ece5..dfe73a49285 100644 --- a/Filters/Imaging/vtkPairwiseExtractHistogram2D.cxx +++ b/Filters/Imaging/vtkPairwiseExtractHistogram2D.cxx @@ -128,8 +128,8 @@ void vtkPairwiseExtractHistogram2D::Learn(vtkTable *inData, // fill it up with new histogram filters for (int i=0; iGetColumn(i)); - vtkDataArray* col2 = vtkDataArray::SafeDownCast(inData->GetColumn(i+1)); + vtkDataArray* col1 = vtkArrayDownCast(inData->GetColumn(i)); + vtkDataArray* col2 = vtkArrayDownCast(inData->GetColumn(i+1)); if (!col1 || !col2) { diff --git a/Filters/Imaging/vtkPairwiseExtractHistogram2D.h b/Filters/Imaging/vtkPairwiseExtractHistogram2D.h index 8fcac7e7f00..e173d03a0c9 100644 --- a/Filters/Imaging/vtkPairwiseExtractHistogram2D.h +++ b/Filters/Imaging/vtkPairwiseExtractHistogram2D.h @@ -125,12 +125,10 @@ class VTKFILTERSIMAGING_EXPORT vtkPairwiseExtractHistogram2D : public vtkStatist // Get a pointer to the idx'th histogram filter. vtkExtractHistogram2D* GetHistogramFilter(int idx); -//BTX enum OutputIndices { HISTOGRAM_IMAGE=3 }; -//ETX // Description: // Given a collection of models, calculate aggregate model. Not used @@ -144,12 +142,10 @@ class VTKFILTERSIMAGING_EXPORT vtkPairwiseExtractHistogram2D : public vtkStatist int ScalarType; int CustomColumnRangeIndex; - //BTX vtkSmartPointer OutputOutlierIds; vtkSmartPointer HistogramFilters; class Internals; Internals* Implementation; - //ETX // Description: // Execute the calculations required by the Learn option. diff --git a/Filters/Matlab/Testing/Cxx/TestMatlabEngineInterface.cxx b/Filters/Matlab/Testing/Cxx/TestMatlabEngineInterface.cxx index 7fa12da2012..09bc367ad75 100644 --- a/Filters/Matlab/Testing/Cxx/TestMatlabEngineInterface.cxx +++ b/Filters/Matlab/Testing/Cxx/TestMatlabEngineInterface.cxx @@ -77,7 +77,7 @@ int TestMatlabEngineInterface(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) d(:,2) = d(:,2) - 0.2;\n\ d(:,3) = d(:,3) - 0.3;\n"); cout << out_buffer << endl; - vtkDoubleArray* rda = vtkDoubleArray::SafeDownCast(mei->GetVtkDataArray("d")); + vtkDoubleArray* rda = vtkArrayDownCast(mei->GetVtkDataArray("d")); test_expression(rda); for(int i = 0;iGetNumberOfTuples();i++) { diff --git a/Filters/Matlab/vtkMatlabEngineFilter.cxx b/Filters/Matlab/vtkMatlabEngineFilter.cxx index 11a37cb8441..1ffb2840411 100644 --- a/Filters/Matlab/vtkMatlabEngineFilter.cxx +++ b/Filters/Matlab/vtkMatlabEngineFilter.cxx @@ -423,7 +423,7 @@ int vtkMatlabEngineFilter::RequestData(vtkInformation *vtkNotUsed(request), if(tableinp->GetColumnByName(VectorIterator->VTKArrName.c_str())) { - currentArray = vtkDataArray::SafeDownCast(tableinp->GetColumnByName(VectorIterator->VTKArrName.c_str())); + currentArray = vtkArrayDownCast(tableinp->GetColumnByName(VectorIterator->VTKArrName.c_str())); } if(currentArray) diff --git a/Filters/Matlab/vtkMatlabMexAdapter.h b/Filters/Matlab/vtkMatlabMexAdapter.h index fc91a86a2a2..daef6ea339c 100644 --- a/Filters/Matlab/vtkMatlabMexAdapter.h +++ b/Filters/Matlab/vtkMatlabMexAdapter.h @@ -75,7 +75,6 @@ class VTKFILTERSMATLAB_EXPORT vtkMatlabMexAdapter : public vtkObject static vtkMatlabMexAdapter *New(); -//BTX // Description: // Create a mxArray copy of a vtkDataArray (Allocates memory by default) mxArray* vtkDataArrayToMxArray(vtkDataArray* aa, bool ShallowCopy = false); @@ -112,8 +111,6 @@ class VTKFILTERSMATLAB_EXPORT vtkMatlabMexAdapter : public vtkObject // Match Matlab and VTK data types for conversion. static vtkDataArray* GetVTKDataType(mxClassID cid); -//ETX - protected: vtkMatlabMexAdapter(); diff --git a/Filters/Modeling/Testing/Cxx/TestQuadRotationalExtrusionMultiBlock.cxx b/Filters/Modeling/Testing/Cxx/TestQuadRotationalExtrusionMultiBlock.cxx index 4277929c787..338e8a702de 100644 --- a/Filters/Modeling/Testing/Cxx/TestQuadRotationalExtrusionMultiBlock.cxx +++ b/Filters/Modeling/Testing/Cxx/TestQuadRotationalExtrusionMultiBlock.cxx @@ -48,22 +48,25 @@ int TestQuadRotationalExtrusionMultiBlock( int argc, char * argv [] ) reader1->Update(); delete [] fName1; - // Create multi-block data set for quad-based sweep + // Create multi-block data set tree for quad-based sweep vtkNew inMesh; inMesh->SetNumberOfBlocks( 2 ); inMesh->GetMetaData( static_cast( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Block 0" ); inMesh->SetBlock( 0, reader0->GetOutput() ); - inMesh->GetMetaData( static_cast( 1 ) )->Set( vtkCompositeDataSet::NAME(), "Block 1" ); - inMesh->SetBlock( 1, reader1->GetOutput() ); + vtkNew inMesh2; + inMesh->SetBlock( 1, inMesh2.Get() ); + inMesh2->SetNumberOfBlocks( 1 ); + inMesh2->GetMetaData( static_cast( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Block 1" ); + inMesh2->SetBlock( 0, reader1->GetOutput() ); // Create 3/4 of a cylinder by rotational extrusion vtkNew sweeper; sweeper->SetResolution( 18 ); - sweeper->SetInputData( inMesh.GetPointer() ); + sweeper->SetInputData( inMesh.Get() ); sweeper->SetAxisToX(); sweeper->SetDefaultAngle( 270 ); sweeper->AddPerBlockAngle( 1, 90. ); - sweeper->AddPerBlockAngle( 2, 45.) ; + sweeper->AddPerBlockAngle( 3, 45.); // Turn composite output into single polydata vtkNew outMesh; @@ -80,7 +83,7 @@ int TestQuadRotationalExtrusionMultiBlock( int argc, char * argv [] ) // Create actor for surface representation of whole mesh vtkNew outMeshActor; - outMeshActor->SetMapper( outMeshMapper.GetPointer() ); + outMeshActor->SetMapper( outMeshMapper.Get() ); outMeshActor->GetProperty()->SetRepresentationToSurface(); outMeshActor->GetProperty()->SetInterpolationToGouraud(); outMeshActor->GetProperty()->SetColor( .9, .9, .9 ); @@ -89,7 +92,9 @@ int TestQuadRotationalExtrusionMultiBlock( int argc, char * argv [] ) sweeper->Update(); vtkMultiBlockDataSet* outMeshMB = sweeper->GetOutput(); vtkPolyData* outMesh0 = vtkPolyData::SafeDownCast( outMeshMB->GetBlock( 0 ) ); - vtkPolyData* outMesh1 = vtkPolyData::SafeDownCast( outMeshMB->GetBlock( 1 ) ); + vtkMultiBlockDataSet* outMeshMB2 = + vtkMultiBlockDataSet::SafeDownCast( outMeshMB->GetBlock( 1 ) ); + vtkPolyData* outMesh1 = vtkPolyData::SafeDownCast( outMeshMB2->GetBlock( 0 ) ); // Create mapper for wireframe representation of block 0 vtkNew outBlockMapper0; @@ -98,7 +103,7 @@ int TestQuadRotationalExtrusionMultiBlock( int argc, char * argv [] ) // Create actor for wireframe representation of block 0 vtkNew outBlockActor0; - outBlockActor0->SetMapper( outBlockMapper0.GetPointer() ); + outBlockActor0->SetMapper( outBlockMapper0.Get() ); outBlockActor0->GetProperty()->SetRepresentationToWireframe(); outBlockActor0->GetProperty()->SetColor( .9, 0., 0.); outBlockActor0->GetProperty()->SetAmbient( 1. ); @@ -112,7 +117,7 @@ int TestQuadRotationalExtrusionMultiBlock( int argc, char * argv [] ) // Create actor for wireframe representation of block 1 vtkNew outBlockActor1; - outBlockActor1->SetMapper( outBlockMapper1.GetPointer() ); + outBlockActor1->SetMapper( outBlockMapper1.Get() ); outBlockActor1->GetProperty()->SetRepresentationToWireframe(); outBlockActor1->GetProperty()->SetColor( 0., .9, 0.); outBlockActor1->GetProperty()->SetAmbient( 1. ); @@ -121,14 +126,14 @@ int TestQuadRotationalExtrusionMultiBlock( int argc, char * argv [] ) // Create a renderer, add actors to it vtkNew ren1; - ren1->AddActor( outMeshActor.GetPointer() ); - ren1->AddActor( outBlockActor0.GetPointer() ); - ren1->AddActor( outBlockActor1.GetPointer() ); + ren1->AddActor( outMeshActor.Get() ); + ren1->AddActor( outBlockActor0.Get() ); + ren1->AddActor( outBlockActor1.Get() ); ren1->SetBackground( 1., 1., 1. ); // Create a renderWindow vtkNew renWin; - renWin->AddRenderer( ren1.GetPointer() ); + renWin->AddRenderer( ren1.Get() ); renWin->SetSize( 400, 400 ); renWin->SetMultiSamples( 0 ); @@ -139,17 +144,17 @@ int TestQuadRotationalExtrusionMultiBlock( int argc, char * argv [] ) camera->SetPosition( 37.77735939083618, 0.42739828159854326, 2.988046512725565 ); camera->SetViewUp( -0.40432906992858864, 0.8891923825021084, 0.21413759621072337 ); camera->SetViewAngle( 30. ); - ren1->SetActiveCamera( camera.GetPointer() ); + ren1->SetActiveCamera( camera.Get() ); ren1->ResetCameraClippingRange(); // Create interactor vtkNew iren; - iren->SetRenderWindow( renWin.GetPointer() ); + iren->SetRenderWindow( renWin.Get() ); // Render and test renWin->Render(); - int retVal = vtkRegressionTestImage( renWin.GetPointer() ); + int retVal = vtkRegressionTestImage( renWin.Get() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR ) { iren->Start(); diff --git a/Filters/Modeling/vtkButterflySubdivisionFilter.cxx b/Filters/Modeling/vtkButterflySubdivisionFilter.cxx index 808611632f7..296058d6274 100644 --- a/Filters/Modeling/vtkButterflySubdivisionFilter.cxx +++ b/Filters/Modeling/vtkButterflySubdivisionFilter.cxx @@ -462,7 +462,7 @@ void vtkButterflySubdivisionFilter::GenerateButterflyStencil ( } else { - vtkWarningMacro (<< "bad p5, p4 " << p5 << ", " << p4); + vtkWarningMacro (<< "bad p6, p4 " << p6 << ", " << p4); } if (p7 != -1) @@ -488,7 +488,7 @@ void vtkButterflySubdivisionFilter::GenerateButterflyStencil ( } else { - vtkWarningMacro (<< "bad p7, p8 " << p7 << ", " << p3); + vtkWarningMacro (<< "bad p8, p3 " << p8 << ", " << p3); } diff --git a/Filters/Modeling/vtkLinearExtrusionFilter.h b/Filters/Modeling/vtkLinearExtrusionFilter.h index 79c91c9abc6..ec94c1e0c91 100644 --- a/Filters/Modeling/vtkLinearExtrusionFilter.h +++ b/Filters/Modeling/vtkLinearExtrusionFilter.h @@ -113,13 +113,11 @@ class VTKFILTERSMODELING_EXPORT vtkLinearExtrusionFilter : public vtkPolyDataAlg double Vector[3]; double ExtrusionPoint[3]; - //BTX void (vtkLinearExtrusionFilter::*ExtrudePoint)(double x[3], vtkIdType id, vtkDataArray *normals); void ViaNormal(double x[3], vtkIdType id, vtkDataArray *normals); void ViaVector(double x[3], vtkIdType id, vtkDataArray *normals=0); void ViaPoint(double x[3], vtkIdType id, vtkDataArray *normals=0); - //ETX private: vtkLinearExtrusionFilter(const vtkLinearExtrusionFilter&); // Not implemented. diff --git a/Filters/Modeling/vtkQuadRotationalExtrusionFilter.cxx b/Filters/Modeling/vtkQuadRotationalExtrusionFilter.cxx index 35a97d277d2..7471edf721f 100644 --- a/Filters/Modeling/vtkQuadRotationalExtrusionFilter.cxx +++ b/Filters/Modeling/vtkQuadRotationalExtrusionFilter.cxx @@ -172,11 +172,11 @@ int vtkQuadRotationalExtrusionFilter::RequestData( vtkInformation* vtkNotUsed( r // Get composite input vtkCompositeDataSet * compositeInput = vtkCompositeDataSet::SafeDownCast( - inInfo->Get( vtkDataObject::DATA_OBJECT() ) ); + inInfo->Get( vtkDataObject::DATA_OBJECT() ) ); // Get typed output vtkMultiBlockDataSet * compositeOutput = vtkMultiBlockDataSet::SafeDownCast( - outInfo->Get( vtkDataObject::DATA_OBJECT() )); + outInfo->Get( vtkDataObject::DATA_OBJECT() )); if( compositeInput==0 || compositeOutput==0 ) { @@ -184,23 +184,36 @@ int vtkQuadRotationalExtrusionFilter::RequestData( vtkInformation* vtkNotUsed( r return 0; } - std::map outputBlocks; - vtkDebugMacro(<<"input="<GetClassName()<<"\n"); + // we want the output to have the same structure than the input + compositeOutput->CopyStructure(compositeInput); + // allocate composite iterator vtkCompositeDataIterator * inputIterator = compositeInput->NewIterator(); - inputIterator->SkipEmptyNodesOn(); + inputIterator->SkipEmptyNodesOff(); inputIterator->InitTraversal(); - inputIterator->GoToFirstItem(); + + vtkCompositeDataIterator * outputIterator = compositeOutput->NewIterator(); + outputIterator->SkipEmptyNodesOff(); + outputIterator->InitTraversal(); while ( inputIterator->IsDoneWithTraversal() == 0 ) { // get the input and ouptut - vtkPolyData *input = vtkPolyData::SafeDownCast( inputIterator->GetCurrentDataObject() ); - vtkPolyData *output = vtkPolyData::New(); int blockId = inputIterator->GetCurrentFlatIndex(); + vtkPolyData *input = vtkPolyData::SafeDownCast( inputIterator->GetCurrentDataObject() ); inputIterator->GoToNextItem(); + if (!input) + { + outputIterator->GoToNextItem(); + continue; + } + + vtkPolyData *output = vtkPolyData::New(); + compositeOutput->SetDataSet(outputIterator, output); + outputIterator->GoToNextItem(); + output->Delete(); vtkIdType numPts, numCells; numPts = input->GetNumberOfPoints(); @@ -488,29 +501,12 @@ int vtkQuadRotationalExtrusionFilter::RequestData( vtkInformation* vtkNotUsed( r output->Squeeze(); - if ( blockId == -1 ) - { - blockId = static_cast( outputBlocks.size() ); - } - outputBlocks[blockId] = output; - } /* if numPts>0 && numCells>0 */ } /* Iterate over input blocks */ - inputIterator->Delete(); - - // build final composite output. also tagging blocks with their associated Id - compositeOutput->SetNumberOfBlocks( static_cast( outputBlocks.size() ) ); - int blockIndex=0; - for( std::map::iterator it=outputBlocks.begin(); it!=outputBlocks.end(); ++it, ++blockIndex ) - { - if( it->second->GetNumberOfCells() > 0 ) - { - compositeOutput->SetBlock( blockIndex , it->second ); - it->second->Delete(); - } - } + inputIterator->Delete(); + outputIterator->Delete(); return 1; } diff --git a/Filters/Modeling/vtkQuadRotationalExtrusionFilter.h b/Filters/Modeling/vtkQuadRotationalExtrusionFilter.h index e75c11dea6a..fec200113b8 100644 --- a/Filters/Modeling/vtkQuadRotationalExtrusionFilter.h +++ b/Filters/Modeling/vtkQuadRotationalExtrusionFilter.h @@ -77,14 +77,12 @@ class VTKFILTERSMODELING_EXPORT vtkQuadRotationalExtrusionFilter : public vtkMul // vector (0,0,1), and point (0,0,0). static vtkQuadRotationalExtrusionFilter *New(); -//BTX enum RotationAxis { USE_X = 0, USE_Y = 1, USE_Z = 2 }; -//ETX // Description: // Set the axis of rotation to use. It is set by default to Z. @@ -148,9 +146,7 @@ class VTKFILTERSMODELING_EXPORT vtkQuadRotationalExtrusionFilter : public vtkMul double Translation; double DeltaRadius; -//BTX std::map PerBlockAngles; -//ETX private: vtkQuadRotationalExtrusionFilter(const vtkQuadRotationalExtrusionFilter&); // Not implemented. diff --git a/Filters/Modeling/vtkSelectEnclosedPoints.h b/Filters/Modeling/vtkSelectEnclosedPoints.h index 4d0d3fc2c85..293fb7a7dba 100644 --- a/Filters/Modeling/vtkSelectEnclosedPoints.h +++ b/Filters/Modeling/vtkSelectEnclosedPoints.h @@ -130,7 +130,7 @@ class VTKFILTERSMODELING_EXPORT vtkSelectEnclosedPoints : public vtkDataSetAlgor virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); virtual int FillInputPortInformation(int, vtkInformation *); - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; private: vtkSelectEnclosedPoints(const vtkSelectEnclosedPoints&); // Not implemented. diff --git a/Filters/Parallel/Testing/Cxx/ParallelResampling.cxx b/Filters/Parallel/Testing/Cxx/ParallelResampling.cxx index 53b36a9ac2f..e105188cf10 100644 --- a/Filters/Parallel/Testing/Cxx/ParallelResampling.cxx +++ b/Filters/Parallel/Testing/Cxx/ParallelResampling.cxx @@ -109,8 +109,8 @@ void MyProcess::Execute() vtkImageData *result = sampler->GetOutput(); // Compare RTData Array - vtkFloatArray* rtDataRef = vtkFloatArray::SafeDownCast(reference->GetPointData()->GetArray("RTData")); - vtkFloatArray* rtDataTest = vtkFloatArray::SafeDownCast(result->GetPointData()->GetArray("RTData")); + vtkFloatArray* rtDataRef = vtkArrayDownCast(reference->GetPointData()->GetArray("RTData")); + vtkFloatArray* rtDataTest = vtkArrayDownCast(result->GetPointData()->GetArray("RTData")); vtkIdType sizeRef = rtDataRef->GetNumberOfTuples(); if(sizeRef == rtDataTest->GetNumberOfTuples() && rtDataRef->GetNumberOfComponents() == 1) { diff --git a/Filters/Parallel/vtkAngularPeriodicFilter.cxx b/Filters/Parallel/vtkAngularPeriodicFilter.cxx index 0d5a3330ce6..03787898706 100644 --- a/Filters/Parallel/vtkAngularPeriodicFilter.cxx +++ b/Filters/Parallel/vtkAngularPeriodicFilter.cxx @@ -40,6 +40,7 @@ vtkStandardNewMacro(vtkAngularPeriodicFilter); //---------------------------------------------------------------------------- vtkAngularPeriodicFilter::vtkAngularPeriodicFilter() { + this->ComputeRotationsOnTheFly = true; this->RotationMode = VTK_ROTATION_MODE_DIRECT_ANGLE; this->RotationAngle = 180.; this->RotationArrayName = 0; @@ -59,6 +60,8 @@ vtkAngularPeriodicFilter::~vtkAngularPeriodicFilter() void vtkAngularPeriodicFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); + os << indent << "Compute Rotations on-the-fly: " << this->ComputeRotationsOnTheFly + << endl; if (this->RotationMode == VTK_ROTATION_MODE_DIRECT_ANGLE) { os << indent << "Rotation Mode: Direct Angle" << endl; @@ -188,6 +191,7 @@ void vtkAngularPeriodicFilter::CreatePeriodicDataSet( this->PeriodNumbers.push_back(periodsNb); output->SetDataSet(loc, multiPiece.Get()); } + //---------------------------------------------------------------------------- void vtkAngularPeriodicFilter::SetPeriodNumber(vtkCompositeDataIterator* loc, vtkCompositeDataSet* output, @@ -270,8 +274,18 @@ vtkDataArray* vtkAngularPeriodicFilter::TransformDataArray( pArray->SetCenter(this->Center); } pArray->SetNormalize(normalize); - pArray->InitializeArray(vtkFloatArray::SafeDownCast(inputArray)); - periodicArray = pArray; + pArray->InitializeArray(vtkArrayDownCast(inputArray)); + if (this->ComputeRotationsOnTheFly) + { + periodicArray = pArray; + } + else + { + vtkFloatArray *concrete = vtkFloatArray::New(); + concrete->DeepCopy(pArray); // instantiate the array + periodicArray = concrete; + pArray->Delete(); + } break; } case VTK_DOUBLE: @@ -285,8 +299,18 @@ vtkDataArray* vtkAngularPeriodicFilter::TransformDataArray( pArray->SetCenter(this->Center); } pArray->SetNormalize(normalize); - pArray->InitializeArray(vtkDoubleArray::SafeDownCast(inputArray)); - periodicArray = pArray; + pArray->InitializeArray(vtkArrayDownCast(inputArray)); + if (this->ComputeRotationsOnTheFly) + { + periodicArray = pArray; + } + else + { + vtkDoubleArray *concrete = vtkDoubleArray::New(); + concrete->DeepCopy(pArray); // instantiate the array + periodicArray = concrete; + pArray->Delete(); + } break; } default: @@ -297,6 +321,7 @@ vtkDataArray* vtkAngularPeriodicFilter::TransformDataArray( break; } } + return periodicArray; } diff --git a/Filters/Parallel/vtkAngularPeriodicFilter.h b/Filters/Parallel/vtkAngularPeriodicFilter.h index b3bee2fade2..927d5bece60 100644 --- a/Filters/Parallel/vtkAngularPeriodicFilter.h +++ b/Filters/Parallel/vtkAngularPeriodicFilter.h @@ -52,6 +52,14 @@ class VTKFILTERSPARALLEL_EXPORT vtkAngularPeriodicFilter : public vtkPeriodicFil vtkTypeMacro(vtkAngularPeriodicFilter, vtkPeriodicFilter); void PrintSelf(ostream& os, vtkIndent indent); + // Description: + // Set/Get whether the rotated array values should be computed + // on-the-fly (default), which is compute-intensive, or the arrays should be + // explicitly generated and stored, at the cost of using more memory. + vtkSetMacro(ComputeRotationsOnTheFly, bool); + vtkGetMacro(ComputeRotationsOnTheFly, bool); + vtkBooleanMacro(ComputeRotationsOnTheFly, bool); + // Description: // Set/Get The rotation mode. // VTK_ROTATION_MODE_DIRECT_ANGLE to specifiy a angle value (default), @@ -144,6 +152,8 @@ class VTKFILTERSPARALLEL_EXPORT vtkAngularPeriodicFilter : public vtkPeriodicFil vtkAngularPeriodicFilter(const vtkAngularPeriodicFilter&); // Not implemented. void operator=(const vtkAngularPeriodicFilter&); // Not implemented. + bool ComputeRotationsOnTheFly; + int RotationMode; char* RotationArrayName; // user-provided array name to use as angle, for ROTATION_MODE_ARRAY_VALUE diff --git a/Filters/Parallel/vtkCollectGraph.cxx b/Filters/Parallel/vtkCollectGraph.cxx index 96fb9151e00..e6a38fcc771 100644 --- a/Filters/Parallel/vtkCollectGraph.cxx +++ b/Filters/Parallel/vtkCollectGraph.cxx @@ -267,10 +267,10 @@ int vtkCollectGraph::RequestData( } vtkAbstractArray *idArr = curGraph->GetVertexData()->GetAbstractArray(idFieldName); - vtkStringArray *idArrStr = vtkStringArray::SafeDownCast(idArr); - vtkIntArray *idArrInt = vtkIntArray::SafeDownCast(idArr); + vtkStringArray *idArrStr = vtkArrayDownCast(idArr); + vtkIntArray *idArrInt = vtkArrayDownCast(idArr); - vtkIntArray *ghostLevelsArr = vtkIntArray::SafeDownCast( + vtkIntArray *ghostLevelsArr = vtkArrayDownCast( wholePointData->GetAbstractArray(vtkDataSetAttributes::GhostArrayName())); // Add new vertices @@ -340,7 +340,7 @@ int vtkCollectGraph::RequestData( } // Add non-ghost edges - vtkIntArray* edgeGhostLevelsArr = vtkIntArray::SafeDownCast( + vtkIntArray* edgeGhostLevelsArr = vtkArrayDownCast( curGraph->GetEdgeData()->GetAbstractArray(vtkDataSetAttributes::GhostArrayName())); curGraph->GetEdges(edges); while (edges->HasNext()) diff --git a/Filters/Parallel/vtkCollectGraph.h b/Filters/Parallel/vtkCollectGraph.h index 3f22e035c4a..29c92eb1e57 100644 --- a/Filters/Parallel/vtkCollectGraph.h +++ b/Filters/Parallel/vtkCollectGraph.h @@ -57,13 +57,11 @@ class VTKFILTERSPARALLEL_EXPORT vtkCollectGraph : public vtkGraphAlgorithm vtkGetMacro(PassThrough, int); vtkBooleanMacro(PassThrough, int); - //BTX enum { DIRECTED_OUTPUT, UNDIRECTED_OUTPUT, USE_INPUT_TYPE }; - //ETX // Description: // Directedness flag, used to signal whether the output graph is directed or undirected. diff --git a/Filters/Parallel/vtkExtractUserDefinedPiece.h b/Filters/Parallel/vtkExtractUserDefinedPiece.h index 82c1c2a32bc..a52dab4c865 100644 --- a/Filters/Parallel/vtkExtractUserDefinedPiece.h +++ b/Filters/Parallel/vtkExtractUserDefinedPiece.h @@ -43,9 +43,7 @@ class VTKFILTERSPARALLEL_EXPORT vtkExtractUserDefinedPiece : public vtkExtractUn static vtkExtractUserDefinedPiece *New(); virtual void PrintSelf(ostream& os, vtkIndent indent); -//BTX typedef int (*UserDefFunc)(vtkIdType cellID, vtkUnstructuredGrid *grid, void *constantData); -//ETX // Set the function used to identify the piece. The function should // return 1 if the cell is in the piece, and 0 otherwise. diff --git a/Filters/Parallel/vtkPExtractArraysOverTime.cxx b/Filters/Parallel/vtkPExtractArraysOverTime.cxx index a5f26275e07..492e0ddb3d0 100644 --- a/Filters/Parallel/vtkPExtractArraysOverTime.cxx +++ b/Filters/Parallel/vtkPExtractArraysOverTime.cxx @@ -196,7 +196,7 @@ void vtkPExtractArraysOverTime::MergeTables( return; } - vtkUnsignedCharArray* rValidPts = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray* rValidPts = vtkArrayDownCast( routput->GetRowData()->GetArray("vtkValidPointMask")); // Copy the valid values diff --git a/Filters/Parallel/vtkPExtractArraysOverTime.h b/Filters/Parallel/vtkPExtractArraysOverTime.h index e25c6298989..075df4a2822 100644 --- a/Filters/Parallel/vtkPExtractArraysOverTime.h +++ b/Filters/Parallel/vtkPExtractArraysOverTime.h @@ -50,12 +50,10 @@ class VTKFILTERSPARALLEL_EXPORT vtkPExtractArraysOverTime : public vtkExtractArr virtual void SetController(vtkMultiProcessController*); vtkGetObjectMacro(Controller, vtkMultiProcessController); -//BTX enum Tags { EXCHANGE_DATA = 1972 }; -//ETX protected: vtkPExtractArraysOverTime(); diff --git a/Filters/Parallel/vtkPProbeFilter.cxx b/Filters/Parallel/vtkPProbeFilter.cxx index 6cfe13b2da4..2ee9c4722f0 100644 --- a/Filters/Parallel/vtkPProbeFilter.cxx +++ b/Filters/Parallel/vtkPProbeFilter.cxx @@ -93,7 +93,7 @@ int vtkPProbeFilter::RequestData(vtkInformation *request, remotePointData = remoteProbeOutput->GetPointData(); - vtkCharArray* maskArray = vtkCharArray::SafeDownCast( + vtkCharArray* maskArray = vtkArrayDownCast( remotePointData->GetArray(this->ValidPointMaskArrayName)); // Iterate over all point data in the output gathered from the remove diff --git a/Filters/Parallel/vtkPProbeFilter.h b/Filters/Parallel/vtkPProbeFilter.h index 06e9f2d91b2..bee2afeb44d 100644 --- a/Filters/Parallel/vtkPProbeFilter.h +++ b/Filters/Parallel/vtkPProbeFilter.h @@ -39,7 +39,6 @@ class VTKFILTERSPARALLEL_EXPORT vtkPProbeFilter : public vtkCompositeDataProbeFi virtual void SetController(vtkMultiProcessController*); vtkGetObjectMacro(Controller, vtkMultiProcessController); -//BTX protected: vtkPProbeFilter(); ~vtkPProbeFilter(); @@ -59,7 +58,7 @@ class VTKFILTERSPARALLEL_EXPORT vtkPProbeFilter : public vtkCompositeDataProbeFi private: vtkPProbeFilter(const vtkPProbeFilter&); // Not implemented. void operator=(const vtkPProbeFilter&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/Parallel/vtkPReflectionFilter.h b/Filters/Parallel/vtkPReflectionFilter.h index df014ef051c..f1d1108e675 100644 --- a/Filters/Parallel/vtkPReflectionFilter.h +++ b/Filters/Parallel/vtkPReflectionFilter.h @@ -36,7 +36,6 @@ class VTKFILTERSPARALLEL_EXPORT vtkPReflectionFilter : public vtkReflectionFilte void SetController(vtkMultiProcessController*); vtkGetObjectMacro (Controller, vtkMultiProcessController); -//BTX protected: vtkPReflectionFilter(); ~vtkPReflectionFilter(); @@ -49,7 +48,7 @@ class VTKFILTERSPARALLEL_EXPORT vtkPReflectionFilter : public vtkReflectionFilte private: vtkPReflectionFilter(const vtkPReflectionFilter&); // Not implemented. void operator=(const vtkPReflectionFilter&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/Parallel/vtkPResampleFilter.h b/Filters/Parallel/vtkPResampleFilter.h index 459663b48b1..e6b1bf00811 100644 --- a/Filters/Parallel/vtkPResampleFilter.h +++ b/Filters/Parallel/vtkPResampleFilter.h @@ -54,7 +54,6 @@ class VTKFILTERSPARALLEL_EXPORT vtkPResampleFilter : public vtkImageAlgorithm vtkSetVector3Macro(SamplingDimension, int); vtkGetVector3Macro(SamplingDimension, int); -//BTX protected: vtkPResampleFilter(); ~vtkPResampleFilter(); @@ -76,7 +75,7 @@ class VTKFILTERSPARALLEL_EXPORT vtkPResampleFilter : public vtkImageAlgorithm private: vtkPResampleFilter(const vtkPResampleFilter&); // Not implemented. void operator=(const vtkPResampleFilter&); // Not implemented. -//ETX + }; #endif diff --git a/Filters/ParallelDIY2/Testing/Cxx/CMakeLists.txt b/Filters/ParallelDIY2/Testing/Cxx/CMakeLists.txt index 7f6921cb64b..db0bac36fb3 100644 --- a/Filters/ParallelDIY2/Testing/Cxx/CMakeLists.txt +++ b/Filters/ParallelDIY2/Testing/Cxx/CMakeLists.txt @@ -4,6 +4,7 @@ set (${vtk-module}CxxTests-MPI_NUMPROCS 2) vtk_add_test_mpi(${vtk-module}CxxTests-MPI tests TESTING_DATA TestPResampleToImage.cxx + TestPResampleToImageCompositeDataSet.cxx ) vtk_test_mpi_executable(${vtk-module}CxxTests-MPI tests) diff --git a/Filters/ParallelDIY2/Testing/Cxx/TestPResampleToImage.cxx b/Filters/ParallelDIY2/Testing/Cxx/TestPResampleToImage.cxx index 5361bfdc37e..3b921bfb1d3 100644 --- a/Filters/ParallelDIY2/Testing/Cxx/TestPResampleToImage.cxx +++ b/Filters/ParallelDIY2/Testing/Cxx/TestPResampleToImage.cxx @@ -16,6 +16,7 @@ #include "vtkPResampleToImage.h" #include "vtkActor.h" +#include "vtkCamera.h" #include "vtkClipDataSet.h" #include "vtkCompositeRenderManager.h" #include "vtkContourFilter.h" @@ -79,7 +80,7 @@ int TestPResampleToImage(int argc, char *argv[]) voi->SetInputConnection(resample->GetOutputPort()); vtkNew contour; - contour->SetValue(0, 157); + contour->SetValue(0, 200); contour->ComputeNormalsOn(); contour->SetInputConnection(voi->GetOutputPort()); @@ -106,6 +107,8 @@ int TestPResampleToImage(int argc, char *argv[]) if (world.rank() == 0) { prm->ResetAllCameras(); + renderer->GetActiveCamera()->Azimuth(90); + renWin->Render(); retVal = vtkRegressionTester::Test(argc, argv, renWin.GetPointer(), 10); if (retVal == vtkRegressionTester::DO_INTERACTOR) diff --git a/Filters/ParallelDIY2/Testing/Cxx/TestPResampleToImageCompositeDataSet.cxx b/Filters/ParallelDIY2/Testing/Cxx/TestPResampleToImageCompositeDataSet.cxx new file mode 100644 index 00000000000..d02f7279bec --- /dev/null +++ b/Filters/ParallelDIY2/Testing/Cxx/TestPResampleToImageCompositeDataSet.cxx @@ -0,0 +1,148 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestPResampleToImage.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkPResampleToImage.h" + +#include "vtkActor.h" +#include "vtkAssignAttribute.h" +#include "vtkCamera.h" +#include "vtkCompositeRenderManager.h" +#include "vtkContourFilter.h" +#include "vtkExtentTranslator.h" +#include "vtkImageData.h" +#include "vtkMPIController.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkNew.h" +#include "vtkPointDataToCellData.h" +#include "vtkPolyDataMapper.h" +#include "vtkRegressionTestImage.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkRTAnalyticSource.h" +#include "vtkSmartPointer.h" + +#include "vtk_diy2.h" // must include this before any diy header +#include VTK_DIY2_HEADER(diy/mpi.hpp) + + +int TestPResampleToImageCompositeDataSet(int argc, char *argv[]) +{ + diy::mpi::environment mpienv(argc, argv); + vtkNew controller; + controller->Initialize(&argc, &argv, true); + diy::mpi::communicator world; + + + // Setup parallel rendering + vtkNew prm; + vtkSmartPointer renderer = + vtkSmartPointer::Take(prm->MakeRenderer()); + vtkSmartPointer renWin = + vtkSmartPointer::Take(prm->MakeRenderWindow()); + renWin->AddRenderer(renderer.GetPointer()); + renWin->DoubleBufferOn(); + renWin->SetMultiSamples(0); + + vtkNew iren; + iren->SetRenderWindow(renWin.GetPointer()); + + prm->SetRenderWindow(renWin.GetPointer()); + prm->SetController(controller.GetPointer()); + + + // Create input dataset + const int piecesPerRank = 2; + int numberOfPieces = world.size() * piecesPerRank; + + vtkNew input; + input->SetNumberOfBlocks(numberOfPieces); + + vtkNew extentTranslator; + extentTranslator->SetWholeExtent(0, 31, 0, 31, 0, 31); + extentTranslator->SetNumberOfPieces(numberOfPieces); + extentTranslator->SetSplitModeToBlock(); + + vtkNew wavelet; + wavelet->SetWholeExtent(0, 31, 0, 31, 0, 31); + wavelet->SetCenter(16, 16, 16); + vtkNew pointToCell; + pointToCell->SetInputConnection(wavelet->GetOutputPort()); + + for (int i = 0; i < piecesPerRank; ++i) + { + int piece = (world.rank() * piecesPerRank) + i; + int pieceExtent[6]; + extentTranslator->SetPiece(piece); + extentTranslator->PieceToExtent(); + extentTranslator->GetExtent(pieceExtent); + pointToCell->UpdateExtent(pieceExtent); + vtkNew img; + img->DeepCopy(vtkImageData::SafeDownCast(pointToCell->GetOutput())); + input->SetBlock(piece, img.GetPointer()); + } + + + // create pipeline + vtkNew resample; + resample->SetInputDataObject(input.GetPointer()); + resample->SetController(controller.GetPointer()); + resample->SetUseInputBounds(true); + resample->SetSamplingDimensions(64, 64, 64); + + vtkNew assignAttrib; + assignAttrib->SetInputConnection(resample->GetOutputPort()); + assignAttrib->Assign("RTData", vtkDataSetAttributes::SCALARS, + vtkAssignAttribute::POINT_DATA); + + vtkNew contour; + contour->SetInputConnection(assignAttrib->GetOutputPort()); + contour->SetValue(0, 157); + contour->ComputeNormalsOn(); + + + // Execute pipeline and render + vtkNew mapper; + mapper->SetInputConnection(contour->GetOutputPort()); + mapper->Update(); + + vtkNew actor; + actor->SetMapper(mapper.GetPointer()); + renderer->AddActor(actor.GetPointer()); + + int retVal; + if (world.rank() == 0) + { + prm->ResetAllCameras(); + renWin->Render(); + retVal = vtkRegressionTester::Test(argc, argv, renWin.GetPointer(), 10); + if (retVal == vtkRegressionTester::DO_INTERACTOR) + { + prm->StartInteractor(); + } + controller->TriggerBreakRMIs(); + } + else + { + prm->StartServices(); + } + world.barrier(); + + diy::mpi::broadcast(world, retVal, 0); + + controller->Finalize(true); + + return !retVal; +} diff --git a/Filters/ParallelDIY2/Testing/Data/Baseline/TestPResampleToImage.png.md5 b/Filters/ParallelDIY2/Testing/Data/Baseline/TestPResampleToImage.png.md5 index 6701a28f1d3..542e8c10a70 100644 --- a/Filters/ParallelDIY2/Testing/Data/Baseline/TestPResampleToImage.png.md5 +++ b/Filters/ParallelDIY2/Testing/Data/Baseline/TestPResampleToImage.png.md5 @@ -1 +1 @@ -0bd2862d246c6a3993284e24ad7c8dcb +6a41243fcbccb00cc78ad0dbdb0c926f diff --git a/Filters/ParallelDIY2/Testing/Data/Baseline/TestPResampleToImageCompositeDataSet.png.md5 b/Filters/ParallelDIY2/Testing/Data/Baseline/TestPResampleToImageCompositeDataSet.png.md5 new file mode 100644 index 00000000000..069721bbb42 --- /dev/null +++ b/Filters/ParallelDIY2/Testing/Data/Baseline/TestPResampleToImageCompositeDataSet.png.md5 @@ -0,0 +1 @@ +bdc35379c9aee4c3b8e36394d511ddd6 diff --git a/Filters/ParallelDIY2/module.cmake b/Filters/ParallelDIY2/module.cmake index ad20dec53a8..5e252a510ec 100644 --- a/Filters/ParallelDIY2/module.cmake +++ b/Filters/ParallelDIY2/module.cmake @@ -7,11 +7,11 @@ if (NOT WIN32) MPI DEPENDS vtkFiltersCore + vtkParallelMPI vtkdiy2 TEST_DEPENDS vtkFiltersParallelMPI vtkInteractionStyle - vtkParallelMPI vtkRendering${VTK_RENDERING_BACKEND} vtkRenderingParallel vtkTestingCore diff --git a/Filters/ParallelDIY2/vtkPResampleToImage.cxx b/Filters/ParallelDIY2/vtkPResampleToImage.cxx index ce2d21a07f2..7e287412dcd 100644 --- a/Filters/ParallelDIY2/vtkPResampleToImage.cxx +++ b/Filters/ParallelDIY2/vtkPResampleToImage.cxx @@ -14,36 +14,42 @@ =========================================================================*/ #include "vtkPResampleToImage.h" +#include "vtkArrayDispatch.h" #include "vtkCharArray.h" -#include "vtkDataArrayIteratorMacro.h" +#include "vtkCompositeDataProbeFilter.h" +#include "vtkCompositeDataSet.h" +#include "vtkDataArrayAccessor.h" #include "vtkDataSetAttributes.h" #include "vtkExtentTranslator.h" #include "vtkIdList.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationVector.h" -#include "vtkMath.h" +#include "vtkMPI.h" +#include "vtkMPIController.h" +#include "vtkMPICommunicator.h" #include "vtkNew.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" -#include "vtkProbeFilter.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkUnsignedCharArray.h" #include "vtk_diy2.h" // must include this before any diy header -#include VTK_DIY2_HEADER(diy/algorithms.hpp) #include VTK_DIY2_HEADER(diy/assigner.hpp) #include VTK_DIY2_HEADER(diy/link.hpp) #include VTK_DIY2_HEADER(diy/master.hpp) #include VTK_DIY2_HEADER(diy/mpi.hpp) - -#include +#include VTK_DIY2_HEADER(diy/reduce.hpp) +#include VTK_DIY2_HEADER(diy/partners/swap.hpp) +#include VTK_DIY2_HEADER(diy/decomposition.hpp) #include vtkStandardNewMacro(vtkPResampleToImage); +vtkCxxSetObjectMacro(vtkPResampleToImage, Controller, vtkMultiProcessController); + namespace { //---------------------------------------------------------------------------- @@ -81,25 +87,6 @@ struct Array }; -//---------------------------------------------------------------------------- -struct Point -{ - double pos[3]; - int idx[3]; - std::vector data; - - double& operator[](std::size_t i) - { - return pos[i]; - } - - double operator[](std::size_t i) const - { - return pos[i]; - } -}; - - //----------------------------------------------------------------------------- struct FieldMetaData { @@ -127,7 +114,6 @@ inline void ExtractFieldMetaData(vtkDataSetAttributes *data, } } - inline void InitializeFieldData(const std::vector &metadata, vtkIdType numTuples, vtkDataSetAttributes *data) @@ -156,132 +142,126 @@ inline void InitializeFieldData(const std::vector &metadata, } } -template -inline void SaveToBuffer(Iterator begin, std::size_t start, std::size_t count, - diy::MemoryBuffer &bb) + +//---------------------------------------------------------------------------- +class SerializeWorklet { - std::advance(begin, start); - for (std::size_t i = 0; i < count; ++i) - { - diy::save(bb, *begin++); - } -} +public: + SerializeWorklet(vtkIdType tuple, int numComponents, diy::MemoryBuffer &buffer) + : Tuple(tuple), NumComponents(numComponents), Buffer(&buffer) + { } + + template + void operator()(ArrayType *array) const + { + vtkDataArrayAccessor accessor(array); + for (int i = 0; i < this->NumComponents; ++i) + { + diy::save(*this->Buffer, accessor.Get(this->Tuple, i)); + } + } + +private: + vtkIdType Tuple; + int NumComponents; + diy::MemoryBuffer *Buffer; +}; inline void SerializeFieldData(vtkFieldData *field, vtkIdType tuple, - std::vector &bytestream) + diy::MemoryBuffer &bb) { - diy::MemoryBuffer bb; int numFields = field->GetNumberOfArrays(); for (int i = 0; i < numFields; ++i) { vtkDataArray *da = field->GetArray(i); std::size_t numComponents = static_cast(da->GetNumberOfComponents()); - std::size_t index = tuple * numComponents; - switch(da->GetDataType()) + SerializeWorklet worklet(tuple, numComponents, bb); + if (!vtkArrayDispatch::Dispatch::Execute(da, worklet)) { - vtkDataArrayIteratorMacro(da, SaveToBuffer(vtkDABegin, index, numComponents, bb)); + vtkGenericWarningMacro(<< "Dispatch failed, fallback to vtkDataArray Get/Set"); + worklet(da); } } - std::swap(bytestream, bb.buffer); } -template -inline void LoadFromBuffer(Iterator begin, std::size_t start, std::size_t count, - diy::MemoryBuffer &bb) +class DeserializeWorklet { - std::advance(begin, start); - for (std::size_t i = 0; i < count; ++i) - { - diy::load(bb, *begin++); - } -} +public: + DeserializeWorklet(vtkIdType tuple, int numComponents, diy::MemoryBuffer &buffer) + : Tuple(tuple), NumComponents(numComponents), Buffer(&buffer) + { } -inline void DeserializeFieldData(const std::vector &bytestream, - vtkFieldData *field, vtkIdType tuple) -{ - diy::MemoryBuffer bb; - bb.buffer = bytestream; + template + void operator()(ArrayType *array) const + { + vtkDataArrayAccessor accessor(array); + for (int i = 0; i < this->NumComponents; ++i) + { + typename vtkDataArrayAccessor::APIType val; + diy::load(*this->Buffer, val); + accessor.Set(this->Tuple, i, val); + } + } + +private: + vtkIdType Tuple; + int NumComponents; + diy::MemoryBuffer *Buffer; +}; +inline void DeserializeFieldData(diy::MemoryBuffer &bb, vtkFieldData *field, + vtkIdType tuple) +{ int numFields = field->GetNumberOfArrays(); for (int i = 0; i < numFields; ++i) { vtkDataArray *da = field->GetArray(i); std::size_t numComponents = static_cast(da->GetNumberOfComponents()); - std::size_t index = tuple * numComponents; - switch(da->GetDataType()) + DeserializeWorklet worklet(tuple, numComponents, bb); + if (!vtkArrayDispatch::Dispatch::Execute(da, worklet)) { - vtkDataArrayIteratorMacro(da, LoadFromBuffer(vtkDABegin, index, numComponents, bb)); + vtkGenericWarningMacro(<< "Dispatch failed, fallback to vtkDataArray Get/Set"); + worklet(da); } } } //---------------------------------------------------------------------------- -inline void ComputeBoundsFromExtent(const int extent[6], const double origin[3], - const double spacing[3], double bounds[6]) +// A structure representing a list of points from an ImageData. Stores the +// points' 3D indices (Indices) and serialized point data (Data) and they +// should be stored in the same order. +struct PointList { - for (int i = 0; i < 3; ++i) - { - bounds[2*i] = static_cast(extent[2*i]) * spacing[i] + origin[i]; - bounds[2*i + 1] = static_cast(extent[2*i + 1]) * spacing[i] + - origin[i]; - } -} + typedef Array IndexType; -inline void ComputeBoundingExtent(const double origin[3], const double spacing[3], - const double bounds[6], int extent[6]) -{ - for (int i = 0; i < 3; ++i) - { - if (spacing[i] != 0.0) - { - extent[2*i] = - static_cast(vtkMath::Floor((bounds[2*i] - origin[i])/spacing[i])); - extent[2*i + 1] = - static_cast(vtkMath::Ceil((bounds[2*i + 1] - origin[i])/spacing[i])); - } - else - { - extent[2*i] = extent[2*i + 1] = 0; - } - } -} + std::vector Indices; // indices + std::vector Data; // serialized data + vtkIdType DataSize; // size in bytes of serialized data of one point +}; -inline void ComputeTilingExtent(const double origin[3], const double spacing[3], - const double bounds[6], int extent[6]) +inline void swap(PointList &a, PointList &b) { - for (int i = 0; i < 3; ++i) - { - if (spacing[i] != 0.0) - { - extent[2*i] = - static_cast(vtkMath::Floor((bounds[2*i] - origin[i])/spacing[i])); - extent[2*i + 1] = - static_cast(vtkMath::Floor((bounds[2*i + 1] - origin[i])/spacing[i])); - } - else - { - extent[2*i] = extent[2*i + 1] = 0; - } - } + a.Indices.swap(b.Indices); + a.Data.swap(b.Data); + std::swap(a.DataSize, b.DataSize); } -inline bool InsideExtent(const int extent[6], const int ijk[3]) +inline vtkIdType ComputeSerializedFieldDataSize( + const std::vector &fieldMetaData) { - return ijk[0] >= extent[0] && ijk[0] <= extent[1] && - ijk[1] >= extent[2] && ijk[1] <= extent[3] && - ijk[2] >= extent[4] && ijk[2] <= extent[5]; + vtkNew attribs; + InitializeFieldData(fieldMetaData, 1, attribs.GetPointer()); + diy::MemoryBuffer bb; + SerializeFieldData(attribs.GetPointer(), 0, bb); + return static_cast(bb.buffer.size()); } - //---------------------------------------------------------------------------- struct Block { - double Origin[3]; - double Spacing[3]; - std::vector Points; - - double Bounds[6]; + PointList Points; + int Extent[6]; }; inline void* CreateBlock() @@ -295,25 +275,25 @@ inline void DestroyBlock(void *blockp) } -inline void GetPoint(vtkImageData *img, const int ijk[3], double x[3]) +//--------------------------------------------------------------------------- +// Creates a PointList of all the valid points in img +inline void GetPointsFromImage(vtkImageData *img, const char *maskArrayName, + PointList *points) { - double *origin = img->GetOrigin(); - double *spacing = img->GetSpacing(); - for (int i = 0; i < 3; ++i) - { - x[i] = origin[i] + (static_cast(ijk[i]) * spacing[i]); - } -} + if (img->GetNumberOfPoints() <= 0) + { + return; + } -inline void AddPointsToBlock(vtkImageData *piece, const char *maskArrayName, - Block *block) -{ - vtkPointData *pd = piece->GetPointData(); - vtkCharArray *maskArray = vtkCharArray::SafeDownCast(pd->GetArray(maskArrayName)); + vtkPointData *pd = img->GetPointData(); + vtkCharArray *maskArray = vtkArrayDownCast(pd->GetArray(maskArrayName)); char *mask = maskArray->GetPointer(0); + // use diy's serialization facilities + diy::MemoryBuffer bb; + int extent[6]; - piece->GetExtent(extent); + img->GetExtent(extent); for (int k = extent[4]; k <= extent[5]; ++k) { for (int j = extent[2]; j <= extent[3]; ++j) @@ -321,105 +301,43 @@ inline void AddPointsToBlock(vtkImageData *piece, const char *maskArrayName, for (int i = extent[0]; i <= extent[1]; ++i) { int ijk[3] = { i, j, k }; - vtkIdType id = piece->ComputePointId(ijk); + vtkIdType id = img->ComputePointId(ijk); if (mask[id]) { - double x[3]; - GetPoint(piece, ijk, x); - - Point pt; - std::copy(x, x + 3, pt.pos); - std::copy(ijk, ijk + 3, pt.idx); - SerializeFieldData(pd, id, pt.data); - block->Points.push_back(pt); + PointList::IndexType idx; + std::copy(ijk, ijk + 3, idx.data()); + points->Indices.push_back(idx); + SerializeFieldData(pd, id, bb); } } } } + points->Data.swap(bb.buffer); // get the serialized data buffer } -//--------------------------------------------------------------------------- -struct FindGhostPointsForNeighbors +// Sets the points from the PointList (points) to img. 'points' is modified +// in the process. +void SetPointsToImage(const std::vector &fieldMetaData, + PointList &points, vtkImageData *img) { - void operator()(void *blockp, const diy::Master::ProxyWithLink& cp, void*) const - { - Block &block = *static_cast(blockp); - diy::RegularContinuousLink &link = - *static_cast(cp.link()); - - std::size_t numNeighbors = static_cast(link.size()); - std::vector > extents(numNeighbors); - for (std::size_t i = 0; i < numNeighbors; ++i) - { - const diy::ContinuousBounds &b = link.bounds(static_cast(i)); - double bounds[6] = { b.min[0], b.max[0], b.min[1], b.max[1], b.min[2], b.max[2] }; - ComputeTilingExtent(block.Origin, block.Spacing, bounds, extents[i].data()); - } - - for (std::size_t i = 0; i < block.Points.size(); ++i) - { - const Point &p = block.Points[i]; - for (std::size_t j = 0; j < extents.size(); ++j) - { - if (InsideExtent(extents[j].data(), p.idx)) - { - cp.enqueue(link.target(static_cast(j)), p); - } - } - } - } -}; - -struct ReceiveGhostPoints -{ - void operator()(void *blockp, const diy::Master::ProxyWithLink& cp, void*) const - { - Block &block = *static_cast(blockp); - diy::RegularContinuousLink &link = - *static_cast(cp.link()); - - diy::Master::IncomingQueues &in = *cp.incoming(); - for (diy::Master::IncomingQueues::iterator i = in.begin(); i != in.end(); ++i) - { - while (i->second) - { - Point pt; - cp.dequeue(i->first, pt); - block.Points.push_back(pt); - } - } + vtkPointData *pd = img->GetPointData(); + InitializeFieldData(fieldMetaData, img->GetNumberOfPoints(), pd); - const diy::ContinuousBounds &b = link.bounds(); - for (int i = 0; i < 3; ++i) - { - block.Bounds[2*i] = b.min[i]; - block.Bounds[2*i + 1] = b.max[i]; - } - } -}; - -void MakeResult(const double origin[3], const double spacing[3], - const int extent[3], const std::vector &fieldMetaData, - const std::vector &points, vtkImageData *result) -{ - result->SetOrigin(origin[0], origin[1], origin[2]); - result->SetSpacing(spacing[0], spacing[1], spacing[2]); - result->SetExtent(extent[0], extent[1], extent[2], extent[3], extent[4], extent[5]); - - vtkPointData *pd = result->GetPointData(); - InitializeFieldData(fieldMetaData, result->GetNumberOfPoints(), pd); - - for (std::size_t i = 0; i < points.size(); ++i) + diy::MemoryBuffer bb; + bb.buffer.swap(points.Data); + std::size_t numPoints = points.Indices.size(); + for (std::size_t i = 0; i < numPoints; ++i) { - const Point &p = points[i]; - int idx[3] = { p.idx[0], p.idx[1], p.idx[2] }; - vtkIdType id = result->ComputePointId(idx); - DeserializeFieldData(p.data, pd, id); + vtkIdType id = img->ComputePointId(points.Indices[i].data()); + DeserializeFieldData(bb, pd, id); } + + points.Indices.clear(); // reset the points structure to a valid empty state } //---------------------------------------------------------------------------- -inline void ComputeGlobalBounds(const double lbounds[6], double gbounds[6]) +inline void ComputeGlobalBounds(diy::mpi::communicator &comm, + const double lbounds[6], double gbounds[6]) { Array localBoundsMin, localBoundsMax; for (std::size_t i = 0; i < 3; ++i) @@ -428,11 +346,10 @@ inline void ComputeGlobalBounds(const double lbounds[6], double gbounds[6]) localBoundsMax[i] = lbounds[2*i + 1]; } - diy::mpi::communicator world; Array globalBoundsMin, globalBoundsMax; - diy::mpi::all_reduce(world, localBoundsMin, globalBoundsMin, + diy::mpi::all_reduce(comm, localBoundsMin, globalBoundsMin, diy::mpi::minimum()); - diy::mpi::all_reduce(world, localBoundsMax, globalBoundsMax, + diy::mpi::all_reduce(comm, localBoundsMax, globalBoundsMax, diy::mpi::maximum()); for (std::size_t i = 0; i < 3; ++i) @@ -442,44 +359,151 @@ inline void ComputeGlobalBounds(const double lbounds[6], double gbounds[6]) } } -inline void GetGlobalFieldMetaData(vtkDataSetAttributes *data, +inline void GetGlobalFieldMetaData(diy::mpi::communicator &comm, + vtkDataSetAttributes *data, std::vector *metadata) { - diy::mpi::communicator world; - std::vector local; ExtractFieldMetaData(data, &local); // find a process that has field meta data information (choose the process with // minimum rank) - int rank = local.size() ? world.rank() : world.size(); + int rank = local.size() ? comm.rank() : comm.size(); int source; - diy::mpi::all_reduce(world, rank, source, diy::mpi::minimum()); + diy::mpi::all_reduce(comm, rank, source, diy::mpi::minimum()); - if (source < world.size()) // atleast one process has field meta data + if (source < comm.size()) // atleast one process has field meta data { diy::MemoryBuffer bb; - if (world.rank() == source) + if (comm.rank() == source) { diy::save(bb, local); bb.reset(); } - diy::mpi::broadcast(world, bb.buffer, source); + diy::mpi::broadcast(comm, bb.buffer, source); diy::load(bb, *metadata); } } + +//--------------------------------------------------------------------------- +void Redistribute(void* blockp, const diy::ReduceProxy& srp, + const diy::RegularSwapPartners& partners) +{ + Block *b = static_cast(blockp); + unsigned round = srp.round(); + + // step 1: dequeue all the incoming points and add them to this block's vector + diy::Master::IncomingQueues &in = *srp.incoming(); + for (diy::Master::IncomingQueues::iterator i = in.begin(); i != in.end(); ++i) + { + while (i->second) + { + PointList::IndexType idx; + srp.dequeue(i->first, idx); + b->Points.Indices.push_back(idx); + + std::size_t beg = b->Points.Data.size(); + b->Points.Data.resize(beg + b->Points.DataSize); + srp.dequeue(i->first, &b->Points.Data[beg], b->Points.DataSize); + } + } + + // final round + if (srp.out_link().size() == 0) + { + return; + } + + // find this block's position in the group + int groupSize = srp.out_link().size(); + int myPos = 0; + for (; myPos < groupSize; ++myPos) + { + if (srp.out_link().target(myPos).gid == srp.gid()) + { + break; + } + } + + // step 2: redistribute this block's points among the blocks in the group + int axis = partners.dim(round); + int minIdx = b->Extent[2 * axis]; + int maxIdx = b->Extent[2 * axis + 1]; + int length = (maxIdx - minIdx + 1 + groupSize - 1) / groupSize; + + PointList myPoints; + myPoints.DataSize = b->Points.DataSize; // initilize myPoints + std::size_t numPoints = b->Points.Indices.size(); + for (size_t i = 0; i < numPoints; ++i) + { + PointList::IndexType idx = b->Points.Indices[i]; + const char *data = &b->Points.Data[i * b->Points.DataSize]; + + int nlocs = 1; + int loc[2] = { (idx[axis] - minIdx)/length, 0 }; + + // duplicate shared point + if (((idx[axis] - minIdx)%length == 0) && (loc[0] != 0)) + { + loc[1] = loc[0] - 1; + ++nlocs; + } + + for (int j = 0; j < nlocs; ++j) + { + if (loc[j] == myPos) + { + myPoints.Indices.push_back(idx); + myPoints.Data.insert(myPoints.Data.end(), data, data + myPoints.DataSize); + } + else + { + srp.enqueue(srp.out_link().target(loc[j]), idx); + srp.enqueue(srp.out_link().target(loc[j]), data, myPoints.DataSize); + } + } + } + swap(b->Points, myPoints); + + // step 3: readjust extents for next round + b->Extent[2*axis] = minIdx + (length * myPos); + b->Extent[2*axis + 1] = std::min(b->Extent[2*axis] + length, maxIdx); +} + + +//---------------------------------------------------------------------------- +inline diy::mpi::communicator GetDiyCommunicator(vtkMPIController *controller) +{ + vtkMPICommunicator *vtkcomm = vtkMPICommunicator::SafeDownCast( + controller->GetCommunicator()); + return diy::mpi::communicator(*vtkcomm->GetMPIComm()->GetHandle()); +} + } // anonymous namespace //--------------------------------------------------------------------------- vtkPResampleToImage::vtkPResampleToImage() + : Controller(NULL) { + this->SetController(vtkMultiProcessController::GetGlobalController()); } //---------------------------------------------------------------------------- vtkPResampleToImage::~vtkPResampleToImage() { + this->SetController(NULL); +} + +//---------------------------------------------------------------------------- +void vtkPResampleToImage::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + if (this->Controller) + { + this->Controller->PrintSelf(os, indent); + } } //--------------------------------------------------------------------------- @@ -487,10 +511,8 @@ int vtkPResampleToImage::RequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { - int mpiInitializedFlag = 0; - MPI_Initialized(&mpiInitializedFlag); - - if (!mpiInitializedFlag || diy::mpi::communicator().size() == 1) + vtkMPIController *mpiCont = vtkMPIController::SafeDownCast(this->Controller); + if (!mpiCont || mpiCont->GetNumberOfProcesses() == 1) { return this->Superclass::RequestData(request, inputVector, outputVector); } @@ -500,149 +522,69 @@ int vtkPResampleToImage::RequestData(vtkInformation *request, vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and output - vtkDataSet *input = vtkDataSet::SafeDownCast( - inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkDataObject *input = inInfo->Get(vtkDataObject::DATA_OBJECT()); vtkImageData *output = vtkImageData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); - if (this->SamplingDimensions[0] <= 0 || - this->SamplingDimensions[1] <= 0 || - this->SamplingDimensions[2] <= 0) - { - return 1; - } - // compute global bounds of the dataset - double localBounds[6], globalBounds[6]; - input->GetBounds(localBounds); - ComputeGlobalBounds(localBounds, globalBounds); + diy::mpi::communicator comm = GetDiyCommunicator(mpiCont); - // compute bounds and extent where probing should be performed for this node - double *wholeBounds = this->UseInputBounds ? globalBounds : this->SamplingBounds; - double origin[3] = { wholeBounds[0], wholeBounds[2], wholeBounds[4] }; - double spacing[3]; - for (int i = 0; i < 3; ++i) - { - spacing[i] = (this->SamplingDimensions[i] == 1) ? 0 : - ((wholeBounds[i*2 + 1] - wholeBounds[i*2]) / - static_cast(this->SamplingDimensions[i] - 1)); - } + double localBounds[6]; + ComputeDataBounds(input, localBounds); - int updateExtent[6]; - if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT())) + double samplingBounds[6]; + if (this->UseInputBounds) { - int *ue = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT()); - std::copy(ue, ue + 6, updateExtent); + ComputeGlobalBounds(comm, localBounds, samplingBounds); } else { - updateExtent[0] = updateExtent[2] = updateExtent[4] = 0; - updateExtent[1] = this->SamplingDimensions[0] - 1; - updateExtent[3] = this->SamplingDimensions[1] - 1; - updateExtent[5] = this->SamplingDimensions[2] - 1; - } - - int extent[6]; - ComputeBoundingExtent(origin, spacing, localBounds, extent); - for (int i = 0; i < 3; ++i) - { - extent[2*i] = vtkMath::Max(extent[2*i], updateExtent[2*i]); - extent[2*i + 1] = vtkMath::Min(extent[2*i + 1], updateExtent[2*i + 1]); - if (extent[2*i] > extent[2*i + 1]) // no overlap - { - extent[0] = extent[2] = extent[4] = 0; - extent[1] = extent[3] = extent[5] = -1; - break; - } + std::copy(this->SamplingBounds, this->SamplingBounds + 6, samplingBounds); } - // perform probing - vtkNew prober; - const char *maskArrayName = prober->GetValidPointMaskArrayName(); - - vtkNew structure; - structure->SetOrigin(origin); - structure->SetSpacing(spacing); - structure->SetExtent(extent); + vtkNew mypiece; + this->PerformResampling(input, samplingBounds, true, localBounds, + mypiece.GetPointer()); - prober->SetInputData(structure.GetPointer()); - prober->SetSourceData(input); - prober->Update(); - - vtkImageData *mypiece = static_cast(prober->GetOutput()); // Ensure every node has fields' metadata information std::vector pointFieldMetaData; - GetGlobalFieldMetaData(mypiece->GetPointData(), &pointFieldMetaData); - - // perform kd-tree partitioning on probed points so that each node ends up - // with non-overlapping rectangular regions - diy::mpi::communicator world; - diy::RoundRobinAssigner assigner(world.size(), world.size()); + GetGlobalFieldMetaData(comm, mypiece->GetPointData(), &pointFieldMetaData); - std::vector gids; - assigner.local_gids(world.rank(), gids); + // perform swap-reduce partitioning on probed points to decompose the domain + // into non-overlapping rectangular regions + diy::RoundRobinAssigner assigner(comm.size(), comm.size()); - double updateBounds[6]; - ComputeBoundsFromExtent(updateExtent, origin, spacing, updateBounds); - diy::ContinuousBounds domain; + int *updateExtent = this->GetUpdateExtent(); + diy::DiscreteBounds domain; for (int i = 0; i < 3; ++i) { - domain.min[i] = static_cast(updateBounds[2*i] - 1e-4); - domain.max[i] = static_cast(updateBounds[2*i + 1] + 1e-4); + domain.min[i] = updateExtent[2*i]; + domain.max[i] = updateExtent[2*i + 1]; } - // block and link are freed by master - Block *block = static_cast(CreateBlock()); - std::copy(origin, origin + 3, block->Origin); - std::copy(spacing, spacing + 3, block->Spacing); - AddPointsToBlock(mypiece, maskArrayName, block); - diy::RegularContinuousLink *link = new diy::RegularContinuousLink(3, domain, domain); - - diy::Master master(world, 1, -1, &CreateBlock, &DestroyBlock); - master.add(gids[0], block, link); - - int outExtent[6]; - vtkIdType numPoints = static_cast(block->Points.size()); - vtkIdType sumNumPoints = 0; - diy::mpi::all_reduce(world, numPoints, sumNumPoints, std::plus()); - if (sumNumPoints > 0) - { - const int hist = 32; - diy::kdtree(master, assigner, 3, domain, &Block::Points, 2*hist, false); + diy::Master master(comm, 1, -1, &CreateBlock, &DestroyBlock); - // handle ghost points - master.foreach(FindGhostPointsForNeighbors()); - master.exchange(); - master.foreach(ReceiveGhostPoints()); + diy::RegularDecomposer decomposer(3, domain, comm.size()); + decomposer.decompose(comm.rank(), assigner, master); - // generate output extent - ComputeTilingExtent(block->Origin, block->Spacing, block->Bounds, outExtent); - for (int i = 0; i < 3; ++i) - { - outExtent[2*i] = std::max(outExtent[2*i], updateExtent[2*i]); - outExtent[2*i + 1] = std::min(outExtent[2*i + 1], updateExtent[2*i + 1]); - } - } - else - { - vtkNew extentTranslator; - extentTranslator->PieceToExtentThreadSafe(world.rank(), world.size(), 0, - updateExtent, outExtent, - vtkExtentTranslator::BLOCK_MODE, - false); - } + // Set up master's block + Block *block = master.block(0); + std::copy(updateExtent, updateExtent + 6, block->Extent); + block->Points.DataSize = ComputeSerializedFieldDataSize(pointFieldMetaData); + GetPointsFromImage(mypiece.GetPointer(), this->GetMaskArrayName(), + &block->Points); - MakeResult(origin, spacing, outExtent, pointFieldMetaData, block->Points, output); - vtkResampleToImage::SetBlankPointsAndCells(output, maskArrayName); + diy::RegularSwapPartners partners(decomposer, 2, false); + diy::reduce(master, assigner, partners, &Redistribute); - return 1; -} + output->SetOrigin(mypiece->GetOrigin()); + output->SetSpacing(mypiece->GetSpacing()); + output->SetExtent(block->Extent); + SetPointsToImage(pointFieldMetaData, block->Points, output); + this->SetBlankPointsAndCells(output); -//---------------------------------------------------------------------------- -void vtkPResampleToImage::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); + return 1; } @@ -667,24 +609,6 @@ struct mpi_datatype > } // namespace mpi::detail -template<> -struct Serialization -{ - static void save(BinaryBuffer& bb, const Point& p) - { - diy::save(bb, p.pos, 3); - diy::save(bb, p.idx, 3); - diy::save(bb, p.data); - } - - static void load(BinaryBuffer& bb, Point& p) - { - diy::load(bb, p.pos, 3); - diy::load(bb, p.idx, 3); - diy::load(bb, p.data); - } -}; - template<> struct Serialization { diff --git a/Filters/ParallelDIY2/vtkPResampleToImage.h b/Filters/ParallelDIY2/vtkPResampleToImage.h index d3f3c9de74e..201d913c66c 100644 --- a/Filters/ParallelDIY2/vtkPResampleToImage.h +++ b/Filters/ParallelDIY2/vtkPResampleToImage.h @@ -27,6 +27,7 @@ class vtkDataSet; class vtkImageData; +class vtkMultiProcessController; class VTKFILTERSPARALLELDIY2_EXPORT vtkPResampleToImage : public vtkResampleToImage { @@ -36,6 +37,12 @@ class VTKFILTERSPARALLELDIY2_EXPORT vtkPResampleToImage : public vtkResampleToIm static vtkPResampleToImage *New(); + // Description: + // By defualt this filter uses the global controller, + // but this method can be used to set another instead. + virtual void SetController(vtkMultiProcessController*); + vtkGetObjectMacro(Controller, vtkMultiProcessController); + protected: vtkPResampleToImage(); ~vtkPResampleToImage(); @@ -43,6 +50,8 @@ class VTKFILTERSPARALLELDIY2_EXPORT vtkPResampleToImage : public vtkResampleToIm virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); + vtkMultiProcessController *Controller; + private: vtkPResampleToImage(const vtkPResampleToImage&); // Not implemented. void operator=(const vtkPResampleToImage&); // Not implemented. diff --git a/Filters/ParallelFlowPaths/Testing/Cxx/TestPStreamGeometry.cxx b/Filters/ParallelFlowPaths/Testing/Cxx/TestPStreamGeometry.cxx index 3d7599b114d..82af30dbfff 100644 --- a/Filters/ParallelFlowPaths/Testing/Cxx/TestPStreamGeometry.cxx +++ b/Filters/ParallelFlowPaths/Testing/Cxx/TestPStreamGeometry.cxx @@ -143,7 +143,7 @@ int TestPStreamGeometry( int argc, char* argv[] ) traceMapper->Update(); out = tracer->GetOutput(); vtkDoubleArray* integrationTime = - vtkDoubleArray::SafeDownCast(out->GetPointData()->GetArray("IntegrationTime")); + vtkArrayDownCast(out->GetPointData()->GetArray("IntegrationTime")); for(vtkIdType i=0;iGetNumberOfPoints();i++) { double coord[3]; diff --git a/Filters/ParallelFlowPaths/Testing/Cxx/TestVectorFieldSource.cxx b/Filters/ParallelFlowPaths/Testing/Cxx/TestVectorFieldSource.cxx index e3885f69ef3..93abfb4e248 100644 --- a/Filters/ParallelFlowPaths/Testing/Cxx/TestVectorFieldSource.cxx +++ b/Filters/ParallelFlowPaths/Testing/Cxx/TestVectorFieldSource.cxx @@ -129,7 +129,7 @@ void TestVectorFieldSource::ExecuteDataWithInformation(vtkDataObject *outData,vt } - vtkDataArray* outArray = vtkDataArray::SafeDownCast(vtkAbstractArray::CreateArray(VTK_FLOAT)); + vtkDataArray* outArray = vtkArrayDownCast(vtkAbstractArray::CreateArray(VTK_FLOAT)); outArray->SetName("Gradients"); outArray->SetNumberOfComponents(3); outArray->SetNumberOfTuples(outImage->GetNumberOfPoints()); @@ -173,7 +173,7 @@ void TestVectorFieldSource::ExecuteDataWithInformation(vtkDataObject *outData,vt // add a constant vector field in the z-direction vtkDataArray* velocityArray = - vtkDataArray::SafeDownCast(vtkAbstractArray::CreateArray(VTK_FLOAT)); + vtkArrayDownCast(vtkAbstractArray::CreateArray(VTK_FLOAT)); velocityArray->SetName("Velocity"); velocityArray->SetNumberOfComponents(3); velocityArray->SetNumberOfTuples(outImage->GetNumberOfPoints()); diff --git a/Filters/ParallelFlowPaths/vtkPParticlePathFilter.cxx b/Filters/ParallelFlowPaths/vtkPParticlePathFilter.cxx index 20bd4c2f5a4..e0fa79eeffe 100644 --- a/Filters/ParallelFlowPaths/vtkPParticlePathFilter.cxx +++ b/Filters/ParallelFlowPaths/vtkPParticlePathFilter.cxx @@ -89,8 +89,8 @@ int vtkPParticlePathFilter::OutputParticles(vtkPolyData* particles) this->GetErrorCodeArr(tailPD)->InsertValue(tempId, info.ErrorCode); this->GetParticleAge(tailPD)->InsertValue(tempId, info.age); - vtkDoubleArray::SafeDownCast(tailPD->GetArray("SimulationTime"))->InsertValue(tempId, info.SimulationTime); - vtkIntArray::SafeDownCast(tailPD->GetArray("SimulationTimeStep"))->InsertValue(tempId, info.InjectedStepId+info.TimeStepAge); + vtkArrayDownCast(tailPD->GetArray("SimulationTime"))->InsertValue(tempId, info.SimulationTime); + vtkArrayDownCast(tailPD->GetArray("SimulationTimeStep"))->InsertValue(tempId, info.InjectedStepId+info.TimeStepAge); if(this->GetComputeVorticity()) { diff --git a/Filters/ParallelFlowPaths/vtkPParticleTracerBase.h b/Filters/ParallelFlowPaths/vtkPParticleTracerBase.h index 3dca902b139..bc84421a4e2 100644 --- a/Filters/ParallelFlowPaths/vtkPParticleTracerBase.h +++ b/Filters/ParallelFlowPaths/vtkPParticleTracerBase.h @@ -27,9 +27,7 @@ #include "vtkSmartPointer.h" // For protected ivars. #include "vtkParticleTracerBase.h" -//BTX #include // STL Header -//ETX #include "vtkFiltersParallelFlowPathsModule.h" // For export macro @@ -63,7 +61,6 @@ class VTKFILTERSPARALLELFLOWPATHS_EXPORT vtkPParticleTracerBase : public vtkPart vtkInformationVector* outputVector); // -//BTX virtual vtkPolyData* Execute(vtkInformationVector** inputVector); virtual bool SendParticleToAnotherProcess(vtkParticleTracerBaseNamespace::ParticleInformation & info, @@ -103,7 +100,7 @@ class VTKFILTERSPARALLELFLOWPATHS_EXPORT vtkPParticleTracerBase : public vtkPart // -//ETX + // // MPI controller needed when running in parallel diff --git a/Filters/ParallelFlowPaths/vtkPStreamTracer.cxx b/Filters/ParallelFlowPaths/vtkPStreamTracer.cxx index bcf98bf5d01..30f3ca98142 100644 --- a/Filters/ParallelFlowPaths/vtkPStreamTracer.cxx +++ b/Filters/ParallelFlowPaths/vtkPStreamTracer.cxx @@ -1607,7 +1607,7 @@ int vtkPStreamTracer::RequestData( } int resTerm=vtkStreamTracer::OUT_OF_DOMAIN; - vtkIntArray* resTermArray = vtkIntArray::SafeDownCast( + vtkIntArray* resTermArray = vtkArrayDownCast( traceOut->GetCellData()->GetArray("ReasonForTermination")); if (resTermArray) { diff --git a/Filters/ParallelFlowPaths/vtkPTemporalStreamTracer.h b/Filters/ParallelFlowPaths/vtkPTemporalStreamTracer.h index 62d168f09ad..bb92b272bca 100644 --- a/Filters/ParallelFlowPaths/vtkPTemporalStreamTracer.h +++ b/Filters/ParallelFlowPaths/vtkPTemporalStreamTracer.h @@ -28,10 +28,8 @@ #include "vtkSmartPointer.h" // For protected ivars. #include "vtkTemporalStreamTracer.h" -//BTX #include // STL Header #include // STL Header -//ETX class vtkMultiProcessController; @@ -79,7 +77,7 @@ class VTKFILTERSPARALLELFLOWPATHS_EXPORT vtkPTemporalStreamTracer : public vtkTe vtkInformationVector* outputVector); // -//BTX + // // Description : Before starting the particle trace, classify @@ -110,7 +108,7 @@ class VTKFILTERSPARALLELFLOWPATHS_EXPORT vtkPTemporalStreamTracer : public vtkTe vtkTemporalStreamTracerNamespace::ParticleInformation &info); // -//ETX + // // MPI controller needed when running in parallel diff --git a/Filters/ParallelGeometry/Testing/Cxx/TestPStructuredGridGhostDataGenerator.cxx b/Filters/ParallelGeometry/Testing/Cxx/TestPStructuredGridGhostDataGenerator.cxx index 1a569f217d7..6854c1ec778 100644 --- a/Filters/ParallelGeometry/Testing/Cxx/TestPStructuredGridGhostDataGenerator.cxx +++ b/Filters/ParallelGeometry/Testing/Cxx/TestPStructuredGridGhostDataGenerator.cxx @@ -188,7 +188,7 @@ bool CheckNodeFieldsForGrid( vtkStructuredGrid *grid ) double xyz[3]; vtkDoubleArray *array = - vtkDoubleArray::SafeDownCast( grid->GetPointData()->GetArray("NODE-XYZ") ); + vtkArrayDownCast( grid->GetPointData()->GetArray("NODE-XYZ") ); assert("pre: num tuples must match number of nodes" && (array->GetNumberOfTuples() == grid->GetNumberOfPoints()) ); assert("pre: num components must be 3" && @@ -219,7 +219,7 @@ bool CheckCellFieldsForGrid( vtkStructuredGrid *grid ) double centroid[3]; double xyz[3]; vtkDoubleArray *array = - vtkDoubleArray::SafeDownCast(grid->GetCellData()->GetArray("CELL-XYZ") ); + vtkArrayDownCast(grid->GetCellData()->GetArray("CELL-XYZ") ); assert("pre: num tuples must match number of nodes" && (array->GetNumberOfTuples() == grid->GetNumberOfCells()) ); assert("pre: num components must be 3" && diff --git a/Filters/ParallelGeometry/Testing/Cxx/TestPUniformGridGhostDataGenerator.cxx b/Filters/ParallelGeometry/Testing/Cxx/TestPUniformGridGhostDataGenerator.cxx index 3ba88021b10..963ecb62be4 100644 --- a/Filters/ParallelGeometry/Testing/Cxx/TestPUniformGridGhostDataGenerator.cxx +++ b/Filters/ParallelGeometry/Testing/Cxx/TestPUniformGridGhostDataGenerator.cxx @@ -161,7 +161,7 @@ bool CheckNodeFieldsForGrid( vtkUniformGrid *grid ) double xyz[3]; vtkDoubleArray *array = - vtkDoubleArray::SafeDownCast( grid->GetPointData()->GetArray("NODE-XYZ") ); + vtkArrayDownCast( grid->GetPointData()->GetArray("NODE-XYZ") ); assert("pre: num tuples must match number of nodes" && (array->GetNumberOfTuples() == grid->GetNumberOfPoints()) ); assert("pre: num components must be 3" && @@ -192,7 +192,7 @@ bool CheckCellFieldsForGrid( vtkUniformGrid *grid ) double centroid[3]; double xyz[3]; vtkDoubleArray *array = - vtkDoubleArray::SafeDownCast(grid->GetCellData()->GetArray("CELL-XYZ") ); + vtkArrayDownCast(grid->GetCellData()->GetArray("CELL-XYZ") ); assert("pre: num tuples must match number of nodes" && (array->GetNumberOfTuples() == grid->GetNumberOfCells()) ); assert("pre: num components must be 3" && diff --git a/Filters/ParallelGeometry/Testing/Cxx/TestPUnstructuredGridGhostCellsGenerator.cxx b/Filters/ParallelGeometry/Testing/Cxx/TestPUnstructuredGridGhostCellsGenerator.cxx index 48f78f1ee4f..6e46fe6c1b3 100644 --- a/Filters/ParallelGeometry/Testing/Cxx/TestPUnstructuredGridGhostCellsGenerator.cxx +++ b/Filters/ParallelGeometry/Testing/Cxx/TestPUnstructuredGridGhostCellsGenerator.cxx @@ -189,7 +189,7 @@ int TestPUnstructuredGridGhostCellsGenerator(int argc, char* argv[]) for (int step = 0; step < 2; ++step) { - vtkUnsignedCharArray* ghosts = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray* ghosts = vtkArrayDownCast( outGrids[step]->GetCellGhostArray()); if (initialNbOfCells >= outGrids[step]->GetNumberOfCells()) { diff --git a/Filters/ParallelGeometry/Testing/Cxx/UnstructuredGhostZonesCommon.cxx b/Filters/ParallelGeometry/Testing/Cxx/UnstructuredGhostZonesCommon.cxx index fac87f6ed5a..41076ff0cf5 100644 --- a/Filters/ParallelGeometry/Testing/Cxx/UnstructuredGhostZonesCommon.cxx +++ b/Filters/ParallelGeometry/Testing/Cxx/UnstructuredGhostZonesCommon.cxx @@ -39,7 +39,7 @@ int CheckGrid(vtkUnstructuredGrid* ghostGrid, const int iteration) // check node fields by the iteration number vtkDoubleArray* nodeXYZ = - vtkDoubleArray::SafeDownCast( + vtkArrayDownCast( ghostGrid->GetPointData()->GetArray("NodeXYZ")); assert("pre: nodeXYZ != NULL" && (nodeXYZ != NULL) ); assert("pre: nodeXYZ numtuples mismatch!" && @@ -80,7 +80,7 @@ int CheckGrid(vtkUnstructuredGrid* ghostGrid, const int iteration) // likewise, check cell-fields vtkDoubleArray* cellXYZ = - vtkDoubleArray::SafeDownCast( + vtkArrayDownCast( ghostGrid->GetCellData()->GetArray("CentroidXYZ")); assert("pre: nodeXYZ numtuples mismatch!" && (ghostGrid->GetNumberOfCells()==cellXYZ->GetNumberOfTuples())); @@ -146,7 +146,7 @@ void UpdateGrid(const int iteration) { // increment node fields by the iteration number vtkDoubleArray* nodeXYZ = - vtkDoubleArray::SafeDownCast( + vtkArrayDownCast( global::Grid->GetPointData()->GetArray("NodeXYZ")); assert("pre: nodeXYZ != NULL" && (nodeXYZ != NULL) ); assert("pre: nodeXYZ numtuples mismatch!" && @@ -164,7 +164,7 @@ void UpdateGrid(const int iteration) // increment cell fields by the iteration number vtkDoubleArray* cellXYZ = - vtkDoubleArray::SafeDownCast( + vtkArrayDownCast( global::Grid->GetCellData()->GetArray("CentroidXYZ")); assert("pre: nodeXYZ numtuples mismatch!" && (global::Grid->GetNumberOfCells()==cellXYZ->GetNumberOfTuples())); diff --git a/Filters/ParallelGeometry/vtkPStructuredGridConnectivity.h b/Filters/ParallelGeometry/vtkPStructuredGridConnectivity.h index 79e6255d484..0ee5e7c2639 100644 --- a/Filters/ParallelGeometry/vtkPStructuredGridConnectivity.h +++ b/Filters/ParallelGeometry/vtkPStructuredGridConnectivity.h @@ -115,7 +115,6 @@ class VTKFILTERSPARALLELGEOMETRY_EXPORT vtkPStructuredGridConnectivity : int Rank; bool Initialized; - // BTX std::vector< int > GridRanks; // Corresponding rank for each grid std::vector< int > GridIds; // List of GridIds, owned by this process @@ -140,7 +139,6 @@ class VTKFILTERSPARALLELGEOMETRY_EXPORT vtkPStructuredGridConnectivity : // Array of MPI requests vtkMPICommunicator::Request *MPIRequests; - // ETX // Description: // Returns true if the two extents are equal, otherwise false. diff --git a/Filters/ParallelGeometry/vtkPUnstructuredGridConnectivity.cxx b/Filters/ParallelGeometry/vtkPUnstructuredGridConnectivity.cxx index 87145ac79fb..b0d75267272 100644 --- a/Filters/ParallelGeometry/vtkPUnstructuredGridConnectivity.cxx +++ b/Filters/ParallelGeometry/vtkPUnstructuredGridConnectivity.cxx @@ -1409,7 +1409,7 @@ void vtkPUnstructuredGridConnectivity::ProcessRemoteGrid( // Get the GlobalID array of the output GhostGrid. This method grows that // array accordingly as ghost nodes are inserted. vtkIdTypeArray* ghostGridGlobalIdArray = - vtkIdTypeArray::SafeDownCast( + vtkArrayDownCast( this->GhostedGrid->GetPointData()->GetArray(this->GlobalIDFieldName)); assert("pre: cannot get global ID field from GhostedGrid" && (ghostGridGlobalIdArray != NULL) ); diff --git a/Filters/ParallelGeometry/vtkPUnstructuredGridConnectivity.h b/Filters/ParallelGeometry/vtkPUnstructuredGridConnectivity.h index b8b8058d50e..126da4e4797 100644 --- a/Filters/ParallelGeometry/vtkPUnstructuredGridConnectivity.h +++ b/Filters/ParallelGeometry/vtkPUnstructuredGridConnectivity.h @@ -138,10 +138,8 @@ class VTKFILTERSPARALLELGEOMETRY_EXPORT vtkPUnstructuredGridConnectivity : vtkUnstructuredGrid* GhostedGrid; // This is the output from this class. vtkMPIController* Controller; // Supplied MPI controller. -// BTX vtk::details::GridInfo* AuxiliaryData; // Data used to build the ghost zones. vtk::details::CommunicationLinks* CommLists; // Persistent comm lists. -// ETX // Description: // Given the deserialized cell-centered ghost data from the given neighboring diff --git a/Filters/ParallelGeometry/vtkPUnstructuredGridGhostCellsGenerator.cxx b/Filters/ParallelGeometry/vtkPUnstructuredGridGhostCellsGenerator.cxx index f6e59beec09..fbd02f74d48 100644 --- a/Filters/ParallelGeometry/vtkPUnstructuredGridGhostCellsGenerator.cxx +++ b/Filters/ParallelGeometry/vtkPUnstructuredGridGhostCellsGenerator.cxx @@ -391,7 +391,7 @@ void vtkPUnstructuredGridGhostCellsGenerator::ExtractAndReduceSurfacePoints() surfaceCells->InitTraversal(); vtkIdType npts, *pts; - vtkIdTypeArray *surfaceOriginalPointIds = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray *surfaceOriginalPointIds = vtkArrayDownCast( surface->GetPointData()->GetArray(surfaceFilter->GetOriginalPointIdsName())); if (this->Internals->InputGlobalPointIds) diff --git a/Filters/ParallelImaging/vtkPComputeHistogram2DOutliers.cxx b/Filters/ParallelImaging/vtkPComputeHistogram2DOutliers.cxx index 8e8f85150ef..a4cae1e1dde 100644 --- a/Filters/ParallelImaging/vtkPComputeHistogram2DOutliers.cxx +++ b/Filters/ParallelImaging/vtkPComputeHistogram2DOutliers.cxx @@ -95,7 +95,7 @@ int vtkPComputeHistogram2DOutliers::RequestData( vtkSmartPointer gatheredTable = vtkSmartPointer::New(); for (int i=0; iGetNumberOfColumns(); i++) { - vtkAbstractArray* col = vtkAbstractArray::SafeDownCast(outputTable->GetColumn(i)); + vtkAbstractArray* col = vtkArrayDownCast(outputTable->GetColumn(i)); if (!col) continue; diff --git a/Filters/ParallelMPI/Testing/Cxx/TestImplicitConnectivity.cxx b/Filters/ParallelMPI/Testing/Cxx/TestImplicitConnectivity.cxx index de66b13264d..8a4b2b6174c 100644 --- a/Filters/ParallelMPI/Testing/Cxx/TestImplicitConnectivity.cxx +++ b/Filters/ParallelMPI/Testing/Cxx/TestImplicitConnectivity.cxx @@ -428,7 +428,7 @@ int CheckGrid(vtkDataSet* grid) return 1; } - vtkDoubleArray* array=vtkDoubleArray::SafeDownCast(PD->GetArray("NODE-XYZ")); + vtkDoubleArray* array=vtkArrayDownCast(PD->GetArray("NODE-XYZ")); if( array==NULL ) { std::cerr << "ERROR: null vtkDataArray!\n"; diff --git a/Filters/ParallelMPI/vtkDistributedDataFilter.cxx b/Filters/ParallelMPI/vtkDistributedDataFilter.cxx index 4996a5154ea..6ad93388624 100644 --- a/Filters/ParallelMPI/vtkDistributedDataFilter.cxx +++ b/Filters/ParallelMPI/vtkDistributedDataFilter.cxx @@ -80,7 +80,7 @@ namespace void convertGhostLevelsToBitFields(vtkDataSetAttributes* dsa, unsigned int bit) { vtkDataArray *da = dsa->GetArray(vtkDataSetAttributes::GhostArrayName()); - vtkUnsignedCharArray *uca = vtkUnsignedCharArray::SafeDownCast(da); + vtkUnsignedCharArray *uca = vtkArrayDownCast(da); unsigned char *ghosts = uca->GetPointer(0); for (vtkIdType i=0; i < da->GetNumberOfTuples(); ++i) { @@ -200,7 +200,7 @@ void vtkDistributedDataFilter::SetUserRegionAssignments( vtkIdTypeArray *vtkDistributedDataFilter::GetGlobalElementIdArray(vtkDataSet *set) { vtkDataArray *da = set->GetCellData()->GetGlobalIds(); - return vtkIdTypeArray::SafeDownCast(da); + return vtkArrayDownCast(da); } //---------------------------------------------------------------------------- @@ -219,7 +219,7 @@ vtkIdType *vtkDistributedDataFilter::GetGlobalElementIds(vtkDataSet *set) vtkIdTypeArray *vtkDistributedDataFilter::GetGlobalNodeIdArray(vtkDataSet *set) { vtkDataArray *da = set->GetPointData()->GetGlobalIds(); - return vtkIdTypeArray::SafeDownCast(da); + return vtkArrayDownCast(da); } //---------------------------------------------------------------------------- @@ -2773,7 +2773,7 @@ static int insideBoxFunction(vtkIdType cellId, vtkUnstructuredGrid *grid, void * char *arrayName = (char *)data; vtkDataArray *da= grid->GetCellData()->GetArray(arrayName); - vtkUnsignedCharArray *inside = vtkUnsignedCharArray::SafeDownCast(da); + vtkUnsignedCharArray *inside = vtkArrayDownCast(da); unsigned char where = inside->GetValue(cellId); diff --git a/Filters/ParallelMPI/vtkDistributedDataFilter.h b/Filters/ParallelMPI/vtkDistributedDataFilter.h index 2499bdede55..09f71ed55a6 100644 --- a/Filters/ParallelMPI/vtkDistributedDataFilter.h +++ b/Filters/ParallelMPI/vtkDistributedDataFilter.h @@ -169,13 +169,11 @@ class VTKFILTERSPARALLELMPI_EXPORT vtkDistributedDataFilter: public vtkDataObjec vtkGetMacro(ClipCells, int); vtkSetMacro(ClipCells, int); -//BTX enum BoundaryModes { ASSIGN_TO_ONE_REGION=0, ASSIGN_TO_ALL_INTERSECTING_REGIONS=1, SPLIT_BOUNDARY_CELLS=2 }; -//ETX // Description: // Handling of ClipCells and IncludeAllIntersectingCells. @@ -299,7 +297,7 @@ class VTKFILTERSPARALLELMPI_EXPORT vtkDistributedDataFilter: public vtkDataObjec // Description: // Implementation for request data. int RequestDataInternal(vtkDataSet* input, vtkUnstructuredGrid* output); -//BTX + private: enum{ @@ -557,6 +555,6 @@ class VTKFILTERSPARALLELMPI_EXPORT vtkDistributedDataFilter: public vtkDataObjec class vtkInternals; vtkInternals* Internals; -//ETX + }; #endif diff --git a/Filters/ParallelStatistics/Testing/Cxx/TestRandomPContingencyStatisticsMPI.cxx b/Filters/ParallelStatistics/Testing/Cxx/TestRandomPContingencyStatisticsMPI.cxx index ac14081ef37..7b446255e23 100644 --- a/Filters/ParallelStatistics/Testing/Cxx/TestRandomPContingencyStatisticsMPI.cxx +++ b/Filters/ParallelStatistics/Testing/Cxx/TestRandomPContingencyStatisticsMPI.cxx @@ -274,7 +274,7 @@ void RandomContingencyStatistics( vtkMultiProcessController* controller, void* a << " absolute tolerance).\n"; } - vtkIdTypeArray* keys = vtkIdTypeArray::SafeDownCast( outputContingency->GetColumnByName( "Key" ) ); + vtkIdTypeArray* keys = vtkArrayDownCast( outputContingency->GetColumnByName( "Key" ) ); if ( ! keys ) { cout << "*** Error: " @@ -284,7 +284,7 @@ void RandomContingencyStatistics( vtkMultiProcessController* controller, void* a } vtkStdString proName = "P"; - vtkDoubleArray* prob = vtkDoubleArray::SafeDownCast( outputContingency->GetColumnByName( proName ) ); + vtkDoubleArray* prob = vtkArrayDownCast( outputContingency->GetColumnByName( proName ) ); if ( ! prob ) { cout << "*** Error: " diff --git a/Filters/ParallelStatistics/Testing/Cxx/TestRandomPMomentStatisticsMPI.cxx b/Filters/ParallelStatistics/Testing/Cxx/TestRandomPMomentStatisticsMPI.cxx index b8d8fe67ac1..0e61d86154b 100644 --- a/Filters/ParallelStatistics/Testing/Cxx/TestRandomPMomentStatisticsMPI.cxx +++ b/Filters/ParallelStatistics/Testing/Cxx/TestRandomPMomentStatisticsMPI.cxx @@ -403,7 +403,7 @@ void RandomSampleStatistics( vtkMultiProcessController* controller, void* arg ) if ( relDevArr ) { // Assessed column should be an array of doubles - vtkDoubleArray* relDev = vtkDoubleArray::SafeDownCast( relDevArr ); + vtkDoubleArray* relDev = vtkArrayDownCast( relDevArr ); if ( relDev ) { // Allocate and initialize counters diff --git a/Filters/ParallelStatistics/vtkPBivariateLinearTableThreshold.cxx b/Filters/ParallelStatistics/vtkPBivariateLinearTableThreshold.cxx index 9ddd7c0c916..8779e18f9c6 100644 --- a/Filters/ParallelStatistics/vtkPBivariateLinearTableThreshold.cxx +++ b/Filters/ParallelStatistics/vtkPBivariateLinearTableThreshold.cxx @@ -79,7 +79,7 @@ int vtkPBivariateLinearTableThreshold::RequestData(vtkInformation* request , vtkSmartPointer gatheredTable = vtkSmartPointer::New(); for (int i=0; iGetNumberOfColumns(); i++) { - vtkAbstractArray* col = vtkAbstractArray::SafeDownCast(outRowDataTable->GetColumn(i)); + vtkAbstractArray* col = vtkArrayDownCast(outRowDataTable->GetColumn(i)); if (!col) continue; diff --git a/Filters/ParallelStatistics/vtkPContingencyStatistics.cxx b/Filters/ParallelStatistics/vtkPContingencyStatistics.cxx index ae49032b60d..cdc53cfea1e 100644 --- a/Filters/ParallelStatistics/vtkPContingencyStatistics.cxx +++ b/Filters/ParallelStatistics/vtkPContingencyStatistics.cxx @@ -89,10 +89,10 @@ static bool StringArrayToStringBuffer( vtkTable* contingencyTab, std::vector& kcValues ) { // Downcast meta columns to string arrays for efficient data access - vtkIdTypeArray* keys = vtkIdTypeArray::SafeDownCast( contingencyTab->GetColumnByName( "Key" ) ); + vtkIdTypeArray* keys = vtkArrayDownCast( contingencyTab->GetColumnByName( "Key" ) ); vtkAbstractArray* valx = contingencyTab->GetColumnByName( "x" ); vtkAbstractArray* valy = contingencyTab->GetColumnByName( "y" ); - vtkIdTypeArray* card = vtkIdTypeArray::SafeDownCast( contingencyTab->GetColumnByName( "Cardinality" ) ); + vtkIdTypeArray* card = vtkArrayDownCast( contingencyTab->GetColumnByName( "Cardinality" ) ); if ( ! keys || ! valx || ! valy || ! card ) { return true; diff --git a/Filters/ParallelStatistics/vtkPContingencyStatistics.h b/Filters/ParallelStatistics/vtkPContingencyStatistics.h index de410faacb1..cfcb1a142ff 100644 --- a/Filters/ParallelStatistics/vtkPContingencyStatistics.h +++ b/Filters/ParallelStatistics/vtkPContingencyStatistics.h @@ -40,9 +40,7 @@ #include "vtkFiltersParallelStatisticsModule.h" // For export macro #include "vtkContingencyStatistics.h" -//BTX #include // STL Header -//ETX class vtkMultiBlockDataSet; class vtkMultiProcessController; @@ -70,7 +68,6 @@ class VTKFILTERSPARALLELSTATISTICS_EXPORT vtkPContingencyStatistics : public vtk vtkPContingencyStatistics(); ~vtkPContingencyStatistics(); -//BTX // Description: // Reduce the collection of local contingency tables to the global one bool Reduce( vtkIdType&, @@ -88,7 +85,6 @@ class VTKFILTERSPARALLELSTATISTICS_EXPORT vtkPContingencyStatistics : public vtk vtkIdType, std::vector&, vtkIdType ); -//ETX vtkMultiProcessController* Controller; private: diff --git a/Filters/ParallelStatistics/vtkPOrderStatistics.cxx b/Filters/ParallelStatistics/vtkPOrderStatistics.cxx index fa773086f03..a130afe1398 100644 --- a/Filters/ParallelStatistics/vtkPOrderStatistics.cxx +++ b/Filters/ParallelStatistics/vtkPOrderStatistics.cxx @@ -187,7 +187,7 @@ void vtkPOrderStatistics::Learn( vtkTable* inData, // Downcast columns to typed arrays for efficient data access vtkAbstractArray* vals = histoTab->GetColumnByName( "Value" ); - vtkIdTypeArray* card = vtkIdTypeArray::SafeDownCast( histoTab->GetColumnByName( "Cardinality" ) ); + vtkIdTypeArray* card = vtkArrayDownCast( histoTab->GetColumnByName( "Cardinality" ) ); if ( ! vals || ! card ) { vtkErrorMacro("Column fetching error on process " @@ -219,7 +219,7 @@ void vtkPOrderStatistics::Learn( vtkTable* inData, if ( vals->IsA("vtkDataArray") ) { // Downcast column to data array for subsequent typed message passing - vtkDataArray* dVals = vtkDataArray::SafeDownCast( vals ); + vtkDataArray* dVals = vtkArrayDownCast( vals ); // Create column for global histogram values of the same type as the values vtkDataArray* dVals_g = vtkDataArray::CreateDataArray( dVals->GetDataType() ); @@ -274,7 +274,7 @@ void vtkPOrderStatistics::Learn( vtkTable* inData, else if ( vals->IsA("vtkStringArray") ) { // Downcast column to string array for subsequent typed message passing - vtkStringArray* sVals = vtkStringArray::SafeDownCast( vals ); + vtkStringArray* sVals = vtkArrayDownCast( vals ); // Packing step: concatenate all string values vtkStdString sPack_l; diff --git a/Filters/ParallelStatistics/vtkPOrderStatistics.h b/Filters/ParallelStatistics/vtkPOrderStatistics.h index 6bc41f60cea..7774532c42b 100644 --- a/Filters/ParallelStatistics/vtkPOrderStatistics.h +++ b/Filters/ParallelStatistics/vtkPOrderStatistics.h @@ -40,9 +40,7 @@ PURPOSE. See the above copyright notice for more information. #include "vtkFiltersParallelStatisticsModule.h" // For export macro #include "vtkOrderStatistics.h" -//BTX #include // STL Header -//ETX class vtkIdTypeArray; class vtkMultiBlockDataSet; @@ -71,7 +69,6 @@ class VTKFILTERSPARALLELSTATISTICS_EXPORT vtkPOrderStatistics : public vtkOrderS vtkPOrderStatistics(); ~vtkPOrderStatistics(); -//BTX // Description: // Reduce the collection of local histograms to the global one for data inputs bool Reduce( vtkIdTypeArray*, @@ -90,7 +87,6 @@ class VTKFILTERSPARALLELSTATISTICS_EXPORT vtkPOrderStatistics : public vtkOrderS vtkIdTypeArray*, vtkStringArray*, vtkIdType ); -//ETX vtkMultiProcessController* Controller; private: diff --git a/Filters/Points/CMakeLists.txt b/Filters/Points/CMakeLists.txt index 4b3e6508dbe..f46c1ac37fc 100644 --- a/Filters/Points/CMakeLists.txt +++ b/Filters/Points/CMakeLists.txt @@ -1,26 +1,25 @@ set(Module_SRCS - vtkArrayListTemplate.txx vtkEllipsoidalGaussianKernel.cxx vtkGaussianKernel.cxx + vtkGeneralizedKernel.cxx vtkInterpolationKernel.cxx - vtkPointInterpolator.cxx vtkLinearKernel.cxx + vtkPointInterpolator.cxx + vtkPointInterpolator2D.cxx + vtkProbabilisticVoronoiKernel.cxx + vtkSPHInterpolator.cxx + vtkSPHCubicKernel.cxx vtkSPHKernel.cxx + vtkSPHQuarticKernel.cxx + vtkSPHQuinticKernel.cxx vtkShepardKernel.cxx vtkVoronoiKernel.cxx ) -set(${vtk-module}_HDRS - vtkArrayListTemplate.h - ) - set_source_files_properties( + vtkGeneralizedKernel.cxx vtkInterpolationKernel ABSTRACT ) -set_source_files_properties( - vtkArrayListTemplate.txx - WRAP_EXCLUDE -) vtk_module_library(vtkFiltersPoints ${Module_SRCS}) diff --git a/Filters/Points/Testing/Cxx/CMakeLists.txt b/Filters/Points/Testing/Cxx/CMakeLists.txt new file mode 100644 index 00000000000..d8afa56c198 --- /dev/null +++ b/Filters/Points/Testing/Cxx/CMakeLists.txt @@ -0,0 +1,4 @@ +vtk_add_test_cxx(${vtk-module}CxxTests tests + UnitTestKernels.cxx,NO_VALID + ) +vtk_test_cxx_executable(${vtk-module}CxxTests tests) diff --git a/Filters/Points/Testing/Cxx/UnitTestKernels.cxx b/Filters/Points/Testing/Cxx/UnitTestKernels.cxx new file mode 100644 index 00000000000..8ca8bc829f6 --- /dev/null +++ b/Filters/Points/Testing/Cxx/UnitTestKernels.cxx @@ -0,0 +1,533 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: UnitTestKernels.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkSmartPointer.h" +#include "vtkLinearKernel.h" +#include "vtkGaussianKernel.h" +#include "vtkEllipsoidalGaussianKernel.h" +#include "vtkShepardKernel.h" +#include "vtkProbabilisticVoronoiKernel.h" +#include "vtkVoronoiKernel.h" +#include "vtkPointSource.h" +#include "vtkSphereSource.h" +#include "vtkStaticPointLocator.h" +#include "vtkPointData.h" +#include "vtkPoints.h" +#include "vtkDoubleArray.h" +#include "vtkMath.h" +#include "vtkMathUtilities.h" + +#include +#include +#include + +template int TestProbabilisticKernel (vtkSmartPointer kernel, vtkIdType numberOfPoints, std::string description = "", bool useProbs = true); +template int TestKernel (vtkSmartPointer kernel, vtkIdType numberOfPoints, std::string description = ""); + +//----------------------------------------------------------------------------- +int UnitTestKernels(int, char*[]) +{ + const vtkIdType numberOfPoints = 100000; + int status = 0; + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToNClosest(); + kernel->SetNumberOfPoints(100); + kernel->SetSharpness(5.0); + kernel->NormalizeWeightsOn(); + status += TestProbabilisticKernel (kernel, numberOfPoints, "GaussianKernel: NClosest(100): Sharpness(5.0)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToRadius(); + kernel->SetRadius(.05); + status += TestProbabilisticKernel (kernel, numberOfPoints, "GaussianKernel: Radius(.05)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToNClosest(); + kernel->SetNumberOfPoints(100); + status += TestProbabilisticKernel (kernel, numberOfPoints, "ShepardKernel: NClosest(100)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToRadius(); + kernel->SetRadius(.05); + status += TestProbabilisticKernel (kernel, numberOfPoints, "ShepardKernel: Radius(.05)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToRadius(); + kernel->SetPowerParameter(10.0); + kernel->SetRadius(.05); + status += TestProbabilisticKernel (kernel, numberOfPoints, "ShepardKernel: Radius(.05) PowerParameter(10)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToRadius(); + kernel->SetPowerParameter(1.0); + kernel->SetRadius(.05); + status += TestProbabilisticKernel (kernel, numberOfPoints, "ShepardKernel: Radius(.05) PowerParameter(1)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToNClosest(); + kernel->SetNumberOfPoints(100); + status += TestProbabilisticKernel (kernel, numberOfPoints, "ProbabilisticVoronoiKernel: NClosest(100)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToRadius(); + kernel->SetRadius(.05); + status += TestProbabilisticKernel (kernel, numberOfPoints, "ProbabilisticVoronoiKernel: Radius(.05)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToNClosest(); + kernel->SetNumberOfPoints(100); + status += TestProbabilisticKernel (kernel, numberOfPoints, "LinearKernel: NClosest(100)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToRadius(); + kernel->SetRadius(.05); + status += TestProbabilisticKernel (kernel, numberOfPoints, "LinearKernel: Radius(.05)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetKernelFootprintToRadius(); + kernel->SetRadius(.05); + status += TestProbabilisticKernel (kernel, numberOfPoints, "LinearKernel: Radius(.05), No Probabilities", false); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + std::ostringstream superPrint; + kernel->Superclass::Print(superPrint); + + kernel->UseNormalsOff(); + kernel->UseScalarsOn(); + kernel->SetScaleFactor(2.0); + + kernel->SetScalarsArrayName("TestDistances"); + kernel->RequiresInitializationOff(); + kernel->SetRadius(.05); + status += TestKernel (kernel, numberOfPoints, "EllipsoidalGaussianKernel: Radius(.05)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->UseNormalsOn(); + kernel->SetNormalsArrayName("TestNormals"); + kernel->UseScalarsOff(); + kernel->SetRadius(.05); + kernel->SetSharpness(5.0); + status += TestKernel (kernel, numberOfPoints, "EllipsoidalGaussianKernel: Radius(.05) Sharpness(5.0)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetRadius(.05); + kernel->SetEccentricity(.1); + status += TestKernel (kernel, numberOfPoints, "EllipsoidalGaussianKernel: Radius(.05) Eccentricity(.1)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + kernel->SetRadius(.05); + kernel->SetEccentricity(10.0); + status += TestKernel (kernel, numberOfPoints, "EllipsoidalGaussianKernel: Radius(.05) Eccentricity(10.0)"); + } + { + vtkSmartPointer kernel = + vtkSmartPointer::New(); + std::ostringstream emptyPrint; + kernel->Print(emptyPrint); + + kernel->RequiresInitializationOff(); + status += TestKernel (kernel, numberOfPoints, "VoronoiKernel"); + } + return status; +} + +template int TestProbabilisticKernel (vtkSmartPointer kernel, vtkIdType numberOfPoints, std::string description, bool useProbs) +{ + int status = EXIT_SUCCESS; + + std::cout << "Testing " << description; + + if ( !kernel->IsTypeOf("vtkGeneralizedKernel")) + { + std::cout << " ERROR: " << kernel->GetClassName() + << " is not a subclass of vtkGeneralizedKernel"; + std::cout << " FAILED" << std::endl; + status = EXIT_FAILURE; + } + if ( !kernel->IsTypeOf("vtkInterpolationKernel")) + { + std::cout << " ERROR: " << kernel->GetClassName() + << " is not a subclass of vtkInterpolationKernel"; + std::cout << " FAILED" << std::endl; + status = EXIT_FAILURE; + } + + vtkSmartPointer sphere = + vtkSmartPointer::New(); + sphere->SetPhiResolution(11); + sphere->SetThetaResolution(21); + sphere->SetRadius(.5); + sphere->Update(); + + vtkSmartPointer randomSphere = + vtkSmartPointer::New(); + randomSphere->SetRadius(sphere->GetRadius() * 2.0);; + randomSphere->SetNumberOfPoints(numberOfPoints); + randomSphere->Update(); + vtkSmartPointer distances = + vtkSmartPointer::New(); + distances->SetNumberOfTuples(randomSphere->GetOutput()->GetNumberOfPoints()); + + double refPt[3]; + refPt[0] = 0.0; + refPt[1] = 0.0; + refPt[2] = 0.0; + for (vtkIdType id = 0; id < randomSphere->GetOutput()->GetNumberOfPoints(); ++id) + { + double distance; + double pt[3]; + + randomSphere->GetOutput()->GetPoint(id, pt); + distance = std::sqrt(vtkMath::Distance2BetweenPoints(refPt, pt)); + distances->SetTuple1(id, distance); + } + distances->SetName("Distances"); + + randomSphere->GetOutput()->GetPointData()->SetScalars(distances); + + vtkSmartPointer locator = + vtkSmartPointer::New(); + locator->SetDataSet(randomSphere->GetOutput()); + double meanProbe = 0.0; + kernel->Initialize(locator, randomSphere->GetOutput(), randomSphere->GetOutput()->GetPointData()); + + std::ostringstream fullPrint; + kernel->Print(fullPrint); + + for (vtkIdType id = 0; id < sphere->GetOutput()->GetNumberOfPoints(); ++id) + { + double point[3]; + sphere->GetOutput()->GetPoints()->GetPoint(id, point); + vtkSmartPointer ptIds = + vtkSmartPointer::New(); + vtkSmartPointer weights = + vtkSmartPointer::New(); + kernel->ComputeBasis(point, ptIds); + vtkSmartPointer probabilities = + vtkSmartPointer::New(); + probabilities->SetNumberOfTuples(ptIds->GetNumberOfIds()); + for (vtkIdType p = 0; p < ptIds->GetNumberOfIds(); ++p) + { + double distance; + double pt[3]; + randomSphere->GetOutput()->GetPoint(p, pt); + distance = std::sqrt(vtkMath::Distance2BetweenPoints(refPt, pt)); + probabilities->SetTuple1(p, (2.0 - distance) / 2.0); + } + if (useProbs) + { + kernel->ComputeWeights(point, ptIds, probabilities, weights); + } + else + { + kernel->ComputeWeights(point, ptIds, NULL, weights); + } + double scalar; + randomSphere->GetOutput()->GetPointData()->GetArray("Distances")->GetTuple(id, &scalar); + double probe = 0.0; + if (id == 0) + { + std::cout << " # points: " << ptIds->GetNumberOfIds(); + } + for (vtkIdType p = 0; p < ptIds->GetNumberOfIds(); ++p) + { + double value; + randomSphere->GetOutput()->GetPointData()->GetArray("Distances")->GetTuple(ptIds->GetId(p), &value);; + double weight; + weights->GetTuple(p, &weight); + probe += weight * value; + } + meanProbe += probe; + } + meanProbe /= static_cast (sphere->GetOutput()->GetNumberOfPoints()); + std::cout << " Mean probe:" << meanProbe; + + if (!vtkMathUtilities::FuzzyCompare(meanProbe, .5, .01)) + { + std::cout << " ERROR: Mean of the probes: " << meanProbe << " is not within .01 of the radius .5"; + std::cout << " FAILED" << std::endl; + status = EXIT_FAILURE; + } + + // Test for exact points + vtkSmartPointer exactLocator = + vtkSmartPointer::New(); + exactLocator->SetDataSet(sphere->GetOutput()); + vtkSmartPointer radii = + vtkSmartPointer::New(); + radii->SetNumberOfTuples(sphere->GetOutput()->GetNumberOfPoints()); + radii->FillComponent(0, .5); + sphere->GetOutput()->GetPointData()->SetScalars(radii); + kernel->Initialize(exactLocator, + sphere->GetOutput(), + sphere->GetOutput()->GetPointData()); + for (vtkIdType id = 0; id < sphere->GetOutput()->GetNumberOfPoints(); ++id) + { + double point[3]; + sphere->GetOutput()->GetPoints()->GetPoint(id, point); + vtkSmartPointer ptIds = + vtkSmartPointer::New(); + kernel->ComputeBasis(point, ptIds); + vtkSmartPointer weights = + vtkSmartPointer::New(); + kernel->ComputeWeights(point, ptIds, NULL, weights); + + double probe = 0.0; + for (vtkIdType p = 0; p < ptIds->GetNumberOfIds(); ++p) + { + double value; + sphere->GetOutput()->GetPointData()->GetScalars()->GetTuple(ptIds->GetId(p), &value);; + double weight; + weights->GetTuple(p, &weight); + probe += weight * value; + } + if (!vtkMathUtilities::FuzzyCompare(probe, .5, std::numeric_limits::epsilon()*256.0)) + { + status = EXIT_FAILURE; + std::cout << "Expected .5 but got " << probe << std::endl; + } + } + + if (status == EXIT_SUCCESS) + { + std::cout << " PASSED" << std::endl; + } + return status; +} + +template int TestKernel (vtkSmartPointer kernel, vtkIdType numberOfPoints, std::string description) +{ + int status = 0; + std::cout << "Testing " << description; + vtkSmartPointer sphere = + vtkSmartPointer::New(); + sphere->SetPhiResolution(21); + sphere->SetThetaResolution(21); + sphere->SetRadius(.5); + sphere->Update(); + + vtkSmartPointer randomSphere = + vtkSmartPointer::New(); + randomSphere->SetRadius(sphere->GetRadius() * 2.0); + randomSphere->SetNumberOfPoints(numberOfPoints); + randomSphere->Update(); + vtkSmartPointer distances = + vtkSmartPointer::New(); + distances->SetNumberOfTuples(randomSphere->GetOutput()->GetNumberOfPoints()); + vtkSmartPointer normals = + vtkSmartPointer::New(); + normals->SetNumberOfComponents(3); + normals->SetNumberOfTuples(randomSphere->GetOutput()->GetNumberOfPoints()); + + double refPt[3]; + refPt[0] = 0.0; + refPt[1] = 0.0; + refPt[2] = 0.0; + for (vtkIdType id = 0; id < randomSphere->GetOutput()->GetNumberOfPoints(); ++id) + { + double distance; + double pt[3]; + randomSphere->GetOutput()->GetPoint(id, pt); + distance = std::sqrt(vtkMath::Distance2BetweenPoints(refPt, pt)); + distances->SetTuple1(id, distance); + double normal[3]; + normal[0] = pt[0]; + normal[1] = pt[1]; + normal[2] = pt[2]; + normals->SetTuple3(id, normal[0], normal[1], normal[2]); + } + distances->SetName("TestDistances"); + normals->SetName("TestNormals"); + + randomSphere->GetOutput()->GetPointData()->AddArray(distances); + randomSphere->GetOutput()->GetPointData()->AddArray(normals); + + vtkSmartPointer locator = + vtkSmartPointer::New(); + locator->SetDataSet(randomSphere->GetOutput()); + double meanProbe = 0.0; + kernel->Initialize(locator, randomSphere->GetOutput(), randomSphere->GetOutput()->GetPointData()); + + std::ostringstream fullPrint; + kernel->Print(fullPrint); + for (vtkIdType id = 0; id < sphere->GetOutput()->GetNumberOfPoints(); ++id) + { + double point[3]; + sphere->GetOutput()->GetPoints()->GetPoint(id, point); + vtkSmartPointer ptIds = + vtkSmartPointer::New(); + vtkSmartPointer weights = + vtkSmartPointer::New(); + kernel->ComputeBasis(point, ptIds); + kernel->ComputeWeights(point, ptIds, weights); + if (id == 0) + { + std::cout << " # points: " << ptIds->GetNumberOfIds(); + } + double scalar; + randomSphere->GetOutput()->GetPointData()->GetArray("TestDistances")->GetTuple(id, &scalar); + double probe = 0.0; + for (vtkIdType p = 0; p < ptIds->GetNumberOfIds(); ++p) + { + double value; + randomSphere->GetOutput()->GetPointData()->GetArray("TestDistances")->GetTuple(ptIds->GetId(p), &value);; + double weight; + weights->GetTuple(p, &weight); + probe += weight * value; + } + meanProbe += probe; + } + meanProbe /= static_cast (sphere->GetOutput()->GetNumberOfPoints()); + std::cout << " Mean probe:" << meanProbe; + if (!vtkMathUtilities::FuzzyCompare(meanProbe, .5, .01)) + { + std::cout << "ERROR: Mean of the probes: " << meanProbe << " is not within .01 of the radius .5"; + std::cout << " FAILED" << std::endl; + status = EXIT_FAILURE; + } + + // Test for exact points + vtkSmartPointer exactLocator = + vtkSmartPointer::New(); + exactLocator->SetDataSet(sphere->GetOutput()); + vtkSmartPointer radii = + vtkSmartPointer::New(); + radii->SetNumberOfTuples(sphere->GetOutput()->GetNumberOfPoints()); + radii->FillComponent(0, .5); + sphere->GetOutput()->GetPointData()->SetScalars(radii); + kernel->Initialize(exactLocator, + sphere->GetOutput(), + sphere->GetOutput()->GetPointData()); + for (vtkIdType id = 0; id < sphere->GetOutput()->GetNumberOfPoints(); ++id) + { + double point[3]; + sphere->GetOutput()->GetPoints()->GetPoint(id, point); + vtkSmartPointer ptIds = + vtkSmartPointer::New(); + vtkSmartPointer weights = + vtkSmartPointer::New(); + kernel->ComputeBasis(point, ptIds); + kernel->ComputeWeights(point, ptIds, weights); + + double probe = 0.0; + for (vtkIdType p = 0; p < ptIds->GetNumberOfIds(); ++p) + { + double value; + sphere->GetOutput()->GetPointData()->GetScalars()->GetTuple(ptIds->GetId(p), &value);; + double weight; + weights->GetTuple(p, &weight); + probe += weight * value; + } + if (!vtkMathUtilities::FuzzyCompare(probe, .5, std::numeric_limits::epsilon()*256.0)) + { + status = EXIT_FAILURE; + std::cout << "Expected .5 but got " << probe << std::endl; + } + } + + if (status == EXIT_SUCCESS) + { + std::cout << " PASSED" << std::endl; + } + return status; +} diff --git a/Filters/Points/Testing/Data/Baseline/TestEllipsoidalGaussianKernel.png.md5 b/Filters/Points/Testing/Data/Baseline/TestEllipsoidalGaussianKernel.png.md5 new file mode 100644 index 00000000000..25400594bbf --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestEllipsoidalGaussianKernel.png.md5 @@ -0,0 +1 @@ +73d5fffe9ccbce2da8e0505a93727217 diff --git a/Filters/Points/Testing/Data/Baseline/TestPointInterpolator.png.md5 b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator.png.md5 index 2b1a186b7d6..fd20469479c 100644 --- a/Filters/Points/Testing/Data/Baseline/TestPointInterpolator.png.md5 +++ b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator.png.md5 @@ -1 +1 @@ -86105d4788a02f09d98bcb4118866279 +93edd45fbd9d9e8541b7be12e2955df0 diff --git a/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D.png.md5 b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D.png.md5 new file mode 100644 index 00000000000..219f183fe01 --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D.png.md5 @@ -0,0 +1 @@ +4ed9638e439baae400e9e309cb0fb6c4 diff --git a/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2.png.md5 b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2.png.md5 new file mode 100644 index 00000000000..1cba95767ad --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2.png.md5 @@ -0,0 +1 @@ +e80a22b6d9f2f7744e898e4547c3ee18 diff --git a/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2_1.png.md5 b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2_1.png.md5 new file mode 100644 index 00000000000..f5be24186b0 --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2_1.png.md5 @@ -0,0 +1 @@ +72709e4ea35a38107148f873613a7f5a diff --git a/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2_2.png.md5 b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2_2.png.md5 new file mode 100644 index 00000000000..635637bbad9 --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2_2.png.md5 @@ -0,0 +1 @@ +b589dc50f69dc98f6cae40d95257367b diff --git a/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2_3.png.md5 b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2_3.png.md5 new file mode 100644 index 00000000000..3932e6c54eb --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D2_3.png.md5 @@ -0,0 +1 @@ +61b7a42f541aad2ed9583ba004049d6c diff --git a/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D_1.png.md5 b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D_1.png.md5 new file mode 100644 index 00000000000..e515a230603 --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestPointInterpolator2D_1.png.md5 @@ -0,0 +1 @@ +26fb9f36b081f039bc3dca34aea59b28 diff --git a/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator.png.md5 b/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator.png.md5 new file mode 100644 index 00000000000..8c9473af2dc --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator.png.md5 @@ -0,0 +1 @@ +7e7701189523f36a2ca3f7e6703175ad diff --git a/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator2D.png.md5 b/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator2D.png.md5 new file mode 100644 index 00000000000..e36b922d007 --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator2D.png.md5 @@ -0,0 +1 @@ +70a3d0ecf0356815e8fd922112b87e85 diff --git a/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator2D_1.png.md5 b/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator2D_1.png.md5 new file mode 100644 index 00000000000..b7a5da0c717 --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator2D_1.png.md5 @@ -0,0 +1 @@ +1404d26c216ce2fde7770a2712ef8980 diff --git a/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator_1.png.md5 b/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator_1.png.md5 new file mode 100644 index 00000000000..2858b770d0c --- /dev/null +++ b/Filters/Points/Testing/Data/Baseline/TestSPHInterpolator_1.png.md5 @@ -0,0 +1 @@ +2948b025605a5c8801327b58403980a0 diff --git a/Filters/Points/Testing/Python/CMakeLists.txt b/Filters/Points/Testing/Python/CMakeLists.txt index 38a103114ee..afaa380cdb0 100644 --- a/Filters/Points/Testing/Python/CMakeLists.txt +++ b/Filters/Points/Testing/Python/CMakeLists.txt @@ -1,5 +1,9 @@ - vtk_add_test_python( + TestEllipsoidalGaussianKernel.py TestPointInterpolator.py TestPointInterpolator2.py + TestPointInterpolator2D.py + TestPointInterpolator2D2.py + TestSPHInterpolator.py + TestSPHInterpolator2D.py ) diff --git a/Filters/Points/Testing/Python/TestEllipsoidalGaussianKernel.py b/Filters/Points/Testing/Python/TestEllipsoidalGaussianKernel.py new file mode 100755 index 00000000000..eeb74fad5be --- /dev/null +++ b/Filters/Points/Testing/Python/TestEllipsoidalGaussianKernel.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python +import vtk +import vtk.test.Testing +from vtk.util.misc import vtkGetDataRoot +VTK_DATA_ROOT = vtkGetDataRoot() + +# Parameters for testing +res = 250 + +# Graphics stuff +ren0 = vtk.vtkRenderer() +renWin = vtk.vtkRenderWindow() +renWin.AddRenderer(ren0) +iren = vtk.vtkRenderWindowInteractor() +iren.SetRenderWindow(renWin) + +# Create a volume to interpolate on to +volume = vtk.vtkImageData() +volume.SetDimensions(res,res,res) +volume.SetOrigin(0,0,0) +volume.SetSpacing(1,1,1) +fa = vtk.vtkFloatArray() +fa.SetName("scalars") +fa.Allocate(res ** 3) +volume.GetPointData().SetScalars(fa) + +center = volume.GetCenter() +bounds = volume.GetBounds() + +# Create a single point with a normal and scalar +onePts = vtk.vtkPoints() +onePts.SetNumberOfPoints(1) +onePts.SetPoint(0,center) + +oneScalars = vtk.vtkFloatArray() +oneScalars.SetNumberOfTuples(1) +oneScalars.SetTuple1(0,5.0) +oneScalars.SetName("scalarPt") + +oneNormals = vtk.vtkFloatArray() +oneNormals.SetNumberOfComponents(3) +oneNormals.SetNumberOfTuples(1) +oneNormals.SetTuple3(0,1,1,1) +oneNormals.SetName("normalPt") + +oneData = vtk.vtkPolyData() +oneData.SetPoints(onePts) +oneData.GetPointData().SetScalars(oneScalars) +oneData.GetPointData().SetNormals(oneNormals) + +# Interpolation ------------------------------------------------ +eKernel = vtk.vtkEllipsoidalGaussianKernel() +eKernel.SetKernelFootprintToRadius() +eKernel.SetRadius(50.0) +eKernel.UseScalarsOn() +eKernel.UseNormalsOn() +eKernel.SetScaleFactor(0.5) +eKernel.SetEccentricity(3) +eKernel.NormalizeWeightsOff() + +interpolator = vtk.vtkPointInterpolator() +interpolator.SetInputData(volume) +interpolator.SetSourceData(oneData) +interpolator.SetKernel(eKernel) +interpolator.Update() + +# Extract iso surface ------------------------------------------------ +contour = vtk.vtkFlyingEdges3D() +contour.SetInputConnection(interpolator.GetOutputPort()) +contour.SetValue(0,10) + +intMapper = vtk.vtkPolyDataMapper() +intMapper.SetInputConnection(contour.GetOutputPort()) + +intActor = vtk.vtkActor() +intActor.SetMapper(intMapper) + +# Create an outline +outline = vtk.vtkOutlineFilter() +outline.SetInputData(volume) + +outlineMapper = vtk.vtkPolyDataMapper() +outlineMapper.SetInputConnection(outline.GetOutputPort()) + +outlineActor = vtk.vtkActor() +outlineActor.SetMapper(outlineMapper) + +ren0.AddActor(intActor) +#ren0.AddActor(outlineActor) +ren0.SetBackground(1,1,1) + +iren.Initialize() +renWin.Render() + +#iren.Start() diff --git a/Filters/Points/Testing/Python/TestPointInterpolator.py b/Filters/Points/Testing/Python/TestPointInterpolator.py index 9cbc3c679c0..d3c3abbc954 100755 --- a/Filters/Points/Testing/Python/TestPointInterpolator.py +++ b/Filters/Points/Testing/Python/TestPointInterpolator.py @@ -140,22 +140,24 @@ outlineActor2 = vtk.vtkActor() outlineActor2.SetMapper(outlineMapper2) -# SPH kernel------------------------------------------------------- -SPHKernel = vtk.vtkSPHKernel() +# Linear kernel------------------------------------------------------- +linearKernel = vtk.vtkLinearKernel() +linearKernel.SetRadius(0.5) interpolator3 = vtk.vtkPointInterpolator() interpolator3.SetInputConnection(plane.GetOutputPort()) interpolator3.SetSourceData(output) -interpolator3.SetKernel(voronoiKernel) -#interpolator3.SetKernel(SPHKernel) +interpolator3.SetKernel(linearKernel) interpolator3.SetLocator(locator) +interpolator3.SetNullPointsStrategyToNullValue() +interpolator3.AddExcludedArray("StagnationEnergy") # Time execution timer.StartTimer() interpolator3.Update() timer.StopTimer() time = timer.GetElapsedTime() -print("Interpolate Points (SPH): {0}".format(time)) +print("Interpolate Points (Linear): {0}".format(time)) intMapper3 = vtk.vtkPolyDataMapper() intMapper3.SetInputConnection(interpolator3.GetOutputPort()) diff --git a/Filters/Points/Testing/Python/TestPointInterpolator2.py b/Filters/Points/Testing/Python/TestPointInterpolator2.py index ddfd4a5b12d..5cbc15fb2c8 100755 --- a/Filters/Points/Testing/Python/TestPointInterpolator2.py +++ b/Filters/Points/Testing/Python/TestPointInterpolator2.py @@ -49,6 +49,7 @@ interpolator.SetSourceData(output) interpolator.SetKernel(gaussianKernel) interpolator.SetLocator(locator) +interpolator.SetNullPointsStrategyToClosestPoint() # Time execution timer = vtk.vtkTimerLog() diff --git a/Filters/Points/Testing/Python/TestPointInterpolator2D.py b/Filters/Points/Testing/Python/TestPointInterpolator2D.py new file mode 100755 index 00000000000..c5ca110a127 --- /dev/null +++ b/Filters/Points/Testing/Python/TestPointInterpolator2D.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python +import vtk +from vtk.test import Testing +from vtk.util.misc import vtkGetDataRoot +VTK_DATA_ROOT = vtkGetDataRoot() + +# Parameters for debugging +NPts = 1000000 +math = vtk.vtkMath() + +# create pipeline: use terrain dataset +# +# Read the data: a height field results +demReader = vtk.vtkDEMReader() +demReader.SetFileName(VTK_DATA_ROOT + "/Data/SainteHelens.dem") +demReader.Update() + +lo = demReader.GetOutput().GetScalarRange()[0] +hi = demReader.GetOutput().GetScalarRange()[1] + +geom = vtk.vtkImageDataGeometryFilter() +geom.SetInputConnection(demReader.GetOutputPort()) + +warp = vtk.vtkWarpScalar() +warp.SetInputConnection(geom.GetOutputPort()) +warp.SetNormal(0, 0, 1) +warp.UseNormalOn() +warp.SetScaleFactor(2) +warp.Update() + +bds = warp.GetOutput().GetBounds() +center = warp.GetOutput().GetCenter() + +# A randomized point cloud, whose attributes are set via implicit function +points = vtk.vtkPoints() +points.SetDataTypeToFloat() +points.SetNumberOfPoints(NPts) +for i in range(0,NPts): + points.SetPoint(i,math.Random(bds[0],bds[1]),math.Random(bds[2],bds[3]),math.Random(bds[4],bds[5])) + +source = vtk.vtkPolyData() +source.SetPoints(points) + +sphere = vtk.vtkSphere() +sphere.SetCenter(center[0],center[1]-7500,center[2]) + +attr = vtk.vtkSampleImplicitFunctionFilter() +attr.SetInputData(source) +attr.SetImplicitFunction(sphere) +attr.Update() + +# Gaussian kernel------------------------------------------------------- +gaussianKernel = vtk.vtkGaussianKernel() +gaussianKernel.SetSharpness(4) +gaussianKernel.SetRadius(50) + +voronoiKernel = vtk.vtkVoronoiKernel() + +interpolator1 = vtk.vtkPointInterpolator2D() +interpolator1.SetInputConnection(warp.GetOutputPort()) +interpolator1.SetSourceConnection(attr.GetOutputPort()) +#interpolator1.SetKernel(gaussianKernel) +interpolator1.SetKernel(voronoiKernel) +interpolator1.SetNullPointsStrategyToClosestPoint() + +# Time execution +timer = vtk.vtkTimerLog() +timer.StartTimer() +interpolator1.Update() +timer.StopTimer() +time = timer.GetElapsedTime() +print("Interpolate Terrain Points (Gaussian): {0}".format(time)) + +scalarRange = attr.GetOutput().GetScalarRange() + +intMapper1 = vtk.vtkPolyDataMapper() +intMapper1.SetInputConnection(interpolator1.GetOutputPort()) +intMapper1.SetScalarRange(scalarRange) + +intActor1 = vtk.vtkActor() +intActor1.SetMapper(intMapper1) + +# Create an outline +outline1 = vtk.vtkOutlineFilter() +outline1.SetInputConnection(warp.GetOutputPort()) + +outlineMapper1 = vtk.vtkPolyDataMapper() +outlineMapper1.SetInputConnection(outline1.GetOutputPort()) + +outlineActor1 = vtk.vtkActor() +outlineActor1.SetMapper(outlineMapper1) + +# Create the RenderWindow, Renderer and both Actors +# +ren0 = vtk.vtkRenderer() +renWin = vtk.vtkRenderWindow() +renWin.AddRenderer(ren0) +iren = vtk.vtkRenderWindowInteractor() +iren.SetRenderWindow(renWin) + +# Add the actors to the renderer, set the background and size +# +ren0.AddActor(intActor1) +ren0.AddActor(outlineActor1) +ren0.SetBackground(0.1, 0.2, 0.4) + +renWin.SetSize(250, 250) + +cam = ren0.GetActiveCamera() +cam.SetFocalPoint(center) + +fp = cam.GetFocalPoint() +cam.SetPosition(fp[0]+.2,fp[1]+.1,fp[2]+1) +ren0.ResetCamera() + +iren.Initialize() + +# render the image +# +renWin.Render() + +#iren.Start() diff --git a/Filters/Points/Testing/Python/TestPointInterpolator2D2.py b/Filters/Points/Testing/Python/TestPointInterpolator2D2.py new file mode 100755 index 00000000000..cf1fcf04f63 --- /dev/null +++ b/Filters/Points/Testing/Python/TestPointInterpolator2D2.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +import vtk +from vtk.test import Testing +from vtk.util.misc import vtkGetDataRoot +VTK_DATA_ROOT = vtkGetDataRoot() + +# Parameters for debugging +res = 500 +math = vtk.vtkMath() + +# create pipeline: use terrain dataset. Just for kicks we'll treat the elevations +# as a "point cloud" and interpolate the elevation onto a plane. +# +# Read the data: a height field results +demReader = vtk.vtkDEMReader() +demReader.SetFileName(VTK_DATA_ROOT + "/Data/SainteHelens.dem") +demReader.Update() + +lo = demReader.GetOutput().GetScalarRange()[0] +hi = demReader.GetOutput().GetScalarRange()[1] + +bds = demReader.GetOutput().GetBounds() +center = demReader.GetOutput().GetCenter() + +# Create a plane of onto which to map the elevation data +plane = vtk.vtkPlaneSource() +plane.SetResolution(res,res) +plane.SetOrigin(bds[0],bds[2],bds[4]) +plane.SetPoint1(bds[1],bds[2],bds[4]) +plane.SetPoint2(bds[0],bds[3],bds[4]) +plane.Update() + + +# Gaussian kernel------------------------------------------------------- +gaussianKernel = vtk.vtkGaussianKernel() +gaussianKernel.SetSharpness(2) +gaussianKernel.SetRadius(200) + +interp = vtk.vtkPointInterpolator2D() +interp.SetInputConnection(plane.GetOutputPort()) +interp.SetSourceConnection(demReader.GetOutputPort()) +interp.SetKernel(gaussianKernel) +interp.SetNullPointsStrategyToClosestPoint() +interp.GetLocator().SetNumberOfPointsPerBucket(1) +interp.InterpolateZOff() + +# Time execution +timer = vtk.vtkTimerLog() +timer.StartTimer() +interp.Update() +timer.StopTimer() +time = timer.GetElapsedTime() +print("Interpolate Terrain Points (Gaussian): {0}".format(time)) + +scalarRange = interp.GetOutput().GetPointData().GetArray("Elevation").GetRange() + +lut = vtk.vtkLookupTable() +lut.SetHueRange(0.6, 0) +lut.SetSaturationRange(1.0, 0) +lut.SetValueRange(0.5, 1.0) + +intMapper = vtk.vtkPolyDataMapper() +intMapper.SetInputConnection(interp.GetOutputPort()) +intMapper.SetScalarModeToUsePointFieldData() +intMapper.SelectColorArray("Elevation") +intMapper.SetScalarRange(scalarRange) +intMapper.SetLookupTable(lut) + +intActor = vtk.vtkActor() +intActor.SetMapper(intMapper) + +# Create some contours +cf = vtk.vtkContourFilter() +cf.SetInputConnection(interp.GetOutputPort()) +cf.GenerateValues(20,scalarRange) + +cfMapper = vtk.vtkPolyDataMapper() +cfMapper.SetInputConnection(cf.GetOutputPort()) + +cfActor = vtk.vtkActor() +cfActor.SetMapper(cfMapper) + +# Create the RenderWindow, Renderer and both Actors +# +ren0 = vtk.vtkRenderer() +renWin = vtk.vtkRenderWindow() +renWin.AddRenderer(ren0) +iren = vtk.vtkRenderWindowInteractor() +iren.SetRenderWindow(renWin) + +# Add the actors to the renderer, set the background and size +# +ren0.AddActor(intActor) +ren0.AddActor(cfActor) +ren0.SetBackground(0.1, 0.2, 0.4) + +renWin.SetSize(300, 300) + +cam = ren0.GetActiveCamera() +cam.SetFocalPoint(center) + +fp = cam.GetFocalPoint() +cam.SetPosition(fp[0]+.2,fp[1]+.1,fp[2]+1) +ren0.ResetCamera() + +iren.Initialize() + +# render the image +# +renWin.Render() +#iren.Start() diff --git a/Filters/Points/Testing/Python/TestSPHInterpolator.py b/Filters/Points/Testing/Python/TestSPHInterpolator.py new file mode 100755 index 00000000000..dd9465f5427 --- /dev/null +++ b/Filters/Points/Testing/Python/TestSPHInterpolator.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python +import vtk +import vtk.test.Testing +from vtk.util.misc import vtkGetDataRoot +VTK_DATA_ROOT = vtkGetDataRoot() + +# Parameters for testing +res = 250 + +# Graphics stuff +ren0 = vtk.vtkRenderer() +renWin = vtk.vtkRenderWindow() +renWin.AddRenderer(ren0) +iren = vtk.vtkRenderWindowInteractor() +iren.SetRenderWindow(renWin) + +# create pipeline +# +reader = vtk.vtkXMLUnstructuredGridReader() +reader.SetFileName(VTK_DATA_ROOT + "/Data/SPH_Points.vtu") +reader.Update() +output = reader.GetOutput() +scalarRange = output.GetPointData().GetArray("Rho").GetRange() + +# Something to sample with +center = output.GetCenter() +bounds = output.GetBounds() +length = output.GetLength() + +plane = vtk.vtkPlaneSource() +plane.SetResolution(res,res) +plane.SetOrigin(bounds[0],bounds[2],bounds[4]) +plane.SetPoint1(bounds[1],bounds[2],bounds[4]) +plane.SetPoint2(bounds[0],bounds[3],bounds[4]) +plane.SetCenter(center) +plane.SetNormal(0,0,1) +plane.Push(1.15) +plane.Update() + +# SPH kernel------------------------------------------------ +# Start with somethign weird: process an empty input +emptyPts = vtk.vtkPoints() +emptyData = vtk.vtkPolyData() +emptyData.SetPoints(emptyPts) + +sphKernel = vtk.vtkSPHQuinticKernel() +sphKernel.SetSpatialStep(0.1) + +interpolator = vtk.vtkSPHInterpolator() +interpolator.SetInputConnection(plane.GetOutputPort()) +interpolator.SetSourceData(emptyData) +interpolator.SetKernel(sphKernel) +interpolator.Update() + +timer = vtk.vtkTimerLog() + +# SPH kernel------------------------------------------------ +interpolator.SetInputConnection(plane.GetOutputPort()) +interpolator.SetSourceConnection(reader.GetOutputPort()) + +# Time execution +timer.StartTimer() +interpolator.Update() +timer.StopTimer() +time = timer.GetElapsedTime() +print("Interpolate Points (SPH): {0}".format(time)) + +intMapper = vtk.vtkPolyDataMapper() +intMapper.SetInputConnection(interpolator.GetOutputPort()) +intMapper.SetScalarModeToUsePointFieldData() +intMapper.SelectColorArray("Rho") +intMapper.SetScalarRange(0,720) + +intActor = vtk.vtkActor() +intActor.SetMapper(intMapper) + +# Create an outline +outline = vtk.vtkOutlineFilter() +outline.SetInputData(output) + +outlineMapper = vtk.vtkPolyDataMapper() +outlineMapper.SetInputConnection(outline.GetOutputPort()) + +outlineActor = vtk.vtkActor() +outlineActor.SetMapper(outlineMapper) + +ren0.AddActor(intActor) +ren0.AddActor(outlineActor) +ren0.SetBackground(0.1, 0.2, 0.4) + +iren.Initialize() +renWin.Render() + +#iren.Start() diff --git a/Filters/Points/Testing/Python/TestSPHInterpolator2D.py b/Filters/Points/Testing/Python/TestSPHInterpolator2D.py new file mode 100755 index 00000000000..cb1590d7e71 --- /dev/null +++ b/Filters/Points/Testing/Python/TestSPHInterpolator2D.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python +import vtk +import vtk.test.Testing +from vtk.util.misc import vtkGetDataRoot +VTK_DATA_ROOT = vtkGetDataRoot() + +# Parameters for testing +res = 250 + +# Graphics stuff +ren0 = vtk.vtkRenderer() +renWin = vtk.vtkRenderWindow() +renWin.AddRenderer(ren0) +iren = vtk.vtkRenderWindowInteractor() +iren.SetRenderWindow(renWin) + +# create pipeline +# +reader = vtk.vtkXMLUnstructuredGridReader() +reader.SetFileName(VTK_DATA_ROOT + "/Data/SPH_Points2D.vtu") +reader.Update() +output = reader.GetOutput() +scalarRange = output.GetPointData().GetArray("Rho").GetRange() + +# Something to sample with +center = output.GetCenter() +bounds = output.GetBounds() +length = output.GetLength() + +plane = vtk.vtkPlaneSource() +plane.SetResolution(res,res) +plane.SetOrigin(bounds[0],bounds[2],bounds[4]) +plane.SetPoint1(bounds[1],bounds[2],bounds[4]) +plane.SetPoint2(bounds[0],bounds[3],bounds[4]) +plane.SetCenter(center) +plane.SetNormal(0,0,1) +plane.Update() + +timer = vtk.vtkTimerLog() + +# SPH kernel------------------------------------------------ +sphKernel = vtk.vtkSPHQuinticKernel() +sphKernel.SetSpatialStep(0.00002) +sphKernel.SetDimension(2) + +interpolator = vtk.vtkSPHInterpolator() +interpolator.SetInputConnection(plane.GetOutputPort()) +interpolator.SetSourceConnection(reader.GetOutputPort()) +interpolator.SetKernel(sphKernel) +interpolator.Update() + +# Time execution +timer.StartTimer() +interpolator.Update() +timer.StopTimer() +time = timer.GetElapsedTime() +print("Interpolate Points (SPH): {0}".format(time)) + +intMapper = vtk.vtkPolyDataMapper() +intMapper.SetInputConnection(interpolator.GetOutputPort()) +intMapper.SetScalarModeToUsePointFieldData() +intMapper.SelectColorArray("Rho") +intMapper.SetScalarRange(750,1050) + +intActor = vtk.vtkActor() +intActor.SetMapper(intMapper) + +# Create an outline +outline = vtk.vtkOutlineFilter() +outline.SetInputData(output) + +outlineMapper = vtk.vtkPolyDataMapper() +outlineMapper.SetInputConnection(outline.GetOutputPort()) + +outlineActor = vtk.vtkActor() +outlineActor.SetMapper(outlineMapper) + +ren0.AddActor(intActor) +ren0.AddActor(outlineActor) +ren0.SetBackground(0.1, 0.2, 0.4) + +iren.Initialize() +renWin.Render() + +#iren.Start() diff --git a/Filters/Points/module.cmake b/Filters/Points/module.cmake index fc25f4a692b..38099879b45 100644 --- a/Filters/Points/module.cmake +++ b/Filters/Points/module.cmake @@ -2,6 +2,7 @@ vtk_module(vtkFiltersPoints GROUPS StandAlone DEPENDS + vtkCommonDataModel vtkCommonExecutionModel vtkCommonSystem vtkCommonMisc diff --git a/Filters/Points/vtkArrayListTemplate.h b/Filters/Points/vtkArrayListTemplate.h deleted file mode 100644 index 00e494cd90e..00000000000 --- a/Filters/Points/vtkArrayListTemplate.h +++ /dev/null @@ -1,174 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkArrayListTemplate.h - - Copyright (c) Kitware, Inc. - All rights reserved. - See LICENSE file for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -// .NAME vtkArrayListTemplate - thread-safe and efficient data attribute manipulation - -// .SECTION Description -// vtkArrayListTemplate supplements the vtkDataSetAttributes class to provide -// threaded processing of data arrays. It is also more efficient for certain -// interpolation operations. The expectation is that it will be replaced one -// day once vtkPointData, vtkCellData, vtkDataSetAttributes, and vtkFieldData -// properly support multithreading and/or are redesigned. Note that this -// implementation does not support incremental operations (like InsertNext()). -// -// Generally the way this helper class is used is to first invoke -// vtkDataSetAttributes::CopyInterpolate() or InterpolateAllocate() which -// performs the initial magic of constructing input and output arrays. Then -// the input attributes, and output attributes, are passed to initialize the -// internal structures. Internally, pairs of typed arrays are created; the -// operations (e.g., interpolate) occur on these typed arrays using a -// typeless, virtual dispatch base class. - - -// .SECTION See Also -// vtkFieldData vtkDataSetAttributes vtkPointData vtkCellData - -#ifndef vtkArrayListTemplate_h -#define vtkArrayListTemplate_h - -#include "vtkDataArray.h" -#include "vtkDataSetAttributes.h" - -// Create a generic class supporting virtual dispatch to type-specific -// subclasses. -struct BaseArrayPair -{ - vtkIdType Num; - int NumComp; - - BaseArrayPair(vtkIdType num, int numComp) : Num(num), NumComp(numComp) - { - } - virtual ~BaseArrayPair() - { - } - - virtual void Copy(vtkIdType inId, vtkIdType outId) = 0; - virtual void Interpolate(int numWeights, const vtkIdType *ids, - const double *weights, vtkIdType outPtId) = 0; - virtual void AssignNullValue(vtkIdType outId) = 0; -}; - -// Type specific interpolation on a matched pair of data arrays -template -struct ArrayPair : public BaseArrayPair -{ - T *Input; - T *Output; - T NullValue; - - ArrayPair(T *in, T *out, vtkIdType num, int numComp, T null) : - BaseArrayPair(num,numComp), Input(in), Output(out), NullValue(null) - { - } - virtual ~ArrayPair() //calm down some finicky compilers - { - } - - virtual void Copy(vtkIdType inId, vtkIdType outId) - { - for (int j=0; j < this->NumComp; ++j) - { - this->Output[outId*this->NumComp+j] = this->Input[inId*this->NumComp+j]; - } - } - - virtual void Interpolate(int numWeights, const vtkIdType *ids, - const double *weights, vtkIdType outPtId) - { - for (int j=0; j < this->NumComp; ++j) - { - double v = 0.0; - for (vtkIdType i=0; i < numWeights; ++i) - { - v += weights[i] * static_cast(this->Input[ids[i]*this->NumComp+j]); - } - this->Output[outPtId*this->NumComp+j] = static_cast(v); - } - } - - virtual void AssignNullValue(vtkIdType outId) - { - for (int j=0; j < this->NumComp; ++j) - { - this->Output[outId*this->NumComp+j] = this->NullValue; - } - } - -}; - -// Forward declarations. This makes working with vtkTemplateMacro easier. -struct ArrayList; - -template -void CreateArrayPair(ArrayList *list, T *inData, T *outData, - vtkIdType numPts, int numComp, T nullValue); - - -// A list of the arrays to interpolate, and a method to invoke interpolation on the list -struct ArrayList -{ - // The list of arrays - std::vector Arrays; - - // Add the arrays to interpolate here - void AddArrays(vtkIdType numOutPts, vtkDataSetAttributes *inPD, - vtkDataSetAttributes *outPD, double nullValue=0.0); - - // Loop over the array pairs and copy data from one to another - void Copy(vtkIdType inId, vtkIdType outId) - { - for (std::vector::iterator it = Arrays.begin(); - it != Arrays.end(); ++it) - { - (*it)->Copy(inId, outId); - } - } - - // Loop over the arrays and have them interpolate themselves - void Interpolate(int numWeights, const vtkIdType *ids, const double *weights, vtkIdType outPtId) - { - for (std::vector::iterator it = Arrays.begin(); - it != Arrays.end(); ++it) - { - (*it)->Interpolate(numWeights, ids, weights, outPtId); - } - } - - // Loop over the arrays and have them interpolate themselves - void AssignNullValue(vtkIdType outId) - { - for (std::vector::iterator it = Arrays.begin(); - it != Arrays.end(); ++it) - { - (*it)->AssignNullValue(outId); - } - } - - // Only you can prevent memory leaks! - ~ArrayList() - { - for (std::vector::iterator it = Arrays.begin(); - it != Arrays.end(); ++it) - { - delete (*it); - } - } -}; - - -#include "vtkArrayListTemplate.txx" - -#endif -// VTK-HeaderTest-Exclude: vtkArrayListTemplate.h diff --git a/Filters/Points/vtkArrayListTemplate.txx b/Filters/Points/vtkArrayListTemplate.txx deleted file mode 100644 index c83f01b9f12..00000000000 --- a/Filters/Points/vtkArrayListTemplate.txx +++ /dev/null @@ -1,75 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkArrayListTemplate.txx - - Copyright (c) Kitware, Inc. - All rights reserved. - See LICENSE file for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkArrayListTemplate.h" - - -#ifndef vtkArrayListTemplate_txx -#define vtkArrayListTemplate_txx - -//---------------------------------------------------------------------------- -// Sort of a little object factory (in conjunction w/ vtkTemplateMacro()) -template -void CreateArrayPair(ArrayList *list, T *inData, T *outData, - vtkIdType numPts, int numComp, T nullValue) -{ - ArrayPair *pair = new ArrayPair(inData,outData,numPts,numComp, nullValue); - list->Arrays.push_back(pair); -} - -// Add the arrays to interpolate here -void ArrayList:: -AddArrays(vtkIdType numOutPts, vtkDataSetAttributes *inPD, vtkDataSetAttributes *outPD, - double nullValue) -{ - // Build the vector of interpolation pairs. Note that InterpolateAllocate should have - // been called at this point (output arrays created and allocated). - char *name; - vtkDataArray *iArray, *oArray; - int iType, oType; - void *iD, *oD; - int iNumComp, oNumComp; - int i, numArrays = outPD->GetNumberOfArrays(); - for (i=0; i < numArrays; ++i) - { - oArray = outPD->GetArray(i); - if ( oArray ) - { - name = oArray->GetName(); - iArray = inPD->GetArray(name); - if ( iArray ) - { - iType = iArray->GetDataType(); - oType = oArray->GetDataType(); - iNumComp = iArray->GetNumberOfComponents(); - oNumComp = oArray->GetNumberOfComponents(); - oArray->SetNumberOfTuples(numOutPts); - - if ( (iType == oType) && (iNumComp == oNumComp) ) //sanity check - { - iD = iArray->GetVoidPointer(0); - oD = oArray->GetVoidPointer(0); - switch (iType) - { - vtkTemplateMacro(CreateArrayPair(this, static_cast(iD), - static_cast(oD),numOutPts,oNumComp, - static_cast(nullValue))); - }//over all VTK types - }//if matching types - }//if matching input array - }//if output array - }//for each candidate array -} - -#endif diff --git a/Filters/Points/vtkEllipsoidalGaussianKernel.cxx b/Filters/Points/vtkEllipsoidalGaussianKernel.cxx index be40984be69..f270983cd2c 100644 --- a/Filters/Points/vtkEllipsoidalGaussianKernel.cxx +++ b/Filters/Points/vtkEllipsoidalGaussianKernel.cxx @@ -20,23 +20,27 @@ #include "vtkDataSet.h" #include "vtkPointData.h" #include "vtkMath.h" +#include "vtkMathUtilities.h" vtkStandardNewMacro(vtkEllipsoidalGaussianKernel); //---------------------------------------------------------------------------- vtkEllipsoidalGaussianKernel::vtkEllipsoidalGaussianKernel() { - this->Radius = 1.0; - this->Sharpness = 2.0; - this->Eccentricity = 2.0; - - this->Normals = NULL; - this->Scalars = NULL; this->UseNormals = true; this->UseScalars = false; + this->NormalsArrayName = "Normals"; + this->ScalarsArrayName = "Scalars"; + + this->ScaleFactor = 1.0; + this->Sharpness = 2.0; + this->Eccentricity = 2.0; + this->F2 = this->Sharpness / this->Radius; this->E2 = this->Eccentricity * this->Eccentricity; + this->NormalsArray = NULL; + this->ScalarsArray = NULL; } @@ -53,16 +57,16 @@ FreeStructures() { this->Superclass::FreeStructures(); - if ( this->Normals ) + if ( this->NormalsArray ) { - this->Normals->Delete(); - this->Normals = NULL; + this->NormalsArray->Delete(); + this->NormalsArray = NULL; } - if ( this->Scalars ) + if ( this->ScalarsArray ) { - this->Scalars->Delete(); - this->Scalars = NULL; + this->ScalarsArray->Delete(); + this->ScalarsArray = NULL; } } @@ -72,27 +76,44 @@ Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, vtkPointData *pd) { this->Superclass::Initialize(loc, ds, pd); - this->Scalars = pd->GetScalars(); - if ( this->UseScalars && this->Scalars && - this->Scalars->GetNumberOfComponents() == 1 ) + // Grab the scalars if requested + if ( this->UseScalars) { - this->Scalars->Register(this); + this->ScalarsArray = pd->GetScalars(); + if ( !this->ScalarsArray ) + { + this->ScalarsArray = pd->GetArray(this->ScalarsArrayName); + } + if ( this->ScalarsArray && + this->ScalarsArray->GetNumberOfComponents() == 1 ) + { + this->ScalarsArray->Register(this); + } } else { - this->Scalars = NULL; + this->ScalarsArray = NULL; } - this->Normals = pd->GetNormals(); - if ( this->UseNormals && this->Normals ) - { - this->Normals->Register(this); - } - else + // Grab the normals if requested + if ( this->UseNormals) { - this->Normals = NULL; + this->NormalsArray = pd->GetNormals(); + if ( !this->NormalsArray ) + { + this->NormalsArray = pd->GetArray(this->NormalsArrayName); + } + if ( this->NormalsArray ) + { + this->NormalsArray->Register(this); + } + else + { + this->NormalsArray = NULL; + } } + // Set up computation this->F2 = this->Sharpness / this->Radius; this->F2 = this->F2 * this->F2; this->E2 = this->Eccentricity * this->Eccentricity; @@ -100,24 +121,18 @@ Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, vtkPointData *pd) //---------------------------------------------------------------------------- vtkIdType vtkEllipsoidalGaussianKernel:: -ComputeBasis(double x[3], vtkIdList *pIds) -{ - this->Locator->FindPointsWithinRadius(this->Radius, x, pIds); - return pIds->GetNumberOfIds(); -} - -//---------------------------------------------------------------------------- -vtkIdType vtkEllipsoidalGaussianKernel:: -ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights) +ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *prob, + vtkDoubleArray *weights) { vtkIdType numPts = pIds->GetNumberOfIds(); int i; vtkIdType id; double sum = 0.0; weights->SetNumberOfTuples(numPts); + double *p = (prob ? prob->GetPointer(0) : NULL); double *w = weights->GetPointer(0); double y[3], v[3], r2, z2, rxy2, mag; - double n[3], s; + double n[3], s, scale; double f2=this->F2, e2=this->E2; for (i=0; i::epsilon()*256.0 )) //precise hit on existing point { pIds->SetNumberOfIds(1); pIds->SetId(0,id); @@ -141,40 +156,47 @@ ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights) else // continue computing weights { // Normal affect - if ( this->Normals ) + if ( this->NormalsArray ) { - this->Normals->GetTuple(id,n); + this->NormalsArray->GetTuple(id,n); mag = vtkMath::Dot(n,n); mag = ( mag == 0.0 ? 1.0 : sqrt(mag) ); + z2 = vtkMath::Dot(v,n) / mag; + z2 = z2*z2; } else { + z2 = 0.0; mag = 1.0; } // Scalar scaling - if ( this->Scalars ) + if ( this->ScalarsArray ) { - this->Scalars->GetTuple(id,&s); + this->ScalarsArray->GetTuple(id,&s); } else { s = 1.0; } - z2 = vtkMath::Dot(v,n) / mag; - z2 = z2*z2; rxy2 = r2 - z2; - w[i] = s * exp(-f2 * (rxy2/e2 + z2)); + scale = this->ScaleFactor * (p ? p[i] : 1.0); + + w[i] = scale * s * exp(-f2 * (rxy2/e2 + z2)); + sum += w[i]; }//computing weights }//over all points // Normalize - for (i=0; iNormalizeWeights && sum != 0.0 ) { - w[i] /= sum; + for (i=0; iSuperclass::PrintSelf(os,indent); - os << indent << "Radius: " << this->Radius << endl; - os << indent << "Sharpness: " << this->Sharpness << endl; - os << indent << "Eccentricity: " << this->Eccentricity << endl; os << indent << "Use Normals: " - << (this->UseNormals? "On" : " Off") << "\n"; + << (this->GetUseNormals()? "On" : " Off") << "\n"; os << indent << "Use Scalars: " - << (this->UseScalars? "On" : " Off") << "\n"; + << (this->GetUseScalars()? "On" : " Off") << "\n"; + + os << indent << "Scalars Array Name: " << this->GetScalarsArrayName() << "\n"; + os << indent << "Normals Array Name: " << this->GetNormalsArrayName() << "\n"; + + os << indent << "Radius: " << this->GetRadius() << endl; + os << indent << "ScaleFactor: " << this->GetScaleFactor() << endl; + os << indent << "Sharpness: " << this->GetSharpness() << endl; + os << indent << "Eccentricity: " << this->GetEccentricity() << endl; + } diff --git a/Filters/Points/vtkEllipsoidalGaussianKernel.h b/Filters/Points/vtkEllipsoidalGaussianKernel.h index 7ee41dc8d24..9cb263b9e4d 100644 --- a/Filters/Points/vtkEllipsoidalGaussianKernel.h +++ b/Filters/Points/vtkEllipsoidalGaussianKernel.h @@ -38,28 +38,29 @@ // point takes on the values associated with p. // .SECTION See Also -// vtkPointInterpolator vtkInterpolationKernel vtkGaussianKernel -// vtkVoronoiKernel vtkSPHKernel vtkShepardKernel +// vtkPointInterpolator vtkInterpolationKernel vtkGeneralizedKernel +// vtkGaussianKernel vtkVoronoiKernel vtkSPHKernel vtkShepardKernel #ifndef vtkEllipsoidalGaussianKernel_h #define vtkEllipsoidalGaussianKernel_h #include "vtkFiltersPointsModule.h" // For export macro -#include "vtkInterpolationKernel.h" +#include "vtkGeneralizedKernel.h" +#include "vtkStdString.h" // For vtkStdString ivars class vtkIdList; class vtkDataArray; class vtkDoubleArray; -class VTKFILTERSPOINTS_EXPORT vtkEllipsoidalGaussianKernel : public vtkInterpolationKernel +class VTKFILTERSPOINTS_EXPORT vtkEllipsoidalGaussianKernel : public vtkGeneralizedKernel { public: // Description: // Standard methods for instantiation, obtaining type information, and printing. static vtkEllipsoidalGaussianKernel *New(); - vtkTypeMacro(vtkEllipsoidalGaussianKernel,vtkInterpolationKernel); + vtkTypeMacro(vtkEllipsoidalGaussianKernel,vtkGeneralizedKernel); void PrintSelf(ostream& os, vtkIndent indent); // Description: @@ -68,24 +69,24 @@ class VTKFILTERSPOINTS_EXPORT vtkEllipsoidalGaussianKernel : public vtkInterpola virtual void Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, vtkPointData *pd); - // Description: - // Given a point x, determine the points around x which form an - // interpolation basis. The user must provide the vtkIdList pids, which will - // be dynamically resized as necessary. The method returns the number of - // points in the basis. Typically this method is called before - // ComputeWeights(). - virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds); + // Re-use any superclass signatures that we don't override. + using vtkGeneralizedKernel::ComputeWeights; // Description: - // Given a point x, and a list of basis points pIds, compute interpolation - // weights associated with these basis points. Note that both the nearby - // basis points list pIds and the weights array are of length numPts, are - // provided by the caller of the method, and may be dynamically resized as - // necessary. Typically this method is called after ComputeBasis(), - // although advanced users can invoke ComputeWeights() and provide the - // interpolation basis points pIds directly. + // Given a point x, a list of basis points pIds, and a probability + // weighting function prob, compute interpolation weights associated with + // these basis points. Note that basis points list pIds, the probability + // weighting prob, and the weights array are provided by the caller of the + // method, and may be dynamically resized as necessary. The method returns + // the number of weights (pIds may be resized in some cases). Typically + // this method is called after ComputeBasis(), although advanced users can + // invoke ComputeWeights() and provide the interpolation basis points pIds + // directly. The probably weighting prob are numbers 0<=prob<=1 which are + // multiplied against the interpolation weights before normalization. They + // are estimates of local confidence of weights. The prob may be NULL in + // which all probabilities are considered =1. virtual vtkIdType ComputeWeights(double x[3], vtkIdList *pIds, - vtkDoubleArray *weights); + vtkDoubleArray *prob, vtkDoubleArray *weights); // Description: // Specify whether vector values should be used to affect the shape @@ -94,6 +95,14 @@ class VTKFILTERSPOINTS_EXPORT vtkEllipsoidalGaussianKernel : public vtkInterpola vtkGetMacro(UseNormals,bool); vtkBooleanMacro(UseNormals,bool); + // Description: + // Specify the normals array name. Used to orient the ellipsoid. Note that + // by default the input normals are used (i.e. the input to + // vtkPointInterpolator). If no input normals are available, then the named + // NormalsArrayName is used. + vtkSetMacro(NormalsArrayName,vtkStdString); + vtkGetMacro(NormalsArrayName,vtkStdString); + // Description: // Specify whether scalar values should be used to scale the weights. // By default this is off. @@ -102,11 +111,19 @@ class VTKFILTERSPOINTS_EXPORT vtkEllipsoidalGaussianKernel : public vtkInterpola vtkBooleanMacro(UseScalars,bool); // Description: - // Specify the radius of the kernel. Points within this radius will be - // used for interpolation. If no point is found, then the closest point - // will be used. - vtkSetClampMacro(Radius,double,0.000001,VTK_FLOAT_MAX); - vtkGetMacro(Radius,double); + // Specify the scalars array name. Used to scale the ellipsoid. Note that + // by default the input scalars are used (i.e. the input to + // vtkPointInterpolator). If no input scalars are available, then the named + // ScalarsArrayName is used. + vtkSetMacro(ScalarsArrayName,vtkStdString); + vtkGetMacro(ScalarsArrayName,vtkStdString); + + // Description: + // Multiply the Gaussian splat distribution by this value. If UseScalars is + // on and a scalar aray is provided, then the scalar value will be + // multiplied by the ScaleFactor times the Gaussian function. + vtkSetClampMacro(ScaleFactor,double,0.0,VTK_DOUBLE_MAX); + vtkGetMacro(ScaleFactor,double); // Description: // Set / Get the sharpness (i.e., falloff) of the Gaussian. By default @@ -127,18 +144,20 @@ class VTKFILTERSPOINTS_EXPORT vtkEllipsoidalGaussianKernel : public vtkInterpola vtkEllipsoidalGaussianKernel(); ~vtkEllipsoidalGaussianKernel(); - double Radius; - double Sharpness; - double Eccentricity; - bool UseNormals; bool UseScalars; - vtkDataArray *Normals; - vtkDataArray *Scalars; + vtkStdString NormalsArrayName; + vtkStdString ScalarsArrayName; + + double ScaleFactor; + double Sharpness; + double Eccentricity; // Internal structure to reduce computation double F2, E2; + vtkDataArray *NormalsArray; + vtkDataArray *ScalarsArray; virtual void FreeStructures(); diff --git a/Filters/Points/vtkGaussianKernel.cxx b/Filters/Points/vtkGaussianKernel.cxx index 1444989936d..b5a870c664d 100644 --- a/Filters/Points/vtkGaussianKernel.cxx +++ b/Filters/Points/vtkGaussianKernel.cxx @@ -20,15 +20,14 @@ #include "vtkDataSet.h" #include "vtkPointData.h" #include "vtkMath.h" +#include "vtkMathUtilities.h" vtkStandardNewMacro(vtkGaussianKernel); //---------------------------------------------------------------------------- vtkGaussianKernel::vtkGaussianKernel() { - this->Radius = 1.0; this->Sharpness = 2.0; - this->F2 = this->Sharpness / this->Radius; } @@ -50,21 +49,15 @@ Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, vtkPointData *pd) //---------------------------------------------------------------------------- vtkIdType vtkGaussianKernel:: -ComputeBasis(double x[3], vtkIdList *pIds) -{ - this->Locator->FindPointsWithinRadius(this->Radius, x, pIds); - return pIds->GetNumberOfIds(); -} - -//---------------------------------------------------------------------------- -vtkIdType vtkGaussianKernel:: -ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights) +ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *prob, + vtkDoubleArray *weights) { vtkIdType numPts = pIds->GetNumberOfIds(); int i; vtkIdType id; double d2, y[3], sum = 0.0; weights->SetNumberOfTuples(numPts); + double *p = (prob ? prob->GetPointer(0) : NULL); double *w = weights->GetPointer(0); double f2=this->F2; @@ -74,7 +67,7 @@ ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights) this->DataSet->GetPoint(id,y); d2 = vtkMath::Distance2BetweenPoints(x,y); - if ( d2 == 0.0 ) //precise hit on existing point + if ( vtkMathUtilities::FuzzyCompare(d2, 0.0, std::numeric_limits::epsilon()*256.0 )) //precise hit on existing point { pIds->SetNumberOfIds(1); pIds->SetId(0,id); @@ -84,15 +77,18 @@ ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights) } else { - w[i] = exp(-f2 * d2); + w[i] = (p ? p[i]*exp(-f2 * d2) : exp(-f2 * d2)); sum += w[i]; } }//over all points // Normalize - for (i=0; iNormalizeWeights && sum != 0.0 ) { - w[i] /= sum; + for (i=0; iSuperclass::PrintSelf(os,indent); - os << indent << "Radius: " << this->Radius << endl; - os << indent << "Sharpness: " << this->Sharpness << endl; + os << indent << "Sharpness: " << this->GetSharpness() << endl; } diff --git a/Filters/Points/vtkGaussianKernel.h b/Filters/Points/vtkGaussianKernel.h index f45768cd578..51355205de9 100644 --- a/Filters/Points/vtkGaussianKernel.h +++ b/Filters/Points/vtkGaussianKernel.h @@ -36,19 +36,19 @@ #define vtkGaussianKernel_h #include "vtkFiltersPointsModule.h" // For export macro -#include "vtkInterpolationKernel.h" +#include "vtkGeneralizedKernel.h" class vtkIdList; class vtkDoubleArray; -class VTKFILTERSPOINTS_EXPORT vtkGaussianKernel : public vtkInterpolationKernel +class VTKFILTERSPOINTS_EXPORT vtkGaussianKernel : public vtkGeneralizedKernel { public: // Description: // Standard methods for instantiation, obtaining type information, and printing. static vtkGaussianKernel *New(); - vtkTypeMacro(vtkGaussianKernel,vtkInterpolationKernel); + vtkTypeMacro(vtkGaussianKernel,vtkGeneralizedKernel); void PrintSelf(ostream& os, vtkIndent indent); // Description: @@ -57,30 +57,24 @@ class VTKFILTERSPOINTS_EXPORT vtkGaussianKernel : public vtkInterpolationKernel virtual void Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, vtkPointData *pd); - // Description: - // Given a point x, determine the points around x which form an - // interpolation basis. The user must provide the vtkIdList pids, which will - // be dynamically resized as necessary. The method returns the number of - // points in the basis. Typically this method is called before - // ComputeWeights(). - virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds); + // Re-use any superclass signatures that we don't override. + using vtkGeneralizedKernel::ComputeWeights; // Description: - // Given a point x, and a list of basis points pIds, compute interpolation - // weights associated with these basis points. Note that both the nearby - // basis points list pIds and the weights array are provided by the caller - // of the method, and may be dynamically resized as necessary. Typically + // Given a point x, a list of basis points pIds, and a probability + // weighting function prob, compute interpolation weights associated with + // these basis points. Note that basis points list pIds, the probability + // weighting prob, and the weights array are provided by the caller of the + // method, and may be dynamically resized as necessary. The method returns + // the number of weights (pIds may be resized in some cases). Typically // this method is called after ComputeBasis(), although advanced users can // invoke ComputeWeights() and provide the interpolation basis points pIds - // directly. + // directly. The probably weighting prob are numbers 0<=prob<=1 which are + // multiplied against the interpolation weights before normalization. They + // are estimates of local confidence of weights. The prob may be NULL in + // which all probabilities are considered =1. virtual vtkIdType ComputeWeights(double x[3], vtkIdList *pIds, - vtkDoubleArray *weights); - - // Description: - // Specify the radius of the kernel. Points within this radius will be - // used for interpolation (if ComputeBasis() is invoked). - vtkSetClampMacro(Radius,double,0.000001,VTK_FLOAT_MAX); - vtkGetMacro(Radius,double); + vtkDoubleArray *prob, vtkDoubleArray *weights); // Description: // Set / Get the sharpness (i.e., falloff) of the Gaussian. By default @@ -93,7 +87,6 @@ class VTKFILTERSPOINTS_EXPORT vtkGaussianKernel : public vtkInterpolationKernel vtkGaussianKernel(); ~vtkGaussianKernel(); - double Radius; double Sharpness; // Internal structure to reduce computation diff --git a/Filters/Points/vtkGeneralizedKernel.cxx b/Filters/Points/vtkGeneralizedKernel.cxx new file mode 100644 index 00000000000..8dddc40d2c0 --- /dev/null +++ b/Filters/Points/vtkGeneralizedKernel.cxx @@ -0,0 +1,66 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkGeneralizedKernel.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkGeneralizedKernel.h" +#include "vtkAbstractPointLocator.h" +#include "vtkObjectFactory.h" +#include "vtkIdList.h" +#include "vtkDoubleArray.h" +#include "vtkDataSet.h" +#include "vtkPointData.h" +#include "vtkMath.h" + +//---------------------------------------------------------------------------- +vtkGeneralizedKernel::vtkGeneralizedKernel() +{ + this->KernelFootprint = vtkGeneralizedKernel::RADIUS; + this->Radius = 1.0; + this->NumberOfPoints = 8; + this->NormalizeWeights = true; +} + + +//---------------------------------------------------------------------------- +vtkGeneralizedKernel::~vtkGeneralizedKernel() +{ +} + +//---------------------------------------------------------------------------- +vtkIdType vtkGeneralizedKernel:: +ComputeBasis(double x[3], vtkIdList *pIds, vtkIdType) +{ + if ( this->KernelFootprint == vtkGeneralizedKernel::RADIUS ) + { + this->Locator->FindPointsWithinRadius(this->Radius, x, pIds); + } + else + { + this->Locator->FindClosestNPoints(this->NumberOfPoints, x, pIds); + } + + return pIds->GetNumberOfIds(); +} + +//---------------------------------------------------------------------------- +void vtkGeneralizedKernel::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); + + os << indent << "Kernel Footprint: " << this->GetKernelFootprint() << "\n"; + os << indent << "Radius: " << this->GetRadius() << "\n"; + os << indent << "Number of Points: " << this->GetNumberOfPoints() << "\n"; + os << indent << "Normalize Weights: " + << (this->GetNormalizeWeights() ? "On\n" : "Off\n"); + +} diff --git a/Filters/Points/vtkGeneralizedKernel.h b/Filters/Points/vtkGeneralizedKernel.h new file mode 100644 index 00000000000..cdcb1adee71 --- /dev/null +++ b/Filters/Points/vtkGeneralizedKernel.h @@ -0,0 +1,175 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkGeneralizedKernel.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkGeneralizedKernel - flexible, general interpolation kernels + +// .SECTION Description +// vtkGeneralizedKernel is an abstract class that defines an API for concrete +// general-purpose, kernel subclasses. vtkGeneralizedKernels has important +// properties that make them useful in a variety of interpolation +// applications: +//
+// 1. The weights are normalized.
+// 2. The footprint of the basis is configurable.
+// 3. Probablistic weighting functions can be used to favor certain weights.
+// 
+// The following paragraphs describe each of these properties in more detail. +// +// Normalized weightings simple mean Sum(w_i) = 1. This ensures that the +// interpolation process is well behaved. +// +// The interpolation footprint is the set of points that are used to perform +// the interpolation process. For example, it is possible to choose between a +// radius-based kernel selection, and one based on the N nearest +// neighbors. Note that the performance and mathematical properties of +// kernels may vary greatly depending on which kernel style is selected. For +// example, if a radius-based kernel footprint is used, and the radius is too +// big, the algorithm can perform in n^3 fashion. +// +// Finally, in advanced usage, probability functions can be applied to the +// interpolation weights (prior to normalization). These probability +// functions are confidence estimates that the data at a particular point is +// accurate. A typical application is when laser scans are used to acquire +// point measurements, which return normals that indicate glancing returns +// versus direct, near orthogonal hits. Another use is when point clouds are +// combined, where some clouds are acquired with more accurate, detailed +// devices versus a broad, potentially coarser acquisition process. + +// .SECTION Caveats +// Some kernels, like the Voronoi kernel, cannot be subclasses of this class +// because their definition inherently defines the basis style. For example, +// the Voronoi kernel is simply the single closest point. SPH kernals are +// similar, because they implicitly depend on a particle distribution +// consistent with simulation constraints such as conservation of mass, etc. + +// .SECTION See Also +// vtkPointInterpolator vtkPointInterpolator2D vtkGaussianKernel vtkSPHKernel +// vtkShepardKernel vtkLinearKernel vtkVoronoiKernel + + +#ifndef vtkGeneralizedKernel_h +#define vtkGeneralizedKernel_h + +#include "vtkFiltersPointsModule.h" // For export macro +#include "vtkInterpolationKernel.h" + + +class VTKFILTERSPOINTS_EXPORT vtkGeneralizedKernel : public vtkInterpolationKernel +{ +public: + // Description: + // Standard methods for type and printing. + vtkTypeMacro(vtkGeneralizedKernel, vtkInterpolationKernel) + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Based on the kernel style, invoke the appropriate locator method to + // obtain the points making up the basis. Given a point x (and optional + // associated point id), determine the points around x which form an + // interpolation basis. The user must provide the vtkIdList pIds, which + // will be dynamically resized as necessary. The method returns the number + // of points in the basis. Typically this method is called before + // ComputeWeights(). Note that ptId is optional in most cases, although in + // some kernels it is used to facilitate basis computation. + virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds, vtkIdType ptId=0); + + // Description: + // Given a point x, a list of basis points pIds, and a probability + // weighting function prob, compute interpolation weights associated with + // these basis points. Note that basis points list pIds, the probability + // weighting prob, and the weights array are provided by the caller of the + // method, and may be dynamically resized as necessary. The method returns + // the number of weights (pIds may be resized in some cases). Typically + // this method is called after ComputeBasis(), although advanced users can + // invoke ComputeWeights() and provide the interpolation basis points pIds + // directly. The probably weighting prob are numbers 0<=prob<=1 which are + // multiplied against the interpolation weights before normalization. They + // are estimates of local confidence of weights. The prob may be NULL in + // which all probabilities are considered =1. + virtual vtkIdType ComputeWeights(double x[3], vtkIdList *pIds, + vtkDoubleArray *prob, vtkDoubleArray *weights) = 0; + + // Description: + // Given a point x, and a list of basis points pIds, compute interpolation + // weights associated with these basis points. Note that both the nearby + // basis points list pIds and the weights array are provided by the caller + // of the method, and may be dynamically resized as necessary. Typically + // this method is called after ComputeBasis(), although advanced users can + // invoke ComputeWeights() and provide the interpolation basis points pIds + // directly. + virtual vtkIdType ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights) + { + return this->ComputeWeights(x,pIds,NULL,weights); + } + + // Description: + // Enum used to select the interpolation basis form. By default, a Radius + // form is used (i.e., the basis is defined from all points within a + // specified radius). However, it is also possible to select the N closest + // points (NClosest). + enum KernelStyle + { + RADIUS=0, + N_CLOSEST=1 + }; + + // Description: + // Specify the interpolation basis style. By default, a Radius style is + // used (i.e., the basis is defined from all points within a specified + // radius). However, it is also possible to select the N closest points + // (NClosest). Note that in most formulations the Radius style is assumed + // as it provides better mathematical properties. However, for convenience + // some bases are easier to use when the N closest points are taken. + vtkSetMacro(KernelFootprint,int); + vtkGetMacro(KernelFootprint,int); + void SetKernelFootprintToRadius() + { this->SetKernelFootprint(RADIUS); } + void SetKernelFootprintToNClosest() + { this->SetKernelFootprint(N_CLOSEST); } + + // Description: + // If the interpolation basis style is Radius, then this method specifies + // the radius within which the basis points must lie. + vtkSetClampMacro(Radius,double,0.0,VTK_FLOAT_MAX); + vtkGetMacro(Radius,double); + + // Description: + // If the interpolation basis style is NClosest, then this method specifies + // the number of the closest points used to form the interpolation basis. + vtkSetClampMacro(NumberOfPoints,int,1,VTK_INT_MAX); + vtkGetMacro(NumberOfPoints,int); + + // Description: + // Indicate whether the interpolation weights should be normalized after they + // are computed. Generally this is left on as it results in more reasonable + // behavior. + vtkSetMacro(NormalizeWeights,bool); + vtkGetMacro(NormalizeWeights,bool); + vtkBooleanMacro(NormalizeWeights,bool); + +protected: + vtkGeneralizedKernel(); + ~vtkGeneralizedKernel(); + + int KernelFootprint; + double Radius; + int NumberOfPoints; + bool NormalizeWeights; + +private: + vtkGeneralizedKernel(const vtkGeneralizedKernel&); // Not implemented. + void operator=(const vtkGeneralizedKernel&); // Not implemented. +}; + +#endif diff --git a/Filters/Points/vtkInterpolationKernel.cxx b/Filters/Points/vtkInterpolationKernel.cxx index 2bbfdf0392d..b1f2c20e742 100644 --- a/Filters/Points/vtkInterpolationKernel.cxx +++ b/Filters/Points/vtkInterpolationKernel.cxx @@ -87,7 +87,7 @@ void vtkInterpolationKernel::PrintSelf(ostream& os, vtkIndent indent) this->Superclass::PrintSelf(os,indent); os << indent << "Requires Initialization: " - << (this->RequiresInitialization ? "On\n" : "Off\n"); + << (this->GetRequiresInitialization() ? "On\n" : "Off\n"); if ( this->Locator ) { diff --git a/Filters/Points/vtkInterpolationKernel.h b/Filters/Points/vtkInterpolationKernel.h index f6afca3535f..e79dbeeca95 100644 --- a/Filters/Points/vtkInterpolationKernel.h +++ b/Filters/Points/vtkInterpolationKernel.h @@ -17,29 +17,33 @@ // .SECTION Description // vtkInterpolationKernel specifies an abstract interface for interpolation // kernels. An interpolation kernel is used to produce an interpolated data -// value from the data in a local neighborhood surounding a point X. For -// example, given the N nearest points surrounding X, the interpolation -// kernel provides N weights, which when combined with the N data values -// associated with the nearest points, produces a data value at point X. +// value at a point X from the points + data in a local neighborhood +// surounding X. For example, given the N nearest points surrounding X, the +// interpolation kernel provides N weights, which when combined with the N +// data values associated with these nearest points, produces an interpolated +// data value at point X. // // Note that various kernel initialization methods are provided. The basic // method requires providing a point locator to accelerate neigborhood // queries. Some kernels may refer back to the original dataset, or the point -// attribute data associated with the dataset. +// attribute data associated with the dataset. The initialization method +// enables different styles of initialization and is kernel-dependent. // // Typically the kernels are invoked in two parts: first, the basis is -// computed using the supplied point locator and dataset. These are the +// computed using the supplied point locator and dataset. This basis is a +// local footprint of point surrounding a poitnX. In this footprint are the // neighboring points used to compute the interpolation weights. Then, the // weights are computed from points forming the basis. However, advanced // users can develop their own basis, skipping the ComputeBasis() method, and // then invoke ComputeWeights() directly. // .SECTION Caveats -// The ComputeWeights() method is thread safe. +// The ComputeBasis() and ComputeWeights() methods must be thread safe as they +// are used in threaded algorithms. // .SECTION See Also -// vtkPointInterpolator vtkGaussianKernel vtkSPHKernel vtkShepardKernel -// vtkVoronoiKernel +// vtkPointInterpolator vtkPointInterpolator2D vtkGeneralizedKernel +// vtkGaussianKernel vtkSPHKernel vtkShepardKernel vtkVoronoiKernel #ifndef vtkInterpolationKernel_h @@ -59,8 +63,8 @@ class VTKFILTERSPOINTS_EXPORT vtkInterpolationKernel : public vtkObject { public: // Description: - // Standard methods for type and printing. - vtkTypeMacro(vtkInterpolationKernel,vtkObject); + // Standard method for type and printing. + vtkAbstractTypeMacro(vtkInterpolationKernel, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: @@ -84,12 +88,14 @@ class VTKFILTERSPOINTS_EXPORT vtkInterpolationKernel : public vtkObject vtkBooleanMacro(RequiresInitialization, bool); // Description: - // Given a point x, determine the points around x which form an - // interpolation basis. The user must provide the vtkIdList pids, which will - // be dynamically resized as necessary. The method returns the number of - // points in the basis. Typically this method is called before - // ComputeBasis(). - virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds) = 0; + // Given a point x (and optional associated point id), determine the points + // around x which form an interpolation basis. The user must provide the + // vtkIdList pIds, which will be dynamically resized as necessary. The + // method returns the number of points in the basis. Typically this method + // is called before ComputeWeights(). Note that ptId is optional in most + // cases, although in some kernels it is used to facilitate basis + // computation. + virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds, vtkIdType ptId=0) = 0; // Description: // Given a point x, and a list of basis points pIds, compute interpolation diff --git a/Filters/Points/vtkLinearKernel.cxx b/Filters/Points/vtkLinearKernel.cxx index bf3831d5674..e7979f228e1 100644 --- a/Filters/Points/vtkLinearKernel.cxx +++ b/Filters/Points/vtkLinearKernel.cxx @@ -23,7 +23,6 @@ vtkStandardNewMacro(vtkLinearKernel); //---------------------------------------------------------------------------- vtkLinearKernel::vtkLinearKernel() { - this->Radius = 1.0; } @@ -35,23 +34,39 @@ vtkLinearKernel::~vtkLinearKernel() //---------------------------------------------------------------------------- vtkIdType vtkLinearKernel:: -ComputeBasis(double x[3], vtkIdList *pIds) -{ - this->Locator->FindPointsWithinRadius(this->Radius, x, pIds); - return pIds->GetNumberOfIds(); -} - -//---------------------------------------------------------------------------- -vtkIdType vtkLinearKernel:: -ComputeWeights(double*, vtkIdList *pIds, vtkDoubleArray *weights) +ComputeWeights(double*, vtkIdList *pIds, vtkDoubleArray *prob, + vtkDoubleArray *weights) { vtkIdType numPts = pIds->GetNumberOfIds(); - double w = 1.0 / static_cast(numPts); - + double *p = (prob ? prob->GetPointer(0) : NULL); weights->SetNumberOfTuples(numPts); - for (vtkIdType i=0; i < numPts; ++i) + double *w = weights->GetPointer(0); + double weight = 1.0 / static_cast(numPts); + + if ( ! prob ) //standard linear interpolation { - weights->SetValue(i,w); + for (vtkIdType i=0; i < numPts; ++i) + { + w[i] = weight; + } + } + + else //weight by probability + { + double sum=0.0; + for (vtkIdType i=0; i < numPts; ++i) + { + w[i] = weight * p[i]; + sum += w[i]; + } + // Now normalize + if ( this->NormalizeWeights && sum != 0.0 ) + { + for (vtkIdType i=0; i < numPts; ++i) + { + w[i] /= sum; + } + } } return numPts; @@ -61,5 +76,4 @@ ComputeWeights(double*, vtkIdList *pIds, vtkDoubleArray *weights) void vtkLinearKernel::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); - } diff --git a/Filters/Points/vtkLinearKernel.h b/Filters/Points/vtkLinearKernel.h index eaaf9780cd1..fa4a5174b97 100644 --- a/Filters/Points/vtkLinearKernel.h +++ b/Filters/Points/vtkLinearKernel.h @@ -19,59 +19,52 @@ // of all points in the basis. // .SECTION See Also -// vtkInterpolationKernel vtkGaussianKernel vtkLinearKernel vtkShepardKernel +// vtkPointInterpolator vtkInterpolationKernel vtkGeneralizedKernel +// vtkGaussianKernel vtkLinearKernel vtkShepardKernel #ifndef vtkLinearKernel_h #define vtkLinearKernel_h #include "vtkFiltersPointsModule.h" // For export macro -#include "vtkInterpolationKernel.h" +#include "vtkGeneralizedKernel.h" class vtkIdList; class vtkDoubleArray; -class VTKFILTERSPOINTS_EXPORT vtkLinearKernel : public vtkInterpolationKernel +class VTKFILTERSPOINTS_EXPORT vtkLinearKernel : public vtkGeneralizedKernel { public: // Description: // Standard methods for instantiation, obtaining type information, and printing. static vtkLinearKernel *New(); - vtkTypeMacro(vtkLinearKernel,vtkInterpolationKernel); + vtkTypeMacro(vtkLinearKernel,vtkGeneralizedKernel); void PrintSelf(ostream& os, vtkIndent indent); - // Description: - // Given a point x, determine the points around x which form an - // interpolation basis. The user must provide the vtkIdList pids, which will - // be dynamically resized as necessary. The method returns the number of - // points in the basis. Typically this method is called before - // ComputeWeights(). - virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds); + // Re-use any superclass signatures that we don't override. + using vtkGeneralizedKernel::ComputeWeights; // Description: - // Given a point x, and a list of basis points pIds, compute interpolation - // weights associated with these basis points. Note that both the nearby - // basis points list pIds and the weights array are provided by the caller - // of the method, and may be dynamically resized as necessary. Typically + // Given a point x, a list of basis points pIds, and a probability + // weighting function prob, compute interpolation weights associated with + // these basis points. Note that basis points list pIds, the probability + // weighting prob, and the weights array are provided by the caller of the + // method, and may be dynamically resized as necessary. The method returns + // the number of weights (pIds may be resized in some cases). Typically // this method is called after ComputeBasis(), although advanced users can // invoke ComputeWeights() and provide the interpolation basis points pIds - // directly. + // directly. The probably weighting prob are numbers 0<=prob<=1 which are + // multiplied against the interpolation weights before normalization. They + // are estimates of local confidence of weights. The prob may be NULL in + // which all probabilities are considered =1. virtual vtkIdType ComputeWeights(double x[3], vtkIdList *pIds, - vtkDoubleArray *weights); - - // Description: - // Specify the radius of the kernel. Points within this radius will be used - // for interpolation (if ComputeBasis() is used). - vtkSetClampMacro(Radius,double,0.000001,VTK_FLOAT_MAX); - vtkGetMacro(Radius,double); + vtkDoubleArray *prob, vtkDoubleArray *weights); protected: vtkLinearKernel(); ~vtkLinearKernel(); - double Radius; - private: vtkLinearKernel(const vtkLinearKernel&); // Not implemented. void operator=(const vtkLinearKernel&); // Not implemented. diff --git a/Filters/Points/vtkPointInterpolator.cxx b/Filters/Points/vtkPointInterpolator.cxx index 5acd909a817..52b3da274f6 100644 --- a/Filters/Points/vtkPointInterpolator.cxx +++ b/Filters/Points/vtkPointInterpolator.cxx @@ -15,14 +15,16 @@ #include "vtkPointInterpolator.h" #include "vtkObjectFactory.h" -#include "vtkVoronoiKernel.h" +#include "vtkLinearKernel.h" #include "vtkAbstractPointLocator.h" +#include "vtkArrayListTemplate.h" #include "vtkStaticPointLocator.h" #include "vtkDataSet.h" #include "vtkDataArray.h" #include "vtkImageData.h" #include "vtkPoints.h" #include "vtkCharArray.h" +#include "vtkFloatArray.h" #include "vtkDoubleArray.h" #include "vtkCellData.h" #include "vtkPointData.h" @@ -43,12 +45,10 @@ vtkCxxSetObjectMacro(vtkPointInterpolator,Kernel,vtkInterpolationKernel); //---------------------------------------------------------------------------- // Helper classes to support efficient computing, and threaded execution. namespace { - -#include "vtkArrayListTemplate.h" - // The threaded core of the algorithm struct ProbePoints { + vtkPointInterpolator *PointInterpolator; vtkDataSet *Input; vtkInterpolationKernel *Kernel; vtkAbstractPointLocator *Locator; @@ -57,18 +57,36 @@ struct ProbePoints ArrayList Arrays; char *Valid; int Strategy; + bool Promote; // Don't want to allocate these working arrays on every thread invocation, // so make them thread local. vtkSMPThreadLocalObject PIds; vtkSMPThreadLocalObject Weights; - ProbePoints(vtkDataSet *input, vtkInterpolationKernel *kernel,vtkAbstractPointLocator *loc, - vtkPointData *inPD, vtkPointData *outPD, int strategy, char *valid, double nullV) : - Input(input), Kernel(kernel), Locator(loc), InPD(inPD), OutPD(outPD), - Valid(valid), Strategy(strategy) + ProbePoints(vtkPointInterpolator *ptInt, vtkDataSet *input, vtkPointData *inPD, + vtkPointData *outPD, char *valid) : + PointInterpolator(ptInt), Input(input), InPD(inPD), OutPD(outPD), Valid(valid) { - this->Arrays.AddArrays(input->GetNumberOfPoints(), inPD, outPD, nullV); + // Gather information from the interpolator + this->Kernel = ptInt->GetKernel(); + this->Locator = ptInt->GetLocator(); + this->Strategy = ptInt->GetNullPointsStrategy(); + double nullV = ptInt->GetNullValue(); + this->Promote = ptInt->GetPromoteOutputArrays(); + + // Manage arrays for interpolation + for (int i=0; i < ptInt->GetNumberOfExcludedArrays(); ++i) + { + const char *arrayName = ptInt->GetExcludedArray(i); + vtkDataArray *array = this->InPD->GetArray(arrayName); + if ( array != NULL ) + { + outPD->RemoveArray(array->GetName()); + this->Arrays.ExcludeArray(array); + } + } + this->Arrays.AddArrays(input->GetNumberOfPoints(), inPD, outPD, nullV, this->Promote); } // Just allocate a little bit of memory to get started. @@ -143,11 +161,10 @@ struct ImageProbePoints : public ProbePoints double Origin[3]; double Spacing[3]; - ImageProbePoints(vtkImageData *image, int dims[3], double origin[3], - double spacing[3], vtkInterpolationKernel *kernel, - vtkAbstractPointLocator *loc, vtkPointData *inPD, - vtkPointData *outPD, int strategy, char *valid, double nullV) : - ProbePoints(image, kernel, loc, inPD, outPD, strategy, valid, nullV) + ImageProbePoints(vtkPointInterpolator *ptInt, vtkImageData *image, int dims[3], + double origin[3], double spacing[3], vtkPointData *inPD, + vtkPointData *outPD, char *valid) : + ProbePoints(ptInt, image, inPD, outPD, valid) { for (int i=0; i < 3; ++i) { @@ -211,14 +228,15 @@ vtkPointInterpolator::vtkPointInterpolator() this->Locator = vtkStaticPointLocator::New(); - this->Kernel = vtkVoronoiKernel::New(); + this->Kernel = vtkLinearKernel::New(); - this->NullPointsStrategy = vtkPointInterpolator::CLOSEST_POINT; + this->NullPointsStrategy = vtkPointInterpolator::NULL_VALUE; this->NullValue = 0.0; this->ValidPointsMask = NULL; - this->ValidPointsMaskArrayName = 0; - this->SetValidPointsMaskArrayName("vtkValidPointMask"); + this->ValidPointsMaskArrayName = "vtkValidPointMask"; + + this->PromoteOutputArrays = true; this->PassPointArrays = true; this->PassCellArrays = true; @@ -315,15 +333,13 @@ Probe(vtkDataSet *input, vtkDataSet *source, vtkDataSet *output) int dims[3]; double origin[3], spacing[3]; this->ExtractImageDescription(imgInput,dims,origin,spacing); - ImageProbePoints imageProbe(imgInput, dims, origin, spacing, - this->Kernel,this->Locator,inPD,outPD, - this->NullPointsStrategy,mask,this->NullValue); + ImageProbePoints imageProbe(this, imgInput, dims, origin, spacing, + inPD, outPD, mask); vtkSMPTools::For(0, dims[2], imageProbe);//over slices } else { - ProbePoints probe(input,this->Kernel,this->Locator,inPD,outPD, - this->NullPointsStrategy,mask,this->NullValue); + ProbePoints probe(this, input, inPD, outPD, mask); vtkSMPTools::For(0, numPts, probe); } @@ -390,9 +406,10 @@ int vtkPointInterpolator::RequestData( vtkDataSet *output = vtkDataSet::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); - if (!source) + if (!source || source->GetNumberOfPoints() < 1 ) { - return 0; + vtkWarningMacro(<<"No source points to interpolate from"); + return 1; } // Copy the input geometry and topology to the output @@ -475,6 +492,24 @@ int vtkPointInterpolator::RequestUpdateExtent( return 1; } +//-------------------------------------------------------------------------- +unsigned long vtkPointInterpolator::GetMTime() +{ + unsigned long mTime=this->Superclass::GetMTime(); + unsigned long mTime2; + if ( this->Locator != NULL ) + { + mTime2 = this->Locator->GetMTime(); + mTime = ( mTime2 > mTime ? mTime2 : mTime ); + } + if ( this->Kernel != NULL ) + { + mTime2 = this->Kernel->GetMTime(); + mTime = ( mTime2 > mTime ? mTime2 : mTime ); + } + return mTime; +} + //---------------------------------------------------------------------------- void vtkPointInterpolator::PrintSelf(ostream& os, vtkIndent indent) { @@ -484,10 +519,22 @@ void vtkPointInterpolator::PrintSelf(ostream& os, vtkIndent indent) os << indent << "Source: " << source << "\n"; os << indent << "Locator: " << this->Locator << "\n"; os << indent << "Kernel: " << this->Kernel << "\n"; + os << indent << "Null Points Strategy: " << this->NullPointsStrategy << endl; os << indent << "Null Value: " << this->NullValue << "\n"; os << indent << "Valid Points Mask Array Name: " << (this->ValidPointsMaskArrayName ? this->ValidPointsMaskArrayName : "(none)") << "\n"; + + os << indent << "Number of Excluded Arrays:" << this->GetNumberOfExcludedArrays() << endl; + vtkIndent nextIndent=indent.GetNextIndent(); + for (int i=0; iGetNumberOfExcludedArrays(); ++i) + { + os << nextIndent << "Excluded Array: " << this->ExcludedArrays[i] << endl; + } + + os << indent << "Promote Output Arrays: " + << (this->PromoteOutputArrays ? "On" : " Off") << "\n"; + os << indent << "Pass Point Arrays: " << (this->PassPointArrays? "On" : " Off") << "\n"; os << indent << "Pass Cell Arrays: " diff --git a/Filters/Points/vtkPointInterpolator.h b/Filters/Points/vtkPointInterpolator.h index 7694be10e3d..e6a0516741c 100644 --- a/Filters/Points/vtkPointInterpolator.h +++ b/Filters/Points/vtkPointInterpolator.h @@ -54,15 +54,17 @@ // as in the NullPointsStrategy). // .SECTION See Also -// vtkProbeFilter vtkGaussianSplatter vtkCheckerboardSplatter -// vtkShepardMethod vtkVoronoiKernel vtkShepardKernel vtkGaussianKernel -// vtkSPHKernel +// vtkPointInterpolator2D vtkProbeFilter vtkGaussianSplatter +// vtkCheckerboardSplatter vtkShepardMethod vtkVoronoiKernel vtkShepardKernel +// vtkGaussianKernel vtkSPHKernel #ifndef vtkPointInterpolator_h #define vtkPointInterpolator_h #include "vtkFiltersPointsModule.h" // For export macro #include "vtkDataSetAlgorithm.h" +#include "vtkStdString.h" // For vtkStdString ivars +#include //For STL vector class vtkAbstractPointLocator; class vtkIdList; @@ -105,9 +107,9 @@ class VTKFILTERSPOINTS_EXPORT vtkPointInterpolator : public vtkDataSetAlgorithm vtkGetObjectMacro(Locator,vtkAbstractPointLocator); // Description: - // Specify an interpolation kernel. By default a vtkVoronoiKernel is used - // (i.e., closest point). The interpolation kernel changes the basis of the - // interpolation. + // Specify an interpolation kernel. By default a vtkLinearKernel is used + // (i.e., linear combination of closest points). The interpolation kernel + // changes the basis of the interpolation. void SetKernel(vtkInterpolationKernel *kernel); vtkGetObjectMacro(Kernel,vtkInterpolationKernel); @@ -124,10 +126,10 @@ class VTKFILTERSPOINTS_EXPORT vtkPointInterpolator : public vtkDataSetAlgorithm // nearby points to interpolate from) is empty. If the strategy is set to // MaskPoints, then an output array is created that marks points as being // valid (=1) or null (invalid =0) (and the NullValue is set as well). If - // the strategy is set to NullValue, then the output data value(s) are set - // to the NullPoint value (specified in the output point data). Finally, - // the default strategy ClosestPoint is to simply use the closest point to - // perform the interpolation. + // the strategy is set to NullValue (this is the default), then the output + // data value(s) are set to the NullPoint value (specified in the output + // point data). Finally, the strategy ClosestPoint is to simply use the + // closest point to perform the interpolation. vtkSetMacro(NullPointsStrategy,int); vtkGetMacro(NullPointsStrategy,int); void SetNullPointsStrategyToMaskPoints() @@ -142,8 +144,8 @@ class VTKFILTERSPOINTS_EXPORT vtkPointInterpolator : public vtkDataSetAlgorithm // each input point. This vtkCharArray is placed into the output of the filter, // with a non-zero value for a valid point, and zero otherwise. The name of // this masking array is specified here. - vtkSetStringMacro(ValidPointsMaskArrayName); - vtkGetStringMacro(ValidPointsMaskArrayName); + vtkSetMacro(ValidPointsMaskArrayName, vtkStdString); + vtkGetMacro(ValidPointsMaskArrayName, vtkStdString); // Description: // Specify the null point value. When a null point is encountered then all @@ -152,6 +154,48 @@ class VTKFILTERSPOINTS_EXPORT vtkPointInterpolator : public vtkDataSetAlgorithm vtkSetMacro(NullValue,double); vtkGetMacro(NullValue,double); + // Description: + // Adds an array to the list of arrays which are to be excluded from the + // interpolation process. + void AddExcludedArray(const vtkStdString &excludedArray) + { + this->ExcludedArrays.push_back(excludedArray); + this->Modified(); + } + + // Description: + // Clears the contents of excluded array list. + void ClearExcludedArrays() + { + this->ExcludedArrays.clear(); + this->Modified(); + } + + // Description: + // Return the number of excluded arrays. + int GetNumberOfExcludedArrays() + {return static_cast(this->ExcludedArrays.size());} + + // Description: + // Return the name of the ith excluded array. + const char* GetExcludedArray(int i) + { + if ( i < 0 || i >= static_cast(this->ExcludedArrays.size()) ) + { + return NULL; + } + return this->ExcludedArrays[i].c_str(); + } + + // Description: + // If enabled, then input arrays that are non-real types (i.e., not float + // or double) are promoted to float type on output. This is because the + // interpolation process may not be well behaved when integral types are + // combined using interpolation weights. + vtkSetMacro(PromoteOutputArrays, bool); + vtkBooleanMacro(PromoteOutputArrays, bool); + vtkGetMacro(PromoteOutputArrays, bool); + // Description: // Indicate whether to shallow copy the input point data arrays to the // output. On by default. @@ -173,6 +217,10 @@ class VTKFILTERSPOINTS_EXPORT vtkPointInterpolator : public vtkDataSetAlgorithm vtkBooleanMacro(PassFieldArrays, bool); vtkGetMacro(PassFieldArrays, bool); + // Description: + // Get the MTime of this object also considering the locator and kernel. + unsigned long GetMTime(); + protected: vtkPointInterpolator(); ~vtkPointInterpolator(); @@ -182,9 +230,13 @@ class VTKFILTERSPOINTS_EXPORT vtkPointInterpolator : public vtkDataSetAlgorithm int NullPointsStrategy; double NullValue; - char* ValidPointsMaskArrayName; + vtkStdString ValidPointsMaskArrayName; vtkCharArray *ValidPointsMask; + std::vector ExcludedArrays; + + bool PromoteOutputArrays; + bool PassCellArrays; bool PassPointArrays; bool PassFieldArrays; @@ -197,13 +249,13 @@ class VTKFILTERSPOINTS_EXPORT vtkPointInterpolator : public vtkDataSetAlgorithm vtkInformationVector *); // Description: - // Equivalent to calling BuildFieldList(); InitializeForProbing(); DoProbing(). - void Probe(vtkDataSet *input, vtkDataSet *source, vtkDataSet *output); + // Virtual for specialized subclass(es) + virtual void Probe(vtkDataSet *input, vtkDataSet *source, vtkDataSet *output); // Description: // Call at end of RequestData() to pass attribute data respecting the // PassCellArrays, PassPointArrays, PassFieldArrays flags. - void PassAttributeData( + virtual void PassAttributeData( vtkDataSet* input, vtkDataObject* source, vtkDataSet* output); // Description: diff --git a/Filters/Points/vtkPointInterpolator2D.cxx b/Filters/Points/vtkPointInterpolator2D.cxx new file mode 100644 index 00000000000..bd1fa4dec06 --- /dev/null +++ b/Filters/Points/vtkPointInterpolator2D.cxx @@ -0,0 +1,302 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkPointInterpolator2D.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkPointInterpolator2D.h" + +#include "vtkObjectFactory.h" +#include "vtkVoronoiKernel.h" +#include "vtkAbstractPointLocator.h" +#include "vtkArrayListTemplate.h" +#include "vtkStaticPointLocator.h" +#include "vtkDataSet.h" +#include "vtkDataArray.h" +#include "vtkImageData.h" +#include "vtkPolyData.h" +#include "vtkPoints.h" +#include "vtkCharArray.h" +#include "vtkFloatArray.h" +#include "vtkDoubleArray.h" +#include "vtkCellData.h" +#include "vtkPointData.h" +#include "vtkIdList.h" +#include "vtkInformation.h" +#include "vtkInformationVector.h" +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkMath.h" +#include "vtkSMPTools.h" +#include "vtkSMPThreadLocalObject.h" + +vtkStandardNewMacro(vtkPointInterpolator2D); + +//---------------------------------------------------------------------------- +// Helper classes to support efficient computing, and threaded execution. +namespace { +// Project source points onto plane +struct ProjectPoints +{ + vtkDataSet *Source; + double *OutPoints; + + ProjectPoints(vtkDataSet *source, double *outPts) : + Source(source), OutPoints(outPts) + { + } + + // Threaded projection + void operator() (vtkIdType ptId, vtkIdType endPtId) + { + double *p = this->OutPoints + 3*ptId; + double x[3]; + for ( ; ptId < endPtId; ++ptId) + { + this->Source->GetPoint(ptId,x); + *p++ = x[0]; + *p++ = x[1]; + *p++ = 0.0; //x-y projection + } + } +}; + +// Project source points onto plane +struct ProjectPointsWithScalars +{ + vtkDataSet *Source; + double *OutPoints; + double *ZScalars; + + ProjectPointsWithScalars(vtkDataSet *source, double *outPts, double *zScalars) : + Source(source), OutPoints(outPts), ZScalars(zScalars) + { + } + + // Threaded projection + void operator() (vtkIdType ptId, vtkIdType endPtId) + { + double *p = this->OutPoints + 3*ptId; + double *s = this->ZScalars + ptId; + double x[3]; + for ( ; ptId < endPtId; ++ptId) + { + this->Source->GetPoint(ptId,x); + *p++ = x[0]; + *p++ = x[1]; + *p++ = 0.0; //x-y projection + *s++ = x[2]; + } + } +}; + +// The threaded core of the algorithm +struct ProbePoints +{ + vtkDataSet *Input; + vtkInterpolationKernel *Kernel; + vtkAbstractPointLocator *Locator; + vtkPointData *InPD; + vtkPointData *OutPD; + ArrayList Arrays; + char *Valid; + int Strategy; + + // Don't want to allocate these working arrays on every thread invocation, + // so make them thread local. + vtkSMPThreadLocalObject PIds; + vtkSMPThreadLocalObject Weights; + + ProbePoints(vtkDataSet *input, vtkInterpolationKernel *kernel,vtkAbstractPointLocator *loc, + vtkPointData *inPD, vtkPointData *outPD, int strategy, char *valid, double nullV) : + Input(input), Kernel(kernel), Locator(loc), InPD(inPD), OutPD(outPD), + Valid(valid), Strategy(strategy) + { + this->Arrays.AddArrays(input->GetNumberOfPoints(), inPD, outPD, nullV); + } + + // Just allocate a little bit of memory to get started. + void Initialize() + { + vtkIdList*& pIds = this->PIds.Local(); + pIds->Allocate(128); //allocate some memory + vtkDoubleArray*& weights = this->Weights.Local(); + weights->Allocate(128); + } + + // When null point is encountered + void AssignNullPoint(const double x[3], vtkIdList *pIds, + vtkDoubleArray *weights, vtkIdType ptId) + { + if ( this->Strategy == vtkPointInterpolator2D::MASK_POINTS) + { + this->Valid[ptId] = 0; + this->Arrays.AssignNullValue(ptId); + } + else if ( this->Strategy == vtkPointInterpolator2D::NULL_VALUE) + { + this->Arrays.AssignNullValue(ptId); + } + else //vtkPointInterpolator2D::CLOSEST_POINT: + { + pIds->SetNumberOfIds(1); + vtkIdType pId = this->Locator->FindClosestPoint(x); + pIds->SetId(0,pId); + weights->SetNumberOfTuples(1); + weights->SetValue(0,1.0); + this->Arrays.Interpolate(1, pIds->GetPointer(0), + weights->GetPointer(0), ptId); + } + } + + // Threaded interpolation method + void operator() (vtkIdType ptId, vtkIdType endPtId) + { + double x[3]; + vtkIdList*& pIds = this->PIds.Local(); + vtkIdType numWeights; + vtkDoubleArray*& weights = this->Weights.Local(); + + for ( ; ptId < endPtId; ++ptId) + { + this->Input->GetPoint(ptId,x); + x[2] = 0.0; //x-y projection + + if ( this->Kernel->ComputeBasis(x, pIds) > 0 ) + { + numWeights = this->Kernel->ComputeWeights(x, pIds, weights); + this->Arrays.Interpolate(numWeights, pIds->GetPointer(0), + weights->GetPointer(0), ptId); + } + else + { + this->AssignNullPoint(x, pIds, weights, ptId); + }// null point + }//for all dataset points + } + + void Reduce() + { + } + +}; //ProbePoints + + +} //anonymous namespace + +//================= Begin class proper ======================================= +//---------------------------------------------------------------------------- +vtkPointInterpolator2D::vtkPointInterpolator2D() +{ + this->InterpolateZ = true; + this->ZArrayName = "Elevation"; +} + +//---------------------------------------------------------------------------- +vtkPointInterpolator2D::~vtkPointInterpolator2D() +{ +} + +//---------------------------------------------------------------------------- +// The driver of the algorithm +void vtkPointInterpolator2D:: +Probe(vtkDataSet *input, vtkDataSet *source, vtkDataSet *output) +{ + // Make sure there is a kernel + if ( !this->Kernel ) + { + vtkErrorMacro(<<"Interpolation kernel required\n"); + return; + } + + // Start by building the locator + if ( !this->Locator ) + { + vtkErrorMacro(<<"Point locator required\n"); + return; + } + + // We need to project the source points to the z=0.0 plane + vtkIdType numSourcePts = source->GetNumberOfPoints(); + vtkPolyData *projSource = vtkPolyData::New(); + projSource->ShallowCopy(source); + vtkPoints *projPoints = vtkPoints::New(); + projPoints->SetDataTypeToDouble(); + projPoints->SetNumberOfPoints(numSourcePts); + projSource->SetPoints(projPoints); + projPoints->UnRegister(this); + vtkDoubleArray *zScalars=NULL; + + // Create elevation scalars if necessary + if ( this->InterpolateZ ) + { + zScalars = vtkDoubleArray::New(); + zScalars->SetName(this->GetZArrayName()); + zScalars->SetNumberOfTuples(numSourcePts); + ProjectPointsWithScalars + project(source, static_cast(projPoints->GetVoidPointer(0)), + static_cast(zScalars->GetVoidPointer(0))); + vtkSMPTools::For(0, numSourcePts, project); + projSource->GetPointData()->AddArray(zScalars); + zScalars->UnRegister(this); + } + else + { + ProjectPoints project(source,static_cast(projPoints->GetVoidPointer(0))); + vtkSMPTools::For(0, numSourcePts, project); + } + + this->Locator->SetDataSet(projSource); + this->Locator->BuildLocator(); + + // Set up the interpolation process + vtkIdType numPts = input->GetNumberOfPoints(); + vtkPointData *inPD = projSource->GetPointData(); + vtkPointData *outPD = output->GetPointData(); + outPD->InterpolateAllocate(inPD,numPts); + + // Masking if requested + char *mask=NULL; + if ( this->NullPointsStrategy == vtkPointInterpolator2D::MASK_POINTS ) + { + this->ValidPointsMask = vtkCharArray::New(); + this->ValidPointsMask->SetNumberOfTuples(numPts); + mask = this->ValidPointsMask->GetPointer(0); + std::fill_n(mask, numPts, 1); + } + + // Now loop over input points, finding closest points and invoking kernel. + if ( this->Kernel->GetRequiresInitialization() ) + { + this->Kernel->Initialize(this->Locator, source, inPD); + } + + // If the input is image data then there is a faster path + ProbePoints probe(input,this->Kernel,this->Locator,inPD,outPD, + this->NullPointsStrategy,mask,this->NullValue); + vtkSMPTools::For(0, numPts, probe); + + // Clean up + if ( mask ) + { + this->ValidPointsMask->SetName(this->ValidPointsMaskArrayName); + outPD->AddArray(this->ValidPointsMask); + this->ValidPointsMask->Delete(); + } +} + +//---------------------------------------------------------------------------- +void vtkPointInterpolator2D::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); + + os << indent << "Interpolate Z: " + << (this->InterpolateZ ? "On" : " Off") << "\n"; +} diff --git a/Filters/Points/vtkPointInterpolator2D.h b/Filters/Points/vtkPointInterpolator2D.h new file mode 100644 index 00000000000..9f7bacb930f --- /dev/null +++ b/Filters/Points/vtkPointInterpolator2D.h @@ -0,0 +1,108 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkPointInterpolator2D.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkPointInterpolator2D - interpolate point cloud attribute data +// onto x-y plane using various kernels + +// .SECTION Description +// vtkPointInterpolator2D probes a point cloud Pc (the filter Source) with a +// set of points P (the filter Input), interpolating the data values from Pc +// onto P. Note however that the descriptive phrase "point cloud" is a +// misnomer: Pc can be represented by any vtkDataSet type, with the points of +// the dataset forming Pc. Similary, the output P can also be represented by +// any vtkDataSet type; and the topology/geometry structure of P is passed +// through to the output along with the newly interpolated arrays. However, +// this filter presumes that P lies on a plane z=0.0, thus z-coordinates +// are set accordingly during the interpolation process. +// +// The optional boolen flag InterpolateZ is provided for convenience. In +// effect it turns the source z coordinates into an additional array that is +// interpolated onto the output data. For example, if the source is a x-y-z +// LIDAR point cloud, then z can be interpolated onto the output dataset as a +// vertical elevation(z-coordinate). +// +// A key input to this filter is the specification of the interpolation +// kernel, and the parameters which control the associated interpolation +// process. Interpolation kernels include Voronoi, Gaussian, Shepard, and SPH +// (smoothed particle hydrodynamics), with additional kernels to be added in +// the future. See vtkPointInterpolator for more information. + +// .SECTION Caveats +// This class has been threaded with vtkSMPTools. Using TBB or other +// non-sequential type (set in the CMake variable +// VTK_SMP_IMPLEMENTATION_TYPE) may improve performance significantly. +// +// For widely spaced points in Pc, or when p is located outside the bounding +// region of Pc, the interpolation may behave badly and the interpolation +// process will adapt as necessary to produce output. For example, if the N +// closest points within R are requested to interpolate p, if N=0 then the +// interpolation will switch to a different strategy (which can be controlled +// as in the NullPointsStrategy). + +// .SECTION See Also +// vtkPointInterpolator + +#ifndef vtkPointInterpolator2D_h +#define vtkPointInterpolator2D_h + +#include "vtkFiltersPointsModule.h" // For export macro +#include "vtkPointInterpolator.h" +#include "vtkStdString.h" // For vtkStdString ivars + + +class VTKFILTERSPOINTS_EXPORT vtkPointInterpolator2D : public vtkPointInterpolator +{ +public: + // Description: + // Standard methods for instantiating, obtaining type information, and + // printing. + static vtkPointInterpolator2D *New(); + vtkTypeMacro(vtkPointInterpolator2D,vtkPointInterpolator); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Specify whether to take the z-coordinate values of the source points as + // attributes to be interpolated. This is in addition to any other point + // attribute data associated with the source. By default this is enabled. + vtkSetMacro(InterpolateZ,bool); + vtkGetMacro(InterpolateZ,bool); + vtkBooleanMacro(InterpolateZ,bool); + + // Description: + // Specify the name of the output array containing z values. This method is + // only applicable when InterpolateZ is enabled. By default the output + // array name is "Elevation". + vtkSetMacro(ZArrayName, vtkStdString); + vtkGetMacro(ZArrayName, vtkStdString); + +protected: + vtkPointInterpolator2D(); + ~vtkPointInterpolator2D(); + + // Interpolate z values? + bool InterpolateZ; + + // Name of output array + vtkStdString ZArrayName; + + // The driver of the algorithm + virtual void Probe(vtkDataSet *input, vtkDataSet *source, vtkDataSet *output); + +private: + vtkPointInterpolator2D(const vtkPointInterpolator2D&); // Not implemented. + void operator=(const vtkPointInterpolator2D&); // Not implemented. + +}; + +#endif diff --git a/Filters/Points/vtkProbabilisticVoronoiKernel.cxx b/Filters/Points/vtkProbabilisticVoronoiKernel.cxx new file mode 100644 index 00000000000..bb9718429ac --- /dev/null +++ b/Filters/Points/vtkProbabilisticVoronoiKernel.cxx @@ -0,0 +1,94 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkProbabilisticVoronoiKernel.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkProbabilisticVoronoiKernel.h" +#include "vtkAbstractPointLocator.h" +#include "vtkObjectFactory.h" +#include "vtkIdList.h" +#include "vtkDoubleArray.h" +#include "vtkDataSet.h" +#include "vtkPointData.h" +#include "vtkMath.h" +#include "vtkMathUtilities.h" + +vtkStandardNewMacro(vtkProbabilisticVoronoiKernel); + +//---------------------------------------------------------------------------- +vtkProbabilisticVoronoiKernel::vtkProbabilisticVoronoiKernel() +{ +} + + +//---------------------------------------------------------------------------- +vtkProbabilisticVoronoiKernel::~vtkProbabilisticVoronoiKernel() +{ +} + +//---------------------------------------------------------------------------- +vtkIdType vtkProbabilisticVoronoiKernel:: +ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *prob, + vtkDoubleArray *weights) +{ + vtkIdType numPts = pIds->GetNumberOfIds(); + double *p = (prob ? prob->GetPointer(0) : NULL); + double highestProbability=VTK_FLOAT_MIN; + vtkIdType id, mostProbableId=0; + + if ( p ) // return the point in the neighborhood with the highest probability + { + for (int i=0; i highestProbability ) + { + mostProbableId = pIds->GetId(i); + highestProbability = p[i]; + } + } + } + + else //return the closest point in the footprint provided + { + double y[3], d, minD=VTK_FLOAT_MAX; + for (int i=0; iGetId(i); + this->DataSet->GetPoint(id,y); + d = vtkMath::Distance2BetweenPoints(x,y); + if ( vtkMathUtilities::FuzzyCompare(d, 0.0, std::numeric_limits::epsilon()*256.0 )) //precise hit on existing point + { + mostProbableId = id; + break; + } + else if ( d <= minD ) + { + mostProbableId = id; + minD = d; + } + }//over all points + } + + // Okay let's get out + pIds->SetNumberOfIds(1); + pIds->SetId(0,mostProbableId); + weights->SetNumberOfTuples(1); + weights->SetValue(0,1.0); + + return 1; +} + +//---------------------------------------------------------------------------- +void vtkProbabilisticVoronoiKernel::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); +} diff --git a/Filters/Points/vtkProbabilisticVoronoiKernel.h b/Filters/Points/vtkProbabilisticVoronoiKernel.h new file mode 100644 index 00000000000..d18e718fbbc --- /dev/null +++ b/Filters/Points/vtkProbabilisticVoronoiKernel.h @@ -0,0 +1,81 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkProbabilisticVoronoiKernel.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkProbabilisticVoronoiKernel - interpolate from the weighted closest point + +// .SECTION Description +// vtkProbabilisticVoronoiKernel is an interpolation kernel that interpolates +// from the closest weighted point from a neighborhood of points. The weights +// refer to the probabilistic weighting that can be provided to the +// ComputeWeights() method. +// +// Note that the local neighborhood is taken from the kernel footprint +// specified in the superclass vtkGeneralizedKernel. + +// .SECTION Caveats +// If probability weightings are not defined, then the kernel provides the +// same results as vtkVoronoiKernel, except a less efficiently. + +// .SECTION See Also +// vtkInterpolationKernel vtkGeneralizedKernel vtkVoronoiKernel + + +#ifndef vtkProbabilisticVoronoiKernel_h +#define vtkProbabilisticVoronoiKernel_h + +#include "vtkFiltersPointsModule.h" // For export macro +#include "vtkGeneralizedKernel.h" + +class vtkIdList; +class vtkDoubleArray; + + +class VTKFILTERSPOINTS_EXPORT vtkProbabilisticVoronoiKernel : public vtkGeneralizedKernel +{ +public: + // Description: + // Standard methods for instantiation, obtaining type information, and printing. + static vtkProbabilisticVoronoiKernel *New(); + vtkTypeMacro(vtkProbabilisticVoronoiKernel,vtkGeneralizedKernel); + void PrintSelf(ostream& os, vtkIndent indent); + + // Re-use any superclass signatures that we don't override. + using vtkGeneralizedKernel::ComputeWeights; + + // Description: + // Given a point x, a list of basis points pIds, and a probability + // weighting function prob, compute interpolation weights associated with + // these basis points. Note that basis points list pIds, the probability + // weighting prob, and the weights array are provided by the caller of the + // method, and may be dynamically resized as necessary. The method returns + // the number of weights (pIds may be resized in some cases). Typically + // this method is called after ComputeBasis(), although advanced users can + // invoke ComputeWeights() and provide the interpolation basis points pIds + // directly. The probably weighting prob are numbers 0<=prob<=1 which are + // multiplied against the interpolation weights before normalization. They + // are estimates of local confidence of weights. The prob may be NULL in + // which all probabilities are considered =1. + virtual vtkIdType ComputeWeights(double x[3], vtkIdList *pIds, + vtkDoubleArray *prob, vtkDoubleArray *weights); + +protected: + vtkProbabilisticVoronoiKernel(); + ~vtkProbabilisticVoronoiKernel(); + +private: + vtkProbabilisticVoronoiKernel(const vtkProbabilisticVoronoiKernel&); // Not implemented. + void operator=(const vtkProbabilisticVoronoiKernel&); // Not implemented. +}; + +#endif diff --git a/Filters/Points/vtkSPHCubicKernel.cxx b/Filters/Points/vtkSPHCubicKernel.cxx new file mode 100644 index 00000000000..f4030099752 --- /dev/null +++ b/Filters/Points/vtkSPHCubicKernel.cxx @@ -0,0 +1,73 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSPHCubicKernel.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkSPHCubicKernel.h" +#include "vtkAbstractPointLocator.h" +#include "vtkObjectFactory.h" +#include "vtkMath.h" + +vtkStandardNewMacro(vtkSPHCubicKernel); + +//---------------------------------------------------------------------------- +vtkSPHCubicKernel::vtkSPHCubicKernel() +{ + this->CutoffFactor = 2.0; + + if ( this->Dimension == 1 ) + { + this->Sigma = 2.0/3.0; + } + else if ( this->Dimension == 2 ) + { + this->Sigma = 10.0/(7.0*vtkMath::Pi()); + } + else //if ( this->Dimension == 3 ) + { + this->Sigma = 1.0/vtkMath::Pi(); + } +} + +//---------------------------------------------------------------------------- +vtkSPHCubicKernel::~vtkSPHCubicKernel() +{ +} + +//---------------------------------------------------------------------------- +// At this point, the spatial step, the dimension of the kernel, and the cutoff +// factor should be known. +void vtkSPHCubicKernel:: +Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, vtkPointData *attr) +{ + if ( this->Dimension == 1 ) + { + this->Sigma = 2.0 / 3.0; + } + else if ( this->Dimension == 2 ) + { + this->Sigma = 10.0 / (7.0*vtkMath::Pi()); + } + else //if ( this->Dimension == 3 ) + { + this->Sigma = 1.0 / vtkMath::Pi(); + } + + // Sigma must be set before vtkSPHKernel::Initialize is invoked + this->Superclass::Initialize(loc, ds, attr); +} + +//---------------------------------------------------------------------------- +void vtkSPHCubicKernel::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); +} diff --git a/Filters/Points/vtkSPHCubicKernel.h b/Filters/Points/vtkSPHCubicKernel.h new file mode 100644 index 00000000000..4ce4ab77662 --- /dev/null +++ b/Filters/Points/vtkSPHCubicKernel.h @@ -0,0 +1,89 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSPHCubicKernel.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkSPHCubicKernel - a cubic SPH interpolation kernel + +// .SECTION Description +// vtkSPHCubicKernel is an smooth particle hydrodynamics interpolation kernel as +// described by D.J. Price. This is a cubic formulation. +// +// .SECTION Caveats +// For more information see D.J. Price, Smoothed particle hydrodynamics and +// magnetohydrodynamics, J. Comput. Phys. 231:759-794, 2012. Especially +// equation 49. + +// .SECTION Acknowledgments +// The following work has been generously supported by Altair Engineering +// and FluiDyna GmbH. Please contact Steve Cosgrove or Milos Stanic for +// more information. + +// .SECTION See Also +// vtkSPHKernel vtkSPHInterpolator + + +#ifndef vtkSPHCubicKernel_h +#define vtkSPHCubicKernel_h + +#include "vtkFiltersPointsModule.h" // For export macro +#include "vtkSPHKernel.h" +#include // For std::min() + +class vtkIdList; +class vtkDoubleArray; + + +class VTKFILTERSPOINTS_EXPORT vtkSPHCubicKernel : public vtkSPHKernel +{ +public: + // Description: + // Standard methods for instantiation, obtaining type information, and printing. + static vtkSPHCubicKernel *New(); + vtkTypeMacro(vtkSPHCubicKernel,vtkSPHKernel); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Produce the computational parameters for the kernel. Invoke this method + // after setting initial values like SpatialStep. + virtual void Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, + vtkPointData *pd); + + // Description: + // Compute weighting factor given a normalized distance from a sample point. + virtual double ComputeFunctionWeight(const double d) + { + double tmp1 = 2.0 - std::min(d,2.0); + double tmp2 = 1.0 - std::min(d,1.0); + return (0.25*tmp1*tmp1*tmp1 - tmp2*tmp2*tmp2); + } + + // Description: + // Compute weighting factor for derivative quantities given a normalized + // distance from a sample point. + virtual double ComputeGradientWeight(const double d) + { + double tmp1 = 2.0 - std::min(d,2.0); + double tmp2 = 1.0 - std::min(d,1.0); + return (0.25*tmp1*tmp1 - tmp2*tmp2); + } + +protected: + vtkSPHCubicKernel(); + ~vtkSPHCubicKernel(); + +private: + vtkSPHCubicKernel(const vtkSPHCubicKernel&); // Not implemented. + void operator=(const vtkSPHCubicKernel&); // Not implemented. +}; + +#endif diff --git a/Filters/Points/vtkSPHInterpolator.cxx b/Filters/Points/vtkSPHInterpolator.cxx new file mode 100644 index 00000000000..9342ff7e7c2 --- /dev/null +++ b/Filters/Points/vtkSPHInterpolator.cxx @@ -0,0 +1,630 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSPHInterpolator.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkSPHInterpolator.h" + +#include "vtkObjectFactory.h" +#include "vtkSPHQuinticKernel.h" +#include "vtkVoronoiKernel.h" +#include "vtkAbstractPointLocator.h" +#include "vtkArrayListTemplate.h" +#include "vtkStaticPointLocator.h" +#include "vtkDataSet.h" +#include "vtkDataArray.h" +#include "vtkImageData.h" +#include "vtkPoints.h" +#include "vtkCharArray.h" +#include "vtkDoubleArray.h" +#include "vtkFloatArray.h" +#include "vtkCellData.h" +#include "vtkPointData.h" +#include "vtkIdList.h" +#include "vtkInformation.h" +#include "vtkInformationVector.h" +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkMath.h" +#include "vtkSMPTools.h" +#include "vtkSMPThreadLocalObject.h" + +vtkStandardNewMacro(vtkSPHInterpolator); +vtkCxxSetObjectMacro(vtkSPHInterpolator,Locator,vtkAbstractPointLocator); +vtkCxxSetObjectMacro(vtkSPHInterpolator,Kernel,vtkSPHKernel); + +//---------------------------------------------------------------------------- +// Helper classes to support efficient computing, and threaded execution. +namespace { +// The threaded core of the algorithm +struct ProbePoints +{ + vtkSPHInterpolator *SPHInterpolator; + vtkDataSet *Input; + vtkSPHKernel *Kernel; + vtkAbstractPointLocator *Locator; + vtkPointData *InPD; + vtkPointData *OutPD; + ArrayList Arrays; + ArrayList DerivArrays; + bool ComputeDerivArrays; + char *Valid; + int Strategy; + float *Shepard; + bool Promote; + + // Don't want to allocate these working arrays on every thread invocation, + // so make them thread local. + vtkSMPThreadLocalObject PIds; + vtkSMPThreadLocalObject Weights; + vtkSMPThreadLocalObject GradWeights; + + ProbePoints(vtkSPHInterpolator *sphInt, vtkDataSet *input, + vtkPointData *inPD, vtkPointData *outPD, + char *valid, float *shepCoef) : + SPHInterpolator(sphInt), Input(input), InPD(inPD), OutPD(outPD), + Valid(valid), Shepard(shepCoef) + { + // Gather information from the interpolator + this->Kernel = sphInt->GetKernel(); + this->Locator = sphInt->GetLocator(); + this->Strategy = sphInt->GetNullPointsStrategy(); + double nullV = sphInt->GetNullValue(); + this->Promote = sphInt->GetPromoteOutputArrays(); + + // Manage arrays for interpolation + for (int i=0; i < sphInt->GetNumberOfExcludedArrays(); ++i) + { + const char *arrayName = sphInt->GetExcludedArray(i); + vtkDataArray *array = this->InPD->GetArray(arrayName); + if ( array != NULL ) + { + outPD->RemoveArray(array->GetName()); + this->Arrays.ExcludeArray(array); + this->DerivArrays.ExcludeArray(array); + } + } + this->Arrays.AddArrays(input->GetNumberOfPoints(), inPD, outPD, nullV, this->Promote); + + // Sometimes derivative arrays are requested + for (int i=0; i < sphInt->GetNumberOfDerivativeArrays(); ++i) + { + const char *arrayName = sphInt->GetDerivativeArray(i); + vtkDataArray *array = this->InPD->GetArray(arrayName); + if ( array != NULL ) + { + vtkStdString outName = arrayName; outName += "_deriv"; + if (vtkDataArray* outArray = this->DerivArrays.AddArrayPair( + array->GetNumberOfTuples(), array, outName, nullV, this->Promote)) + { + outPD->AddArray(outArray); + } + } + } + this->ComputeDerivArrays = (this->DerivArrays.Arrays.size() > 0 ? true : false); + } + + // Just allocate a little bit of memory to get started. + void Initialize() + { + vtkIdList*& pIds = this->PIds.Local(); + pIds->Allocate(128); //allocate some memory + vtkDoubleArray*& weights = this->Weights.Local(); + weights->Allocate(128); + vtkDoubleArray*& gradWeights = this->GradWeights.Local(); + gradWeights->Allocate(128); + } + + // Threaded interpolation method + void operator() (vtkIdType ptId, vtkIdType endPtId) + { + double x[3]; + vtkIdList*& pIds = this->PIds.Local(); + vtkIdType numWeights; + vtkDoubleArray*& weights = this->Weights.Local(); + vtkDoubleArray*& gradWeights = this->GradWeights.Local(); + + for ( ; ptId < endPtId; ++ptId) + { + this->Input->GetPoint(ptId,x); + + if ( (numWeights=this->Kernel->ComputeBasis(x, pIds, ptId)) > 0 ) + { + if ( ! this->ComputeDerivArrays ) + { + this->Kernel->ComputeWeights(x, pIds, weights); + } + else + { + this->Kernel->ComputeGradWeights(x, pIds, weights, gradWeights); + this->DerivArrays.Interpolate(numWeights, pIds->GetPointer(0), + gradWeights->GetPointer(0), ptId); + } + this->Arrays.Interpolate(numWeights, pIds->GetPointer(0), + weights->GetPointer(0), ptId); + } + else // no neighborhood points + { + this->Arrays.AssignNullValue(ptId); + if ( this->Strategy == vtkSPHInterpolator::MASK_POINTS) + { + this->Valid[ptId] = 0; + } + }// null point + + // Shepard's coefficient if requested + if ( this->Shepard ) + { + double sum=0.0, *w=weights->GetPointer(0); + for (int i=0; i < numWeights; ++i) + { + sum += w[i]; + } + this->Shepard[ptId] = sum; + } + }//for all dataset points + } + + void Reduce() + { + } + +}; //ProbePoints + +// Probe points using an image. Uses a more efficient iteration scheme. +struct ImageProbePoints : public ProbePoints +{ + int Dims[3]; + double Origin[3]; + double Spacing[3]; + + ImageProbePoints(vtkSPHInterpolator *sphInt, vtkImageData *image, int dims[3], + double origin[3], double spacing[3], vtkPointData *inPD, + vtkPointData *outPD, char *valid, float *shep) : + ProbePoints(sphInt, image, inPD, outPD, valid, shep) + { + for (int i=0; i < 3; ++i) + { + this->Dims[i] = dims[i]; + this->Origin[i] = origin[i]; + this->Spacing[i] = spacing[i]; + } + } + + // Threaded interpolation method specialized to image traversal + void operator() (vtkIdType slice, vtkIdType sliceEnd) + { + double x[3]; + vtkIdType numWeights; + double *origin=this->Origin; + double *spacing=this->Spacing; + int *dims=this->Dims; + vtkIdType ptId, jOffset, kOffset, sliceSize=dims[0]*dims[1]; + vtkIdList*& pIds = this->PIds.Local(); + vtkDoubleArray*& weights = this->Weights.Local(); + vtkDoubleArray*& gradWeights = this->GradWeights.Local(); + + for ( ; slice < sliceEnd; ++slice) + { + x[2] = origin[2] + slice*spacing[2]; + kOffset = slice*sliceSize; + + for ( int j=0; j < dims[1]; ++j) + { + x[1] = origin[1] + j*spacing[1]; + jOffset = j*dims[0]; + + for ( int i=0; i < dims[0]; ++i) + { + x[0] = origin[0] + i*spacing[0]; + ptId = i + jOffset + kOffset; + + if ( (numWeights=this->Kernel->ComputeBasis(x, pIds, ptId)) > 0 ) + { + if ( ! this->ComputeDerivArrays ) + { + this->Kernel->ComputeWeights(x, pIds, weights); + } + else + { + this->Kernel->ComputeGradWeights(x, pIds, weights, gradWeights); + this->DerivArrays.Interpolate(numWeights, pIds->GetPointer(0), + gradWeights->GetPointer(0), ptId); + } + this->Arrays.Interpolate(numWeights, pIds->GetPointer(0), + weights->GetPointer(0), ptId); + } + else + { + this->Arrays.AssignNullValue(ptId); + if ( this->Strategy == vtkSPHInterpolator::MASK_POINTS) + { + this->Valid[ptId] = 0; + } + }// null point + + // Shepard's coefficient if requested + if ( this->Shepard ) + { + double sum=0.0, *w=weights->GetPointer(0); + for (int ii=0; ii < numWeights; ++ii) //numWieights=0 for null point + { + sum += w[ii]; + } + this->Shepard[ptId] = sum; + } + + }//over i + }//over j + }//over slices + } +}; //ImageProbePoints + +} //anonymous namespace + +//================= Begin class proper ======================================= +//---------------------------------------------------------------------------- +vtkSPHInterpolator::vtkSPHInterpolator() +{ + this->SetNumberOfInputPorts(2); + + this->Locator = vtkStaticPointLocator::New(); + + this->Kernel = vtkSPHQuinticKernel::New(); + + this->CutoffArrayName = ""; + + this->DensityArrayName = "Rho"; + this->MassArrayName = ""; + + this->NullPointsStrategy = vtkSPHInterpolator::NULL_VALUE; + this->NullValue = 0.0; + + this->ValidPointsMask = NULL; + this->ValidPointsMaskArrayName = "vtkValidPointMask"; + + this->ComputeShepardSum = true; + this->ShepardSumArrayName = "Shepard Summation"; + + this->PromoteOutputArrays = true; + + this->PassPointArrays = true; + this->PassCellArrays = true; + this->PassFieldArrays = true; +} + +//---------------------------------------------------------------------------- +vtkSPHInterpolator::~vtkSPHInterpolator() +{ + this->SetLocator(NULL); + this->SetKernel(NULL); +} + +//---------------------------------------------------------------------------- +void vtkSPHInterpolator::SetSourceConnection(vtkAlgorithmOutput* algOutput) +{ + this->SetInputConnection(1, algOutput); +} + +//---------------------------------------------------------------------------- +void vtkSPHInterpolator::SetSourceData(vtkDataObject *input) +{ + this->SetInputData(1, input); +} + +//---------------------------------------------------------------------------- +vtkDataObject *vtkSPHInterpolator::GetSource() +{ + if (this->GetNumberOfInputConnections(1) < 1) + { + return NULL; + } + + return this->GetExecutive()->GetInputData(1, 0); +} + +//---------------------------------------------------------------------------- +void vtkSPHInterpolator:: +ExtractImageDescription(vtkImageData *input, int dims[3], double origin[3], + double spacing[3]) +{ + input->GetDimensions(dims); + input->GetOrigin(origin); + input->GetSpacing(spacing); +} + +//---------------------------------------------------------------------------- +// The driver of the algorithm +void vtkSPHInterpolator:: +Probe(vtkDataSet *input, vtkDataSet *source, vtkDataSet *output) +{ + // Make sure there is a kernel + if ( !this->Kernel ) + { + vtkErrorMacro(<<"Interpolation kernel required\n"); + return; + } + + // Start by building the locator + if ( !this->Locator ) + { + vtkErrorMacro(<<"Point locator required\n"); + return; + } + this->Locator->SetDataSet(source); + this->Locator->BuildLocator(); + + // Set up the interpolation process + vtkIdType numPts = input->GetNumberOfPoints(); + vtkPointData *inPD = input->GetPointData(); + vtkPointData *sourcePD = source->GetPointData(); + vtkPointData *outPD = output->GetPointData(); + outPD->InterpolateAllocate(sourcePD,numPts); + + // Masking if requested + char *mask=NULL; + if ( this->NullPointsStrategy == vtkSPHInterpolator::MASK_POINTS ) + { + this->ValidPointsMask = vtkCharArray::New(); + this->ValidPointsMask->SetNumberOfTuples(numPts); + mask = this->ValidPointsMask->GetPointer(0); + std::fill_n(mask, numPts, 1); + } + + // Shepard summation if requested + float *shepardArray=NULL; + if ( this->ComputeShepardSum ) + { + this->ShepardSumArray = vtkFloatArray::New(); + this->ShepardSumArray->SetNumberOfTuples(numPts); + shepardArray=this->ShepardSumArray->GetPointer(0); + } + + // Initialize the SPH kernel + if ( this->Kernel->GetRequiresInitialization() ) + { + this->Kernel->SetCutoffArray(inPD->GetArray(this->CutoffArrayName)); + this->Kernel->SetDensityArray(sourcePD->GetArray(this->DensityArrayName)); + this->Kernel->SetMassArray(sourcePD->GetArray(this->MassArrayName)); + this->Kernel->Initialize(this->Locator, source, sourcePD); + } + + // Now loop over input points, finding closest points and invoking kernel. + // If the input is image data then there is a (slightly) faster path. + vtkImageData *imgInput = vtkImageData::SafeDownCast(input); + if ( imgInput ) + { + int dims[3]; + double origin[3], spacing[3]; + this->ExtractImageDescription(imgInput,dims,origin,spacing); + ImageProbePoints imageProbe(this, imgInput, dims, origin, + spacing, sourcePD, outPD, mask, shepardArray); + vtkSMPTools::For(0, dims[2], imageProbe);//over slices + } + else + { + ProbePoints probe(this, input, sourcePD, outPD, mask, shepardArray); + vtkSMPTools::For(0, numPts, probe); + } + + // Clean up + if ( this->ShepardSumArray ) + { + this->ShepardSumArray->SetName(this->ShepardSumArrayName); + outPD->AddArray(this->ShepardSumArray); + this->ShepardSumArray->Delete(); + this->ShepardSumArray = NULL; + } + + if ( mask ) + { + this->ValidPointsMask->SetName(this->ValidPointsMaskArrayName); + outPD->AddArray(this->ValidPointsMask); + this->ValidPointsMask->Delete(); + this->ValidPointsMask = NULL; + } +} + +//---------------------------------------------------------------------------- +void vtkSPHInterpolator:: +PassAttributeData(vtkDataSet* input, vtkDataObject* vtkNotUsed(source), + vtkDataSet* output) +{ + // copy point data arrays + if (this->PassPointArrays) + { + int numPtArrays = input->GetPointData()->GetNumberOfArrays(); + for (int i=0; iGetPointData()->AddArray(input->GetPointData()->GetArray(i)); + } + } + + // copy cell data arrays + if (this->PassCellArrays) + { + int numCellArrays = input->GetCellData()->GetNumberOfArrays(); + for (int i=0; iGetCellData()->AddArray(input->GetCellData()->GetArray(i)); + } + } + + if (this->PassFieldArrays) + { + // nothing to do, vtkDemandDrivenPipeline takes care of that. + } + else + { + output->GetFieldData()->Initialize(); + } +} + +//---------------------------------------------------------------------------- +int vtkSPHInterpolator::RequestData( + vtkInformation *vtkNotUsed(request), + vtkInformationVector **inputVector, + vtkInformationVector *outputVector) +{ + vtkDebugMacro(<< "Executing SPH Interpolator"); + + // get the info objects + vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); + vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0); + vtkInformation *outInfo = outputVector->GetInformationObject(0); + + // get the input and output + vtkDataSet *input = vtkDataSet::SafeDownCast( + inInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkDataSet *source = vtkDataSet::SafeDownCast( + sourceInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkDataSet *output = vtkDataSet::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT())); + + if (!source || source->GetNumberOfPoints() < 1 ) + { + vtkWarningMacro(<<"No source points to interpolate from"); + return 1; + } + + // Copy the input geometry and topology to the output + output->CopyStructure(input); + + // Perform the probing + this->Probe(input, source, output); + + // Pass attribute data as requested + this->PassAttributeData(input, source, output); + + return 1; +} + +//---------------------------------------------------------------------------- +int vtkSPHInterpolator::RequestInformation( + vtkInformation *vtkNotUsed(request), + vtkInformationVector **inputVector, + vtkInformationVector *outputVector) +{ + // get the info objects + vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); + vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0); + vtkInformation *outInfo = outputVector->GetInformationObject(0); + + outInfo->CopyEntry(sourceInfo, + vtkStreamingDemandDrivenPipeline::TIME_STEPS()); + outInfo->CopyEntry(sourceInfo, + vtkStreamingDemandDrivenPipeline::TIME_RANGE()); + + outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), + inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()), + 6); + + // Make sure that the scalar type and number of components + // are propagated from the source not the input. + if (vtkImageData::HasScalarType(sourceInfo)) + { + vtkImageData::SetScalarType(vtkImageData::GetScalarType(sourceInfo), + outInfo); + } + if (vtkImageData::HasNumberOfScalarComponents(sourceInfo)) + { + vtkImageData::SetNumberOfScalarComponents( + vtkImageData::GetNumberOfScalarComponents(sourceInfo), + outInfo); + } + + return 1; +} + +//---------------------------------------------------------------------------- +int vtkSPHInterpolator::RequestUpdateExtent( + vtkInformation *vtkNotUsed(request), + vtkInformationVector **inputVector, + vtkInformationVector *outputVector) +{ + // get the info objects + vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); + vtkInformation *sourceInfo = inputVector[1]->GetInformationObject(0); + vtkInformation *outInfo = outputVector->GetInformationObject(0); + + inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), 0); + inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), 1); + inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(), 0); + sourceInfo->Set( + vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER(), + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER())); + sourceInfo->Set( + vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES(), + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES())); + sourceInfo->Set( + vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS(), + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_GHOST_LEVELS())); + sourceInfo->Set( + vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), + sourceInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()), + 6); + + return 1; +} + +//-------------------------------------------------------------------------- +unsigned long vtkSPHInterpolator::GetMTime() +{ + unsigned long mTime=this->Superclass::GetMTime(); + unsigned long mTime2; + if ( this->Locator != NULL ) + { + mTime2 = this->Locator->GetMTime(); + mTime = ( mTime2 > mTime ? mTime2 : mTime ); + } + if ( this->Kernel != NULL ) + { + mTime2 = this->Kernel->GetMTime(); + mTime = ( mTime2 > mTime ? mTime2 : mTime ); + } + return mTime; +} + +//---------------------------------------------------------------------------- +void vtkSPHInterpolator::PrintSelf(ostream& os, vtkIndent indent) +{ + vtkDataObject *source = this->GetSource(); + + this->Superclass::PrintSelf(os,indent); + os << indent << "Source: " << source << "\n"; + os << indent << "Locator: " << this->Locator << "\n"; + os << indent << "Kernel: " << this->Kernel << "\n"; + + os << indent << "Cutoff Array Name: " << this->CutoffArrayName << "\n"; + + os << indent << "Density Array Name: " << this->DensityArrayName << "\n"; + os << indent << "Mass Array Name: " << this->MassArrayName << "\n"; + + os << indent << "Null Points Strategy: " << this->NullPointsStrategy << endl; + os << indent << "Null Value: " << this->NullValue << "\n"; + os << indent << "Valid Points Mask Array Name: " + << (this->ValidPointsMaskArrayName ? this->ValidPointsMaskArrayName : "(none)") << "\n"; + + os << indent << "Compute Shepard Sum: " + << (this->ComputeShepardSum ? "On" : " Off") << "\n"; + os << indent << "Shepard Sum Array Name: " + << (this->ShepardSumArrayName ? this->ShepardSumArrayName : "(none)") << "\n"; + + os << indent << "Promote Output Arrays: " + << (this->PromoteOutputArrays ? "On" : " Off") << "\n"; + + os << indent << "Pass Point Arrays: " + << (this->PassPointArrays? "On" : " Off") << "\n"; + os << indent << "Pass Cell Arrays: " + << (this->PassCellArrays? "On" : " Off") << "\n"; + os << indent << "Pass Field Arrays: " + << (this->PassFieldArrays? "On" : " Off") << "\n"; +} diff --git a/Filters/Points/vtkSPHInterpolator.h b/Filters/Points/vtkSPHInterpolator.h new file mode 100644 index 00000000000..4a5820788fe --- /dev/null +++ b/Filters/Points/vtkSPHInterpolator.h @@ -0,0 +1,366 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSPHInterpolator.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkSPHInterpolator - interpolate over point cloud using SPH kernels + +// .SECTION Description +// This filter uses SPH (smooth particle hydrodynamics) kernels to +// interpolate a data source onto an input structure. For example, while the +// data source is a set of particles, the data from these particles can be +// interpolated onto an input object such as a line, plane or volume. Then +// the output (which consists of the input structure plus interpolated data) +// can then be visualized using classical visualization techniques such as +// isocontouring, slicing, heat maps and so on. +// +// To use this filter, besides setting the input P and source Pc, specify a +// point locator (which accelerates queries about points and their neighbors) +// and an interpolation kernel (a subclass of vtkSPHKernel). In addition, the +// name of the source's density and mass arrays can optionally be provided; +// however if not provided then the local volume is computed from the +// kernel's spatial step. Finally, a cutoff distance array can optionall be +// provided when the local neighborhood around each point varies. The cutoff +// distance defines a local neighborhood in which the points in that +// neighborhood are used to interpolate values. If not provided, then the +// cutoff distance is computed from the spatial step size times the cutoff +// factor (see vtkSPHKernel). +// +// Other options to the filter include specifying which data attributes to +// interpolate from the source. By default, all data attributes contained in +// the source are interpolated. However, by adding array names to the +// exclusion list, these arrays will not be interpolated. Also, it is +// possible to use a SPH derivative formulation to interpolate from the +// source data attributes. This requires adding arrays (by name) to the +// derivative list, in which case the derivative formulation will be applied +// to create a new output array named "X_deriv" where X is the name of a +// source point attribute array. + +// .SECTION Caveats +// This class has been threaded with vtkSMPTools. Using TBB or other +// non-sequential type (set in the CMake variable +// VTK_SMP_IMPLEMENTATION_TYPE) may improve performance significantly. +// +// For widely spaced points in Pc, or when p is located outside the bounding +// region of Pc, the interpolation may behave badly and the interpolation +// process will adapt as necessary to produce output. For example, if the N +// closest points within R are requested to interpolate p, if N=0 then the +// interpolation will switch to a different strategy (which can be controlled +// as in the NullPointsStrategy). +// +// For more information and technical reference, see D.J. Price, Smoothed +// particle hydrodynamics and magnetohydrodynamics, +// J. Comput. Phys. 231:759-794, 2012. Especially equation 49. + +// .SECTION Acknowledgments +// The following work has been generously supported by Altair Engineering +// and FluiDyna GmbH. Please contact Steve Cosgrove or Milos Stanic for +// more information. + +// .SECTION See Also +// vtkPointInterpolator vtkSPHKernel vtkSPHQuinticKernel + +#ifndef vtkSPHInterpolator_h +#define vtkSPHInterpolator_h + +#include "vtkFiltersPointsModule.h" // For export macro +#include "vtkDataSetAlgorithm.h" +#include "vtkStdString.h" // For vtkStdString ivars +#include //For STL vector + +class vtkAbstractPointLocator; +class vtkIdList; +class vtkDoubleArray; +class vtkSPHKernel; +class vtkCharArray; +class vtkFloatArray; + + +class VTKFILTERSPOINTS_EXPORT vtkSPHInterpolator : public vtkDataSetAlgorithm +{ +public: + // Description: + // Standard methods for instantiating, obtaining type information, and + // printing. + static vtkSPHInterpolator *New(); + vtkTypeMacro(vtkSPHInterpolator,vtkDataSetAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Specify the dataset Pc that will be probed by the input points P. The + // Input P defines the dataset structure (the points and cells) for the + // output, while the Source Pc is probed (interpolated) to generate the + // scalars, vectors, etc. for the output points based on the point + // locations. + void SetSourceData(vtkDataObject *source); + vtkDataObject *GetSource(); + + // Description: + // Specify the dataset Pc that will be probed by the input points P. The + // Input P defines the structure (the points and cells) for the output, + // while the Source Pc is probed (interpolated) to generate the scalars, + // vectors, etc. for the output points based on the point locations. + void SetSourceConnection(vtkAlgorithmOutput* algOutput); + + // Description: + // Specify a point locator. By default a vtkStaticPointLocator is + // used. The locator performs efficient searches to locate near a + // specified interpolation position. + void SetLocator(vtkAbstractPointLocator *locator); + vtkGetObjectMacro(Locator,vtkAbstractPointLocator); + + // Description: + // Specify an interpolation kernel. By default a vtkSPHQuinticKernel is used + // (i.e., closest point). The interpolation kernel changes the basis of the + // interpolation. + void SetKernel(vtkSPHKernel *kernel); + vtkGetObjectMacro(Kernel,vtkSPHKernel); + + // Description: + // Specify an (optional) cutoff distance for each point in the input P. If + // not specified, then the kernel cutoff is used. + vtkSetMacro(CutoffArrayName,vtkStdString); + vtkGetMacro(CutoffArrayName,vtkStdString); + + // Description: + // Specify the density array name. This is optional. Typically both the density + // and mass arrays are specified together (in order to compute the local volume). + // Both the mass and density arrays must consist of tuples of 1-component. (Note that + // the density array name specifies a point array found in the Pc source.) + vtkSetMacro(DensityArrayName,vtkStdString); + vtkGetMacro(DensityArrayName,vtkStdString); + + // Description: + // Specify the mass array name. This is optional. Typically both the + // density and mass arrays are specified together (in order to compute the + // local volume). Both the mass and density arrays must consist of tuples + // of 1-component. (Note that the mass array name specifies a point + // array found in the Pc source.) + vtkSetMacro(MassArrayName,vtkStdString); + vtkGetMacro(MassArrayName,vtkStdString); + + // Description: + // Adds an array to the list of arrays which are to be excluded from the + // interpolation process. + void AddExcludedArray(const vtkStdString &excludedArray) + { + this->ExcludedArrays.push_back(excludedArray); + this->Modified(); + } + + // Description: + // Clears the contents of excluded array list. + void ClearExcludedArrays() + { + this->ExcludedArrays.clear(); + this->Modified(); + } + + // Description: + // Return the number of excluded arrays. + int GetNumberOfExcludedArrays() + {return static_cast(this->ExcludedArrays.size());} + + // Description: + // Return the name of the ith excluded array. + const char* GetExcludedArray(int i) + { + if ( i < 0 || i >= static_cast(this->ExcludedArrays.size()) ) + { + return NULL; + } + return this->ExcludedArrays[i].c_str(); + } + + // Description: + // Adds an array to the list of arrays whose derivative is to be taken. If + // the name of the array is "derivArray" this will produce an output array + // with the name "derivArray_deriv" (after filter execution). + void AddDerivativeArray(const vtkStdString &derivArray) + { + this->DerivArrays.push_back(derivArray); + this->Modified(); + } + + // Description: + // Clears the contents of derivative array list. + void ClearDerivativeArrays() + { + this->DerivArrays.clear(); + this->Modified(); + } + + // Description: + // Return the number of derivative arrays. + int GetNumberOfDerivativeArrays() + {return static_cast(this->DerivArrays.size());} + + // Description: + // Return the name of the ith derivative array. + const char* GetDerivativeArray(int i) + { + if ( i < 0 || i >= static_cast(this->DerivArrays.size()) ) + { + return NULL; + } + return this->DerivArrays[i].c_str(); + } + + // How to handle NULL points + enum NullStrategy + { + MASK_POINTS=0, + NULL_VALUE=1 + }; + + // Description: + // Specify a strategy to use when encountering a "null" point during the + // interpolation process. Null points occur when the local neighborhood (of + // nearby points to interpolate from) is empty. If the strategy is set to + // MaskPoints, then an output array is created that marks points as being + // valid (=1) or null (invalid =0) (and the NullValue is set as well). If + // the strategy is set to NullValue, then the output data value(s) are set + // to the NullPoint value. + vtkSetMacro(NullPointsStrategy,int); + vtkGetMacro(NullPointsStrategy,int); + void SetNullPointsStrategyToMaskPoints() + { this->SetNullPointsStrategy(MASK_POINTS); } + void SetNullPointsStrategyToNullValue() + { this->SetNullPointsStrategy(NULL_VALUE); } + + // Description: + // If the NullPointsStrategy == MASK_POINTS, then an array is generated for + // each input point. This vtkCharArray is placed into the output of the filter, + // with a non-zero value for a valid point, and zero otherwise. The name of + // this masking array is specified here. + vtkSetMacro(ValidPointsMaskArrayName, vtkStdString); + vtkGetMacro(ValidPointsMaskArrayName, vtkStdString); + + // Description: + // Specify the null point value. When a null point is encountered then all + // components of each null tuple are set to this value. By default the + // null value is set to zero. + vtkSetMacro(NullValue,double); + vtkGetMacro(NullValue,double); + + // Description: + // Indicate whether to compute the summation of weighting coefficients (the + // so-called Shepard sum). In the interior of a SPH point cloud, the + // Shephard summation value should be ~1.0. Towards the boundary, the + // Shepard summation generally falls off <1.0. If ComputeShepardSum is specified, then the + // output will contain an array of summed Shepard weights for each output + // point. On by default. + vtkSetMacro(ComputeShepardSum, bool); + vtkBooleanMacro(ComputeShepardSum, bool); + vtkGetMacro(ComputeShepardSum, bool); + + // Description: + // If ComputeShepardSum is on, then an array is generated with name + // ShepardSumArrayName for each input point. This vtkFloatArray is placed + // into the output of the filter, and NullPoints have value =0.0. The + // default name is "Shepard Summation". + vtkSetMacro(ShepardSumArrayName, vtkStdString); + vtkGetMacro(ShepardSumArrayName, vtkStdString); + + // Description: + // If enabled, then input arrays that are non-real types (i.e., not float + // or double) are promoted to float type on output. This is because the + // interpolation process may not be well behaved when integral types are + // combined using interpolation weights. + vtkSetMacro(PromoteOutputArrays, bool); + vtkBooleanMacro(PromoteOutputArrays, bool); + vtkGetMacro(PromoteOutputArrays, bool); + + // Description: + // Indicate whether to shallow copy the input point data arrays to the + // output. On by default. + vtkSetMacro(PassPointArrays, bool); + vtkBooleanMacro(PassPointArrays, bool); + vtkGetMacro(PassPointArrays, bool); + + // Description: + // Indicate whether to shallow copy the input cell data arrays to the + // output. On by default. + vtkSetMacro(PassCellArrays, bool); + vtkBooleanMacro(PassCellArrays, bool); + vtkGetMacro(PassCellArrays, bool); + + // Description: + // Indicate whether to pass the field-data arrays from the input to the + // output. On by default. + vtkSetMacro(PassFieldArrays, bool); + vtkBooleanMacro(PassFieldArrays, bool); + vtkGetMacro(PassFieldArrays, bool); + + // Description: + // Get the MTime of this object also considering the locator and kernel. + unsigned long GetMTime(); + +protected: + vtkSPHInterpolator(); + ~vtkSPHInterpolator(); + + vtkAbstractPointLocator *Locator; + vtkSPHKernel *Kernel; + + vtkStdString CutoffArrayName; + + vtkStdString DensityArrayName; + vtkStdString MassArrayName; + + std::vector ExcludedArrays; + std::vector DerivArrays; + + int NullPointsStrategy; + double NullValue; + vtkStdString ValidPointsMaskArrayName; + vtkCharArray *ValidPointsMask; + + bool ComputeShepardSum; + vtkStdString ShepardSumArrayName; + vtkFloatArray *ShepardSumArray; + + bool PromoteOutputArrays; + + bool PassCellArrays; + bool PassPointArrays; + bool PassFieldArrays; + + virtual int RequestData(vtkInformation *, vtkInformationVector **, + vtkInformationVector *); + virtual int RequestInformation(vtkInformation *, vtkInformationVector **, + vtkInformationVector *); + virtual int RequestUpdateExtent(vtkInformation *, vtkInformationVector **, + vtkInformationVector *); + + // Description: + // Virtual for specialized subclass(es) + virtual void Probe(vtkDataSet *input, vtkDataSet *source, vtkDataSet *output); + + // Description: + // Call at end of RequestData() to pass attribute data respecting the + // PassCellArrays, PassPointArrays, PassFieldArrays flags. + virtual void PassAttributeData( + vtkDataSet* input, vtkDataObject* source, vtkDataSet* output); + + // Description: + // Internal method to extract image metadata + void ExtractImageDescription(vtkImageData *input, int dims[3], + double origin[3], double spacing[3]); + +private: + vtkSPHInterpolator(const vtkSPHInterpolator&); // Not implemented. + void operator=(const vtkSPHInterpolator&); // Not implemented. + +}; + +#endif diff --git a/Filters/Points/vtkSPHKernel.cxx b/Filters/Points/vtkSPHKernel.cxx index 98867aeab14..cc8c464e95e 100644 --- a/Filters/Points/vtkSPHKernel.cxx +++ b/Filters/Points/vtkSPHKernel.cxx @@ -17,40 +17,159 @@ #include "vtkObjectFactory.h" #include "vtkIdList.h" #include "vtkDoubleArray.h" +#include "vtkFloatArray.h" +#include "vtkDataArray.h" +#include "vtkDataSet.h" +#include "vtkMath.h" -vtkStandardNewMacro(vtkSPHKernel); +vtkCxxSetObjectMacro(vtkSPHKernel,CutoffArray,vtkDataArray); +vtkCxxSetObjectMacro(vtkSPHKernel,DensityArray,vtkDataArray); +vtkCxxSetObjectMacro(vtkSPHKernel,MassArray,vtkDataArray); //---------------------------------------------------------------------------- vtkSPHKernel::vtkSPHKernel() { + this->RequiresInitialization = true; + this->SpatialStep = 0.001; + this->Dimension = 3; + this->CutoffArray = NULL; + this->DensityArray = NULL; + this->MassArray = NULL; } - //---------------------------------------------------------------------------- vtkSPHKernel::~vtkSPHKernel() { + this->SetCutoffArray(NULL); + this->SetDensityArray(NULL); + this->SetMassArray(NULL); } +//---------------------------------------------------------------------------- +// At this point, the spatial step, the dimension of the kernel, the cutoff +// factor, and the sigma normalization factor should be known. +void vtkSPHKernel:: +Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, vtkPointData *attr) +{ + this->Superclass::Initialize(loc, ds, attr); + + // this->CutoffFactor should have been set by subclass + this->Cutoff = this->CutoffFactor * this->SpatialStep; + this->DistNorm = 1.0 / this->SpatialStep; + this->DimNorm = this->Sigma * pow(this->DistNorm,this->Dimension); + this->DefaultVolume = pow(this->SpatialStep,this->Dimension); + + // See if cutoff array is provided. + if ( this->CutoffArray && this->CutoffArray->GetNumberOfComponents() == 1 ) + { + this->UseCutoffArray = true; + } + else + { + this->UseCutoffArray = false; + } + + // See if local mass and density information is provided + if ( this->DensityArray && this->MassArray && + this->DensityArray->GetNumberOfComponents() == 1 && + this->MassArray->GetNumberOfComponents() == 1 ) + { + this->UseArraysForVolume = true; + } + else + { + this->UseArraysForVolume = false; + } +} //---------------------------------------------------------------------------- +// Radius around point is cutoff factor * smoothing length. That is unless +// cutoff array is provided. vtkIdType vtkSPHKernel:: -ComputeBasis(double x[3], vtkIdList *pIds) +ComputeBasis(double x[3], vtkIdList *pIds, vtkIdType ptId) { - pIds->SetNumberOfIds(1); - vtkIdType pId = this->Locator->FindClosestPoint(x); - pIds->SetId(0,pId); + double cutoff; + if ( this->UseCutoffArray ) + { + this->CutoffArray->GetTuple(ptId,&cutoff); + } + else + { + cutoff = this->Cutoff; + } - return 1; + this->Locator->FindPointsWithinRadius(cutoff, x, pIds); + return pIds->GetNumberOfIds(); } //---------------------------------------------------------------------------- vtkIdType vtkSPHKernel:: -ComputeWeights(double*, vtkIdList*, vtkDoubleArray *weights) +ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights) { - weights->SetNumberOfTuples(1); - weights->SetValue(0,1.0); + vtkIdType numPts = pIds->GetNumberOfIds(); + int i; + vtkIdType id; + double d, y[3]; + weights->SetNumberOfTuples(numPts); + double *w = weights->GetPointer(0); + double KW, mass, density, volume; + + // Compute SPH coefficients. + for (i=0; iGetId(i); + this->DataSet->GetPoint(id,y); + d = sqrt( vtkMath::Distance2BetweenPoints(x,y) ); + + KW = this->ComputeFunctionWeight(d*this->DistNorm); + + if ( this->UseArraysForVolume ) + { + this->MassArray->GetTuple(id,&mass); + this->DensityArray->GetTuple(id,&density); + volume = mass /density; + } + else + { + volume = this->DefaultVolume; + } + + w[i] = this->DimNorm * KW * volume; + }//over all neighbor points - return 1; + return numPts; +} + +//---------------------------------------------------------------------------- +vtkIdType vtkSPHKernel:: +ComputeGradWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights, + vtkDoubleArray *gradWeights) +{ + vtkIdType numPts = pIds->GetNumberOfIds(); + int i; + vtkIdType id; + double d, y[3]; + weights->SetNumberOfTuples(numPts); + double *w = weights->GetPointer(0); + gradWeights->SetNumberOfTuples(numPts); + double *gw = gradWeights->GetPointer(0); + double KW, GW, volume=this->DefaultVolume; + + // Compute SPH coefficients for data and deriative data + for (i=0; iGetId(i); + this->DataSet->GetPoint(id,y); + d = sqrt( vtkMath::Distance2BetweenPoints(x,y) ); + + KW = this->ComputeFunctionWeight(d*this->DistNorm); + GW = this->ComputeGradientWeight(d*this->DistNorm); + + w[i] = this->DimNorm * KW * volume; + gw[i] = this->DimNorm * GW * volume; + }//over all neighbor points + + return numPts; } //---------------------------------------------------------------------------- @@ -58,4 +177,12 @@ void vtkSPHKernel::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); + os << indent << "Spatial Step: " << this->SpatialStep << "\n"; + os << indent << "Dimension: " << this->Dimension << "\n"; + os << indent << "Cutoff Factor: " << this->CutoffFactor << "\n"; + os << indent << "Sigma: " << this->Sigma << "\n"; + + os << indent << "Cutoff Array: " << this->CutoffArray<< "\n"; + os << indent << "Density Array: " << this->DensityArray << "\n"; + os << indent << "Mass Array: " << this->MassArray << "\n"; } diff --git a/Filters/Points/vtkSPHKernel.h b/Filters/Points/vtkSPHKernel.h index d0567a99ab6..e9a801dcdeb 100644 --- a/Filters/Points/vtkSPHKernel.h +++ b/Filters/Points/vtkSPHKernel.h @@ -12,19 +12,42 @@ PURPOSE. See the above copyright notice for more information. =========================================================================*/ -// .NAME vtkSPHKernel - a SPH interpolation kernel +// .NAME vtkSPHKernel - a family of SPH interpolation kernels // .SECTION Description -// vtkSPHKernel is an interpolation kernel that uses a spherical h -// closest point to a point to be interpolated. A single weight ise returned -// with value=1.0. +// vtkSPHKernel is an abstract superclass for smoothed-particle hydrodynamics +// interpolation kernels as described by D.J. Price (see full reference +// below). +// +// Note that the kernel operates over a volume in space defined by a radius +// at a sampling point. The kernel implicitly assumes that the particles +// making up the input data satisfies physical properties such as +// conservation of mass. Therefore subclasses of this kernel are not +// generally applicable for interpolation processes, and therefore operate in +// conjunction with the vthSPHInterpolator class. +// +// By default the kernel computes local particle volume from the spatial step^3. +// However, if both an optional mass and density arrays are provided then they are +// used to compute local volume. +// +// Also be default, the local neighborhood around a point to be interpolated is +// computed as the CutoffFactor * SpatialStep. (Note the CutoffFactor varies for +// each type of SPH kernel.) However, the user may specify a CutoffArray which +// enables variable cutoff distances per each point. // .SECTION Caveats -// In degenerate cases (where a point x is equidistance from more than one -// point) the kernel basis arbitrarily chooses one of the equidistant points. +// For more information see D.J. Price, Smoothed particle hydrodynamics and +// magnetohydrodynamics, J. Comput. Phys. 231:759-794, 2012. Especially +// equation 49. + +// .SECTION Acknowledgments +// The following work has been generously supported by Altair Engineering +// and FluiDyna GmbH. Please contact Steve Cosgrove or Milos Stanic for +// more information. // .SECTION See Also -// vtkInterpolationKernel vtkGaussianKernel vtkSPHKernel vtkShepardKernel +// vtkSPHKernel vtkSPHQuinticKernel vtkInterpolationKernel vtkGaussianKernel +// vtkShepardKernel vtkLinearKernel #ifndef vtkSPHKernel_h @@ -32,9 +55,12 @@ #include "vtkFiltersPointsModule.h" // For export macro #include "vtkInterpolationKernel.h" +#include "vtkStdString.h" // For vtkStdString ivars class vtkIdList; class vtkDoubleArray; +class vtkDataArray; +class vtkFloatArray; class VTKFILTERSPOINTS_EXPORT vtkSPHKernel : public vtkInterpolationKernel @@ -42,33 +68,106 @@ class VTKFILTERSPOINTS_EXPORT vtkSPHKernel : public vtkInterpolationKernel public: // Description: // Standard methods for instantiation, obtaining type information, and printing. - static vtkSPHKernel *New(); vtkTypeMacro(vtkSPHKernel,vtkInterpolationKernel); void PrintSelf(ostream& os, vtkIndent indent); // Description: - // Given a point x, determine the points around x which form an - // interpolation basis. The user must provide the vtkIdList pids, which will - // be dynamically resized as necessary. The method returns the number of - // points in the basis. Typically this method is called before - // ComputeWeights(). - virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds); + // The user defined intial particle spatial step. This is also referred to as + // the smoothing length. + vtkSetClampMacro(SpatialStep,double,0.0,VTK_FLOAT_MAX); + vtkGetMacro(SpatialStep,double); + + // Description: + // The domain dimension, default to 3. + vtkSetClampMacro(Dimension,int,1,3); + vtkGetMacro(Dimension,int); + + // Description: + // Return the cutoff factor. This is hard wired into the kernel (e.g., the + // vtkSPHQuinticKernel has a cutoff factor = 3.0). + vtkGetMacro(CutoffFactor,double); + + // Description: + // Specify the (optional) array defining a cutoff distance. If provided this + // distance is used to find the interpolating points within the local + // neighborbood. Otherwise the cutoff distance is defined as the cutoff + // factor times the spatial step size. + virtual void SetCutoffArray(vtkDataArray*); + vtkGetObjectMacro(CutoffArray,vtkDataArray); + + // Description: + // Specify the (optional) density array. Used with the mass array to + // compute local particle volumes. + virtual void SetDensityArray(vtkDataArray*); + vtkGetObjectMacro(DensityArray,vtkDataArray); + + // Description: + // Specify the (optional) mass array. Used with the density array to + // compute local particle volumes. + virtual void SetMassArray(vtkDataArray*); + vtkGetObjectMacro(MassArray,vtkDataArray); + + // Description: + // Produce the computational parameters for the kernel. Invoke this method + // after setting initial values like SpatialStep. + virtual void Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, + vtkPointData *pd); + + // Description: + // Given a point x (and optional associated ptId), determine the points + // around x which form an interpolation basis. The user must provide the + // vtkIdList pIds, which will be dynamically resized as necessary. The + // method returns the number of points in the basis. Typically this method + // is called before ComputeWeights(). Note that while ptId is optional in most + // cases, if a cutoff array is provided, then ptId must be provided. + virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds, vtkIdType ptId=0); // Description: // Given a point x, and a list of basis points pIds, compute interpolation - // weights associated with these basis points. Note that both the nearby - // basis points list pIds and the weights array are of length numPts, are - // provided by the caller of the method, and may be dynamically resized as - // necessary. Typically this method is called after ComputeBasis(), - // although advanced users can invoke ComputeWeights() and provide the - // interpolation basis points pIds directly. + // weights associated with these basis points. virtual vtkIdType ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights); + // Description: + // Given a point x, and a list of basis points pIds, compute interpolation + // weights, plus derivative weights, associated with these basis points. + virtual vtkIdType ComputeGradWeights(double x[3], vtkIdList *pIds, + vtkDoubleArray *weights, + vtkDoubleArray *gradWeights); + + // Description: + // Compute weighting factor given a normalized distance from a sample point. + virtual double ComputeFunctionWeight(const double d) = 0; + + // Description: + // Compute weighting factor for derivative quantities given a normalized + // distance from a sample point. + virtual double ComputeGradientWeight(const double d) = 0; + protected: vtkSPHKernel(); ~vtkSPHKernel(); + // Instance variables + double SpatialStep; //also known as smoothing length h + int Dimension; //sptial dimension of the kernel + + // Optional arrays aid in the interpolation process (computes volume) + vtkDataArray *CutoffArray; + vtkDataArray *DensityArray; + vtkDataArray *MassArray; + + // Internal data members generated during construction and initialization + // Terminology is spatial step = smoothing length h + double CutoffFactor; //varies across each kernel, e.g. cubic=2, quartic=2.5, quintic=3 + double Cutoff; //the spatial step * cutoff factor + double Sigma; //normalization constant + double DistNorm; //distance normalization factor 1/(spatial step) + double DimNorm; //dimensional normalization factor sigma/(spatial step)^Dimension + double DefaultVolume; //if mass and density arrays not specified, use this + bool UseCutoffArray; //if single component cutoff array provided + bool UseArraysForVolume; //if both mass and density arrays are present + private: vtkSPHKernel(const vtkSPHKernel&); // Not implemented. void operator=(const vtkSPHKernel&); // Not implemented. diff --git a/Filters/Points/vtkSPHQuarticKernel.cxx b/Filters/Points/vtkSPHQuarticKernel.cxx new file mode 100644 index 00000000000..48609a77db9 --- /dev/null +++ b/Filters/Points/vtkSPHQuarticKernel.cxx @@ -0,0 +1,73 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSPHQuarticKernel.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkSPHQuarticKernel.h" +#include "vtkAbstractPointLocator.h" +#include "vtkObjectFactory.h" +#include "vtkMath.h" + +vtkStandardNewMacro(vtkSPHQuarticKernel); + +//---------------------------------------------------------------------------- +vtkSPHQuarticKernel::vtkSPHQuarticKernel() +{ + this->CutoffFactor = 2.5; + + if ( this->Dimension == 1 ) + { + this->Sigma = 1.0/24.0; + } + else if ( this->Dimension == 2 ) + { + this->Sigma = 96.0/(1199.0*vtkMath::Pi()); + } + else //if ( this->Dimension == 3 ) + { + this->Sigma = 1.0/(20.0*vtkMath::Pi()); + } +} + +//---------------------------------------------------------------------------- +vtkSPHQuarticKernel::~vtkSPHQuarticKernel() +{ +} + +//---------------------------------------------------------------------------- +// At this point, the spatial step, the dimension of the kernel, and the cutoff +// factor should be known. +void vtkSPHQuarticKernel:: +Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, vtkPointData *attr) +{ + if ( this->Dimension == 1 ) + { + this->Sigma = 1.0 / 24.0; + } + else if ( this->Dimension == 2 ) + { + this->Sigma = 96.0 / (1199.0*vtkMath::Pi()); + } + else //if ( this->Dimension == 3 ) + { + this->Sigma = 1.0 / (20.0*vtkMath::Pi()); + } + + // Sigma must be set before vtkSPHKernel::Initialize is invoked + this->Superclass::Initialize(loc, ds, attr); +} + +//---------------------------------------------------------------------------- +void vtkSPHQuarticKernel::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); +} diff --git a/Filters/Points/vtkSPHQuarticKernel.h b/Filters/Points/vtkSPHQuarticKernel.h new file mode 100644 index 00000000000..b9ef7024b83 --- /dev/null +++ b/Filters/Points/vtkSPHQuarticKernel.h @@ -0,0 +1,92 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSPHQuarticKernel.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkSPHQuarticKernel - a quartic SPH interpolation kernel + +// .SECTION Description +// vtkSPHQuarticKernel is an smooth particle hydrodynamics interpolation kernel as +// described by D.J. Price. This is a quartic formulation. +// +// .SECTION Caveats +// For more information see D.J. Price, Smoothed particle hydrodynamics and +// magnetohydrodynamics, J. Comput. Phys. 231:759-794, 2012. Especially +// equation 49. + +// .SECTION Acknowledgments +// The following work has been generously supported by Altair Engineering +// and FluiDyna GmbH. Please contact Steve Cosgrove or Milos Stanic for +// more information. + +// .SECTION See Also +// vtkSPHKernel vtkSPHInterpolator + + +#ifndef vtkSPHQuarticKernel_h +#define vtkSPHQuarticKernel_h + +#include "vtkFiltersPointsModule.h" // For export macro +#include "vtkSPHKernel.h" +#include // For std::min() + +class vtkIdList; +class vtkDoubleArray; + + +class VTKFILTERSPOINTS_EXPORT vtkSPHQuarticKernel : public vtkSPHKernel +{ +public: + // Description: + // Standard methods for instantiation, obtaining type information, and printing. + static vtkSPHQuarticKernel *New(); + vtkTypeMacro(vtkSPHQuarticKernel,vtkSPHKernel); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Produce the computational parameters for the kernel. Invoke this method + // after setting initial values like SpatialStep. + virtual void Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, + vtkPointData *pd); + + // Description: + // Compute weighting factor given a normalized distance from a sample point. + virtual double ComputeFunctionWeight(const double d) + { + double tmp1 = 2.5 - std::min(d,2.5); + double tmp2 = 1.5 - std::min(d,1.5); + double tmp3 = 0.5 - std::min(d,0.5); + return (tmp1*tmp1*tmp1*tmp1 - 5.0*tmp2*tmp2*tmp2*tmp2 + + 10.0*tmp3*tmp3*tmp3*tmp3); + } + + // Description: + // Compute weighting factor for derivative quantities given a normalized + // distance from a sample point. + virtual double ComputeGradientWeight(const double d) + { + double tmp1 = 2.5 - std::min(d,2.5); + double tmp2 = 1.5 - std::min(d,1.5); + double tmp3 = 0.5 - std::min(d,0.5); + return (tmp1*tmp1*tmp1 - 5.0*tmp2*tmp2*tmp2 + 10.0*tmp3*tmp3*tmp3); + } + +protected: + vtkSPHQuarticKernel(); + ~vtkSPHQuarticKernel(); + +private: + vtkSPHQuarticKernel(const vtkSPHQuarticKernel&); // Not implemented. + void operator=(const vtkSPHQuarticKernel&); // Not implemented. +}; + +#endif diff --git a/Filters/Points/vtkSPHQuinticKernel.cxx b/Filters/Points/vtkSPHQuinticKernel.cxx new file mode 100644 index 00000000000..e289f5443bd --- /dev/null +++ b/Filters/Points/vtkSPHQuinticKernel.cxx @@ -0,0 +1,60 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSPHQuinticKernel.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkSPHQuinticKernel.h" +#include "vtkAbstractPointLocator.h" +#include "vtkObjectFactory.h" +#include "vtkMath.h" + +vtkStandardNewMacro(vtkSPHQuinticKernel); + +//---------------------------------------------------------------------------- +vtkSPHQuinticKernel::vtkSPHQuinticKernel() +{ + this->CutoffFactor = 3.0; +} + +//---------------------------------------------------------------------------- +vtkSPHQuinticKernel::~vtkSPHQuinticKernel() +{ +} + +//---------------------------------------------------------------------------- +// At this point, the spatial step, the dimension of the kernel, and the cutoff +// factor should be known. +void vtkSPHQuinticKernel:: +Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, vtkPointData *attr) +{ + if ( this->Dimension == 1 ) + { + this->Sigma = 1.0 / 120.0; + } + else if ( this->Dimension == 2 ) + { + this->Sigma = 7.0 / (478.0*vtkMath::Pi()); + } + else //if ( this->Dimension == 3 ) + { + this->Sigma = 1.0 / (120.0*vtkMath::Pi()); + } + + // Sigma must be set before vtkSPHKernel::Initialize is invoked + this->Superclass::Initialize(loc, ds, attr); +} + +//---------------------------------------------------------------------------- +void vtkSPHQuinticKernel::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); +} diff --git a/Filters/Points/vtkSPHQuinticKernel.h b/Filters/Points/vtkSPHQuinticKernel.h new file mode 100644 index 00000000000..386671f4198 --- /dev/null +++ b/Filters/Points/vtkSPHQuinticKernel.h @@ -0,0 +1,93 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSPHQuinticKernel.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkSPHQuinticKernel - a quintic SPH interpolation kernel + +// .SECTION Description +// vtkSPHQuinticKernel is an smooth particle hydrodynamics interpolation kernel as +// described by D.J. Price. This is a quintic formulation. +// +// .SECTION Caveats +// FOr more information see D.J. Price, Smoothed particle hydrodynamics and +// magnetohydrodynamics, J. Comput. Phys. 231:759-794, 2012. Especially +// equation 49. + +// .SECTION Acknowledgments +// The following work has been generously supported by Altair Engineering +// and FluiDyna GmbH. Please contact Steve Cosgrove or Milos Stanic for +// more information. + +// .SECTION See Also +// vtkSPHKernel vtkSPHInterpolator + + +#ifndef vtkSPHQuinticKernel_h +#define vtkSPHQuinticKernel_h + +#include "vtkFiltersPointsModule.h" // For export macro +#include "vtkSPHKernel.h" +#include // For std::min() + +class vtkIdList; +class vtkDoubleArray; + + +class VTKFILTERSPOINTS_EXPORT vtkSPHQuinticKernel : public vtkSPHKernel +{ +public: + // Description: + // Standard methods for instantiation, obtaining type information, and printing. + static vtkSPHQuinticKernel *New(); + vtkTypeMacro(vtkSPHQuinticKernel,vtkSPHKernel); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Produce the computational parameters for the kernel. Invoke this method + // after setting initial values like SpatialStep. + virtual void Initialize(vtkAbstractPointLocator *loc, vtkDataSet *ds, + vtkPointData *pd); + + // Description: + // Compute weighting factor given a normalized distance from a sample point. + virtual double ComputeFunctionWeight(const double d) + { + double tmp1 = 3.0 - std::min(d,3.0); + double tmp2 = 2.0 - std::min(d,2.0); + double tmp3 = 1.0 - std::min(d,1.0); + return (tmp1*tmp1*tmp1*tmp1*tmp1 - 6.0*tmp2*tmp2*tmp2*tmp2*tmp2 + + 15.0*tmp3*tmp3*tmp3*tmp3*tmp3); + } + + // Description: + // Compute weighting factor for derivative quantities given a normalized + // distance from a sample point. + virtual double ComputeGradientWeight(const double d) + { + double tmp1 = 3.0 - std::min(d,3.0); + double tmp2 = 2.0 - std::min(d,2.0); + double tmp3 = 1.0 - std::min(d,1.0); + return (tmp1*tmp1*tmp1*tmp1 - 6.0*tmp2*tmp2*tmp2*tmp2 + + 15.0*tmp3*tmp3*tmp3*tmp3); + } + +protected: + vtkSPHQuinticKernel(); + ~vtkSPHQuinticKernel(); + +private: + vtkSPHQuinticKernel(const vtkSPHQuinticKernel&); // Not implemented. + void operator=(const vtkSPHQuinticKernel&); // Not implemented. +}; + +#endif diff --git a/Filters/Points/vtkShepardKernel.cxx b/Filters/Points/vtkShepardKernel.cxx index e0692d22135..1dd74c5f193 100644 --- a/Filters/Points/vtkShepardKernel.cxx +++ b/Filters/Points/vtkShepardKernel.cxx @@ -20,13 +20,13 @@ #include "vtkDataSet.h" #include "vtkPointData.h" #include "vtkMath.h" +#include "vtkMathUtilities.h" vtkStandardNewMacro(vtkShepardKernel); //---------------------------------------------------------------------------- vtkShepardKernel::vtkShepardKernel() { - this->Radius = 1.0; this->PowerParameter = 2.0; } @@ -39,21 +39,15 @@ vtkShepardKernel::~vtkShepardKernel() //---------------------------------------------------------------------------- vtkIdType vtkShepardKernel:: -ComputeBasis(double x[3], vtkIdList *pIds) -{ - this->Locator->FindPointsWithinRadius(this->Radius, x, pIds); - return pIds->GetNumberOfIds(); -} - -//---------------------------------------------------------------------------- -vtkIdType vtkShepardKernel:: -ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights) +ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *prob, + vtkDoubleArray *weights) { vtkIdType numPts = pIds->GetNumberOfIds(); int i; vtkIdType id; - double d, y[3], sum = 0.0; + double d, y[3], sum=0.0; weights->SetNumberOfTuples(numPts); + double *p = (prob ? prob->GetPointer(0) : NULL); double *w = weights->GetPointer(0); for (i=0; iPowerParameter); } - if ( d == 0.0 ) //precise hit on existing point + if ( vtkMathUtilities::FuzzyCompare(d, 0.0, std::numeric_limits::epsilon()*256.0 )) //precise hit on existing point { pIds->SetNumberOfIds(1); pIds->SetId(0,id); @@ -78,15 +72,18 @@ ComputeWeights(double x[3], vtkIdList *pIds, vtkDoubleArray *weights) } else { - w[i] = 1.0 / d; + w[i] = (p ? p[i]/d : 1.0/d); //take into account probability if provided sum += w[i]; } }//over all points // Normalize - for (i=0; iNormalizeWeights && sum != 0.0 ) { - w[i] /= sum; + for (i=0; iSuperclass::PrintSelf(os,indent); - os << indent << "Radius: " << this->Radius << "\n"; os << indent << "Power Parameter: " - << this->PowerParameter << "\n"; + << this->GetPowerParameter() << "\n"; } diff --git a/Filters/Points/vtkShepardKernel.h b/Filters/Points/vtkShepardKernel.h index 04ea1802adc..5f4c369fd6a 100644 --- a/Filters/Points/vtkShepardKernel.h +++ b/Filters/Points/vtkShepardKernel.h @@ -26,54 +26,47 @@ // point takes on the values associated with p. // .SECTION See Also -// vtkPointInterpolator vtkInterpolationKernel vtkGaussianKernel vtkSPHKernel -// vtkShepardKernel +// vtkPointInterpolator vtkPointInterpolator2D vtkInterpolationKernel +// vtkGaussianKernel vtkSPHKernel vtkShepardKernel #ifndef vtkShepardKernel_h #define vtkShepardKernel_h #include "vtkFiltersPointsModule.h" // For export macro -#include "vtkInterpolationKernel.h" +#include "vtkGeneralizedKernel.h" class vtkIdList; class vtkDoubleArray; -class VTKFILTERSPOINTS_EXPORT vtkShepardKernel : public vtkInterpolationKernel +class VTKFILTERSPOINTS_EXPORT vtkShepardKernel : public vtkGeneralizedKernel { public: // Description: // Standard methods for instantiation, obtaining type information, and printing. static vtkShepardKernel *New(); - vtkTypeMacro(vtkShepardKernel,vtkInterpolationKernel); + vtkTypeMacro(vtkShepardKernel,vtkGeneralizedKernel); void PrintSelf(ostream& os, vtkIndent indent); - // Description: - // Given a point x, determine the points around x which form an - // interpolation basis. The user must provide the vtkIdList pids, which will - // be dynamically resized as necessary. The method returns the number of - // points in the basis. Typically this method is called before - // ComputeWeights(). - virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds); + // Re-use any superclass signatures that we don't override. + using vtkGeneralizedKernel::ComputeWeights; // Description: - // Given a point x, and a list of basis points pIds, compute interpolation - // weights associated with these basis points. Note that both the nearby - // basis points list pIds and the weights array are of length numPts, are - // provided by the caller of the method, and may be dynamically resized as - // necessary. Typically this method is called after ComputeBasis(), - // although advanced users can invoke ComputeWeights() and provide the - // interpolation basis points pIds directly. + // Given a point x, a list of basis points pIds, and a probability + // weighting function prob, compute interpolation weights associated with + // these basis points. Note that basis points list pIds, the probability + // weighting prob, and the weights array are provided by the caller of the + // method, and may be dynamically resized as necessary. The method returns + // the number of weights (pIds may be resized in some cases). Typically + // this method is called after ComputeBasis(), although advanced users can + // invoke ComputeWeights() and provide the interpolation basis points pIds + // directly. The probably weighting prob are numbers 0<=prob<=1 which are + // multiplied against the interpolation weights before normalization. They + // are estimates of local confidence of weights. The prob may be NULL in + // which all probabilities are considered =1. virtual vtkIdType ComputeWeights(double x[3], vtkIdList *pIds, - vtkDoubleArray *weights); - - // Description: - // Specify the radius of the kernel. Points within this radius will be - // used for interpolation. If no point is found, then the closest point - // will be used. - vtkSetClampMacro(Radius,double,0.0,VTK_FLOAT_MAX); - vtkGetMacro(Radius,double); + vtkDoubleArray *prob, vtkDoubleArray *weights); // Description: // Set / Get the power parameter p. By default p=2. Values (which must be @@ -85,7 +78,7 @@ class VTKFILTERSPOINTS_EXPORT vtkShepardKernel : public vtkInterpolationKernel vtkShepardKernel(); ~vtkShepardKernel(); - double Radius; + // The exponent of the weights, =2 by default (l2 norm) double PowerParameter; private: diff --git a/Filters/Points/vtkVoronoiKernel.cxx b/Filters/Points/vtkVoronoiKernel.cxx index ea58620eb70..3153089c23d 100644 --- a/Filters/Points/vtkVoronoiKernel.cxx +++ b/Filters/Points/vtkVoronoiKernel.cxx @@ -33,7 +33,7 @@ vtkVoronoiKernel::~vtkVoronoiKernel() //---------------------------------------------------------------------------- vtkIdType vtkVoronoiKernel:: -ComputeBasis(double x[3], vtkIdList *pIds) +ComputeBasis(double x[3], vtkIdList *pIds, vtkIdType) { pIds->SetNumberOfIds(1); vtkIdType pId = this->Locator->FindClosestPoint(x); diff --git a/Filters/Points/vtkVoronoiKernel.h b/Filters/Points/vtkVoronoiKernel.h index 0bc1b84d65e..cabc8d93bfe 100644 --- a/Filters/Points/vtkVoronoiKernel.h +++ b/Filters/Points/vtkVoronoiKernel.h @@ -24,7 +24,7 @@ // point) the kernel basis arbitrarily chooses one of the equidistant points. // .SECTION See Also -// vtkInterpolationKernel vtkGaussianKernel vtkSPHKernel vtkShepardKernel +// vtkInterpolationKernel vtkGeneralizedKernel vtkProbabilisticVoronoiKernel #ifndef vtkVoronoiKernel_h @@ -47,12 +47,12 @@ class VTKFILTERSPOINTS_EXPORT vtkVoronoiKernel : public vtkInterpolationKernel void PrintSelf(ostream& os, vtkIndent indent); // Description: - // Given a point x, determine the points around x which form an - // interpolation basis. The user must provide the vtkIdList pids, which will - // be dynamically resized as necessary. The method returns the number of - // points in the basis. Typically this method is called before - // ComputeWeights(). - virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds); + // Given a point x (and optional associated ptId), determine the points + // around x which form an interpolation basis. The user must provide the + // vtkIdList pIds, which will be dynamically resized as necessary. The + // method returns the number of points in the basis. Typically this method + // is called before ComputeWeights(). + virtual vtkIdType ComputeBasis(double x[3], vtkIdList *pIds, vtkIdType ptId=0); // Description: // Given a point x, and a list of basis points pIds, compute interpolation diff --git a/Filters/Programmable/vtkProgrammableAttributeDataFilter.h b/Filters/Programmable/vtkProgrammableAttributeDataFilter.h index b563c81a520..ad70ea177cb 100644 --- a/Filters/Programmable/vtkProgrammableAttributeDataFilter.h +++ b/Filters/Programmable/vtkProgrammableAttributeDataFilter.h @@ -124,7 +124,7 @@ class VTKFILTERSPROGRAMMABLE_EXPORT vtkProgrammableAttributeDataFilter : public ProgrammableMethodCallbackType ExecuteMethodArgDelete; void *ExecuteMethodArg; - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; private: // hide the superclass' AddInput() from the user and the compiler diff --git a/Filters/ReebGraph/Testing/Cxx/TestReebGraph.cxx b/Filters/ReebGraph/Testing/Cxx/TestReebGraph.cxx index 0f099a5a373..3e81500ff0b 100644 --- a/Filters/ReebGraph/Testing/Cxx/TestReebGraph.cxx +++ b/Filters/ReebGraph/Testing/Cxx/TestReebGraph.cxx @@ -4322,11 +4322,11 @@ double AreaSimplificationMetric::ComputeMetric(vtkDataSet *mesh, int DisplayReebGraph(vtkReebGraph *g) { - vtkDataArray *vertexInfo = vtkDataArray::SafeDownCast( + vtkDataArray *vertexInfo = vtkArrayDownCast( g->GetVertexData()->GetAbstractArray("Vertex Ids")); if(!vertexInfo) return 1; - vtkVariantArray *edgeInfo = vtkVariantArray::SafeDownCast( + vtkVariantArray *edgeInfo = vtkArrayDownCast( g->GetEdgeData()->GetAbstractArray("Vertex Ids")); if(!edgeInfo) return 2; @@ -4399,17 +4399,17 @@ int DisplaySurfaceSkeleton(vtkPolyData *surfaceMesh, vtkTable *skeleton) for(int i = 0; i < skeleton->GetNumberOfColumns(); i++) { - vtkDoubleArray *arc = vtkDoubleArray::SafeDownCast(skeleton->GetColumn(i)); + vtkDoubleArray *arc = vtkArrayDownCast(skeleton->GetColumn(i)); // critical point at the origin of the arc - arc->GetTupleValue(0, point); + arc->GetTypedTuple(0, point); nodeActors[2*i] = vtkActor::New(); nodeActors[2*i]->SetMapper(sphereMapper); nodeActors[2*i]->GetProperty()->SetColor(0, 0, 1); nodeActors[2*i]->SetPosition(point); renderer->AddActor(nodeActors[2*i]); - arc->GetTupleValue(arc->GetNumberOfTuples() - 1, point); + arc->GetTypedTuple(arc->GetNumberOfTuples() - 1, point); nodeActors[2*i + 1] = vtkActor::New(); nodeActors[2*i + 1]->SetMapper(sphereMapper); nodeActors[2*i + 1]->GetProperty()->SetColor(0, 0, 1); @@ -4420,7 +4420,7 @@ int DisplaySurfaceSkeleton(vtkPolyData *surfaceMesh, vtkTable *skeleton) int initialSampleId = sampleId; for(int j = 0; j < arc->GetNumberOfTuples(); j++) { - arc->GetTupleValue(j, point); + arc->GetTypedTuple(j, point); skeletonSamples->SetPoint(sampleId, point); sampleId++; } @@ -4522,17 +4522,17 @@ int DisplayVolumeSkeleton(vtkUnstructuredGrid* vtkNotUsed(volumeMesh), vtkTable for(int i = 0; i < skeleton->GetNumberOfColumns(); i++) { - vtkDoubleArray *arc = vtkDoubleArray::SafeDownCast(skeleton->GetColumn(i)); + vtkDoubleArray *arc = vtkArrayDownCast(skeleton->GetColumn(i)); // critical point at the origin of the arc - arc->GetTupleValue(0, point); + arc->GetTypedTuple(0, point); nodeActors[2*i] = vtkActor::New(); nodeActors[2*i]->SetMapper(sphereMapper); nodeActors[2*i]->GetProperty()->SetColor(0, 0, 1); nodeActors[2*i]->SetPosition(point); renderer->AddActor(nodeActors[2*i]); - arc->GetTupleValue(arc->GetNumberOfTuples() - 1, point); + arc->GetTypedTuple(arc->GetNumberOfTuples() - 1, point); nodeActors[2*i + 1] = vtkActor::New(); nodeActors[2*i + 1]->SetMapper(sphereMapper); nodeActors[2*i + 1]->GetProperty()->SetColor(0, 0, 1); @@ -4543,7 +4543,7 @@ int DisplayVolumeSkeleton(vtkUnstructuredGrid* vtkNotUsed(volumeMesh), vtkTable int initialSampleId = sampleId; for(int j = 0; j < arc->GetNumberOfTuples(); j++) { - arc->GetTupleValue(j, point); + arc->GetTypedTuple(j, point); skeletonSamples->SetPoint(sampleId, point); sampleId++; } diff --git a/Filters/ReebGraph/vtkReebGraphSurfaceSkeletonFilter.cxx b/Filters/ReebGraph/vtkReebGraphSurfaceSkeletonFilter.cxx index 6e69d3287c1..47f1aa2e826 100644 --- a/Filters/ReebGraph/vtkReebGraphSurfaceSkeletonFilter.cxx +++ b/Filters/ReebGraph/vtkReebGraphSurfaceSkeletonFilter.cxx @@ -113,13 +113,13 @@ int vtkReebGraphSurfaceSkeletonFilter::RequestData(vtkInformation* vtkNotUsed(re { // Retrieve the information regarding the critical noes. - vtkDataArray *vertexInfo = vtkDataArray::SafeDownCast( + vtkDataArray *vertexInfo = vtkArrayDownCast( inputGraph->GetVertexData()->GetAbstractArray("Vertex Ids")); if(!vertexInfo) // invalid Reeb graph (no information associated to the vertices) return 0; - vtkVariantArray *edgeInfo = vtkVariantArray::SafeDownCast( + vtkVariantArray *edgeInfo = vtkArrayDownCast( inputGraph->GetEdgeData()->GetAbstractArray("Vertex Ids")); if(!edgeInfo) // invalid Reeb graph (no information associated to the edges) @@ -198,10 +198,10 @@ int vtkReebGraphSurfaceSkeletonFilter::RequestData(vtkInformation* vtkNotUsed(re points[k] = (double *) malloc(sizeof(double)*3); inputMesh->GetPoint(vertices[k], points[k]); meshToSubMeshMap[vertices[k]] = - subCoordinates->InsertNextTupleValue(points[k]); + subCoordinates->InsertNextTypedTuple(points[k]); double scalarFieldValue = scalarField->GetComponent(vertices[k], 0); - subField->InsertNextTupleValue(&scalarFieldValue); + subField->InsertNextTypedTuple(&scalarFieldValue); visitedVertices[vertices[k]] = true; free(points[k]); } @@ -371,7 +371,7 @@ int vtkReebGraphSurfaceSkeletonFilter::RequestData(vtkInformation* vtkNotUsed(re double *point = (double *) malloc(sizeof(double)*3); for(int k = 0; k < 3; k++) point[k] = skeleton[i][j][k]; - outputArc->InsertNextTupleValue(point); + outputArc->InsertNextTypedTuple(point); free(point); } output->AddColumn(outputArc); diff --git a/Filters/ReebGraph/vtkReebGraphToJoinSplitTreeFilter.cxx b/Filters/ReebGraph/vtkReebGraphToJoinSplitTreeFilter.cxx index 88dbf983c50..ec476f6c286 100644 --- a/Filters/ReebGraph/vtkReebGraphToJoinSplitTreeFilter.cxx +++ b/Filters/ReebGraph/vtkReebGraphToJoinSplitTreeFilter.cxx @@ -123,13 +123,13 @@ int vtkReebGraphToJoinSplitTreeFilter::RequestData(vtkInformation* vtkNotUsed(re output->DeepCopy(inputGraph); // Retrieve the information regarding the critical nodes - vtkDataArray *vertexInfo = vtkDataArray::SafeDownCast( + vtkDataArray *vertexInfo = vtkArrayDownCast( inputGraph->GetVertexData()->GetAbstractArray("Vertex Ids")); if(!vertexInfo) // invalid Reeb graph (no information associated to the vertices) return 0; - vtkVariantArray *edgeInfo = vtkVariantArray::SafeDownCast( + vtkVariantArray *edgeInfo = vtkArrayDownCast( inputGraph->GetEdgeData()->GetAbstractArray("Vertex Ids")); if(!edgeInfo) // invalid Reeb graph (no information associated to the edges) @@ -236,7 +236,7 @@ int vtkReebGraphToJoinSplitTreeFilter::RequestData(vtkInformation* vtkNotUsed(re std::vector > halfStars(vertexList.size()); - vertexInfo = vtkDataArray::SafeDownCast( + vertexInfo = vtkArrayDownCast( unCompressedGraph->GetVertexData()->GetAbstractArray("Vertex Ids")); eIt = vtkEdgeListIterator::New(); unCompressedGraph->GetEdges(eIt); diff --git a/Filters/ReebGraph/vtkReebGraphVolumeSkeletonFilter.cxx b/Filters/ReebGraph/vtkReebGraphVolumeSkeletonFilter.cxx index 9d0a4a78114..04e736d23b3 100644 --- a/Filters/ReebGraph/vtkReebGraphVolumeSkeletonFilter.cxx +++ b/Filters/ReebGraph/vtkReebGraphVolumeSkeletonFilter.cxx @@ -116,13 +116,13 @@ int vtkReebGraphVolumeSkeletonFilter::RequestData(vtkInformation* vtkNotUsed(req { // Retrieve the information regarding the critical noes. - vtkDataArray *vertexInfo = vtkDataArray::SafeDownCast( + vtkDataArray *vertexInfo = vtkArrayDownCast( inputGraph->GetVertexData()->GetAbstractArray("Vertex Ids")); if(!vertexInfo) // invalid Reeb graph (no information associated to the vertices) return 0; - vtkVariantArray *edgeInfo = vtkVariantArray::SafeDownCast( + vtkVariantArray *edgeInfo = vtkArrayDownCast( inputGraph->GetEdgeData()->GetAbstractArray("Vertex Ids")); if(!edgeInfo) // invalid Reeb graph (no information associated to the edges) @@ -205,10 +205,10 @@ int vtkReebGraphVolumeSkeletonFilter::RequestData(vtkInformation* vtkNotUsed(req // add also its scalar value to the subField inputMesh->GetPoint(vertexId, point); meshToSubMeshMap[vertexId] = - subCoordinates->InsertNextTupleValue(point); + subCoordinates->InsertNextTypedTuple(point); double scalarFieldValue = scalarField->GetComponent(vertexId, 0); - subField->InsertNextTupleValue(&scalarFieldValue); + subField->InsertNextTypedTuple(&scalarFieldValue); visitedVertices[vertexId] = true; } } @@ -368,7 +368,7 @@ int vtkReebGraphVolumeSkeletonFilter::RequestData(vtkInformation* vtkNotUsed(req { for(int k = 0; k < 3; k++) point[k] = skeleton[i][j][k]; - outputArc->InsertNextTupleValue(point); + outputArc->InsertNextTypedTuple(point); } output->AddColumn(outputArc); outputArc->Delete(); diff --git a/Filters/SMP/Testing/Cxx/TestSMPWarp.cxx b/Filters/SMP/Testing/Cxx/TestSMPWarp.cxx index e703cf85b2d..d54dd284252 100644 --- a/Filters/SMP/Testing/Cxx/TestSMPWarp.cxx +++ b/Filters/SMP/Testing/Cxx/TestSMPWarp.cxx @@ -119,7 +119,7 @@ class vtkBoundsFunctor float* fptr = pts->GetPointer(3*begin); for (vtkIdType i=begin; iGetTupleValue(i, x); + //pts->GetTypedTuple(i, x); x = fptr; lbounds[0] = x[0] < lbounds[0] ? x[0] : lbounds[0]; lbounds[1] = x[0] > lbounds[1] ? x[0] : lbounds[1]; @@ -152,7 +152,7 @@ class vtkSetFunctor #if 0 pts->SetTuple(counter++, pt); #else - pts->SetTupleValue(counter++, pt); + pts->SetTypedTuple(counter++, pt); // pts->SetValue(counter++, i*spacing); // pts->SetValue(counter++, j*spacing); // pts->SetValue(counter++, k*spacing); diff --git a/Filters/SMP/vtkSMPWarpVector.cxx b/Filters/SMP/vtkSMPWarpVector.cxx index d0d83065b59..3940ec5b90c 100644 --- a/Filters/SMP/vtkSMPWarpVector.cxx +++ b/Filters/SMP/vtkSMPWarpVector.cxx @@ -24,7 +24,6 @@ #include "vtkPointData.h" #include "vtkPointSet.h" #include "vtkPoints.h" -#include "vtkTypeTemplate.h" // For vtkTypeTemplate //---------------------------------------------------------------------------- diff --git a/Filters/SMP/vtkThreadedSynchronizedTemplates3D.h b/Filters/SMP/vtkThreadedSynchronizedTemplates3D.h index 482b44d543a..e2bd0b962e2 100644 --- a/Filters/SMP/vtkThreadedSynchronizedTemplates3D.h +++ b/Filters/SMP/vtkThreadedSynchronizedTemplates3D.h @@ -165,11 +165,8 @@ class VTKFILTERSSMP_EXPORT vtkThreadedSynchronizedTemplates3D : public vtkMultiB // template table. -//BTX extern int VTKFILTERSSMP_EXPORT VTK_TSYNCHRONIZED_TEMPLATES_3D_TABLE_1[]; extern int VTKFILTERSSMP_EXPORT VTK_TSYNCHRONIZED_TEMPLATES_3D_TABLE_2[]; -//ETX - #endif diff --git a/Filters/SMP/vtkThreadedSynchronizedTemplatesCutter3D.cxx b/Filters/SMP/vtkThreadedSynchronizedTemplatesCutter3D.cxx index d11c4fb164a..fa588030051 100644 --- a/Filters/SMP/vtkThreadedSynchronizedTemplatesCutter3D.cxx +++ b/Filters/SMP/vtkThreadedSynchronizedTemplatesCutter3D.cxx @@ -179,30 +179,31 @@ void ContourImage(vtkThreadedSynchronizedTemplatesCutter3D *self, int *exExt, bool outputTriangles) { int *inExt = data->GetExtent(); - int xdim = exExt[1] - exExt[0] + 1; - int ydim = exExt[3] - exExt[2] + 1; + vtkIdType xdim = exExt[1] - exExt[0] + 1; + vtkIdType ydim = exExt[3] - exExt[2] + 1; double *values = self->GetValues(); int numContours = self->GetNumberOfContours(); T *inPtrX, *inPtrY, *inPtrZ; T *s0, *s1, *s2, *s3; int xMin, xMax, yMin, yMax, zMin, zMax; - int xInc, yInc, zInc; + vtkIdType xInc, yInc, zInc; int xIncFunc, yIncFunc, zIncFunc, scalarZIncFunc; double *origin = data->GetOrigin(); double *spacing = data->GetSpacing(); - int *isect1Ptr, *isect2Ptr; + vtkIdType *isect1Ptr, *isect2Ptr; double y, z, t; int i, j, k; - int zstep, yisectstep; - int offsets[12]; + vtkIdType zstep, yisectstep; + vtkIdType offsets[12]; int *tablePtr; - int idx, vidx; + vtkIdType idx; + int vidx; double x[3], xz[3]; - int v0, v1, v2, v3; + vtkIdType v0, v1, v2, v3; vtkIdType ptIds[3]; double value; // We need to know the edgePointId's for interpolating attributes. - int edgePtId, inCellId, outCellId; + vtkIdType edgePtId, inCellId, outCellId; vtkPointData *inPD = data->GetPointData(); vtkCellData *inCD = data->GetCellData(); vtkPointData *outPD = output->GetPointData(); @@ -270,7 +271,7 @@ void ContourImage(vtkThreadedSynchronizedTemplatesCutter3D *self, int *exExt, PointIndexToPosition(data, exExt[1], exExt[3], exExt[5], bboxCorners[7]); // allocate storage array - int *isect1 = new int [xdim*ydim*3*2]; + vtkIdType *isect1 = new vtkIdType [xdim*ydim*3*2]; // set impossible edges to -1 for (i = 0; i < ydim; i++) { diff --git a/Filters/Selection/vtkCellDistanceSelector.cxx b/Filters/Selection/vtkCellDistanceSelector.cxx index 907bce58614..a284a018568 100644 --- a/Filters/Selection/vtkCellDistanceSelector.cxx +++ b/Filters/Selection/vtkCellDistanceSelector.cxx @@ -133,7 +133,7 @@ int vtkCellDistanceSelector::RequestData( vtkInformation* vtkNotUsed( request ), vtkSelectionNode* selectionNode = *selNodeIt; ++ selNodeIt; - vtkDataArray* selectionList = vtkDataArray::SafeDownCast( selectionNode->GetSelectionList() ); + vtkDataArray* selectionList = vtkArrayDownCast( selectionNode->GetSelectionList() ); vtkIdType numSeeds = selectionList->GetNumberOfTuples(); if ( numSeeds > 0 && selectionNode->GetContentType() == vtkSelectionNode::INDICES diff --git a/Filters/Sources/vtkArcSource.cxx b/Filters/Sources/vtkArcSource.cxx index 2a5912c4003..94c8f769b54 100644 --- a/Filters/Sources/vtkArcSource.cxx +++ b/Filters/Sources/vtkArcSource.cxx @@ -60,13 +60,15 @@ vtkArcSource::vtkArcSource(int res) // Default arc is a quarter-circle this->Angle = 90.; - // Default resolution + // Ensure resolution (number of line segments to approximate the arc) + // is at least 1 this->Resolution = (res < 1 ? 1 : res); - // Default resolution + // By default use the shortest angular sector + // rather than its complement (a.k.a. negative coterminal) this->Negative = false; - // By default use the original API + // By default use the original API (endpoints + center) this->UseNormalAndAngle = false; this->OutputPointsPrecision = SINGLE_PRECISION; @@ -110,7 +112,7 @@ int vtkArcSource::RequestData( vtkInformation* vtkNotUsed(request), = vtkPolyData::SafeDownCast( outInfo->Get( vtkDataObject::DATA_OBJECT() ) ); // Calculate vector from origin to first point - + // Normal and angle are either specified (consistent API) or calculated (original API) double angle = 0.0; double radius = 0.5; @@ -129,7 +131,7 @@ int vtkArcSource::RequestData( vtkInformation* vtkNotUsed(request), // Calculate perpendicular vector with normal which is specified with this API vtkMath::Cross( this->Normal, this->PolarVector, perpendicular ); - + // Calculate radius radius = vtkMath::Normalize( v1 ); } @@ -144,7 +146,7 @@ int vtkArcSource::RequestData( vtkInformation* vtkNotUsed(request), double v2[3] = { this->Point2[0] - this->Center[0], this->Point2[1] - this->Center[1], this->Point2[2] - this->Center[2] }; - + double normal[3]; vtkMath::Cross( v1, v2, normal ); vtkMath::Cross( normal, v1, perpendicular ); @@ -159,7 +161,7 @@ int vtkArcSource::RequestData( vtkInformation* vtkNotUsed(request), // Calcute radius radius = vtkMath::Normalize( v1 ); } // else - + // Calcute angle increment double angleInc = angle / this->Resolution; diff --git a/Filters/Sources/vtkArcSource.h b/Filters/Sources/vtkArcSource.h index 38329383ae1..6ab58624820 100644 --- a/Filters/Sources/vtkArcSource.h +++ b/Filters/Sources/vtkArcSource.h @@ -18,8 +18,9 @@ // endpoints and a center. The number of segments composing the polyline // is controlled by setting the object resolution. // Alternatively, one can use a better API (that does not allow for -// inconsistent nor ambiguous inputs), using a starting point (polar vector), -// a normal to the plane of the arc, and an angle defining the arc length. +// inconsistent nor ambiguous inputs), using a starting point (polar vector, +// measured from the arc's center), a normal to the plane of the arc, +// and an angle defining the arc length. // Since the default API remains the original one, in order to use // the improved API, one must switch the UseNormalAndAngle flag to TRUE. @@ -91,7 +92,7 @@ class VTKFILTERSSOURCES_EXPORT vtkArcSource : public vtkPolyDataAlgorithm // By default the arc spans the shortest angular sector point1 and point2. // By setting this to true, the longest angular sector is used instead // (i.e. the negative coterminal angle to the shortest one). - // Note: false by default. + // Note: This is only used when UseNormalAndAngle is OFF. False by default. vtkSetMacro(Negative, bool); vtkGetMacro(Negative, bool); vtkBooleanMacro(Negative, bool); diff --git a/Filters/Sources/vtkDiagonalMatrixSource.h b/Filters/Sources/vtkDiagonalMatrixSource.h index 4b0408a2d49..0355df0ecc9 100644 --- a/Filters/Sources/vtkDiagonalMatrixSource.h +++ b/Filters/Sources/vtkDiagonalMatrixSource.h @@ -38,14 +38,12 @@ class VTKFILTERSSOURCES_EXPORT vtkDiagonalMatrixSource : public vtkArrayDataAlgo vtkTypeMacro(vtkDiagonalMatrixSource, vtkArrayDataAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); -//BTX // Determines whether the output matrix will be dense or sparse enum StorageType { DENSE, SPARSE }; -//ETX vtkGetMacro(ArrayType, int); vtkSetMacro(ArrayType, int); diff --git a/Filters/Sources/vtkGraphToPolyData.cxx b/Filters/Sources/vtkGraphToPolyData.cxx index 1f88d9b00f2..23dafb2b110 100644 --- a/Filters/Sources/vtkGraphToPolyData.cxx +++ b/Filters/Sources/vtkGraphToPolyData.cxx @@ -74,7 +74,7 @@ int vtkGraphToPolyData::RequestData( vtkPolyData *arrowOutput = vtkPolyData::SafeDownCast( arrowInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkDataArray* edgeGhostLevels = vtkDataArray::SafeDownCast( + vtkDataArray* edgeGhostLevels = vtkArrayDownCast( input->GetEdgeData()->GetAbstractArray(vtkDataSetAttributes::GhostArrayName())); if (edgeGhostLevels == NULL) diff --git a/Filters/Sources/vtkPlatonicSolidSource.cxx b/Filters/Sources/vtkPlatonicSolidSource.cxx index cb2d5df34aa..62763f80e49 100644 --- a/Filters/Sources/vtkPlatonicSolidSource.cxx +++ b/Filters/Sources/vtkPlatonicSolidSource.cxx @@ -24,6 +24,11 @@ vtkStandardNewMacro(vtkPlatonicSolidSource); +// Wrapping this in namespaces because the short names (a, b, c, etc) are +// throwing warnings on MSVC when inlined methods in vtkGenericDataArray are +// being used ('warning C4459: declaration of 'c' hides global declaration') +namespace { +namespace vtkPlatonicSolidSourceDetail { // The geometry and topology of each solid. Solids are centered at // the origin with radius 1.0. // The golden ration phi = (1+sqrt(5))/2=1.61803398875 enters into many @@ -77,6 +82,8 @@ static vtkIdType IcosaVerts[] = { 4,10,9, 5,11,8, 6,8,11, 1,9,3, 1,5,8, 0,3,10, 0,11,5, 7,10,4, 7,6,11, 2,4,9, 2,8,6 }; +} // end namespace detail +} // end anon namespace vtkPlatonicSolidSource::vtkPlatonicSolidSource() { @@ -111,8 +118,8 @@ int vtkPlatonicSolidSource::RequestData( numPts = 4; cellSize = 3; numCells = 4; - solidPoints = TetraPoints; - solidVerts = TetraVerts; + solidPoints = vtkPlatonicSolidSourceDetail::TetraPoints; + solidVerts = vtkPlatonicSolidSourceDetail::TetraVerts; solidScale = 1.0/sqrt(3.0); break; @@ -120,8 +127,8 @@ int vtkPlatonicSolidSource::RequestData( numPts = 8; cellSize = 4; numCells = 6; - solidPoints = CubePoints; - solidVerts = CubeVerts; + solidPoints = vtkPlatonicSolidSourceDetail::CubePoints; + solidVerts = vtkPlatonicSolidSourceDetail::CubeVerts; solidScale = 1.0/sqrt(3.0); break; @@ -129,8 +136,8 @@ int vtkPlatonicSolidSource::RequestData( numPts = 6; cellSize = 3; numCells = 8; - solidPoints = OctPoints; - solidVerts = OctVerts; + solidPoints = vtkPlatonicSolidSourceDetail::OctPoints; + solidVerts = vtkPlatonicSolidSourceDetail::OctVerts; solidScale = 1.0/sqrt(2.0); break; @@ -138,8 +145,8 @@ int vtkPlatonicSolidSource::RequestData( numPts = 12; cellSize = 3; numCells = 20; - solidPoints = IcosaPoints; - solidVerts = IcosaVerts; + solidPoints = vtkPlatonicSolidSourceDetail::IcosaPoints; + solidVerts = vtkPlatonicSolidSourceDetail::IcosaVerts; solidScale = 1.0/0.58778524999243; break; @@ -147,8 +154,8 @@ int vtkPlatonicSolidSource::RequestData( numPts = 20; cellSize = 5; numCells = 12; - solidPoints = DodePoints; - solidVerts = DodeVerts; + solidPoints = vtkPlatonicSolidSourceDetail::DodePoints; + solidVerts = vtkPlatonicSolidSourceDetail::DodeVerts; solidScale = 1.0/1.070466269319; break; } diff --git a/Filters/Sources/vtkSelectionSource.h b/Filters/Sources/vtkSelectionSource.h index 120bd0a47ca..8d87a9dfcd3 100644 --- a/Filters/Sources/vtkSelectionSource.h +++ b/Filters/Sources/vtkSelectionSource.h @@ -23,9 +23,7 @@ #include "vtkFiltersSourcesModule.h" // For export macro #include "vtkSelectionAlgorithm.h" -//BTX class vtkSelectionSourceInternals; -//ETX class VTKFILTERSSOURCES_EXPORT vtkSelectionSource : public vtkSelectionAlgorithm { diff --git a/Filters/Statistics/Testing/Cxx/TestDescriptiveStatistics.cxx b/Filters/Statistics/Testing/Cxx/TestDescriptiveStatistics.cxx index 474161c1ca0..57e80eb2bf6 100644 --- a/Filters/Statistics/Testing/Cxx/TestDescriptiveStatistics.cxx +++ b/Filters/Statistics/Testing/Cxx/TestDescriptiveStatistics.cxx @@ -244,10 +244,10 @@ int TestDescriptiveStatistics( int, char *[] ) << maxdev << " for metric 1:\n"; - vtkDoubleArray* vals0 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "Metric 0" ) ); - vtkDoubleArray* vals1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "Metric 1" ) ); - vtkDoubleArray* devs0 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "d(Metric 0)" ) ); - vtkDoubleArray* devs1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); + vtkDoubleArray* vals0 = vtkArrayDownCast( outputData1->GetColumnByName( "Metric 0" ) ); + vtkDoubleArray* vals1 = vtkArrayDownCast( outputData1->GetColumnByName( "Metric 1" ) ); + vtkDoubleArray* devs0 = vtkArrayDownCast( outputData1->GetColumnByName( "d(Metric 0)" ) ); + vtkDoubleArray* devs1 = vtkArrayDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); if ( ! devs0 || ! devs1 || ! vals0 || ! vals1 ) { @@ -338,8 +338,8 @@ int TestDescriptiveStatistics( int, char *[] ) ds1->SetAssessOption( true ); ds1->Update(); - vals1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "Metric 1" ) ); - devs1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); + vals1 = vtkArrayDownCast( outputData1->GetColumnByName( "Metric 1" ) ); + devs1 = vtkArrayDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); if ( ! devs1 || ! vals1 ) { diff --git a/Filters/Statistics/Testing/Cxx/TestExtractFunctionalBagPlot.cxx b/Filters/Statistics/Testing/Cxx/TestExtractFunctionalBagPlot.cxx index 246530bf7ec..af3d8d6c42a 100644 --- a/Filters/Statistics/Testing/Cxx/TestExtractFunctionalBagPlot.cxx +++ b/Filters/Statistics/Testing/Cxx/TestExtractFunctionalBagPlot.cxx @@ -175,12 +175,12 @@ int TestExtractFunctionalBagPlot(int , char * []) if (vtksys::SystemTools::StringStartsWith(colName, "Q3Points")) { q3Points = - vtkDoubleArray::SafeDownCast(outBPTable->GetColumn(i)); + vtkArrayDownCast(outBPTable->GetColumn(i)); break; } } vtkDoubleArray* q2Points = - vtkDoubleArray::SafeDownCast(outBPTable->GetColumnByName("QMedPoints")); + vtkArrayDownCast(outBPTable->GetColumnByName("QMedPoints")); if (!q3Points || !q2Points) { diff --git a/Filters/Statistics/Testing/Cxx/TestHighestDensityRegionsStatistics.cxx b/Filters/Statistics/Testing/Cxx/TestHighestDensityRegionsStatistics.cxx index 841a3d4b6d0..cfb280b7d90 100644 --- a/Filters/Statistics/Testing/Cxx/TestHighestDensityRegionsStatistics.cxx +++ b/Filters/Statistics/Testing/Cxx/TestHighestDensityRegionsStatistics.cxx @@ -106,7 +106,7 @@ int TestHighestDensityRegionsStatistics(int , char * []) std::stringstream ss; ss << "HDR (" << namev1 << "," << namev2 << ")"; - vtkDoubleArray* HDRArray = vtkDoubleArray::SafeDownCast( + vtkDoubleArray* HDRArray = vtkArrayDownCast( outputMetaLearn->GetColumnByName(ss.str().c_str())); if (!HDRArray) { diff --git a/Filters/Statistics/Testing/Cxx/TestOrderStatistics.cxx b/Filters/Statistics/Testing/Cxx/TestOrderStatistics.cxx index a657d54b926..f5dd9cf2a51 100644 --- a/Filters/Statistics/Testing/Cxx/TestOrderStatistics.cxx +++ b/Filters/Statistics/Testing/Cxx/TestOrderStatistics.cxx @@ -208,7 +208,7 @@ int TestOrderStatistics( int, char *[] ) } else { - vtkDataArray* dataQuantArr = vtkDoubleArray::SafeDownCast( absQuantArr ); + vtkDataArray* dataQuantArr = vtkArrayDownCast( absQuantArr ); if ( ! dataQuantArr ) { vtkGenericWarningMacro("Quartile array for variable: " diff --git a/Filters/Statistics/vtkAutoCorrelativeStatistics.cxx b/Filters/Statistics/vtkAutoCorrelativeStatistics.cxx index 0a2a02c4a38..9504861b6c1 100644 --- a/Filters/Statistics/vtkAutoCorrelativeStatistics.cxx +++ b/Filters/Statistics/vtkAutoCorrelativeStatistics.cxx @@ -631,7 +631,7 @@ void vtkAutoCorrelativeStatistics::SelectAssessFunctor( vtkTable* outData, vtkStdString varName = rowNames->GetValue( 0 ); // Downcast meta columns to string arrays for efficient data access - vtkStringArray* vars = vtkStringArray::SafeDownCast( modelTab->GetColumnByName( "Variable" ) ); + vtkStringArray* vars = vtkArrayDownCast( modelTab->GetColumnByName( "Variable" ) ); if ( ! vars ) { return; @@ -651,7 +651,7 @@ void vtkAutoCorrelativeStatistics::SelectAssessFunctor( vtkTable* outData, // For auto-correlative statistics, type must be convertible to DataArray // E.g., StringArrays do not fit here - vtkDataArray* vals = vtkDataArray::SafeDownCast( arr ); + vtkDataArray* vals = vtkArrayDownCast( arr ); if ( ! vals ) { return; diff --git a/Filters/Statistics/vtkAutoCorrelativeStatistics.h b/Filters/Statistics/vtkAutoCorrelativeStatistics.h index 0fd1150ae9b..d40f37b5e07 100644 --- a/Filters/Statistics/vtkAutoCorrelativeStatistics.h +++ b/Filters/Statistics/vtkAutoCorrelativeStatistics.h @@ -96,7 +96,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkAutoCorrelativeStatistics : public vtkStati vtkTable* outData ) { this->Superclass::Assess( inData, inMeta, outData, 1 ); } -//BTX // Description: // Calculate p-value. This will be overridden using the object factory with an // R implementation if R is present. @@ -108,7 +107,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkAutoCorrelativeStatistics : public vtkStati vtkDataObject* inMeta, vtkStringArray* rowNames, AssessFunctor*& dfunc ); -//ETX vtkIdType SliceCardinality; diff --git a/Filters/Statistics/vtkBivariateLinearTableThreshold.cxx b/Filters/Statistics/vtkBivariateLinearTableThreshold.cxx index e0cb5b475e9..cd5efd030b2 100644 --- a/Filters/Statistics/vtkBivariateLinearTableThreshold.cxx +++ b/Filters/Statistics/vtkBivariateLinearTableThreshold.cxx @@ -192,7 +192,7 @@ vtkIdTypeArray* vtkBivariateLinearTableThreshold::GetSelectedRowIds(int selectio if (!table) return NULL; - return vtkIdTypeArray::SafeDownCast(table->GetColumn(selection)); + return vtkArrayDownCast(table->GetColumn(selection)); } int vtkBivariateLinearTableThreshold::ApplyThreshold(vtkTable* tableToThreshold, vtkIdTypeArray* acceptedIds) @@ -209,8 +209,8 @@ int vtkBivariateLinearTableThreshold::ApplyThreshold(vtkTable* tableToThreshold, this->GetColumnToThreshold(0,column1,component1); this->GetColumnToThreshold(1,column2,component2); - vtkDataArray* a1 = vtkDataArray::SafeDownCast(tableToThreshold->GetColumn(column1)); - vtkDataArray* a2 = vtkDataArray::SafeDownCast(tableToThreshold->GetColumn(column2)); + vtkDataArray* a1 = vtkArrayDownCast(tableToThreshold->GetColumn(column1)); + vtkDataArray* a2 = vtkArrayDownCast(tableToThreshold->GetColumn(column2)); if (!a1 || !a2) { diff --git a/Filters/Statistics/vtkBivariateLinearTableThreshold.h b/Filters/Statistics/vtkBivariateLinearTableThreshold.h index 1d0f68bd213..4f10e577953 100644 --- a/Filters/Statistics/vtkBivariateLinearTableThreshold.h +++ b/Filters/Statistics/vtkBivariateLinearTableThreshold.h @@ -79,7 +79,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkBivariateLinearTableThreshold : public vtkT // Get the output as a table of row ids. vtkIdTypeArray* GetSelectedRowIds(int selection=0); - //BTX enum OutputPorts { OUTPUT_ROW_IDS=0, @@ -92,7 +91,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkBivariateLinearTableThreshold : public vtkT BLT_NEAR, BLT_BETWEEN }; - //ETX // Description: // Reset the columns to threshold, column ranges, etc. @@ -167,11 +165,9 @@ class VTKFILTERSSTATISTICS_EXPORT vtkBivariateLinearTableThreshold : public vtkT int NumberOfLineEquations; int UseNormalizedDistance; - //BTX vtkSmartPointer LineEquations; class Internals; Internals* Implementation; - //ETX virtual int RequestData( vtkInformation*, diff --git a/Filters/Statistics/vtkContingencyStatistics.cxx b/Filters/Statistics/vtkContingencyStatistics.cxx index 64e5b233cdd..21983bd2985 100644 --- a/Filters/Statistics/vtkContingencyStatistics.cxx +++ b/Filters/Statistics/vtkContingencyStatistics.cxx @@ -70,8 +70,8 @@ class BivariateContingenciesAndInformationFunctor : public vtkStatisticsAlgorith PdfXcY (pdfXcY), PmiX_Y (pmiX_Y) { - this->DataX = vtkDataArray::SafeDownCast (valsX); - this->DataY = vtkDataArray::SafeDownCast (valsY); + this->DataX = vtkArrayDownCast(valsX); + this->DataY = vtkArrayDownCast(valsY); } virtual ~BivariateContingenciesAndInformationFunctor() { } virtual void operator() ( vtkDoubleArray* result, @@ -145,8 +145,8 @@ template void Count (std::map, std::map,vtkIdType> >& table, vtkAbstractArray* valsX, vtkAbstractArray* valsY) { - vtkDataArray* dataX = vtkDataArray::SafeDownCast (valsX); - vtkDataArray* dataY = vtkDataArray::SafeDownCast (valsY); + vtkDataArray* dataX = vtkArrayDownCast(valsX); + vtkDataArray* dataY = vtkArrayDownCast(valsY); if (dataX == 0 || dataY == 0) return; vtkIdType nRow = dataX->GetNumberOfTuples (); @@ -206,8 +206,8 @@ class ContingencyImpl Table table; Count (table, valsX, valsY); - vtkDataArray *dataX = vtkDataArray::SafeDownCast (contingencyTab->GetColumn (1)); - vtkDataArray *dataY = vtkDataArray::SafeDownCast (contingencyTab->GetColumn (2)); + vtkDataArray *dataX = vtkArrayDownCast(contingencyTab->GetColumn (1)); + vtkDataArray *dataY = vtkArrayDownCast(contingencyTab->GetColumn (2)); // Store contingency table int row = contingencyTab->GetNumberOfRows (); @@ -502,14 +502,14 @@ class ContingencyImpl vtkStatisticsAlgorithm::AssessFunctor*& dfunc ) { // Downcast columns to appropriate arrays for efficient data access - vtkIdTypeArray* keys = vtkIdTypeArray::SafeDownCast( contingencyTab->GetColumnByName( "Key" ) ); + vtkIdTypeArray* keys = vtkArrayDownCast( contingencyTab->GetColumnByName( "Key" ) ); vtkType* dataX = vtkType::SafeDownCast( contingencyTab->GetColumnByName( "x" ) ); vtkType* dataY = vtkType::SafeDownCast( contingencyTab->GetColumnByName( "y" ) ); - vtkDoubleArray* pX_Y = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( "P" ) ); - vtkDoubleArray* pYcX = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( "Py|x" ) ); - vtkDoubleArray* pXcY = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( "Px|y" ) ); - vtkDoubleArray* pmis = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( "PMI" ) ); + vtkDoubleArray* pX_Y = vtkArrayDownCast( contingencyTab->GetColumnByName( "P" ) ); + vtkDoubleArray* pYcX = vtkArrayDownCast( contingencyTab->GetColumnByName( "Py|x" ) ); + vtkDoubleArray* pXcY = vtkArrayDownCast( contingencyTab->GetColumnByName( "Px|y" ) ); + vtkDoubleArray* pmis = vtkArrayDownCast( contingencyTab->GetColumnByName( "PMI" ) ); // Verify that assess parameters have been properly obtained if ( ! pX_Y || ! pYcX || ! pXcY || ! pmis ) @@ -870,14 +870,14 @@ class ContingencyImpl vtkStatisticsAlgorithm::AssessFunctor*& dfunc ) { // Downcast columns to appropriate arrays for efficient data access - vtkIdTypeArray* keys = vtkIdTypeArray::SafeDownCast( contingencyTab->GetColumnByName( "Key" ) ); + vtkIdTypeArray* keys = vtkArrayDownCast( contingencyTab->GetColumnByName( "Key" ) ); vtkType* dataX = vtkType::SafeDownCast( contingencyTab->GetColumnByName( "x" ) ); vtkType* dataY = vtkType::SafeDownCast( contingencyTab->GetColumnByName( "y" ) ); - vtkDoubleArray* pX_Y = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( "P" ) ); - vtkDoubleArray* pYcX = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( "Py|x" ) ); - vtkDoubleArray* pXcY = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( "Px|y" ) ); - vtkDoubleArray* pmis = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( "PMI" ) ); + vtkDoubleArray* pX_Y = vtkArrayDownCast( contingencyTab->GetColumnByName( "P" ) ); + vtkDoubleArray* pYcX = vtkArrayDownCast( contingencyTab->GetColumnByName( "Py|x" ) ); + vtkDoubleArray* pXcY = vtkArrayDownCast( contingencyTab->GetColumnByName( "Px|y" ) ); + vtkDoubleArray* pmis = vtkArrayDownCast( contingencyTab->GetColumnByName( "PMI" ) ); // Verify that assess parameters have been properly obtained if ( ! pX_Y || ! pYcX || ! pXcY || ! pmis ) @@ -1019,8 +1019,8 @@ void vtkContingencyStatistics::Learn( vtkTable* inData, continue; } - vtkDataArray* dataX = vtkDataArray::SafeDownCast (inData->GetColumnByName( colX )); - vtkDataArray* dataY = vtkDataArray::SafeDownCast (inData->GetColumnByName( colY )); + vtkDataArray* dataX = vtkArrayDownCast(inData->GetColumnByName( colX )); + vtkDataArray* dataY = vtkArrayDownCast(inData->GetColumnByName( colY )); if (dataX == 0 || dataY == 0) { @@ -1028,8 +1028,8 @@ void vtkContingencyStatistics::Learn( vtkTable* inData, break; } - if (vtkDoubleArray::SafeDownCast (dataX) || vtkFloatArray::SafeDownCast (dataX) || - vtkDoubleArray::SafeDownCast (dataY) || vtkFloatArray::SafeDownCast (dataY)) + if (vtkArrayDownCast(dataX) || vtkArrayDownCast(dataX) || + vtkArrayDownCast(dataY) || vtkArrayDownCast(dataY)) { specialization = Double; } @@ -1150,8 +1150,8 @@ void vtkContingencyStatistics::Learn( vtkTable* inData, vtkAbstractArray* valsX = inData->GetColumnByName( colX ); vtkAbstractArray* valsY = inData->GetColumnByName( colY ); - vtkDataArray* dataX = vtkDataArray::SafeDownCast (valsX); - vtkDataArray* dataY = vtkDataArray::SafeDownCast (valsY); + vtkDataArray* dataX = vtkArrayDownCast(valsX); + vtkDataArray* dataY = vtkArrayDownCast(valsY); switch (specialization) { case None: @@ -1243,17 +1243,17 @@ void vtkContingencyStatistics::Derive( vtkMultiBlockDataSet* inMeta ) } // Downcast columns to typed arrays for efficient data access - vtkStringArray* varX = vtkStringArray::SafeDownCast( summaryTab->GetColumnByName( "Variable X" ) ); - vtkStringArray* varY = vtkStringArray::SafeDownCast( summaryTab->GetColumnByName( "Variable Y" ) ); + vtkStringArray* varX = vtkArrayDownCast( summaryTab->GetColumnByName( "Variable X" ) ); + vtkStringArray* varY = vtkArrayDownCast( summaryTab->GetColumnByName( "Variable Y" ) ); - vtkIdTypeArray* keys = vtkIdTypeArray::SafeDownCast( contingencyTab->GetColumnByName( "Key" ) ); - vtkIdTypeArray* card = vtkIdTypeArray::SafeDownCast( contingencyTab->GetColumnByName( "Cardinality" ) ); + vtkIdTypeArray* keys = vtkArrayDownCast( contingencyTab->GetColumnByName( "Key" ) ); + vtkIdTypeArray* card = vtkArrayDownCast( contingencyTab->GetColumnByName( "Cardinality" ) ); vtkAbstractArray* valsX = contingencyTab->GetColumnByName( "x" ); vtkAbstractArray* valsY = contingencyTab->GetColumnByName( "y" ); - vtkDataArray* dataX = vtkDataArray::SafeDownCast (valsX); - vtkDataArray* dataY = vtkDataArray::SafeDownCast (valsY); + vtkDataArray* dataX = vtkArrayDownCast(valsX); + vtkDataArray* dataY = vtkArrayDownCast(valsY); // Fill cardinality row (0) with invalid values for derived statistics for ( int i = 0; i < nDerivedVals; ++ i ) @@ -1265,7 +1265,7 @@ void vtkContingencyStatistics::Derive( vtkMultiBlockDataSet* inMeta ) for ( int j = 0; j < nDerivedVals; ++ j ) { - derivedCols[j] = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( derivedNames[j] ) ); + derivedCols[j] = vtkArrayDownCast( contingencyTab->GetColumnByName( derivedNames[j] ) ); if ( ! derivedCols[j] ) { @@ -1335,8 +1335,8 @@ void vtkContingencyStatistics::Assess( vtkTable* inData, } // Downcast columns to string arrays for efficient data access - vtkStringArray* varX = vtkStringArray::SafeDownCast( summaryTab->GetColumnByName( "Variable X" ) ); - vtkStringArray* varY = vtkStringArray::SafeDownCast( summaryTab->GetColumnByName( "Variable Y" ) ); + vtkStringArray* varX = vtkArrayDownCast( summaryTab->GetColumnByName( "Variable X" ) ); + vtkStringArray* varY = vtkArrayDownCast( summaryTab->GetColumnByName( "Variable Y" ) ); // Loop over requests vtkIdType nRowSumm = summaryTab->GetNumberOfRows(); @@ -1457,7 +1457,7 @@ void vtkContingencyStatistics::Assess( vtkTable* inData, // ---------------------------------------------------------------------- void vtkContingencyStatistics::CalculatePValues( vtkTable* testTab ) { - vtkIdTypeArray* dimCol = vtkIdTypeArray::SafeDownCast(testTab->GetColumn(0)); + vtkIdTypeArray* dimCol = vtkArrayDownCast(testTab->GetColumn(0)); // Test columns must be created first vtkDoubleArray* testChi2Col = vtkDoubleArray::New(); // Chi square p-value @@ -1538,12 +1538,12 @@ void vtkContingencyStatistics::Test( vtkTable* inData, chi2yCol->SetName( "Chi2 Yates" ); // Downcast columns to typed arrays for efficient data access - vtkStringArray* varX = vtkStringArray::SafeDownCast( summaryTab->GetColumnByName( "Variable X" ) ); - vtkStringArray* varY = vtkStringArray::SafeDownCast( summaryTab->GetColumnByName( "Variable Y" ) ); - vtkIdTypeArray* keys = vtkIdTypeArray::SafeDownCast( contingencyTab->GetColumnByName( "Key" ) ); - vtkStringArray* valx = vtkStringArray::SafeDownCast( contingencyTab->GetColumnByName( "x" ) ); - vtkStringArray* valy = vtkStringArray::SafeDownCast( contingencyTab->GetColumnByName( "y" ) ); - vtkIdTypeArray* card = vtkIdTypeArray::SafeDownCast( contingencyTab->GetColumnByName( "Cardinality" ) ); + vtkStringArray* varX = vtkArrayDownCast( summaryTab->GetColumnByName( "Variable X" ) ); + vtkStringArray* varY = vtkArrayDownCast( summaryTab->GetColumnByName( "Variable Y" ) ); + vtkIdTypeArray* keys = vtkArrayDownCast( contingencyTab->GetColumnByName( "Key" ) ); + vtkStringArray* valx = vtkArrayDownCast( contingencyTab->GetColumnByName( "x" ) ); + vtkStringArray* valy = vtkArrayDownCast( contingencyTab->GetColumnByName( "y" ) ); + vtkIdTypeArray* card = vtkArrayDownCast( contingencyTab->GetColumnByName( "Cardinality" ) ); // Loop over requests vtkIdType nRowSumm = summaryTab->GetNumberOfRows(); @@ -1662,8 +1662,8 @@ void vtkContingencyStatistics::Test( vtkTable* inData, vtkTable* marginalTab = vtkTable::SafeDownCast( inMeta->GetBlock( b ) ); // Downcast columns to appropriate arrays for efficient data access - vtkStringArray* vals = vtkStringArray::SafeDownCast( marginalTab->GetColumnByName( name ) ); - vtkIdTypeArray* marg = vtkIdTypeArray::SafeDownCast( marginalTab->GetColumnByName( "Cardinality" ) ); + vtkStringArray* vals = vtkArrayDownCast( marginalTab->GetColumnByName( name ) ); + vtkIdTypeArray* marg = vtkArrayDownCast( marginalTab->GetColumnByName( "Cardinality" ) ); // Now iterate over all entries and fill count map vtkIdType nRow = marginalTab->GetNumberOfRows(); @@ -1782,10 +1782,10 @@ void vtkContingencyStatistics::SelectAssessFunctor( vtkTable* outData, return; } - vtkDoubleArray* dubx = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( "x" ) ); - vtkDoubleArray* duby = vtkDoubleArray::SafeDownCast( contingencyTab->GetColumnByName( "y" ) ); - vtkLongArray* intx = vtkLongArray::SafeDownCast( contingencyTab->GetColumnByName( "x" ) ); - vtkLongArray* inty = vtkLongArray::SafeDownCast( contingencyTab->GetColumnByName( "y" ) ); + vtkDoubleArray* dubx = vtkArrayDownCast( contingencyTab->GetColumnByName( "x" ) ); + vtkDoubleArray* duby = vtkArrayDownCast( contingencyTab->GetColumnByName( "y" ) ); + vtkLongArray* intx = vtkArrayDownCast( contingencyTab->GetColumnByName( "x" ) ); + vtkLongArray* inty = vtkArrayDownCast( contingencyTab->GetColumnByName( "y" ) ); double cdf; if (dubx && duby) { diff --git a/Filters/Statistics/vtkContingencyStatistics.h b/Filters/Statistics/vtkContingencyStatistics.h index d1a33c9b261..300f688dde9 100644 --- a/Filters/Statistics/vtkContingencyStatistics.h +++ b/Filters/Statistics/vtkContingencyStatistics.h @@ -88,13 +88,12 @@ class VTKFILTERSSTATISTICS_EXPORT vtkContingencyStatistics : public vtkStatistic virtual void Assess( vtkTable*, vtkMultiBlockDataSet*, vtkTable* ); -//BTX + // Description: // Calculate p-value. This will be overridden using the object factory with an // R implementation if R is present. virtual void CalculatePValues(vtkTable*); -//BTX // Description: // Provide the appropriate assessment functor. // This one does nothing because the API is not sufficient for tables indexed @@ -111,7 +110,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkContingencyStatistics : public vtkStatistic vtkIdType pairKey, vtkStringArray* rowNames, AssessFunctor*& dfunc ); -//ETX private: vtkContingencyStatistics(const vtkContingencyStatistics&); // Not implemented diff --git a/Filters/Statistics/vtkCorrelativeStatistics.cxx b/Filters/Statistics/vtkCorrelativeStatistics.cxx index 8fa01b5a125..24d10bf7947 100644 --- a/Filters/Statistics/vtkCorrelativeStatistics.cxx +++ b/Filters/Statistics/vtkCorrelativeStatistics.cxx @@ -550,8 +550,8 @@ void vtkCorrelativeStatistics::Test( vtkTable* inData, statCol->SetName( "Jarque-Bera-Srivastava" ); // Downcast columns to string arrays for efficient data access - vtkStringArray* varsX = vtkStringArray::SafeDownCast( primaryTab->GetColumnByName( "Variable X" ) ); - vtkStringArray* varsY = vtkStringArray::SafeDownCast( primaryTab->GetColumnByName( "Variable Y" ) ); + vtkStringArray* varsX = vtkArrayDownCast( primaryTab->GetColumnByName( "Variable X" ) ); + vtkStringArray* varsY = vtkArrayDownCast( primaryTab->GetColumnByName( "Variable Y" ) ); // Loop over requests vtkIdType nRowData = inData->GetNumberOfRows(); @@ -884,8 +884,8 @@ void vtkCorrelativeStatistics::SelectAssessFunctor( vtkTable* outData, vtkStdString varNameY = rowNames->GetValue( 1 ); // Downcast meta columns to string arrays for efficient data access - vtkStringArray* varX = vtkStringArray::SafeDownCast( primaryTab->GetColumnByName( "Variable X" ) ); - vtkStringArray* varY = vtkStringArray::SafeDownCast( primaryTab->GetColumnByName( "Variable Y" ) ); + vtkStringArray* varX = vtkArrayDownCast( primaryTab->GetColumnByName( "Variable X" ) ); + vtkStringArray* varY = vtkArrayDownCast( primaryTab->GetColumnByName( "Variable Y" ) ); if ( ! varX || ! varY ) { return; @@ -907,8 +907,8 @@ void vtkCorrelativeStatistics::SelectAssessFunctor( vtkTable* outData, } // For descriptive statistics, types must be convertible to DataArrays (e.g., StringArrays do not fit here). - vtkDataArray* valsX = vtkDataArray::SafeDownCast( arrX ); - vtkDataArray* valsY = vtkDataArray::SafeDownCast( arrY ); + vtkDataArray* valsX = vtkArrayDownCast( arrX ); + vtkDataArray* valsY = vtkArrayDownCast( arrY ); if ( ! valsX || ! valsY ) { return; diff --git a/Filters/Statistics/vtkCorrelativeStatistics.h b/Filters/Statistics/vtkCorrelativeStatistics.h index 9fef9b92fce..0659c8cf06a 100644 --- a/Filters/Statistics/vtkCorrelativeStatistics.h +++ b/Filters/Statistics/vtkCorrelativeStatistics.h @@ -89,7 +89,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkCorrelativeStatistics : public vtkStatistic vtkTable* outData ) { this->Superclass::Assess( inData, inMeta, outData, 2 ); } -//BTX // Description: // Calculate p-value. This will be overridden using the object factory with an // R implementation if R is present. @@ -101,7 +100,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkCorrelativeStatistics : public vtkStatistic vtkDataObject* inMeta, vtkStringArray* rowNames, AssessFunctor*& dfunc ); -//ETX private: vtkCorrelativeStatistics(const vtkCorrelativeStatistics&); // Not implemented diff --git a/Filters/Statistics/vtkDescriptiveStatistics.cxx b/Filters/Statistics/vtkDescriptiveStatistics.cxx index a804e268f64..c5d5525b44a 100644 --- a/Filters/Statistics/vtkDescriptiveStatistics.cxx +++ b/Filters/Statistics/vtkDescriptiveStatistics.cxx @@ -536,7 +536,7 @@ void vtkDescriptiveStatistics::Test( vtkTable* inData, statCol->SetName( "Jarque-Bera" ); // Downcast columns to string arrays for efficient data access - vtkStringArray* vars = vtkStringArray::SafeDownCast( primaryTab->GetColumnByName( "Variable" ) ); + vtkStringArray* vars = vtkArrayDownCast( primaryTab->GetColumnByName( "Variable" ) ); // Loop over requests for ( std::set >::const_iterator rit = this->Internals->Requests.begin(); @@ -705,7 +705,7 @@ void vtkDescriptiveStatistics::SelectAssessFunctor( vtkTable* outData, vtkStdString varName = rowNames->GetValue( 0 ); // Downcast meta columns to string arrays for efficient data access - vtkStringArray* vars = vtkStringArray::SafeDownCast( primaryTab->GetColumnByName( "Variable" ) ); + vtkStringArray* vars = vtkArrayDownCast( primaryTab->GetColumnByName( "Variable" ) ); if ( ! vars ) { return; @@ -725,7 +725,7 @@ void vtkDescriptiveStatistics::SelectAssessFunctor( vtkTable* outData, // For descriptive statistics, type must be convertible to DataArray // E.g., StringArrays do not fit here - vtkDataArray* vals = vtkDataArray::SafeDownCast( arr ); + vtkDataArray* vals = vtkArrayDownCast( arr ); if ( ! vals ) { return; diff --git a/Filters/Statistics/vtkDescriptiveStatistics.h b/Filters/Statistics/vtkDescriptiveStatistics.h index 766081d18d0..2570a0d8b8d 100644 --- a/Filters/Statistics/vtkDescriptiveStatistics.h +++ b/Filters/Statistics/vtkDescriptiveStatistics.h @@ -127,7 +127,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkDescriptiveStatistics : public vtkStatistic vtkTable* outData ) { this->Superclass::Assess( inData, inMeta, outData, 1 ); } -//BTX // Description: // Calculate p-value. This will be overridden using the object factory with an // R implementation if R is present. @@ -139,7 +138,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkDescriptiveStatistics : public vtkStatistic vtkDataObject* inMeta, vtkStringArray* rowNames, AssessFunctor*& dfunc ); -//ETX int UnbiasedVariance; int G1Skewness; diff --git a/Filters/Statistics/vtkExtractFunctionalBagPlot.cxx b/Filters/Statistics/vtkExtractFunctionalBagPlot.cxx index 3424adb61c2..9aa1d9c2921 100644 --- a/Filters/Statistics/vtkExtractFunctionalBagPlot.cxx +++ b/Filters/Statistics/vtkExtractFunctionalBagPlot.cxx @@ -88,7 +88,7 @@ int vtkExtractFunctionalBagPlot::RequestData(vtkInformation* /*request*/, return false; } - vtkDoubleArray *density = vtkDoubleArray::SafeDownCast( + vtkDoubleArray *density = vtkArrayDownCast( this->GetInputAbstractArrayToProcess(0, inTableDensity)); if (!density) { @@ -96,7 +96,7 @@ int vtkExtractFunctionalBagPlot::RequestData(vtkInformation* /*request*/, return false; } - vtkStringArray *varName = vtkStringArray::SafeDownCast( + vtkStringArray *varName = vtkArrayDownCast( this->GetInputAbstractArrayToProcess(1, inTableDensity)); if (!varName) { diff --git a/Filters/Statistics/vtkHighestDensityRegionsStatistics.cxx b/Filters/Statistics/vtkHighestDensityRegionsStatistics.cxx index 0b0bc412c57..fa3851fd8e9 100644 --- a/Filters/Statistics/vtkHighestDensityRegionsStatistics.cxx +++ b/Filters/Statistics/vtkHighestDensityRegionsStatistics.cxx @@ -145,9 +145,9 @@ void vtkHighestDensityRegionsStatistics::Learn(vtkTable* inData, // Verify column types vtkDataArray *inputColX = - vtkDataArray::SafeDownCast(inData->GetColumnByName(colX.c_str())); + vtkArrayDownCast(inData->GetColumnByName(colX.c_str())); vtkDataArray *inputColY = - vtkDataArray::SafeDownCast(inData->GetColumnByName(colY.c_str())); + vtkArrayDownCast(inData->GetColumnByName(colY.c_str())); if (!inputColX || !inputColY) { vtkErrorMacro( diff --git a/Filters/Statistics/vtkHighestDensityRegionsStatistics.h b/Filters/Statistics/vtkHighestDensityRegionsStatistics.h index a2812c8b206..da8ad4c35d7 100644 --- a/Filters/Statistics/vtkHighestDensityRegionsStatistics.h +++ b/Filters/Statistics/vtkHighestDensityRegionsStatistics.h @@ -106,14 +106,12 @@ class VTKFILTERSSTATISTICS_EXPORT vtkHighestDensityRegionsStatistics : vtkMultiBlockDataSet*, vtkTable*) { return; } -//BTX // Description: (Not implemented) // Provide the appropriate assessment functor. virtual void SelectAssessFunctor(vtkTable*, vtkDataObject*, vtkStringArray*, AssessFunctor*&) { return; } -//ETX // Description: // Store the smooth matrix parameter H. Specify a smooth direction diff --git a/Filters/Statistics/vtkKMeansDistanceFunctor.cxx b/Filters/Statistics/vtkKMeansDistanceFunctor.cxx index f040a1b7035..51b73735e4c 100644 --- a/Filters/Statistics/vtkKMeansDistanceFunctor.cxx +++ b/Filters/Statistics/vtkKMeansDistanceFunctor.cxx @@ -147,7 +147,7 @@ void vtkKMeansDistanceFunctor::PackElements( vtkTable* curTable, void* vElements for( vtkIdType col = 0; col < numCols; col++ ) { - vtkDoubleArray* doubleArr = vtkDoubleArray::SafeDownCast( curTable->GetColumn( col ) ); + vtkDoubleArray* doubleArr = vtkArrayDownCast( curTable->GetColumn( col ) ); memcpy( &(localElements[col*numRows]), doubleArr->GetPointer( 0 ), numRows*sizeof( double ) ); } } diff --git a/Filters/Statistics/vtkKMeansStatistics.cxx b/Filters/Statistics/vtkKMeansStatistics.cxx index 1636c98a479..b09889f8fc4 100644 --- a/Filters/Statistics/vtkKMeansStatistics.cxx +++ b/Filters/Statistics/vtkKMeansStatistics.cxx @@ -94,7 +94,7 @@ int vtkKMeansStatistics::InitializeDataAndClusterCenters(vtkTable* inParameters, if ( inParameters && inParameters->GetNumberOfRows() > 0 && inParameters->GetNumberOfColumns() > 1 ) { - vtkIdTypeArray* counts = vtkIdTypeArray::SafeDownCast( inParameters->GetColumn( 0 ) ); + vtkIdTypeArray* counts = vtkArrayDownCast( inParameters->GetColumn( 0 ) ); if( !counts ) { vtkWarningMacro( "The first column of the input parameter table should be of vtkIdType." << endl << @@ -533,10 +533,10 @@ void vtkKMeansStatistics::Derive( vtkMultiBlockDataSet* outMeta ) if ( ! outMeta || ! ( outTable = vtkTable::SafeDownCast( outMeta->GetBlock( 0 ) ) ) || - ! ( clusterRunIDs = vtkIdTypeArray::SafeDownCast( outTable->GetColumn( 0 ) ) ) || - ! ( numberOfClusters = vtkIdTypeArray::SafeDownCast( outTable->GetColumn( 1 ) ) ) || - ! ( numIterations = vtkIdTypeArray::SafeDownCast( outTable->GetColumn( 2 ) ) ) || - ! ( error = vtkDoubleArray::SafeDownCast( outTable->GetColumn( 3 ) ) ) + ! ( clusterRunIDs = vtkArrayDownCast( outTable->GetColumn( 0 ) ) ) || + ! ( numberOfClusters = vtkArrayDownCast( outTable->GetColumn( 1 ) ) ) || + ! ( numIterations = vtkArrayDownCast( outTable->GetColumn( 2 ) ) ) || + ! ( error = vtkArrayDownCast( outTable->GetColumn( 3 ) ) ) ) { return; diff --git a/Filters/Statistics/vtkKMeansStatistics.h b/Filters/Statistics/vtkKMeansStatistics.h index 31553aee86f..98999b264aa 100644 --- a/Filters/Statistics/vtkKMeansStatistics.h +++ b/Filters/Statistics/vtkKMeansStatistics.h @@ -142,12 +142,10 @@ class VTKFILTERSSTATISTICS_EXPORT vtkKMeansStatistics : public vtkStatisticsAlgo virtual void Aggregate( vtkDataObjectCollection*, vtkMultiBlockDataSet* ) { return; }; - //BTX // Description: // A convenience method for setting properties by name. virtual bool SetParameter( const char* parameter, int index, vtkVariant value ); - //ETX protected: vtkKMeansStatistics(); @@ -175,14 +173,13 @@ class VTKFILTERSSTATISTICS_EXPORT vtkKMeansStatistics : public vtkStatisticsAlgo vtkMultiBlockDataSet*, vtkTable* ) { return; }; - //BTX // Description: // Provide the appropriate assessment functor. virtual void SelectAssessFunctor( vtkTable* inData, vtkDataObject* inMeta, vtkStringArray* rowNames, AssessFunctor*& dfunc ); - //ETX + // Description: // Subroutine to update new cluster centers from the old centers. // Called from within Learn (and will be overridden by vtkPKMeansStatistics diff --git a/Filters/Statistics/vtkMultiCorrelativeStatistics.cxx b/Filters/Statistics/vtkMultiCorrelativeStatistics.cxx index b23243b1854..21863698c47 100644 --- a/Filters/Statistics/vtkMultiCorrelativeStatistics.cxx +++ b/Filters/Statistics/vtkMultiCorrelativeStatistics.cxx @@ -314,7 +314,7 @@ void vtkMultiCorrelativeStatistics::Learn( vtkTable* inData, for ( colIt = reqIt->begin(); colIt != reqIt->end(); ++ colIt ) { // Ignore invalid column names - vtkDataArray* arr = vtkDataArray::SafeDownCast( inData->GetColumnByName( colIt->c_str() ) ); + vtkDataArray* arr = vtkArrayDownCast( inData->GetColumnByName( colIt->c_str() ) ); if ( arr ) { allColumns.insert( std::pair( *colIt, arr ) ); @@ -530,9 +530,9 @@ void vtkMultiCorrelativeStatistics::Derive( vtkMultiBlockDataSet* outMeta ) if ( ! outMeta || ! ( sparseCov = vtkTable::SafeDownCast( outMeta->GetBlock( 0 ) ) ) || - ! ( col1 = vtkStringArray::SafeDownCast( sparseCov->GetColumnByName( VTK_MULTICORRELATIVE_KEYCOLUMN1 ) ) ) || - ! ( col2 = vtkStringArray::SafeDownCast( sparseCov->GetColumnByName( VTK_MULTICORRELATIVE_KEYCOLUMN2 ) ) ) || - ! ( col3 = vtkDoubleArray::SafeDownCast( sparseCov->GetColumnByName( VTK_MULTICORRELATIVE_ENTRIESCOL ) ) ) + ! ( col1 = vtkArrayDownCast( sparseCov->GetColumnByName( VTK_MULTICORRELATIVE_KEYCOLUMN1 ) ) ) || + ! ( col2 = vtkArrayDownCast( sparseCov->GetColumnByName( VTK_MULTICORRELATIVE_KEYCOLUMN2 ) ) ) || + ! ( col3 = vtkArrayDownCast( sparseCov->GetColumnByName( VTK_MULTICORRELATIVE_ENTRIESCOL ) ) ) ) { return; @@ -795,13 +795,13 @@ bool vtkMultiCorrelativeAssessFunctor::Initialize( vtkTable* inData, vtkTable* reqModel, bool cholesky ) { - vtkDoubleArray* avgs = vtkDoubleArray::SafeDownCast( reqModel->GetColumnByName( VTK_MULTICORRELATIVE_AVERAGECOL ) ); + vtkDoubleArray* avgs = vtkArrayDownCast( reqModel->GetColumnByName( VTK_MULTICORRELATIVE_AVERAGECOL ) ); if ( ! avgs ) { vtkGenericWarningMacro( "Multicorrelative request without a \"" VTK_MULTICORRELATIVE_AVERAGECOL "\" column" ); return false; } - vtkStringArray* name = vtkStringArray::SafeDownCast( reqModel->GetColumnByName( VTK_MULTICORRELATIVE_COLUMNAMES ) ); + vtkStringArray* name = vtkArrayDownCast( reqModel->GetColumnByName( VTK_MULTICORRELATIVE_COLUMNAMES ) ); if ( ! name ) { vtkGenericWarningMacro( "Multicorrelative request without a \"" VTK_MULTICORRELATIVE_COLUMNAMES "\" column" ); @@ -819,14 +819,14 @@ bool vtkMultiCorrelativeAssessFunctor::Initialize( vtkTable* inData, for ( i = 0; i < m ; ++ i ) { vtkStdString colname( name->GetValue( i ) ); - vtkDataArray* arr = vtkDataArray::SafeDownCast( inData->GetColumnByName( colname.c_str() ) ); + vtkDataArray* arr = vtkArrayDownCast( inData->GetColumnByName( colname.c_str() ) ); if ( ! arr ) { vtkGenericWarningMacro( "Multicorrelative input data needs a \"" << colname.c_str() << "\" column" ); return false; } cols.push_back( arr ); - vtkDoubleArray* dar = vtkDoubleArray::SafeDownCast( reqModel->GetColumnByName( colname.c_str() ) ); + vtkDoubleArray* dar = vtkArrayDownCast( reqModel->GetColumnByName( colname.c_str() ) ); if ( ! dar ) { vtkGenericWarningMacro( "Multicorrelative request needs a \"" << colname.c_str() << "\" column" ); diff --git a/Filters/Statistics/vtkMultiCorrelativeStatistics.h b/Filters/Statistics/vtkMultiCorrelativeStatistics.h index 2dbfa6ac07e..f5b0bdf31fa 100644 --- a/Filters/Statistics/vtkMultiCorrelativeStatistics.h +++ b/Filters/Statistics/vtkMultiCorrelativeStatistics.h @@ -129,14 +129,12 @@ class VTKFILTERSSTATISTICS_EXPORT vtkMultiCorrelativeStatistics : public vtkStat vtkMultiBlockDataSet*, vtkTable* ) { return; } - //BTX // Description: // Provide the appropriate assessment functor. virtual void SelectAssessFunctor( vtkTable* inData, vtkDataObject* inMeta, vtkStringArray* rowNames, AssessFunctor*& dfunc ); - //ETX // Description: // Computes the median of inData with vtkOrderStatistics. diff --git a/Filters/Statistics/vtkOrderStatistics.cxx b/Filters/Statistics/vtkOrderStatistics.cxx index 57d91b80271..d802bcf458b 100644 --- a/Filters/Statistics/vtkOrderStatistics.cxx +++ b/Filters/Statistics/vtkOrderStatistics.cxx @@ -194,7 +194,7 @@ void vtkOrderStatistics::Learn( vtkTable* inData, if ( vals->IsA("vtkDataArray") ) { // Downcast column to data array for efficient data access - vtkDataArray* dvals = vtkDataArray::SafeDownCast( vals ); + vtkDataArray* dvals = vtkArrayDownCast( vals ); // Calculate histogram std::map histogram; @@ -248,7 +248,7 @@ void vtkOrderStatistics::Learn( vtkTable* inData, else if ( vals->IsA("vtkStringArray") ) { // Downcast column to string array for efficient data access - vtkStringArray* svals = vtkStringArray::SafeDownCast( vals ); + vtkStringArray* svals = vtkArrayDownCast( vals ); // Calculate histogram std::map histogram; @@ -269,7 +269,7 @@ void vtkOrderStatistics::Learn( vtkTable* inData, else if ( vals->IsA("vtkVariantArray") ) { // Downcast column to variant array for efficient data access - vtkVariantArray* vvals = vtkVariantArray::SafeDownCast( vals ); + vtkVariantArray* vvals = vtkArrayDownCast( vals ); // Calculate histogram std::map histogram; @@ -393,7 +393,7 @@ void vtkOrderStatistics::Derive( vtkMultiBlockDataSet* inMeta ) // Downcast columns to typed arrays for efficient data access vtkAbstractArray* vals = histogramTab->GetColumnByName( "Value" ); - vtkIdTypeArray* card = vtkIdTypeArray::SafeDownCast( histogramTab->GetColumnByName( "Cardinality" ) ); + vtkIdTypeArray* card = vtkArrayDownCast( histogramTab->GetColumnByName( "Cardinality" ) ); // The CDF will be used for quantiles calculation (effectively as a reverse look-up table) vtkIdType nRowHist = histogramTab->GetNumberOfRows(); @@ -432,7 +432,7 @@ void vtkOrderStatistics::Derive( vtkMultiBlockDataSet* inMeta ) } else { - probaCol = vtkDoubleArray::SafeDownCast( abstrCol ); + probaCol = vtkArrayDownCast( abstrCol ); } // Finally calculate and store probabilities @@ -539,7 +539,7 @@ void vtkOrderStatistics::Derive( vtkMultiBlockDataSet* inMeta ) if ( vals->IsA("vtkDataArray") ) { // Downcast column to data array for efficient data access - vtkDataArray* dvals = vtkDataArray::SafeDownCast( vals ); + vtkDataArray* dvals = vtkArrayDownCast( vals ); // Create column for quantiles of the same type as the values vtkDataArray* quantCol = vtkDataArray::CreateDataArray( dvals->GetDataType() ); @@ -582,7 +582,7 @@ void vtkOrderStatistics::Derive( vtkMultiBlockDataSet* inMeta ) else if ( vals->IsA("vtkStringArray") ) { // Downcast column to string array for efficient data access - vtkStringArray* svals = vtkStringArray::SafeDownCast( vals ); + vtkStringArray* svals = vtkArrayDownCast( vals ); // Create column for quantiles of the same type as the values vtkStringArray* quantCol = vtkStringArray::New(); @@ -606,7 +606,7 @@ void vtkOrderStatistics::Derive( vtkMultiBlockDataSet* inMeta ) else if ( vals->IsA("vtkVariantArray") ) { // Downcast column to variant array for efficient data access - vtkVariantArray* vvals = vtkVariantArray::SafeDownCast( vals ); + vtkVariantArray* vvals = vtkArrayDownCast( vals ); // Create column for quantiles of the same type as the values vtkVariantArray* quantCol = vtkVariantArray::New(); @@ -843,8 +843,8 @@ class DataArrayQuantizer : public vtkStatisticsAlgorithm::AssessFunctor DataArrayQuantizer( vtkAbstractArray* vals, vtkAbstractArray* quantiles ) { - this->Data = vtkDataArray::SafeDownCast( vals ); - this->Quantiles = vtkDataArray::SafeDownCast( quantiles ); + this->Data = vtkArrayDownCast( vals ); + this->Quantiles = vtkArrayDownCast( quantiles ); } virtual ~DataArrayQuantizer() { @@ -884,8 +884,8 @@ class StringArrayQuantizer : public vtkStatisticsAlgorithm::AssessFunctor StringArrayQuantizer( vtkAbstractArray* vals, vtkAbstractArray* quantiles ) { - this->Data = vtkStringArray::SafeDownCast( vals ); - this->Quantiles = vtkStringArray::SafeDownCast( quantiles ); + this->Data = vtkArrayDownCast( vals ); + this->Quantiles = vtkArrayDownCast( quantiles ); } virtual ~StringArrayQuantizer() { @@ -925,8 +925,8 @@ class VariantArrayQuantizer : public vtkStatisticsAlgorithm::AssessFunctor VariantArrayQuantizer( vtkAbstractArray* vals, vtkAbstractArray* quantiles ) { - this->Data = vtkVariantArray::SafeDownCast( vals ); - this->Quantiles = vtkVariantArray::SafeDownCast( quantiles ); + this->Data = vtkArrayDownCast( vals ); + this->Quantiles = vtkArrayDownCast( quantiles ); } virtual ~VariantArrayQuantizer() { diff --git a/Filters/Statistics/vtkOrderStatistics.h b/Filters/Statistics/vtkOrderStatistics.h index 4836d3670a4..61714baa493 100644 --- a/Filters/Statistics/vtkOrderStatistics.h +++ b/Filters/Statistics/vtkOrderStatistics.h @@ -55,7 +55,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkOrderStatistics : public vtkStatisticsAlgor void PrintSelf(ostream& os, vtkIndent indent); static vtkOrderStatistics* New(); -//BTX // Description: // The type of quantile definition. enum QuantileDefinitionType { @@ -63,7 +62,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkOrderStatistics : public vtkStatisticsAlgor InverseCDFAveragedSteps = 1, // Identical to method 2 of R, ignored for non-numeric types NearestObservation = 2 // Identical to method 3 of R }; -//ETX // Description: // Set/Get the number of quantiles (with uniform spacing). @@ -131,14 +129,12 @@ class VTKFILTERSSTATISTICS_EXPORT vtkOrderStatistics : public vtkStatisticsAlgor vtkTable* outData ) { this->Superclass::Assess( inData, inMeta, outData, 1 ); } -//BTX // Description: // Provide the appropriate assessment functor. virtual void SelectAssessFunctor( vtkTable* outData, vtkDataObject* inMeta, vtkStringArray* rowNames, AssessFunctor*& dfunc ); -//ETX vtkIdType NumberOfIntervals; QuantileDefinitionType QuantileDefinition; diff --git a/Filters/Statistics/vtkPCAStatistics.cxx b/Filters/Statistics/vtkPCAStatistics.cxx index 699cec7c551..a389e698adc 100644 --- a/Filters/Statistics/vtkPCAStatistics.cxx +++ b/Filters/Statistics/vtkPCAStatistics.cxx @@ -64,8 +64,8 @@ void vtkPCAStatistics::GetEigenvalues(int request, vtkDoubleArray* eigenvalues) vtkErrorMacro(<<"NULL table pointer!"); } - vtkDoubleArray* meanCol = vtkDoubleArray::SafeDownCast(outputMeta->GetColumnByName("Mean")); - vtkStringArray* rowNames = vtkStringArray::SafeDownCast(outputMeta->GetColumnByName("Column")); + vtkDoubleArray* meanCol = vtkArrayDownCast(outputMeta->GetColumnByName("Mean")); + vtkStringArray* rowNames = vtkArrayDownCast(outputMeta->GetColumnByName("Column")); eigenvalues->SetNumberOfComponents(1); @@ -133,8 +133,8 @@ void vtkPCAStatistics::GetEigenvectors(int request, vtkDoubleArray* eigenvectors vtkErrorMacro(<<"NULL table pointer!"); } - vtkDoubleArray* meanCol = vtkDoubleArray::SafeDownCast(outputMeta->GetColumnByName("Mean")); - vtkStringArray* rowNames = vtkStringArray::SafeDownCast(outputMeta->GetColumnByName("Column")); + vtkDoubleArray* meanCol = vtkArrayDownCast(outputMeta->GetColumnByName("Mean")); + vtkStringArray* rowNames = vtkArrayDownCast(outputMeta->GetColumnByName("Column")); eigenvectors->SetNumberOfComponents(numberOfEigenvalues); @@ -152,11 +152,11 @@ void vtkPCAStatistics::GetEigenvectors(int request, vtkDoubleArray* eigenvectors for(int val = 0; val < numberOfEigenvalues; val++) { // The first two columns will always be "Column" and "Mean", so start with the next one - vtkDoubleArray* currentCol = vtkDoubleArray::SafeDownCast(outputMeta->GetColumn(val+2)); + vtkDoubleArray* currentCol = vtkArrayDownCast(outputMeta->GetColumn(val+2)); eigenvector.push_back(currentCol->GetValue(i)); } - eigenvectors->InsertNextTupleValue(&eigenvector.front()); + eigenvectors->InsertNextTypedTuple(&eigenvector.front()); eval++; } } @@ -177,12 +177,12 @@ void vtkPCAStatistics::GetEigenvector(int request, int i, vtkDoubleArray* eigenv this->GetEigenvectors(request, eigenvectors); double* evec = new double[eigenvectors->GetNumberOfComponents()]; - eigenvectors->GetTupleValue(i, evec); + eigenvectors->GetTypedTuple(i, evec); eigenvector->Reset(); eigenvector->Squeeze(); eigenvector->SetNumberOfComponents(eigenvectors->GetNumberOfComponents()); - eigenvector->InsertNextTupleValue(evec); + eigenvector->InsertNextTypedTuple(evec); delete[] evec; } @@ -234,7 +234,7 @@ bool vtkPCAAssessFunctor::InitializePCA( vtkTable* inData, // Put the PCA basis into a matrix form we can use. vtkIdType m = reqModel->GetNumberOfColumns() - 2; - vtkDoubleArray* evalm = vtkDoubleArray::SafeDownCast( reqModel->GetColumnByName( VTK_MULTICORRELATIVE_AVERAGECOL ) ); + vtkDoubleArray* evalm = vtkArrayDownCast( reqModel->GetColumnByName( VTK_MULTICORRELATIVE_AVERAGECOL ) ); if ( ! evalm ) { vtkGenericWarningMacro( "No \"" VTK_MULTICORRELATIVE_AVERAGECOL "\" column in request." ); diff --git a/Filters/Statistics/vtkPCAStatistics.h b/Filters/Statistics/vtkPCAStatistics.h index 0d007ca0dfd..2d9b4279977 100644 --- a/Filters/Statistics/vtkPCAStatistics.h +++ b/Filters/Statistics/vtkPCAStatistics.h @@ -63,7 +63,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkPCAStatistics : public vtkMultiCorrelativeS virtual void PrintSelf( ostream& os, vtkIndent indent ); static vtkPCAStatistics* New(); - //BTX // Description: // Methods by which the covariance matrix may be normalized. enum NormalizationType @@ -84,7 +83,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkPCAStatistics : public vtkMultiCorrelativeS FIXED_BASIS_ENERGY, //!< Use consecutive basis matrix entries whose energies sum to at least T NUM_BASIS_SCHEMES //!< The number of schemes (not a valid scheme). }; - //ETX // Description: // This determines how (or if) the covariance matrix \a cov is normalized before PCA. @@ -240,30 +238,26 @@ class VTKFILTERSSTATISTICS_EXPORT vtkPCAStatistics : public vtkMultiCorrelativeS virtual void Assess( vtkTable*, vtkMultiBlockDataSet*, vtkTable* ); - //BTX + // Description: // Calculate p-value. This will be overridden using the object factory with an // R implementation if R is present. virtual vtkDoubleArray* CalculatePValues(vtkIdTypeArray*, vtkDoubleArray*); - //BTX // Description: // Provide the appropriate assessment functor. virtual void SelectAssessFunctor( vtkTable* inData, vtkDataObject* inMeta, vtkStringArray* rowNames, AssessFunctor*& dfunc ); - //ETX int NormalizationScheme; int BasisScheme; int FixedBasisSize; double FixedBasisEnergy; - //BTX static const char* BasisSchemeEnumNames[NUM_BASIS_SCHEMES + 1]; static const char* NormalizationSchemeEnumNames[NUM_NORMALIZATION_SCHEMES + 1]; - //ETX private: vtkPCAStatistics( const vtkPCAStatistics& ); // Not implemented diff --git a/Filters/Statistics/vtkStatisticsAlgorithm.h b/Filters/Statistics/vtkStatisticsAlgorithm.h index 674c4c67516..a9e0e2953c5 100644 --- a/Filters/Statistics/vtkStatisticsAlgorithm.h +++ b/Filters/Statistics/vtkStatisticsAlgorithm.h @@ -71,7 +71,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkStatisticsAlgorithm : public vtkTableAlgori vtkTypeMacro(vtkStatisticsAlgorithm, vtkTableAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); -//BTX // Description: // enumeration values to specify input port types enum InputPorts @@ -89,7 +88,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkStatisticsAlgorithm : public vtkTableAlgori OUTPUT_MODEL = 1, //!< Output 1 contains any generated model OUTPUT_TEST = 2 //!< Output 2 contains result of statistical test(s) }; -//ETX // Description: // A convenience method for setting learn input parameters (if one is expected or allowed). @@ -145,7 +143,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkStatisticsAlgorithm : public vtkTableAlgori virtual void SetAssessNames( vtkStringArray* ); vtkGetObjectMacro(AssessNames,vtkStringArray); -//BTX // Description: // A base class for a functor that assesses data. class AssessFunctor { @@ -154,7 +151,6 @@ class VTKFILTERSSTATISTICS_EXPORT vtkStatisticsAlgorithm : public vtkTableAlgori vtkIdType ) = 0; virtual ~AssessFunctor() { } }; -//ETX // Description: // Add or remove a column from the current analysis request. @@ -208,9 +204,8 @@ class VTKFILTERSSTATISTICS_EXPORT vtkStatisticsAlgorithm : public vtkTableAlgori // the routine returns NULL. Otherwise it returns the column name. // This version is not thread-safe. virtual const char* GetColumnForRequest( vtkIdType r, vtkIdType c ); - //BTX + virtual int GetColumnForRequest( vtkIdType r, vtkIdType c, vtkStdString& columnName ); - //ETX // Description: // Convenience method to create a request with a single column name \p namCol in a single @@ -287,14 +282,12 @@ class VTKFILTERSSTATISTICS_EXPORT vtkStatisticsAlgorithm : public vtkTableAlgori vtkMultiBlockDataSet*, vtkTable* ) = 0; - //BTX // Description: // A pure virtual method to select the appropriate assessment functor. virtual void SelectAssessFunctor( vtkTable* outData, vtkDataObject* inMeta, vtkStringArray* rowNames, AssessFunctor*& dfunc ) = 0; - //ETX vtkIdType NumberOfPrimaryTables; bool LearnOption; diff --git a/Filters/StatisticsGnuR/Testing/Cxx/TestDescriptiveStatistics.cxx b/Filters/StatisticsGnuR/Testing/Cxx/TestDescriptiveStatistics.cxx index 7cf509f59c0..f395bd14040 100644 --- a/Filters/StatisticsGnuR/Testing/Cxx/TestDescriptiveStatistics.cxx +++ b/Filters/StatisticsGnuR/Testing/Cxx/TestDescriptiveStatistics.cxx @@ -244,10 +244,10 @@ int TestDescriptiveStatistics( int, char *[] ) << maxdev << " for metric 1:\n"; - vtkDoubleArray* vals0 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "Metric 0" ) ); - vtkDoubleArray* vals1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "Metric 1" ) ); - vtkDoubleArray* devs0 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "d(Metric 0)" ) ); - vtkDoubleArray* devs1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); + vtkDoubleArray* vals0 = vtkArrayDownCast( outputData1->GetColumnByName( "Metric 0" ) ); + vtkDoubleArray* vals1 = vtkArrayDownCast( outputData1->GetColumnByName( "Metric 1" ) ); + vtkDoubleArray* devs0 = vtkArrayDownCast( outputData1->GetColumnByName( "d(Metric 0)" ) ); + vtkDoubleArray* devs1 = vtkArrayDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); if ( ! devs0 || ! devs1 || ! vals0 || ! vals1 ) { @@ -338,8 +338,8 @@ int TestDescriptiveStatistics( int, char *[] ) ds1->SetAssessOption( true ); ds1->Update(); - vals1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "Metric 1" ) ); - devs1 = vtkDoubleArray::SafeDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); + vals1 = vtkArrayDownCast( outputData1->GetColumnByName( "Metric 1" ) ); + devs1 = vtkArrayDownCast( outputData1->GetColumnByName( "d(Metric 1)" ) ); if ( ! devs1 || ! vals1 ) { diff --git a/Filters/StatisticsGnuR/Testing/Cxx/TestRCalculatorFilter.cxx b/Filters/StatisticsGnuR/Testing/Cxx/TestRCalculatorFilter.cxx index 0c1a1344293..a2e7a922867 100644 --- a/Filters/StatisticsGnuR/Testing/Cxx/TestRCalculatorFilter.cxx +++ b/Filters/StatisticsGnuR/Testing/Cxx/TestRCalculatorFilter.cxx @@ -218,7 +218,7 @@ int TestRCalculatorFilter(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) double v_weights[5] = {0.0,2.0,3.0,1.0,1.0}; for (i = 0; i < outTree->GetNumberOfEdges(); i++) { - vtkDoubleArray * t_weights = vtkDoubleArray::SafeDownCast(outTree->GetEdgeData()->GetArray("weight")); + vtkDoubleArray * t_weights = vtkArrayDownCast(outTree->GetEdgeData()->GetArray("weight")); test_expression(doubleEquals(t_weights->GetValue(i),double( v_weights[i]), 0.001)); } @@ -226,7 +226,7 @@ int TestRCalculatorFilter(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) const char * t_names[] ={"a","b","c","","",""}; for (i = 0; i < outTree->GetNumberOfVertices(); i++) { - vtkStringArray * v_names = vtkStringArray::SafeDownCast(outTree->GetVertexData()->GetAbstractArray("node name")); + vtkStringArray * v_names = vtkArrayDownCast(outTree->GetVertexData()->GetAbstractArray("node name")); test_expression(stringEquals(v_names->GetValue(i).c_str(), t_names[i] )); } diff --git a/Filters/StatisticsGnuR/Testing/Cxx/TestRInterface.cxx b/Filters/StatisticsGnuR/Testing/Cxx/TestRInterface.cxx index bd24be234cf..be9aac434dc 100644 --- a/Filters/StatisticsGnuR/Testing/Cxx/TestRInterface.cxx +++ b/Filters/StatisticsGnuR/Testing/Cxx/TestRInterface.cxx @@ -91,7 +91,7 @@ int TestRInterface(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) rint->EvalRscript("d[,1] = d[,1] - 0.1\n\ d[,2] = d[,2] - 0.2\n\ d[,3] = d[,3] - 0.3\n"); - vtkDoubleArray* rda = vtkDoubleArray::SafeDownCast(rint->AssignRVariableToVTKDataArray("d")); + vtkDoubleArray* rda = vtkArrayDownCast(rint->AssignRVariableToVTKDataArray("d")); for(int i = 0;iGetNumberOfTuples();i++) { double* iv = da->GetTuple3(i); @@ -192,7 +192,7 @@ int TestRInterface(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) node_label<-r_tr[[5]]\n"); // check edge - vtkDoubleArray* r_edge = vtkDoubleArray::SafeDownCast(rint->AssignRVariableToVTKDataArray("edge")); + vtkDoubleArray* r_edge = vtkArrayDownCast(rint->AssignRVariableToVTKDataArray("edge")); int EDGE_ARRAY[5][2] = { {4,5},{5,6},{5,3},{6,1},{6,2} }; for ( int i = 0; i< r_edge->GetNumberOfTuples(); i++) { @@ -201,16 +201,16 @@ int TestRInterface(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) test_expression(doubleEquals(tup[1],double( EDGE_ARRAY[i][1]), 0.001)); } //check Nnode - vtkDoubleArray* r_Nnode= vtkDoubleArray::SafeDownCast(rint->AssignRVariableToVTKDataArray("Nnode")); + vtkDoubleArray* r_Nnode= vtkArrayDownCast(rint->AssignRVariableToVTKDataArray("Nnode")); test_expression(doubleEquals(r_Nnode->GetValue(0),double(3), 0.001)); //check tip_label, node.label /* TODO: implement R <=> VTKStringArray, so that the following function can be called: - vtkStringArray* r_tip_label= vtkStringArray::SafeDownCast(rint->AssignRVariableToVTKStringArray("tip_label")); + vtkStringArray* r_tip_label= vtkArrayDownCast(rint->AssignRVariableToVTKStringArray("tip_label")); */ //check edge_length - vtkDoubleArray* r_edge_length= vtkDoubleArray::SafeDownCast(rint->AssignRVariableToVTKDataArray("edge_length")); + vtkDoubleArray* r_edge_length= vtkArrayDownCast(rint->AssignRVariableToVTKDataArray("edge_length")); double e_weights[5] = {1.0,2.0,3.0,1.0,1.0}; for (int i = 0; i < r_edge_length->GetNumberOfTuples(); i++) { @@ -229,7 +229,7 @@ int TestRInterface(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) //check edge data for (int i = 0; i < vtk_tr->GetNumberOfEdges(); i++) { - vtkDoubleArray * edge_weights = vtkDoubleArray::SafeDownCast(vtk_tr->GetEdgeData()->GetArray("weight")); + vtkDoubleArray * edge_weights = vtkArrayDownCast(vtk_tr->GetEdgeData()->GetArray("weight")); test_expression(doubleEquals(edge_weights->GetValue(i),double( e_weights[i]), 0.001)); } @@ -237,7 +237,7 @@ int TestRInterface(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) const char * t_names[] ={"a","b","c","","",""}; for (int i = 0; i < vtk_tr->GetNumberOfVertices(); i++) { - vtkStringArray * v_names = vtkStringArray::SafeDownCast(vtk_tr->GetVertexData()->GetAbstractArray("node name")); + vtkStringArray * v_names = vtkArrayDownCast(vtk_tr->GetVertexData()->GetAbstractArray("node name")); test_expression(stringEquals(v_names->GetValue(i).c_str(), t_names[i] )); } diff --git a/Filters/StatisticsGnuR/vtkContingencyStatisticsGnuR.cxx b/Filters/StatisticsGnuR/vtkContingencyStatisticsGnuR.cxx index 84d536a4e27..3f11a62e25d 100644 --- a/Filters/StatisticsGnuR/vtkContingencyStatisticsGnuR.cxx +++ b/Filters/StatisticsGnuR/vtkContingencyStatisticsGnuR.cxx @@ -61,9 +61,9 @@ void vtkContingencyStatisticsGnuR::PrintSelf( ostream &os, vtkIndent indent ) // ---------------------------------------------------------------------- void vtkContingencyStatisticsGnuR::CalculatePValues( vtkTable* outTab) { - vtkIdTypeArray* dimCol = vtkIdTypeArray::SafeDownCast( outTab->GetColumn(0) ); - vtkDoubleArray* chi2Col = vtkDoubleArray::SafeDownCast( outTab->GetColumn(1)); - vtkDoubleArray* chi2yCol = vtkDoubleArray::SafeDownCast( outTab->GetColumn(2)); + vtkIdTypeArray* dimCol = vtkArrayDownCast( outTab->GetColumn(0) ); + vtkDoubleArray* chi2Col = vtkArrayDownCast( outTab->GetColumn(1)); + vtkDoubleArray* chi2yCol = vtkArrayDownCast( outTab->GetColumn(2)); // Prepare VTK - R interface vtkRInterface* ri = vtkRInterface::New(); @@ -86,8 +86,8 @@ void vtkContingencyStatisticsGnuR::CalculatePValues( vtkTable* outTab) ri->EvalRscript( rs.str().c_str() ); // Retrieve the p-values - vtkDoubleArray* testChi2Col = vtkDoubleArray::SafeDownCast( ri->AssignRVariableToVTKDataArray( "p" ) ); - vtkDoubleArray* testChi2yCol = vtkDoubleArray::SafeDownCast( ri->AssignRVariableToVTKDataArray( "py" ) ); + vtkDoubleArray* testChi2Col = vtkArrayDownCast( ri->AssignRVariableToVTKDataArray( "p" ) ); + vtkDoubleArray* testChi2yCol = vtkArrayDownCast( ri->AssignRVariableToVTKDataArray( "py" ) ); if ( ! testChi2Col || ! testChi2yCol || testChi2Col->GetNumberOfTuples() != dimCol->GetNumberOfTuples() || testChi2yCol->GetNumberOfTuples() != dimCol->GetNumberOfTuples() ) diff --git a/Filters/StatisticsGnuR/vtkContingencyStatisticsGnuR.h b/Filters/StatisticsGnuR/vtkContingencyStatisticsGnuR.h index 22bfaca25e1..c04d3b56a36 100644 --- a/Filters/StatisticsGnuR/vtkContingencyStatisticsGnuR.h +++ b/Filters/StatisticsGnuR/vtkContingencyStatisticsGnuR.h @@ -58,9 +58,7 @@ class VTKFILTERSSTATISTICSGNUR_EXPORT vtkContingencyStatisticsGnuR : public vtkC vtkContingencyStatisticsGnuR(); ~vtkContingencyStatisticsGnuR(); -//BTX virtual void CalculatePValues(vtkTable*); -//ETX private: vtkContingencyStatisticsGnuR(const vtkContingencyStatisticsGnuR&); // Not implemented diff --git a/Filters/StatisticsGnuR/vtkCorrelativeStatisticsGnuR.cxx b/Filters/StatisticsGnuR/vtkCorrelativeStatisticsGnuR.cxx index d508ae3e869..0bc6e971253 100644 --- a/Filters/StatisticsGnuR/vtkCorrelativeStatisticsGnuR.cxx +++ b/Filters/StatisticsGnuR/vtkCorrelativeStatisticsGnuR.cxx @@ -59,7 +59,7 @@ vtkDoubleArray* vtkCorrelativeStatisticsGnuR::CalculatePValues(vtkDoubleArray* s ri->EvalRscript( "p=1-pchisq(jbs,3)" ); // Retrieve the p-values - vtkDoubleArray* testCol = vtkDoubleArray::SafeDownCast( ri->AssignRVariableToVTKDataArray( "p" ) ); + vtkDoubleArray* testCol = vtkArrayDownCast( ri->AssignRVariableToVTKDataArray( "p" ) ); if ( ! testCol || testCol->GetNumberOfTuples() != statCol->GetNumberOfTuples() ) { vtkWarningMacro( "Something went wrong with the R calculations. Reported p-values will be invalid." ); diff --git a/Filters/StatisticsGnuR/vtkCorrelativeStatisticsGnuR.h b/Filters/StatisticsGnuR/vtkCorrelativeStatisticsGnuR.h index 53247c40f99..c753cb8692e 100644 --- a/Filters/StatisticsGnuR/vtkCorrelativeStatisticsGnuR.h +++ b/Filters/StatisticsGnuR/vtkCorrelativeStatisticsGnuR.h @@ -58,9 +58,7 @@ class VTKFILTERSSTATISTICSGNUR_EXPORT vtkCorrelativeStatisticsGnuR : public vtkC vtkCorrelativeStatisticsGnuR(); ~vtkCorrelativeStatisticsGnuR(); -//BTX virtual vtkDoubleArray* CalculatePValues(vtkDoubleArray*); -//ETX private: vtkCorrelativeStatisticsGnuR(const vtkCorrelativeStatisticsGnuR&); // Not implemented diff --git a/Filters/StatisticsGnuR/vtkDescriptiveStatisticsGnuR.cxx b/Filters/StatisticsGnuR/vtkDescriptiveStatisticsGnuR.cxx index 64b4cf68653..5fc4e56b0db 100644 --- a/Filters/StatisticsGnuR/vtkDescriptiveStatisticsGnuR.cxx +++ b/Filters/StatisticsGnuR/vtkDescriptiveStatisticsGnuR.cxx @@ -59,7 +59,7 @@ vtkDoubleArray* vtkDescriptiveStatisticsGnuR::CalculatePValues(vtkDoubleArray* s ri->EvalRscript( "p=1-pchisq(jb,2)" ); // Retrieve the p-values - vtkDoubleArray* testCol = vtkDoubleArray::SafeDownCast( ri->AssignRVariableToVTKDataArray( "p" ) ); + vtkDoubleArray* testCol = vtkArrayDownCast( ri->AssignRVariableToVTKDataArray( "p" ) ); if ( ! testCol || testCol->GetNumberOfTuples() != statCol->GetNumberOfTuples() ) { vtkWarningMacro( "Something went wrong with the R calculations. Reported p-values will be invalid." ); diff --git a/Filters/StatisticsGnuR/vtkDescriptiveStatisticsGnuR.h b/Filters/StatisticsGnuR/vtkDescriptiveStatisticsGnuR.h index bb8c70f1bad..2e84a67d0c1 100644 --- a/Filters/StatisticsGnuR/vtkDescriptiveStatisticsGnuR.h +++ b/Filters/StatisticsGnuR/vtkDescriptiveStatisticsGnuR.h @@ -56,9 +56,7 @@ class VTKFILTERSSTATISTICSGNUR_EXPORT vtkDescriptiveStatisticsGnuR : public vtkD vtkDescriptiveStatisticsGnuR(); ~vtkDescriptiveStatisticsGnuR(); -//BTX virtual vtkDoubleArray* CalculatePValues(vtkDoubleArray*); -//ETX private: vtkDescriptiveStatisticsGnuR(const vtkDescriptiveStatisticsGnuR&); // Not implemented diff --git a/Filters/StatisticsGnuR/vtkPCAStatisticsGnuR.cxx b/Filters/StatisticsGnuR/vtkPCAStatisticsGnuR.cxx index ff1973a37bc..07daa2554ca 100644 --- a/Filters/StatisticsGnuR/vtkPCAStatisticsGnuR.cxx +++ b/Filters/StatisticsGnuR/vtkPCAStatisticsGnuR.cxx @@ -62,7 +62,7 @@ vtkDoubleArray* vtkPCAStatisticsGnuR::CalculatePValues(vtkIdTypeArray* dimCol, ri->EvalRscript( rs.str().c_str() ); // Retrieve the p-values - vtkDoubleArray* testCol = vtkDoubleArray::SafeDownCast( ri->AssignRVariableToVTKDataArray( "p" ) ); + vtkDoubleArray* testCol = vtkArrayDownCast( ri->AssignRVariableToVTKDataArray( "p" ) ); if ( ! testCol || testCol->GetNumberOfTuples() != statCol->GetNumberOfTuples() ) { vtkWarningMacro( "Something went wrong with the R calculations. Reported p-values will be invalid." ); diff --git a/Filters/StatisticsGnuR/vtkPCAStatisticsGnuR.h b/Filters/StatisticsGnuR/vtkPCAStatisticsGnuR.h index c9f7706694d..a326891c861 100644 --- a/Filters/StatisticsGnuR/vtkPCAStatisticsGnuR.h +++ b/Filters/StatisticsGnuR/vtkPCAStatisticsGnuR.h @@ -60,9 +60,8 @@ class VTKFILTERSSTATISTICSGNUR_EXPORT vtkPCAStatisticsGnuR : public vtkPCAStatis protected: vtkPCAStatisticsGnuR(); ~vtkPCAStatisticsGnuR(); -//BTX + virtual vtkDoubleArray* CalculatePValues(vtkIdTypeArray*, vtkDoubleArray*); -//ETX private: vtkPCAStatisticsGnuR(const vtkPCAStatisticsGnuR&); // Not implemented diff --git a/Filters/StatisticsGnuR/vtkRAdapter.cxx b/Filters/StatisticsGnuR/vtkRAdapter.cxx index b2e05ffeee4..887e2960897 100644 --- a/Filters/StatisticsGnuR/vtkRAdapter.cxx +++ b/Filters/StatisticsGnuR/vtkRAdapter.cxx @@ -313,7 +313,7 @@ SEXP vtkRAdapter::VTKTableToR(vtkTable* table) for(j=0;jGetColumn(j)->GetName())); - if(vtkDataArray::SafeDownCast(table->GetColumn(j))) + if(vtkArrayDownCast(table->GetColumn(j))) { PROTECT(b = allocVector(REALSXP,nr)); SET_VECTOR_ELT(a,j,b); @@ -560,7 +560,7 @@ SEXP vtkRAdapter::VTKTreeToR(vtkTree* tree) tree->GetEdges(edgeIterator); vtkEdgeType vEdge; int i = 0; - vtkDoubleArray * weights = vtkDoubleArray::SafeDownCast((tree->GetEdgeData())->GetArray("weight")); + vtkDoubleArray * weights = vtkArrayDownCast((tree->GetEdgeData())->GetArray("weight")); while(edgeIterator->HasNext()) { vEdge = edgeIterator->Next(); @@ -574,7 +574,7 @@ SEXP vtkRAdapter::VTKTreeToR(vtkTree* tree) // fill in Nnode , tip_label and node_label // use GetAbstractArray() instead of GetArray() - vtkStringArray * labels = vtkStringArray::SafeDownCast((tree->GetVertexData())->GetAbstractArray("node name")); + vtkStringArray * labels = vtkArrayDownCast((tree->GetVertexData())->GetAbstractArray("node name")); iter->Restart(); while (iter->HasNext()) {// find out all the leaf nodes, and number them sequentially diff --git a/Filters/StatisticsGnuR/vtkRAdapter.h b/Filters/StatisticsGnuR/vtkRAdapter.h index 54a176af550..fda64e50f4d 100644 --- a/Filters/StatisticsGnuR/vtkRAdapter.h +++ b/Filters/StatisticsGnuR/vtkRAdapter.h @@ -76,7 +76,6 @@ class VTKFILTERSSTATISTICSGNUR_EXPORT vtkRAdapter : public vtkObject static vtkRAdapter *New(); -//BTX // Description: // Create a vtkDataArray copy of GNU R input matrix vaiable (deep copy, allocates memory) // Input is a R matrix or vector of doubles or integers @@ -111,7 +110,6 @@ class VTKFILTERSSTATISTICSGNUR_EXPORT vtkRAdapter : public vtkObject // Description: // Create a vtkTree copy of the GNU R input phylo tree variable (deep copy, allocates memory) vtkTree* RToVTKTree(SEXP variable); -//ETX protected: vtkRAdapter(); diff --git a/Filters/StatisticsGnuR/vtkRInterface.cxx b/Filters/StatisticsGnuR/vtkRInterface.cxx index dfc19368bc0..193b0b09777 100644 --- a/Filters/StatisticsGnuR/vtkRInterface.cxx +++ b/Filters/StatisticsGnuR/vtkRInterface.cxx @@ -41,7 +41,7 @@ vtkStandardNewMacro(vtkRInterface); #include "Rversion.h" #include "Rdefines.h" -#ifndef WIN32 +#ifndef _WIN32 #define CSTACK_DEFNS #define R_INTERFACE_PTRS #include "Rinterface.h" @@ -75,7 +75,7 @@ class vtkImplementationRSingleton return; } -#ifndef WIN32 +#ifndef _WIN32 R_SignalHandlers = 0; #endif @@ -97,7 +97,7 @@ class vtkImplementationRSingleton R_CStackLimit = (uintptr_t)-1; #endif - #ifndef WIN32 + #ifndef _WIN32 R_Interactive = static_cast(TRUE); #endif setup_Rmainloop(); @@ -112,7 +112,7 @@ class vtkImplementationRSingleton rcommand.append("f<-file(paste(tempdir(), \"/Routput.txt\", sep = \"\"), open=\"wt+\")\nsink(f)\n"); this->tmpFilePath.clear(); this->tmpFilePath.append(R_TempDir); -#ifdef WIN32 +#ifdef _WIN32 this->tmpFilePath.append("\\Routput.txt"); #else this->tmpFilePath.append("/Routput.txt"); diff --git a/Filters/StatisticsGnuR/vtkRRandomTableSource.h b/Filters/StatisticsGnuR/vtkRRandomTableSource.h index e6781d514cc..5813ee0f5f2 100644 --- a/Filters/StatisticsGnuR/vtkRRandomTableSource.h +++ b/Filters/StatisticsGnuR/vtkRRandomTableSource.h @@ -82,7 +82,6 @@ class VTKFILTERSSTATISTICSGNUR_EXPORT vtkRRandomTableSource : public vtkTableAlg // the random seed provided by Gnu R based on the current time. void SetRandGenSeed(const int seed); -//BTX // Description: // Available statistical distribution output types. Depending on the distribution type, up to three // parameters (param1, param2, param3) must be specified when using SetStatisticalDistributionForColumn(). @@ -200,7 +199,6 @@ class VTKFILTERSSTATISTICSGNUR_EXPORT vtkRRandomTableSource : public vtkTableAlg double param3, const char* ColumnName, int column_index); -//ETX // Description: // Python wrapped version of above method. Use integer equivalent of StatDistType. diff --git a/Filters/Texture/vtkThresholdTextureCoords.h b/Filters/Texture/vtkThresholdTextureCoords.h index fe6017347af..3f554cb46e0 100644 --- a/Filters/Texture/vtkThresholdTextureCoords.h +++ b/Filters/Texture/vtkThresholdTextureCoords.h @@ -93,9 +93,7 @@ class VTKFILTERSTEXTURE_EXPORT vtkThresholdTextureCoords : public vtkDataSetAlgo double InTextureCoord[3]; double OutTextureCoord[3]; - //BTX int (vtkThresholdTextureCoords::*ThresholdFunction)(double s); - //ETX int Lower(double s) {return ( s <= this->LowerThreshold ? 1 : 0 );}; int Upper(double s) {return ( s >= this->UpperThreshold ? 1 : 0 );}; diff --git a/Filters/Verdict/vtkCellQuality.h b/Filters/Verdict/vtkCellQuality.h index 5ea24d1a95a..7bf7ed94f44 100644 --- a/Filters/Verdict/vtkCellQuality.h +++ b/Filters/Verdict/vtkCellQuality.h @@ -18,8 +18,8 @@ // .SECTION Description // vtkCellQuality computes one or more functions of (geometric) quality for each // cell of a mesh. The per-cell quality is added to the mesh's cell data, in an -// array named "Quality." Cell types not supported by this filter or undefined -// quality of supported cell types will have an entry of 0. +// array named "CellQuality." Cell types not supported by this filter or undefined +// quality of supported cell types will have an entry of -1. // // .SECTION Caveats // Most quadrilateral quality functions are intended for planar quadrilaterals @@ -39,7 +39,7 @@ class vtkPoints; class VTKFILTERSVERDICT_EXPORT vtkCellQuality : public vtkDataSetAlgorithm { - //BTX + enum { NONE = 0, @@ -75,7 +75,6 @@ class VTKFILTERSVERDICT_EXPORT vtkCellQuality : public vtkDataSetAlgorithm VOLUME, WARPAGE }; - //ETX public: void PrintSelf (ostream&, vtkIndent); diff --git a/Filters/Verdict/vtkMatrixMathFilter.h b/Filters/Verdict/vtkMatrixMathFilter.h index 1d5df110030..7198c10b7d6 100644 --- a/Filters/Verdict/vtkMatrixMathFilter.h +++ b/Filters/Verdict/vtkMatrixMathFilter.h @@ -33,7 +33,7 @@ class vtkDataArray; class VTKFILTERSVERDICT_EXPORT vtkMatrixMathFilter : public vtkDataSetAlgorithm { - //BTX + enum { NONE = 0, @@ -47,7 +47,6 @@ class VTKFILTERSVERDICT_EXPORT vtkMatrixMathFilter : public vtkDataSetAlgorithm POINT_QUALITY = 0, CELL_QUALITY }; - //ETX public: void PrintSelf (ostream&, vtkIndent); diff --git a/GUISupport/Qt/CMakeLists.txt b/GUISupport/Qt/CMakeLists.txt index a8ede0b7adb..247a89d0411 100644 --- a/GUISupport/Qt/CMakeLists.txt +++ b/GUISupport/Qt/CMakeLists.txt @@ -55,13 +55,24 @@ set(QVTKNonMocHeaders ) if(VTK_QT_VERSION VERSION_GREATER "4") - find_package(Qt5 COMPONENTS Widgets REQUIRED QUIET) + set(qt_component_x11extras) + if(VTK_USE_X) + set(qt_component_x11extras X11Extras) + endif() + + find_package(Qt5 COMPONENTS Widgets ${qt_component_x11extras} REQUIRED QUIET) include_directories(${Qt5Widgets_INCLUDE_DIRS}) add_definitions(${Qt5Widgets_DEFINITIONS}) + if(qt_component_x11extras) + include_directories(${Qt5X11Extras_INCLUDE_DIRS}) + add_definitions(${Qt5X11Extras_DEFINITIONS}) + endif() + qt5_wrap_cpp(QVTKLibMocSrcs ${QVTKMocHeaders}) set(QT_LIBRARIES ${Qt5Widgets_LIBRARIES}) + set(QT_LIBRARIES_PRIVATE ${Qt5X11Extras_LIBRARIES}) # When this module is loaded by an app, load Qt too. vtk_module_export_code_find_package(Qt5Widgets) @@ -73,6 +84,7 @@ else() include(${QT_USE_FILE}) qt4_wrap_cpp(QVTKLibMocSrcs ${QVTKMocHeaders}) + set(QT_LIBRARIES_PRIVATE) endif() foreach(opt @@ -92,6 +104,9 @@ vtk_module_library(${vtk-module} ) vtk_module_link_libraries(${vtk-module} LINK_PUBLIC ${QT_LIBRARIES}) +if(QT_LIBRARIES_PRIVATE) + vtk_module_link_libraries(${vtk-module} LINK_PRIVATE ${QT_LIBRARIES_PRIVATE}) +endif() if(VTK_USE_X) vtk_module_link_libraries(${vtk-module} LINK_PRIVATE ${X11_LIBRARIES}) diff --git a/GUISupport/Qt/QVTKInteractorAdapter.cxx b/GUISupport/Qt/QVTKInteractorAdapter.cxx index fd18d8b8dd8..ee4e3a42aef 100644 --- a/GUISupport/Qt/QVTKInteractorAdapter.cxx +++ b/GUISupport/Qt/QVTKInteractorAdapter.cxx @@ -49,7 +49,7 @@ static const char* ascii_to_key_sym(int); static const char* qt_key_to_key_sym(Qt::Key, Qt::KeyboardModifiers modifiers); QVTKInteractorAdapter::QVTKInteractorAdapter(QObject* parentObject) - : QObject(parentObject) + : QObject(parentObject), AccumulatedDelta(0) { } @@ -264,15 +264,29 @@ bool QVTKInteractorAdapter::ProcessEvent(QEvent* e, vtkRenderWindowInteractor* i (e2->modifiers() & Qt::ControlModifier) > 0 ? 1 : 0, (e2->modifiers() & Qt::ShiftModifier ) > 0 ? 1 : 0); - // invoke vtk event - // if delta is positive, it is a forward wheel event - if(e2->delta() > 0) + this->AccumulatedDelta += e2->delta(); + const int threshold = 120; + + // invoke vtk event when accumulated delta passes the threshold + if(this->AccumulatedDelta >= threshold) { iren->InvokeEvent(vtkCommand::MouseWheelForwardEvent, e2); + this->AccumulatedDelta -= threshold; + // avoid accumulating too much delta per event + if (this->AccumulatedDelta > threshold/2) + { + this->AccumulatedDelta = threshold/2; + } } - else + else if(this->AccumulatedDelta <= -threshold) { iren->InvokeEvent(vtkCommand::MouseWheelBackwardEvent, e2); + this->AccumulatedDelta += threshold; + // avoid accumulating too much delta per event + if (this->AccumulatedDelta < -threshold/2) + { + this->AccumulatedDelta = -threshold/2; + } } return true; } diff --git a/GUISupport/Qt/QVTKInteractorAdapter.h b/GUISupport/Qt/QVTKInteractorAdapter.h index 10013e3c229..4f561050292 100644 --- a/GUISupport/Qt/QVTKInteractorAdapter.h +++ b/GUISupport/Qt/QVTKInteractorAdapter.h @@ -63,6 +63,9 @@ class VTKGUISUPPORTQT_EXPORT QVTKInteractorAdapter : public QObject // Process a QEvent and send it to the interactor // returns whether the event was recognized and processed bool ProcessEvent(QEvent* e, vtkRenderWindowInteractor* iren); + +protected: + int AccumulatedDelta; }; #endif diff --git a/GUISupport/Qt/QVTKWidget.cxx b/GUISupport/Qt/QVTKWidget.cxx index 3a67241a13c..e322238d449 100644 --- a/GUISupport/Qt/QVTKWidget.cxx +++ b/GUISupport/Qt/QVTKWidget.cxx @@ -44,8 +44,10 @@ #include "qsignalmapper.h" #include "qtimer.h" #include "vtkRenderingOpenGLConfigure.h" -#if defined(Q_WS_X11) -#include "qx11info_x11.h" +#if defined(Q_WS_X11) // aka Qt4 +# include "qx11info_x11.h" +#elif defined(Q_OS_LINUX) // aka Qt5 +# include #endif #if defined(Q_OS_WIN) @@ -66,7 +68,7 @@ #include "vtkRenderer.h" #include "vtkRendererCollection.h" -#if defined(VTK_USE_TDX) && defined(Q_WS_X11) +#if defined(VTK_USE_TDX) && (defined(Q_WS_X11) || defined(Q_OS_LINUX)) # include "vtkTDxUnixDevice.h" #endif @@ -75,6 +77,7 @@ QVTKWidget::QVTKWidget(QWidget* p, Qt::WindowFlags f) : QWidget(p, f | Qt::MSWindowsOwnDC), mRenWin(NULL), cachedImageCleanFlag(false), automaticImageCache(false), maxImageCacheRenderRate(1.0), + mDeferRenderInPaintEvent(false), renderEventCallbackObserverId(0) { this->UseTDx=false; @@ -103,6 +106,9 @@ QVTKWidget::QVTKWidget(QWidget* p, Qt::WindowFlags f) mIrenAdapter = new QVTKInteractorAdapter(this); + this->mDeferedRenderTimer.setSingleShot(true); + this->mDeferedRenderTimer.setInterval(0); + this->connect(&this->mDeferedRenderTimer, SIGNAL(timeout()), SLOT(doDeferredRender())); } /*! destructor */ @@ -126,7 +132,7 @@ void QVTKWidget::SetUseTDx(bool useTDx) if(this->UseTDx) { -#if defined(VTK_USE_TDX) && defined(Q_WS_X11) +#if defined(VTK_USE_TDX) && (defined(Q_WS_X11) || defined(Q_OS_LINUX)) QByteArray theSignal= QMetaObject::normalizedSignature("CreateDevice(vtkTDxDevice *)"); if(QApplication::instance()->metaObject()->indexOfSignal(theSignal)!=-1) @@ -191,7 +197,7 @@ void QVTKWidget::SetRenderWindow(vtkRenderWindow* w) { this->mRenWin->Finalize(); } -#ifdef Q_WS_X11 +#if defined(Q_WS_X11) || defined(Q_OS_LINUX) this->mRenWin->SetDisplayId(NULL); #endif this->mRenWin->SetWindowId(NULL); @@ -212,7 +218,7 @@ void QVTKWidget::SetRenderWindow(vtkRenderWindow* w) this->mRenWin->Finalize(); } -#ifdef Q_WS_X11 +#if defined(Q_WS_X11) || defined(Q_OS_LINUX) // give the qt display id to the vtk window this->mRenWin->SetDisplayId(QX11Info::display()); #endif @@ -292,7 +298,7 @@ void QVTKWidget::saveImageToCache() int h = this->height(); this->mCachedImage->SetExtent(0, w-1, 0, h-1, 0, 0); this->mCachedImage->AllocateScalars(VTK_UNSIGNED_CHAR, 3); - vtkUnsignedCharArray* array = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray* array = vtkArrayDownCast( this->mCachedImage->GetPointData()->GetScalars()); // We use back-buffer if this->mRenWin->GetPixelData(0, 0, this->width()-1, this->height()-1, @@ -326,6 +332,16 @@ double QVTKWidget::maxRenderRateForImageCache() const return this->maxImageCacheRenderRate; } +void QVTKWidget::setDeferRenderInPaintEvent(bool val) +{ + this->mDeferRenderInPaintEvent = val; +} + +bool QVTKWidget::deferRenderInPaintEvent() const +{ + return this->mDeferRenderInPaintEvent; +} + vtkImageData* QVTKWidget::cachedImage() { // Make sure image is up to date. @@ -442,30 +458,39 @@ void QVTKWidget::moveEvent(QMoveEvent* e) */ void QVTKWidget::paintEvent(QPaintEvent* ) { - vtkRenderWindowInteractor* iren = NULL; - if(this->mRenWin) - { - iren = this->mRenWin->GetInteractor(); - } - - if(!iren || !iren->GetEnabled()) + vtkRenderWindowInteractor* iren = this->mRenWin ? this->mRenWin->GetInteractor() : NULL; + if (!iren || !iren->GetEnabled()) { return; } + // In Qt 4.1+ let's support redirected painting + // if redirected, let's grab the image from VTK, and paint it to the device + QPaintDevice* device = QPainter::redirected(this); + bool usingRedirectedDevice = (device != NULL && device != this); + // if we have a saved image, use it - if (this->paintCachedImage()) + if (this->paintCachedImage() == false) { - return; + // we don't defer render in redirected painting is active since the target + // being painted to may not be around when the deferred render call happens. + if (!usingRedirectedDevice && this->mDeferRenderInPaintEvent) + { + this->deferRender(); + } + else + { + iren->Render(); + } } - iren->Render(); - - // In Qt 4.1+ let's support redirected painting - // if redirected, let's grab the image from VTK, and paint it to the device - QPaintDevice* device = QPainter::redirected(this); - if(device != NULL && device != this) + // Irrespective of whether cache was used on or, if using redirected painting + // is being employed, we need to "paint" the image from the render window to + // the redirected target. + if (usingRedirectedDevice) { + Q_ASSERT(device); + int w = this->width(); int h = this->height(); QImage img(w, h, QImage::Format_RGB32); @@ -478,7 +503,6 @@ void QVTKWidget::paintEvent(QPaintEvent* ) QPainter painter(this); painter.drawImage(QPointF(0.0,0.0), img); - return; } } @@ -653,7 +677,7 @@ QPaintEngine* QVTKWidget::paintEngine() const // X11 stuff near the bottom of the file // to prevent namespace collisions with Qt headers -#if defined Q_WS_X11 +#if defined(Q_WS_X11) || defined (Q_OS_LINUX) #if defined(VTK_USE_OPENGL_LIBRARY) #include "vtkXOpenGLRenderWindow.h" #endif @@ -664,7 +688,7 @@ QPaintEngine* QVTKWidget::paintEngine() const // Receive notification of the creation of the TDxDevice void QVTKWidget::setDevice(vtkTDxDevice *device) { -#ifdef Q_WS_X11 +#if defined(Q_WS_X11) || defined(Q_OS_LINUX) if(this->GetInteractor()->GetDevice()!=device) { this->GetInteractor()->SetDevice(device); @@ -677,7 +701,10 @@ void QVTKWidget::setDevice(vtkTDxDevice *device) void QVTKWidget::x11_setup_window() { -#if defined Q_WS_X11 +#if defined(Q_WS_X11) + // NOTE: deliberately not executing this code for Qt5. It caused issues with + // glewInit() when I did that. Just letting the Qt create the visual/colormap + // seems to work better. // this whole function is to allow this window to have a // different colormap and visual than the rest of the Qt application @@ -827,7 +854,7 @@ bool QVTKWidget::paintCachedImage() // if we have a saved image, use it if (this->cachedImageCleanFlag) { - vtkUnsignedCharArray* array = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray* array = vtkArrayDownCast( this->mCachedImage->GetPointData()->GetScalars()); // put cached image into back buffer if we can this->mRenWin->SetPixelData(0, 0, this->width()-1, this->height()-1, @@ -862,6 +889,10 @@ void QVTKWidget::renderEventCallback() } } + // Render happened. If we have requested a render to happen, it has happened, + // so no need to request another render. Stop the timer. + this->mDeferedRenderTimer.stop(); + this->markCachedImageAsDirty(); if (this->isAutomaticImageCacheEnabled() && (this->mRenWin->GetDesiredUpdateRate() < this->maxRenderRateForImageCache())) @@ -870,3 +901,19 @@ void QVTKWidget::renderEventCallback() } } } + +//----------------------------------------------------------------------------- +void QVTKWidget::deferRender() +{ + this->mDeferedRenderTimer.start(); +} + +//----------------------------------------------------------------------------- +void QVTKWidget::doDeferredRender() +{ + vtkRenderWindowInteractor* iren = this->mRenWin ? this->mRenWin->GetInteractor() : NULL; + if (iren && iren->GetEnabled()) + { + iren->Render(); + } +} diff --git a/GUISupport/Qt/QVTKWidget.h b/GUISupport/Qt/QVTKWidget.h index b9b13881d00..b9bbcdcaf50 100644 --- a/GUISupport/Qt/QVTKWidget.h +++ b/GUISupport/Qt/QVTKWidget.h @@ -39,6 +39,7 @@ #include "vtkGUISupportQtModule.h" // For export macro #include "QVTKInteractor.h" #include +#include class QVTKInteractorAdapter; @@ -74,6 +75,9 @@ class VTKGUISUPPORTQT_EXPORT QVTKWidget : public QWidget Q_PROPERTY(double maxRenderRateForImageCache READ maxRenderRateForImageCache WRITE setMaxRenderRateForImageCache) + Q_PROPERTY(bool deferRenderInPaintEvent + READ deferRenderInPaintEvent + WRITE setDeferRenderInPaintEvent) public: //! constructor @@ -113,7 +117,7 @@ class VTKGUISUPPORTQT_EXPORT QVTKWidget : public QWidget // Description: // If automatic image caching is enabled, then the image will be cached - // after every render with a DesiredUpdateRate that is greater than + // after every render with a DesiredUpdateRate that is less than // this parameter. By default, the vtkRenderWindowInteractor will // change the desired render rate depending on the user's // interactions. (See vtkRenderWindow::DesiredUpdateRate, @@ -143,6 +147,18 @@ class VTKGUISUPPORTQT_EXPORT QVTKWidget : public QWidget void SetUseTDx(bool useTDx); bool GetUseTDx() const; + // Description: + // When set to true (default is false), paintEvent() will never directly trigger + // a render on the vtkRenderWindow (via vtkRenderWindowInteractor::Render()). + // Instead, it starts a timer that then triggers the render on idle. This, in + // general is a good strategy for cases where Render may take a while with + // applications wanting to report progress and consequently trigger paint + // events on other widgets like progress bars, etc. + // There is one caveat: when paintEvent() is called using a redirected paint device, + // then this flag is ignored and the paintEvent() will trigger + // vtkRenderWindowInteractor::Render(), if needed. + void setDeferRenderInPaintEvent(bool val); + bool deferRenderInPaintEvent() const; Q_SIGNALS: // Description: @@ -180,6 +196,17 @@ public Q_SLOTS: void setDevice(vtkTDxDevice *device); #endif +protected Q_SLOTS: + // Description: + // Request to defer a render call i.e. start the mDeferedRenderTimer. When the + // timer times out, it will call doDeferredRender() to do the actual + // rendering. + virtual void deferRender(); + + // Description: + // Called when the mDeferedRenderTimer times out to do the rendering. + virtual void doDeferredRender(); + protected: // overloaded resize handler virtual void resizeEvent(QResizeEvent* event); @@ -250,12 +277,13 @@ public Q_SLOTS: #endif protected: - vtkImageData* mCachedImage; bool cachedImageCleanFlag; bool automaticImageCache; double maxImageCacheRenderRate; QVTKInteractorAdapter* mIrenAdapter; + bool mDeferRenderInPaintEvent; + private: //! unimplemented operator= @@ -269,6 +297,7 @@ public Q_SLOTS: // Callback called on every vtkCommand::RenderEvent fired by the // vtkRenderWindow. void renderEventCallback(); + QTimer mDeferedRenderTimer; }; #endif diff --git a/GUISupport/Qt/vtkQtAnnotationLayersModelAdapter.cxx b/GUISupport/Qt/vtkQtAnnotationLayersModelAdapter.cxx index 17d9c3bf503..c19d8313886 100644 --- a/GUISupport/Qt/vtkQtAnnotationLayersModelAdapter.cxx +++ b/GUISupport/Qt/vtkQtAnnotationLayersModelAdapter.cxx @@ -182,7 +182,7 @@ QItemSelection vtkQtAnnotationLayersModelAdapter::VTKAnnotationLayersToQItemSele vtkSelectionNode* node = vtksel->GetNode(0); if (node) { - vtkIdTypeArray* arr = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkIdTypeArray* arr = vtkArrayDownCast(node->GetSelectionList()); if (arr) { for (vtkIdType i = 0; i < arr->GetNumberOfTuples(); i++) @@ -237,7 +237,7 @@ QItemSelection vtkQtAnnotationLayersModelAdapter::VTKIndexSelectionToQItemSelect vtkSelectionNode* node = vtksel->GetNode(0); if (node) { - vtkIdTypeArray* arr = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkIdTypeArray* arr = vtkArrayDownCast(node->GetSelectionList()); if (arr) { for (vtkIdType i = 0; i < arr->GetNumberOfTuples(); i++) diff --git a/GUISupport/Qt/vtkQtTableModelAdapter.cxx b/GUISupport/Qt/vtkQtTableModelAdapter.cxx index 4ae63a22d10..77dfb9981a2 100644 --- a/GUISupport/Qt/vtkQtTableModelAdapter.cxx +++ b/GUISupport/Qt/vtkQtTableModelAdapter.cxx @@ -301,7 +301,7 @@ void vtkQtTableModelAdapter::updateModelColumnHashTables() } // If number of components is greater than 1, create a new column for Magnitude - vtkDataArray* dataArray = vtkDataArray::SafeDownCast(this->Table->GetColumn(tableColumn)); + vtkDataArray* dataArray = vtkArrayDownCast(this->Table->GetColumn(tableColumn)); if (nComponents > 1 && dataArray) { vtkSmartPointer magArray = vtkSmartPointer::New(); @@ -415,7 +415,7 @@ QItemSelection vtkQtTableModelAdapter::VTKIndexSelectionToQItemSelection( vtkSelectionNode* node = vtksel->GetNode(0); if (node) { - vtkIdTypeArray* arr = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkIdTypeArray* arr = vtkArrayDownCast(node->GetSelectionList()); if (arr) { for (vtkIdType i = 0; i < arr->GetNumberOfTuples(); i++) @@ -806,7 +806,7 @@ QVariant vtkQtTableModelAdapter::getColorIcon(int row) const { column = this->ModelColumnToFieldDataColumn(this->ColorColumn); } - vtkUnsignedCharArray* colors = vtkUnsignedCharArray::SafeDownCast(this->Table->GetColumn(column)); + vtkUnsignedCharArray* colors = vtkArrayDownCast(this->Table->GetColumn(column)); if (!colors) { return QVariant(); @@ -816,7 +816,7 @@ QVariant vtkQtTableModelAdapter::getColorIcon(int row) const if(nComponents >= 3) { unsigned char rgba[4]; - colors->GetTupleValue(row, rgba); + colors->GetTypedTuple(row, rgba); int rgb[3]; rgb[0] = static_cast(0x0ff & rgba[0]); rgb[1] = static_cast(0x0ff & rgba[1]); @@ -846,7 +846,7 @@ QVariant vtkQtTableModelAdapter::getIcon(int row) const { column = this->ModelColumnToFieldDataColumn(this->IconIndexColumn); } - vtkIntArray* icon_indices = vtkIntArray::SafeDownCast(this->Table->GetColumn(column)); + vtkIntArray* icon_indices = vtkArrayDownCast(this->Table->GetColumn(column)); if (!icon_indices) { return QVariant(); diff --git a/GUISupport/Qt/vtkQtTreeModelAdapter.cxx b/GUISupport/Qt/vtkQtTreeModelAdapter.cxx index 45ac4972844..25f35ef7a65 100644 --- a/GUISupport/Qt/vtkQtTreeModelAdapter.cxx +++ b/GUISupport/Qt/vtkQtTreeModelAdapter.cxx @@ -220,7 +220,7 @@ QItemSelection vtkQtTreeModelAdapter::VTKIndexSelectionToQItemSelection( vtkSelectionNode* node = vtksel->GetNode(j); if (node && node->GetFieldType() == vtkSelectionNode::VERTEX) { - vtkIdTypeArray* arr = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkIdTypeArray* arr = vtkArrayDownCast(node->GetSelectionList()); if (arr) { for (vtkIdType i = 0; i < arr->GetNumberOfTuples(); i++) @@ -259,22 +259,22 @@ void vtkQtTreeModelAdapter::GenerateVTKIndexToQtModelIndex(vtkIdType vtk_index, QVariant vtkQtTreeModelAdapterArrayValue(vtkAbstractArray* arr, vtkIdType i, vtkIdType j) { int comps = arr->GetNumberOfComponents(); - if(vtkDataArray* const data = vtkDataArray::SafeDownCast(arr)) + if(vtkDataArray* const data = vtkArrayDownCast(arr)) { return QVariant(data->GetComponent(i, j)); } - if(vtkStringArray* const data = vtkStringArray::SafeDownCast(arr)) + if(vtkStringArray* const data = vtkArrayDownCast(arr)) { return QVariant(data->GetValue(i*comps + j)); } - if(vtkUnicodeStringArray* const data = vtkUnicodeStringArray::SafeDownCast(arr)) + if(vtkUnicodeStringArray* const data = vtkArrayDownCast(arr)) { return QVariant(QString::fromUtf8(data->GetValue(i*comps + j).utf8_str())); } - if(vtkVariantArray* const data = vtkVariantArray::SafeDownCast(arr)) + if(vtkVariantArray* const data = vtkArrayDownCast(arr)) { return QVariant(QString(data->GetValue(i*comps + j).ToString().c_str())); } @@ -315,7 +315,7 @@ QVariant vtkQtTreeModelAdapter::data(const QModelIndex &idx, int role) const if(this->ColorColumn >= 0) { int colorColumn = this->ModelColumnToFieldDataColumn(this->ColorColumn); - vtkUnsignedCharArray* colors = vtkUnsignedCharArray::SafeDownCast(this->Tree->GetVertexData()->GetAbstractArray(colorColumn)); + vtkUnsignedCharArray* colors = vtkArrayDownCast(this->Tree->GetVertexData()->GetAbstractArray(colorColumn)); if (!colors) { return QVariant(); @@ -328,7 +328,7 @@ QVariant vtkQtTreeModelAdapter::data(const QModelIndex &idx, int role) const } unsigned char rgba[4]; - colors->GetTupleValue(vertex, rgba); + colors->GetTypedTuple(vertex, rgba); int rgb[3]; rgb[0] = static_cast(0x0ff & rgba[0]); rgb[1] = static_cast(0x0ff & rgba[1]); diff --git a/GUISupport/QtWebkit/vtkQtRichTextView.cxx b/GUISupport/QtWebkit/vtkQtRichTextView.cxx index 0ac1355992d..4ee44f865c3 100644 --- a/GUISupport/QtWebkit/vtkQtRichTextView.cxx +++ b/GUISupport/QtWebkit/vtkQtRichTextView.cxx @@ -219,7 +219,7 @@ void vtkQtRichTextView::Update() this->Internal->UI.WebView->history()->clear(); // Workaround for a quirk in QWebHistory - vtkIdTypeArray* selectedRows = vtkIdTypeArray::SafeDownCast(selection->GetNode(0)->GetSelectionList()); + vtkIdTypeArray* selectedRows = vtkArrayDownCast(selection->GetNode(0)->GetSelectionList()); if(selectedRows->GetNumberOfTuples() == 0) { this->Internal->UI.WebView->setHtml(""); diff --git a/Geovis/Core/Testing/Cxx/TestGlobeSource.cxx b/Geovis/Core/Testing/Cxx/TestGlobeSource.cxx index ff129f0eaee..9c8f285c76e 100644 --- a/Geovis/Core/Testing/Cxx/TestGlobeSource.cxx +++ b/Geovis/Core/Testing/Cxx/TestGlobeSource.cxx @@ -67,7 +67,7 @@ int TestGlobeSource(int argc, char* argv[]) VTK_CREATE(vtkDoubleArray, textureCoords); textureCoords->SetNumberOfComponents(2); - vtkDoubleArray* array = vtkDoubleArray::SafeDownCast( + vtkDoubleArray* array = vtkArrayDownCast( globeSource->GetOutput(0)->GetPointData()->GetAbstractArray("LatLong")); double range[] = { (latRange[0] - latRange[1]), @@ -82,7 +82,7 @@ int TestGlobeSource(int argc, char* argv[]) for(int i=0; i < array->GetNumberOfTuples(); ++i) { - array->GetTupleValue(i, val); + array->GetTypedTuple(i, val); // Get the texture coordinates in [0,1] range. newVal[1] = (latRange[0] - val[0]) / range[0]; diff --git a/Geovis/Core/vtkCompassRepresentation.cxx b/Geovis/Core/vtkCompassRepresentation.cxx index c21ac605212..06eb74cdeab 100644 --- a/Geovis/Core/vtkCompassRepresentation.cxx +++ b/Geovis/Core/vtkCompassRepresentation.cxx @@ -172,11 +172,11 @@ void vtkCompassRepresentation::BuildBackdrop() color[1] = 0; color[2] = 0; color[3] = 0; - colors->SetTupleValue(0,color); - colors->SetTupleValue(3,color); + colors->SetTypedTuple(0,color); + colors->SetTypedTuple(3,color); color[3] = 80; - colors->SetTupleValue(1,color); - colors->SetTupleValue(2,color); + colors->SetTypedTuple(1,color); + colors->SetTypedTuple(2,color); backdropPolyData->GetPointData()->SetScalars(colors); this->BackdropMapper = vtkPolyDataMapper2D::New(); @@ -464,7 +464,7 @@ void vtkCompassRepresentation::BuildRepresentation() int *renSize = this->Renderer->GetSize(); vtkUnsignedCharArray* colors = - vtkUnsignedCharArray::SafeDownCast + vtkArrayDownCast ( this->BackdropMapper->GetInput()->GetPointData()->GetScalars() ); unsigned char color[4]; color[0] = 0; @@ -480,14 +480,14 @@ void vtkCompassRepresentation::BuildRepresentation() pts->SetPoint( 0, center[0] - rsize * 5.0, center[1] - rsize * 1.1, 0 ); pts->SetPoint( 3, center[0] - rsize * 5.0, renSize[1], 0 ); color[3] = 80; - colors->SetTupleValue(1,color); + colors->SetTypedTuple(1,color); } else { pts->SetPoint( 0, center[0] - rsize * 3.0, center[1] - rsize * 1.1, 0 ); pts->SetPoint( 3, center[0] - rsize * 3.0, renSize[1], 0 ); color[3] = 0; - colors->SetTupleValue( 1, color ); + colors->SetTypedTuple( 1, color ); } pts->Modified(); colors->Modified(); diff --git a/Geovis/Core/vtkCompassRepresentation.h b/Geovis/Core/vtkCompassRepresentation.h index 1c652f93d43..6c552886324 100644 --- a/Geovis/Core/vtkCompassRepresentation.h +++ b/Geovis/Core/vtkCompassRepresentation.h @@ -127,7 +127,6 @@ class VTKGEOVISCORE_EXPORT vtkCompassRepresentation : virtual void EndDistance(); virtual void SetRenderer(vtkRenderer *ren); -//BTX // Enums are used to describe what is selected enum _InteractionState { @@ -141,7 +140,6 @@ class VTKGEOVISCORE_EXPORT vtkCompassRepresentation : DistanceIn, DistanceAdjusting }; -//ETX protected: vtkCompassRepresentation(); @@ -156,10 +154,9 @@ class VTKGEOVISCORE_EXPORT vtkCompassRepresentation : double OuterRadius; // tilt and distance rep - //BTX + vtkSmartPointer TiltRepresentation; vtkSmartPointer DistanceRepresentation; - //ETX // Define the geometry. It is constructed in canaonical position // along the x-axis and then rotated into position. diff --git a/Geovis/Core/vtkCompassWidget.h b/Geovis/Core/vtkCompassWidget.h index a51cab45f01..7a3d1e2637f 100644 --- a/Geovis/Core/vtkCompassWidget.h +++ b/Geovis/Core/vtkCompassWidget.h @@ -109,7 +109,6 @@ class VTKGEOVISCORE_EXPORT vtkCompassWidget : public vtkAbstractWidget static void MoveAction(vtkAbstractWidget*); static void TimerAction(vtkAbstractWidget*); -//BTX - manage the state of the widget int WidgetState; enum _WidgetState { @@ -119,7 +118,6 @@ class VTKGEOVISCORE_EXPORT vtkCompassWidget : public vtkAbstractWidget TiltAdjusting, DistanceAdjusting }; -//ETX int TimerId; int TimerDuration; diff --git a/Geovis/Core/vtkGeoAlignedImageSource.h b/Geovis/Core/vtkGeoAlignedImageSource.h index 240893f3690..42565432fcb 100644 --- a/Geovis/Core/vtkGeoAlignedImageSource.h +++ b/Geovis/Core/vtkGeoAlignedImageSource.h @@ -89,10 +89,8 @@ class VTKGEOVISCORE_EXPORT vtkGeoAlignedImageSource : public vtkGeoSource double Overlap; bool PowerOfTwoSize; - //BTX class vtkProgressObserver; vtkProgressObserver* ProgressObserver; - //ETX private: vtkGeoAlignedImageSource(const vtkGeoAlignedImageSource&); // Not implemented. diff --git a/Geovis/Core/vtkGeoCamera.h b/Geovis/Core/vtkGeoCamera.h index 041f236d11d..5f15845e8c4 100644 --- a/Geovis/Core/vtkGeoCamera.h +++ b/Geovis/Core/vtkGeoCamera.h @@ -176,10 +176,8 @@ class VTKGEOVISCORE_EXPORT vtkGeoCamera : public vtkObject void UpdateVTKCamera(); void UpdateAngleRanges(); -//BTX vtkSmartPointer VTKCamera; vtkSmartPointer Transform; -//ETX // This point is shifted to 0,0,0 to avoid openGL issues. double OriginLatitude; diff --git a/Geovis/Core/vtkGeoGraticule.h b/Geovis/Core/vtkGeoGraticule.h index 7ed38d86d3a..4f767a34555 100644 --- a/Geovis/Core/vtkGeoGraticule.h +++ b/Geovis/Core/vtkGeoGraticule.h @@ -53,13 +53,11 @@ class VTKGEOVISCORE_EXPORT vtkGeoGraticule : public vtkPolyDataAlgorithm vtkSetVector2Macro(LongitudeBounds,double); vtkGetVector2Macro(LongitudeBounds,double); - //BTX enum LevelLimits { LEVEL_MIN = 0, LEVEL_MAX = 11, NUMBER_OF_LEVELS = ( LEVEL_MAX - LEVEL_MIN + 1 ) }; - //ETX // Description: // The frequency level of latitude lines. @@ -89,12 +87,10 @@ class VTKGEOVISCORE_EXPORT vtkGeoGraticule : public vtkPolyDataAlgorithm vtkSetMacro(GeometryType,int); vtkGetMacro(GeometryType,int); - //BTX enum GeometryType { POLYLINES = 0x1, QUADRILATERALS = 0x2 }; - //ETX protected: vtkGeoGraticule(); diff --git a/Geovis/Core/vtkGeoImageNode.cxx b/Geovis/Core/vtkGeoImageNode.cxx index a457ed2cb61..a38367dfdda 100644 --- a/Geovis/Core/vtkGeoImageNode.cxx +++ b/Geovis/Core/vtkGeoImageNode.cxx @@ -177,7 +177,7 @@ void vtkGeoImageNode::CropImageForTile( storedImage->SetSpacing(this->LongitudeRange[1], this->LatitudeRange[1], 0); vtkXMLImageDataWriter* writer = vtkXMLImageDataWriter::New(); char fn[512]; - sprintf(fn, "%s/tile_%d_%ld.vti", prefix, this->Level, this->Id); + sprintf(fn, "%s/tile_%d_%lu.vti", prefix, this->Level, this->Id); writer->SetFileName(fn); writer->SetInputData(storedImage); writer->Write(); @@ -191,7 +191,7 @@ void vtkGeoImageNode::LoadAnImage(const char* prefix) { vtkXMLImageDataReader* reader = vtkXMLImageDataReader::New(); char fn[512]; - sprintf(fn, "%s/tile_%d_%ld.vti", prefix, this->Level, this->Id); + sprintf(fn, "%s/tile_%d_%lu.vti", prefix, this->Level, this->Id); reader->SetFileName(fn); reader->Update(); vtkImageData* image = reader->GetOutput(); diff --git a/Geovis/Core/vtkGeoImageNode.h b/Geovis/Core/vtkGeoImageNode.h index 9eafce007ca..1193533b017 100644 --- a/Geovis/Core/vtkGeoImageNode.h +++ b/Geovis/Core/vtkGeoImageNode.h @@ -93,10 +93,8 @@ class VTKGEOVISCORE_EXPORT vtkGeoImageNode : public vtkGeoTreeNode int PowerOfTwo(int val); -//BTX vtkSmartPointer Image; vtkSmartPointer Texture; -//ETX private: vtkGeoImageNode(const vtkGeoImageNode&); // Not implemented. diff --git a/Geovis/Core/vtkGeoInteractorStyle.h b/Geovis/Core/vtkGeoInteractorStyle.h index 51dbc16b237..3e5a5e80a67 100644 --- a/Geovis/Core/vtkGeoInteractorStyle.h +++ b/Geovis/Core/vtkGeoInteractorStyle.h @@ -144,15 +144,12 @@ class VTKGEOVISCORE_EXPORT vtkGeoInteractorStyle : int PixelDims[2]; bool LockHeading; -//BTX vtkSmartPointer GeoCamera; // widget handling members vtkSmartPointer CompassWidget; vtkSmartPointer EventCommand; -//ETX - private: vtkGeoInteractorStyle(const vtkGeoInteractorStyle&); // Not implemented. void operator=(const vtkGeoInteractorStyle&); // Not implemented. diff --git a/Geovis/Core/vtkGeoSampleArcs.h b/Geovis/Core/vtkGeoSampleArcs.h index be4d5d1df49..f6a330295a1 100644 --- a/Geovis/Core/vtkGeoSampleArcs.h +++ b/Geovis/Core/vtkGeoSampleArcs.h @@ -52,13 +52,11 @@ class VTKGEOVISCORE_EXPORT vtkGeoSampleArcs : public vtkPolyDataAlgorithm vtkSetMacro(MaximumDistanceMeters, double); vtkGetMacro(MaximumDistanceMeters, double); - //BTX enum { RECTANGULAR, SPHERICAL }; - //ETX // Description: // The input coordinate system. diff --git a/Geovis/Core/vtkGeoSource.h b/Geovis/Core/vtkGeoSource.h index 40d3345149e..20e2db63527 100644 --- a/Geovis/Core/vtkGeoSource.h +++ b/Geovis/Core/vtkGeoSource.h @@ -105,10 +105,8 @@ class VTKGEOVISCORE_EXPORT vtkGeoSource : public vtkObject bool StopThread; bool Initialized; - //BTX class implementation; implementation* Implementation; - //ETX private: vtkGeoSource(const vtkGeoSource&); // Not implemented diff --git a/Geovis/Core/vtkGeoTerrainNode.h b/Geovis/Core/vtkGeoTerrainNode.h index 8377233c52b..ecffcb679f6 100644 --- a/Geovis/Core/vtkGeoTerrainNode.h +++ b/Geovis/Core/vtkGeoTerrainNode.h @@ -111,9 +111,7 @@ class VTKGEOVISCORE_EXPORT vtkGeoTerrainNode : public vtkGeoTreeNode vtkGeoTerrainNode(); ~vtkGeoTerrainNode(); -//BTX vtkSmartPointer Model; -//ETX double BoundingSphereRadius; double BoundingSphereCenter[3]; diff --git a/Geovis/Core/vtkGeoTransform.cxx b/Geovis/Core/vtkGeoTransform.cxx index 247b592697a..789dd77c9e2 100644 --- a/Geovis/Core/vtkGeoTransform.cxx +++ b/Geovis/Core/vtkGeoTransform.cxx @@ -64,8 +64,8 @@ void vtkGeoTransform::TransformPoints( vtkPoints* srcPts, vtkPoints* dstPts ) return; } - vtkDoubleArray* srcCoords = vtkDoubleArray::SafeDownCast( srcPts->GetData() ); - vtkDoubleArray* dstCoords = vtkDoubleArray::SafeDownCast( dstPts->GetData() ); + vtkDoubleArray* srcCoords = vtkArrayDownCast( srcPts->GetData() ); + vtkDoubleArray* dstCoords = vtkArrayDownCast( dstPts->GetData() ); if ( ! srcCoords || ! dstCoords ) { // data not in a form we can use directly anyway... this->Superclass::TransformPoints( srcPts, dstPts ); diff --git a/Geovis/Core/vtkGeoTreeNode.h b/Geovis/Core/vtkGeoTreeNode.h index 4c82de1bd9a..f4289cf72f0 100644 --- a/Geovis/Core/vtkGeoTreeNode.h +++ b/Geovis/Core/vtkGeoTreeNode.h @@ -133,7 +133,6 @@ class VTKGEOVISCORE_EXPORT vtkGeoTreeNode : public vtkObject vtkGeoTreeNode* GetParentTreeNode() { return this->Parent; } -//BTX enum NodeStatus { NONE, @@ -142,7 +141,6 @@ class VTKGEOVISCORE_EXPORT vtkGeoTreeNode : public vtkObject NodeStatus GetStatus(); void SetStatus(NodeStatus status); -//ETX // Description: // Shallow and Deep copy. Deep copy performs a shallow copy @@ -160,13 +158,11 @@ class VTKGEOVISCORE_EXPORT vtkGeoTreeNode : public vtkObject double LongitudeRange[2]; double LatitudeRange[2]; - //BTX vtkSmartPointer Children[4]; vtkGeoTreeNode * Parent; NodeStatus Status; vtkGeoTreeNode* Older; vtkGeoTreeNode* Newer; - //ETX private: vtkGeoTreeNode(const vtkGeoTreeNode&); // Not implemented. diff --git a/Geovis/Core/vtkGeoTreeNodeCache.h b/Geovis/Core/vtkGeoTreeNodeCache.h index 05e0a5063dc..3bda113e4de 100644 --- a/Geovis/Core/vtkGeoTreeNodeCache.h +++ b/Geovis/Core/vtkGeoTreeNodeCache.h @@ -85,10 +85,9 @@ class VTKGEOVISCORE_EXPORT vtkGeoTreeNodeCache : public vtkObject int Size; int CacheMinimumLimit; int CacheMaximumLimit; - //BTX + vtkSmartPointer Newest; vtkSmartPointer Oldest; - //ETX private: vtkGeoTreeNodeCache(const vtkGeoTreeNodeCache&); // Not implemented diff --git a/IO/AMR/vtkAMRBaseReader.h b/IO/AMR/vtkAMRBaseReader.h index cb5c840e1d5..fc2df2ef9dc 100644 --- a/IO/AMR/vtkAMRBaseReader.h +++ b/IO/AMR/vtkAMRBaseReader.h @@ -254,10 +254,7 @@ class VTKIOAMR_EXPORT vtkAMRBaseReader : vtkOverlappingAMR *Metadata; bool LoadedMetaData; - - //BTX std::vector BlockMap; - //ETX private: vtkAMRBaseReader( const vtkAMRBaseReader& ); // Not implemented diff --git a/IO/AMR/vtkAMRDataSetCache.h b/IO/AMR/vtkAMRDataSetCache.h index 35ca16f0f06..63bc1d9dc66 100644 --- a/IO/AMR/vtkAMRDataSetCache.h +++ b/IO/AMR/vtkAMRDataSetCache.h @@ -90,10 +90,8 @@ class VTKIOAMR_EXPORT vtkAMRDataSetCache : public vtkObject vtkAMRDataSetCache(); virtual ~vtkAMRDataSetCache(); -//BTX typedef std::map< int, vtkUniformGrid* > AMRCacheType; AMRCacheType Cache; -//ETX private: vtkAMRDataSetCache( const vtkAMRDataSetCache& ); // Not implemented diff --git a/IO/AMR/vtkAMREnzoParticlesReader.cxx b/IO/AMR/vtkAMREnzoParticlesReader.cxx index 8232c91268e..9ab10e47afd 100644 --- a/IO/AMR/vtkAMREnzoParticlesReader.cxx +++ b/IO/AMR/vtkAMREnzoParticlesReader.cxx @@ -276,7 +276,7 @@ vtkPolyData* vtkAMREnzoParticlesReader::GetParticles( GetDoubleArrayByName( rootIndx, "particle_position_y", ycoords ); GetDoubleArrayByName( rootIndx, "particle_position_z", zcoords ); - vtkIntArray *particleTypes = vtkIntArray::SafeDownCast( + vtkIntArray *particleTypes = vtkArrayDownCast( this->GetParticlesTypeArray( blockIdx ) ); assert( "Coordinate arrays must have the same size: " && diff --git a/IO/AMR/vtkAMREnzoReaderInternal.cxx b/IO/AMR/vtkAMREnzoReaderInternal.cxx index c4d7ec12aa1..6f1e173f193 100644 --- a/IO/AMR/vtkAMREnzoReaderInternal.cxx +++ b/IO/AMR/vtkAMREnzoReaderInternal.cxx @@ -538,7 +538,7 @@ int vtkEnzoReaderInternal::LoadAttribute( const char *atribute, int blockIdx ) this->DataArray = vtkFloatArray::New(); this->DataArray->SetNumberOfTuples( numTupls ); float * arrayPtr = static_cast < float * > - (vtkFloatArray::SafeDownCast( this->DataArray )->GetPointer( 0 ) ); + (vtkArrayDownCast( this->DataArray )->GetPointer( 0 ) ); H5Dread( attrIndx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr ); arrayPtr = NULL; } @@ -548,7 +548,7 @@ int vtkEnzoReaderInternal::LoadAttribute( const char *atribute, int blockIdx ) this->DataArray = vtkDoubleArray::New(); this->DataArray->SetNumberOfTuples( numTupls ); double * arrayPtr = static_cast < double * > - (vtkDoubleArray::SafeDownCast( this->DataArray )->GetPointer( 0 ) ); + (vtkArrayDownCast( this->DataArray )->GetPointer( 0 ) ); H5Dread( attrIndx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr ); arrayPtr = NULL; } @@ -558,7 +558,7 @@ int vtkEnzoReaderInternal::LoadAttribute( const char *atribute, int blockIdx ) this->DataArray = vtkIntArray::New(); this->DataArray->SetNumberOfTuples( numTupls ); int * arrayPtr = static_cast < int * > - (vtkIntArray::SafeDownCast( this->DataArray )->GetPointer( 0 ) ); + (vtkArrayDownCast( this->DataArray )->GetPointer( 0 ) ); H5Dread( attrIndx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr ); arrayPtr = NULL; } @@ -568,7 +568,7 @@ int vtkEnzoReaderInternal::LoadAttribute( const char *atribute, int blockIdx ) this->DataArray = vtkUnsignedIntArray::New(); this->DataArray->SetNumberOfTuples( numTupls ); unsigned int * arrayPtr = static_cast < unsigned int * > - (vtkUnsignedIntArray::SafeDownCast( this->DataArray )->GetPointer( 0 ) ); + (vtkArrayDownCast( this->DataArray )->GetPointer( 0 ) ); H5Dread( attrIndx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr ); arrayPtr = NULL; } @@ -578,7 +578,7 @@ int vtkEnzoReaderInternal::LoadAttribute( const char *atribute, int blockIdx ) this->DataArray = vtkShortArray::New(); this->DataArray->SetNumberOfTuples( numTupls ); short * arrayPtr = static_cast < short * > - (vtkShortArray::SafeDownCast( this->DataArray )->GetPointer( 0 ) ); + (vtkArrayDownCast( this->DataArray )->GetPointer( 0 ) ); H5Dread( attrIndx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr ); arrayPtr = NULL; } @@ -588,7 +588,7 @@ int vtkEnzoReaderInternal::LoadAttribute( const char *atribute, int blockIdx ) this->DataArray = vtkUnsignedShortArray::New(); this->DataArray->SetNumberOfTuples( numTupls ); unsigned short * arrayPtr = static_cast < unsigned short * > - (vtkUnsignedShortArray::SafeDownCast( this->DataArray )->GetPointer( 0 )); + (vtkArrayDownCast( this->DataArray )->GetPointer( 0 )); H5Dread( attrIndx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr ); arrayPtr = NULL; } @@ -599,7 +599,7 @@ int vtkEnzoReaderInternal::LoadAttribute( const char *atribute, int blockIdx ) this->DataArray = vtkUnsignedCharArray::New(); this->DataArray->SetNumberOfTuples( numTupls ); unsigned char * arrayPtr = static_cast < unsigned char * > - (vtkUnsignedCharArray::SafeDownCast( this->DataArray )->GetPointer( 0 ) ); + (vtkArrayDownCast( this->DataArray )->GetPointer( 0 ) ); H5Dread( attrIndx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr ); arrayPtr = NULL; } @@ -609,7 +609,7 @@ int vtkEnzoReaderInternal::LoadAttribute( const char *atribute, int blockIdx ) this->DataArray = vtkLongArray::New(); this->DataArray->SetNumberOfTuples( numTupls ); long * arrayPtr = static_cast < long * > - (vtkLongArray::SafeDownCast( this->DataArray )->GetPointer( 0 ) ); + (vtkArrayDownCast( this->DataArray )->GetPointer( 0 ) ); H5Dread( attrIndx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr ); arrayPtr = NULL; } @@ -619,7 +619,7 @@ int vtkEnzoReaderInternal::LoadAttribute( const char *atribute, int blockIdx ) this->DataArray = vtkLongLongArray::New(); this->DataArray->SetNumberOfTuples( numTupls ); long long * arrayPtr = static_cast < long long * > - ( vtkLongLongArray::SafeDownCast( this->DataArray )->GetPointer( 0 ) ); + ( vtkArrayDownCast( this->DataArray )->GetPointer( 0 ) ); H5Dread( attrIndx, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr ); arrayPtr = NULL; } diff --git a/IO/Core/vtkASCIITextCodec.h b/IO/Core/vtkASCIITextCodec.h index ae905d0bfdf..da1353c9b7c 100644 --- a/IO/Core/vtkASCIITextCodec.h +++ b/IO/Core/vtkASCIITextCodec.h @@ -67,7 +67,6 @@ class VTKIOCORE_EXPORT vtkASCIITextCodec : public vtkTextCodec // advancing the stream through however many places needed to assemble that code point virtual vtkUnicodeString::value_type NextUnicode(istream& inputStream) ; -//BTX protected: vtkASCIITextCodec() ; ~vtkASCIITextCodec() ; @@ -76,7 +75,6 @@ class VTKIOCORE_EXPORT vtkASCIITextCodec : public vtkTextCodec vtkASCIITextCodec(const vtkASCIITextCodec &) ; // Not implemented. void operator=(const vtkASCIITextCodec &) ; // Not implemented. -//ETX }; diff --git a/IO/Core/vtkArrayDataWriter.h b/IO/Core/vtkArrayDataWriter.h index 0e2d911d0d3..d18722b94a7 100644 --- a/IO/Core/vtkArrayDataWriter.h +++ b/IO/Core/vtkArrayDataWriter.h @@ -95,7 +95,6 @@ class VTKIOCORE_EXPORT vtkArrayDataWriter : // Write an arbitrary array to a file, without using the pipeline. static bool Write(vtkArrayData* array, const vtkStdString& file_name, bool WriteBinary = false); -//BTX // Description: // Write input port 0 data to an arbitrary stream. Note: streams should always be opened in // binary mode, to prevent problems reading files on Windows. @@ -105,7 +104,6 @@ class VTKIOCORE_EXPORT vtkArrayDataWriter : // Write arbitrary data to a stream without using the pipeline. Note: streams should always // be opened in binary mode, to prevent problems reading files on Windows. static bool Write(vtkArrayData* array, ostream& stream, bool WriteBinary = false); -//ETX // Description: // Write input port 0 data to a string. Note that the WriteBinary argument is not diff --git a/IO/Core/vtkArrayWriter.h b/IO/Core/vtkArrayWriter.h index 532b4670023..d09d5e40843 100644 --- a/IO/Core/vtkArrayWriter.h +++ b/IO/Core/vtkArrayWriter.h @@ -96,7 +96,6 @@ class VTKIOCORE_EXPORT vtkArrayWriter : // Write an arbitrary array to a file, without using the pipeline. static bool Write(vtkArray* array, const vtkStdString& file_name, bool WriteBinary = false); -//BTX // Description: // Write input port 0 data to an arbitrary stream. Note: streams should always be opened in // binary mode, to prevent problems reading files on Windows. @@ -106,7 +105,6 @@ class VTKIOCORE_EXPORT vtkArrayWriter : // Write arbitrary data to a stream without using the pipeline. Note: streams should always // be opened in binary mode, to prevent problems reading files on Windows. static bool Write(vtkArray* array, ostream& stream, bool WriteBinary = false); -//ETX // Description: // Write input port 0 data to a string. Note that the WriteBinary argument is not diff --git a/IO/Core/vtkDelimitedTextWriter.h b/IO/Core/vtkDelimitedTextWriter.h index e4acee2540e..92e7363a31f 100644 --- a/IO/Core/vtkDelimitedTextWriter.h +++ b/IO/Core/vtkDelimitedTextWriter.h @@ -93,9 +93,9 @@ class VTKIOCORE_EXPORT vtkDelimitedTextWriter : public vtkWriter char* FieldDelimiter; char* StringDelimiter; bool UseStringDelimiter; -//BTX + ostream* Stream; -//ETX + private: vtkDelimitedTextWriter(const vtkDelimitedTextWriter&); // Not implemented. void operator=(const vtkDelimitedTextWriter&); // Not implemented. diff --git a/IO/Core/vtkInputStream.h b/IO/Core/vtkInputStream.h index 9d998401082..8d298e21b5b 100644 --- a/IO/Core/vtkInputStream.h +++ b/IO/Core/vtkInputStream.h @@ -34,12 +34,10 @@ class VTKIOCORE_EXPORT vtkInputStream : public vtkObject static vtkInputStream *New(); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Get/Set the real input stream. vtkSetMacro(Stream, istream*); vtkGetMacro(Stream, istream*); - //ETX // Description: // Called after the stream position has been set by the caller, but diff --git a/IO/Core/vtkJavaScriptDataWriter.cxx b/IO/Core/vtkJavaScriptDataWriter.cxx index 0c865b5bac0..50eb742b714 100644 --- a/IO/Core/vtkJavaScriptDataWriter.cxx +++ b/IO/Core/vtkJavaScriptDataWriter.cxx @@ -171,7 +171,7 @@ void vtkJavaScriptDataWriter::WriteTable(vtkTable* table, ostream *stream_ptr) } // If the array is a string array put "" around it - if (vtkStringArray::SafeDownCast(dsa->GetAbstractArray(c))) + if (vtkArrayDownCast(dsa->GetAbstractArray(c))) { (*stream_ptr) << "\"" << table->GetValue( r, c ).ToString() << "\","; } diff --git a/IO/Core/vtkJavaScriptDataWriter.h b/IO/Core/vtkJavaScriptDataWriter.h index 53322660370..5ee7337f512 100644 --- a/IO/Core/vtkJavaScriptDataWriter.h +++ b/IO/Core/vtkJavaScriptDataWriter.h @@ -90,7 +90,7 @@ class VTKIOCORE_EXPORT vtkJavaScriptDataWriter : public vtkWriter private: vtkJavaScriptDataWriter(const vtkJavaScriptDataWriter&); // Not implemented. void operator=(const vtkJavaScriptDataWriter&); // Not implemented. -//ETX + }; diff --git a/IO/Core/vtkOutputStream.h b/IO/Core/vtkOutputStream.h index 430d29ef46b..3e0ff0d0043 100644 --- a/IO/Core/vtkOutputStream.h +++ b/IO/Core/vtkOutputStream.h @@ -34,12 +34,10 @@ class VTKIOCORE_EXPORT vtkOutputStream : public vtkObject static vtkOutputStream *New(); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Get/Set the real output stream. vtkSetMacro(Stream, ostream*); vtkGetMacro(Stream, ostream*); - //ETX // Description: // Called after the stream position has been set by the caller, but diff --git a/IO/Core/vtkSortFileNames.h b/IO/Core/vtkSortFileNames.h index 26eada1c096..7b8dbfca787 100644 --- a/IO/Core/vtkSortFileNames.h +++ b/IO/Core/vtkSortFileNames.h @@ -33,10 +33,8 @@ class vtkStringArray; -//BTX // this is a helper class defined in the .cxx file class vtkStringArrayVector; -//ETX class VTKIOCORE_EXPORT vtkSortFileNames : public vtkObject { diff --git a/IO/Core/vtkTextCodec.h b/IO/Core/vtkTextCodec.h index 48d49856e0e..5d9ec2b88c7 100644 --- a/IO/Core/vtkTextCodec.h +++ b/IO/Core/vtkTextCodec.h @@ -92,7 +92,6 @@ class VTKIOCORE_EXPORT vtkTextCodec : public vtkObject // code point. virtual vtkUnicodeString::value_type NextUnicode(istream& inputStream) = 0; -//BTX protected: vtkTextCodec(); ~vtkTextCodec(); @@ -101,7 +100,6 @@ class VTKIOCORE_EXPORT vtkTextCodec : public vtkObject vtkTextCodec(const vtkTextCodec &); // Not implemented. void operator=(const vtkTextCodec &); // Not implemented. -//ETX }; #endif diff --git a/IO/Core/vtkTextCodecFactory.h b/IO/Core/vtkTextCodecFactory.h index feafe0ac0c7..3bd00d812ff 100644 --- a/IO/Core/vtkTextCodecFactory.h +++ b/IO/Core/vtkTextCodecFactory.h @@ -77,7 +77,6 @@ class VTKIOCORE_EXPORT vtkTextCodecFactory : public vtkObject // Initialize core text codecs - needed for the static compilation case. static void Initialize(); -//BTX protected: vtkTextCodecFactory(); ~vtkTextCodecFactory(); @@ -91,7 +90,6 @@ class VTKIOCORE_EXPORT vtkTextCodecFactory : public vtkObject class CallbackVector; static CallbackVector* Callbacks; -//ETX }; #endif // vtkTextCodecFactory_h diff --git a/IO/Core/vtkUTF16TextCodec.h b/IO/Core/vtkUTF16TextCodec.h index 07778cbfbac..ceea6c3181a 100644 --- a/IO/Core/vtkUTF16TextCodec.h +++ b/IO/Core/vtkUTF16TextCodec.h @@ -73,7 +73,6 @@ class VTKIOCORE_EXPORT vtkUTF16TextCodec : public vtkTextCodec // advancing begin through however many places needed to assemble that code point virtual vtkUnicodeString::value_type NextUnicode(istream& inputStream) ; -//BTX protected: vtkUTF16TextCodec() ; ~vtkUTF16TextCodec() ; @@ -85,7 +84,6 @@ class VTKIOCORE_EXPORT vtkUTF16TextCodec : public vtkTextCodec vtkUTF16TextCodec(const vtkUTF16TextCodec &) ; // Not implemented. void operator=(const vtkUTF16TextCodec &) ; // Not implemented. -//ETX }; diff --git a/IO/Core/vtkUTF8TextCodec.h b/IO/Core/vtkUTF8TextCodec.h index db73308e028..674bc7e0e5b 100644 --- a/IO/Core/vtkUTF8TextCodec.h +++ b/IO/Core/vtkUTF8TextCodec.h @@ -66,7 +66,6 @@ class VTKIOCORE_EXPORT vtkUTF8TextCodec : public vtkTextCodec // advancing the stream through however many places needed to assemble that code point virtual vtkUnicodeString::value_type NextUnicode(istream& inputStream) ; -//BTX protected: vtkUTF8TextCodec() ; ~vtkUTF8TextCodec() ; @@ -75,7 +74,6 @@ class VTKIOCORE_EXPORT vtkUTF8TextCodec : public vtkTextCodec vtkUTF8TextCodec(const vtkUTF8TextCodec &) ; // Not implemented. void operator=(const vtkUTF8TextCodec &) ; // Not implemented. -//ETX }; diff --git a/IO/Core/vtkWriter.h b/IO/Core/vtkWriter.h index 6b6d1bd7611..7ddac158552 100644 --- a/IO/Core/vtkWriter.h +++ b/IO/Core/vtkWriter.h @@ -67,10 +67,9 @@ class VTKIOCORE_EXPORT vtkWriter : public vtkAlgorithm // Set/get the input to this writer. void SetInputData(vtkDataObject *input); void SetInputData(int index, vtkDataObject *input); -//BTX + vtkDataObject *GetInput(); vtkDataObject *GetInput(int port); -//ETX protected: vtkWriter(); diff --git a/IO/EnSight/vtkEnSightGoldBinaryReader.cxx b/IO/EnSight/vtkEnSightGoldBinaryReader.cxx index fe7bd3a9b68..164ad7ba851 100644 --- a/IO/EnSight/vtkEnSightGoldBinaryReader.cxx +++ b/IO/EnSight/vtkEnSightGoldBinaryReader.cxx @@ -34,9 +34,17 @@ #include #include -vtkStandardNewMacro(vtkEnSightGoldBinaryReader); - +#if defined(_WIN32) && (VTK_SIZEOF_ID_TYPE==8) +# define VTK_STAT_STRUCT struct _stat64 +# define VTK_STAT_FUNC _stat64 +#else +// here, we're relying on _FILE_OFFSET_BITS defined in vtkWin32Header.h to help +// us on POSIX without resorting to using stat64. +# define VTK_STAT_STRUCT struct stat +# define VTK_STAT_FUNC stat +#endif +vtkStandardNewMacro(vtkEnSightGoldBinaryReader); class vtkEnSightGoldBinaryReader::FileOffsetMapInternal { typedef std::string MapKey; @@ -97,11 +105,11 @@ int vtkEnSightGoldBinaryReader::OpenFile(const char* filename) // Open the new file vtkDebugMacro(<< "Opening file " << filename); - struct stat fs; - if ( !stat( filename, &fs) ) + VTK_STAT_STRUCT fs; + if ( !VTK_STAT_FUNC( filename, &fs) ) { // Find out how big the file is. - this->FileSize = (vtkIdType)(fs.st_size); + this->FileSize = static_cast(fs.st_size); #ifdef _WIN32 this->IFile = new ifstream(filename, ios::in | ios::binary); diff --git a/IO/EnSight/vtkEnSightGoldBinaryReader.h b/IO/EnSight/vtkEnSightGoldBinaryReader.h index 16840d4580d..09a09ff90e6 100644 --- a/IO/EnSight/vtkEnSightGoldBinaryReader.h +++ b/IO/EnSight/vtkEnSightGoldBinaryReader.h @@ -207,10 +207,8 @@ class VTKIOENSIGHT_EXPORT vtkEnSightGoldBinaryReader : public vtkEnSightReader // The size of the file could be used to choose byte order. vtkIdType FileSize; - //BTX class FileOffsetMapInternal; FileOffsetMapInternal *FileOffsets; - //ETX private: int SizeOfInt; diff --git a/IO/EnSight/vtkEnSightGoldReader.h b/IO/EnSight/vtkEnSightGoldReader.h index 0139d147381..8ba77789bb0 100644 --- a/IO/EnSight/vtkEnSightGoldReader.h +++ b/IO/EnSight/vtkEnSightGoldReader.h @@ -161,17 +161,13 @@ class VTKIOENSIGHT_EXPORT vtkEnSightGoldReader : public vtkEnSightReader int NodeIdsListed; int ElementIdsListed; - //BTX class UndefPartialInternal; // Description: // Handle the undef / partial support for EnSight gold UndefPartialInternal* UndefPartial; - //ETX - //BTX class FileOffsetMapInternal; FileOffsetMapInternal *FileOffsets; - //ETX private: vtkEnSightGoldReader(const vtkEnSightGoldReader&); // Not implemented. diff --git a/IO/EnSight/vtkEnSightReader.h b/IO/EnSight/vtkEnSightReader.h index 5475ac7e82f..0580f5ed5f8 100644 --- a/IO/EnSight/vtkEnSightReader.h +++ b/IO/EnSight/vtkEnSightReader.h @@ -33,7 +33,6 @@ class VTKIOENSIGHT_EXPORT vtkEnSightReader : public vtkGenericEnSightReader vtkTypeMacro(vtkEnSightReader, vtkGenericEnSightReader); void PrintSelf(ostream& os, vtkIndent indent); - //BTX enum ElementTypesList { POINT = 0, @@ -78,7 +77,6 @@ class VTKIOENSIGHT_EXPORT vtkEnSightReader : public vtkGenericEnSightReader BLOCK = 1, ELEMENT = 2 }; - //ETX // Description: // Get the Measured file name. Made public to allow access from diff --git a/IO/EnSight/vtkGenericEnSightReader.h b/IO/EnSight/vtkGenericEnSightReader.h index 127c07f6325..64bf68c6bab 100644 --- a/IO/EnSight/vtkGenericEnSightReader.h +++ b/IO/EnSight/vtkGenericEnSightReader.h @@ -28,11 +28,8 @@ class vtkDataArrayCollection; class vtkDataArraySelection; class vtkIdListCollection; -//BTX class TranslationTableType; -//ETX -//BTX // Cell/Point Ids store mode: // Sparse Mode is supposed to be for a large number of distributed processes (Unstructured) // Non Sparse Mode is supposed to be for a small number of distributed processes (Unstructured) @@ -44,7 +41,6 @@ enum EnsightReaderCellIdMode NON_SPARSE_MODE, IMPLICIT_STRUCTURED_MODE }; -//ETX class VTKIOENSIGHT_EXPORT vtkGenericEnSightReader : public vtkMultiBlockDataSetAlgorithm { @@ -164,7 +160,6 @@ class VTKIOENSIGHT_EXPORT vtkGenericEnSightReader : public vtkMultiBlockDataSetA void SetPointArrayStatus(const char* name, int status); void SetCellArrayStatus(const char* name, int status); - //BTX enum FileTypes { ENSIGHT_6 = 0, @@ -173,7 +168,6 @@ class VTKIOENSIGHT_EXPORT vtkGenericEnSightReader : public vtkMultiBlockDataSetA ENSIGHT_GOLD_BINARY = 3, ENSIGHT_MASTER_SERVER = 4 }; - //ETX // Description: // Set the byte order of the file (remember, more Unix workstations @@ -186,14 +180,12 @@ class VTKIOENSIGHT_EXPORT vtkGenericEnSightReader : public vtkMultiBlockDataSetA vtkGetMacro(ByteOrder, int); const char *GetByteOrderAsString(); -//BTX enum { FILE_BIG_ENDIAN=0, FILE_LITTLE_ENDIAN=1, FILE_UNKNOWN_ENDIAN=2 }; -//ETX // Description: // Get the Geometry file name. Made public to allow access from diff --git a/IO/Exodus/Testing/Cxx/CMakeLists.txt b/IO/Exodus/Testing/Cxx/CMakeLists.txt index 0a81581fd5c..1df040962dc 100644 --- a/IO/Exodus/Testing/Cxx/CMakeLists.txt +++ b/IO/Exodus/Testing/Cxx/CMakeLists.txt @@ -8,10 +8,17 @@ if(NOT CMAKE_GENERATOR MATCHES "Visual Studio 6") ) endif() +# We need typed arrays to be supported by the dispatcher to run the insitu test: +if(VTK_DISPATCH_TYPED_ARRAYS) + set(extra_tests ${extra_tests} + TestInSituExodus.cxx,NO_VALID + ) +endif() + vtk_add_test_cxx(${vtk-module}CxxTests tests TestExodusAttributes.cxx,NO_VALID,NO_OUTPUT TestExodusSideSets.cxx,NO_VALID,NO_OUTPUT - TestInSituExodus.cxx,NO_VALID + ${extra_tests} ) vtk_test_cxx_executable(${vtk-module}CxxTests tests RENDERING_FACTORY) diff --git a/IO/Exodus/Testing/Cxx/TestExodusSideSets.cxx b/IO/Exodus/Testing/Cxx/TestExodusSideSets.cxx index f132fc635f5..50001df1fc7 100644 --- a/IO/Exodus/Testing/Cxx/TestExodusSideSets.cxx +++ b/IO/Exodus/Testing/Cxx/TestExodusSideSets.cxx @@ -52,10 +52,10 @@ int TestExodusSideSets(int argc, char* argv[]) return 1; } - vtkIdTypeArray* sourceelementids = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* sourceelementids = vtkArrayDownCast( cd->GetArray(vtkExodusIIReader::GetSideSetSourceElementIdArrayName())); - vtkIntArray* sourceelementsides = vtkIntArray::SafeDownCast( + vtkIntArray* sourceelementsides = vtkArrayDownCast( cd->GetArray(vtkExodusIIReader::GetSideSetSourceElementSideArrayName())); if(!sourceelementsides || !sourceelementids) diff --git a/IO/Exodus/vtkCPExodusIINodalCoordinatesTemplate.h b/IO/Exodus/vtkCPExodusIINodalCoordinatesTemplate.h index 5ad2a5af9c5..a96cb792604 100644 --- a/IO/Exodus/vtkCPExodusIINodalCoordinatesTemplate.h +++ b/IO/Exodus/vtkCPExodusIINodalCoordinatesTemplate.h @@ -27,20 +27,21 @@ #include "vtkMappedDataArray.h" #include "vtkIOExodusModule.h" // For export macro -#include "vtkTypeTemplate.h" // For templated vtkObject API #include "vtkObjectFactory.h" // for vtkStandardNewMacro template -class vtkCPExodusIINodalCoordinatesTemplate: - public vtkTypeTemplate, - vtkMappedDataArray > +class vtkCPExodusIINodalCoordinatesTemplate: public vtkMappedDataArray { public: + vtkAbstractTemplateTypeMacro(vtkCPExodusIINodalCoordinatesTemplate, + vtkMappedDataArray) vtkMappedDataArrayNewInstanceMacro( vtkCPExodusIINodalCoordinatesTemplate) static vtkCPExodusIINodalCoordinatesTemplate *New(); virtual void PrintSelf(ostream &os, vtkIndent indent); + typedef typename Superclass::ValueType ValueType; + // Description: // Set the raw scalar arrays for the coordinate set. This class takes // ownership of the arrays and deletes them with delete[]. @@ -52,7 +53,7 @@ class vtkCPExodusIINodalCoordinatesTemplate: void GetTuples(vtkIdList *ptIds, vtkAbstractArray *output); void GetTuples(vtkIdType p1, vtkIdType p2, vtkAbstractArray *output); void Squeeze(); - vtkArrayIterator *NewIterator(); + VTK_NEWINSTANCE vtkArrayIterator *NewIterator(); vtkIdType LookupValue(vtkVariant value); void LookupValue(vtkVariant value, vtkIdList *ids); vtkVariant GetVariantValue(vtkIdType idx); @@ -61,9 +62,9 @@ class vtkCPExodusIINodalCoordinatesTemplate: void GetTuple(vtkIdType i, double *tuple); vtkIdType LookupTypedValue(Scalar value); void LookupTypedValue(Scalar value, vtkIdList *ids); - Scalar GetValue(vtkIdType idx); - Scalar& GetValueReference(vtkIdType idx); - void GetTupleValue(vtkIdType idx, Scalar *t); + ValueType GetValue(vtkIdType idx) const; + ValueType& GetValueReference(vtkIdType idx); + void GetTypedTuple(vtkIdType idx, Scalar *t) const; // Description: // This container is read only -- this method does nothing but print a @@ -95,9 +96,9 @@ class vtkCPExodusIINodalCoordinatesTemplate: void RemoveTuple(vtkIdType id); void RemoveFirstTuple(); void RemoveLastTuple(); - void SetTupleValue(vtkIdType i, const Scalar *t); - void InsertTupleValue(vtkIdType i, const Scalar *t); - vtkIdType InsertNextTupleValue(const Scalar *t); + void SetTypedTuple(vtkIdType i, const Scalar *t); + void InsertTypedTuple(vtkIdType i, const Scalar *t); + vtkIdType InsertNextTypedTuple(const Scalar *t); void SetValue(vtkIdType idx, Scalar value); vtkIdType InsertNextValue(Scalar v); void InsertValue(vtkIdType idx, Scalar v); diff --git a/IO/Exodus/vtkCPExodusIINodalCoordinatesTemplate.txx b/IO/Exodus/vtkCPExodusIINodalCoordinatesTemplate.txx index c4767ec6814..42b7d8d1131 100644 --- a/IO/Exodus/vtkCPExodusIINodalCoordinatesTemplate.txx +++ b/IO/Exodus/vtkCPExodusIINodalCoordinatesTemplate.txx @@ -202,15 +202,18 @@ template void vtkCPExodusIINodalCoordinatesTemplate } //------------------------------------------------------------------------------ -template Scalar vtkCPExodusIINodalCoordinatesTemplate -::GetValue(vtkIdType idx) +template +typename vtkCPExodusIINodalCoordinatesTemplate::ValueType +vtkCPExodusIINodalCoordinatesTemplate::GetValue(vtkIdType idx) const { - return this->GetValueReference(idx); + return const_cast*>( + this)->GetValueReference(idx); } //------------------------------------------------------------------------------ -template Scalar& vtkCPExodusIINodalCoordinatesTemplate -::GetValueReference(vtkIdType idx) +template +typename vtkCPExodusIINodalCoordinatesTemplate::ValueType& +vtkCPExodusIINodalCoordinatesTemplate::GetValueReference(vtkIdType idx) { const vtkIdType tuple = idx / this->NumberOfComponents; const vtkIdType comp = idx % this->NumberOfComponents; @@ -231,7 +234,7 @@ template Scalar& vtkCPExodusIINodalCoordinatesTemplate //------------------------------------------------------------------------------ template void vtkCPExodusIINodalCoordinatesTemplate -::GetTupleValue(vtkIdType tupleId, Scalar *tuple) +::GetTypedTuple(vtkIdType tupleId, Scalar *tuple) const { tuple[0] = this->XArray[tupleId]; tuple[1] = this->YArray[tupleId]; @@ -429,7 +432,7 @@ template void vtkCPExodusIINodalCoordinatesTemplate //------------------------------------------------------------------------------ template void vtkCPExodusIINodalCoordinatesTemplate -::SetTupleValue(vtkIdType, const Scalar*) +::SetTypedTuple(vtkIdType, const Scalar*) { vtkErrorMacro("Read only container.") return; @@ -437,7 +440,7 @@ template void vtkCPExodusIINodalCoordinatesTemplate //------------------------------------------------------------------------------ template void vtkCPExodusIINodalCoordinatesTemplate -::InsertTupleValue(vtkIdType, const Scalar*) +::InsertTypedTuple(vtkIdType, const Scalar*) { vtkErrorMacro("Read only container.") return; @@ -445,7 +448,7 @@ template void vtkCPExodusIINodalCoordinatesTemplate //------------------------------------------------------------------------------ template vtkIdType vtkCPExodusIINodalCoordinatesTemplate -::InsertNextTupleValue(const Scalar *) +::InsertNextTypedTuple(const Scalar *) { vtkErrorMacro("Read only container.") return -1; diff --git a/IO/Exodus/vtkCPExodusIIResultsArrayTemplate.h b/IO/Exodus/vtkCPExodusIIResultsArrayTemplate.h index b6e5e5f2af1..cd248373ccd 100644 --- a/IO/Exodus/vtkCPExodusIIResultsArrayTemplate.h +++ b/IO/Exodus/vtkCPExodusIIResultsArrayTemplate.h @@ -26,19 +26,20 @@ #include "vtkMappedDataArray.h" -#include "vtkTypeTemplate.h" // For templated vtkObject API #include "vtkObjectFactory.h" // for vtkStandardNewMacro template -class vtkCPExodusIIResultsArrayTemplate: - public vtkTypeTemplate, - vtkMappedDataArray > +class vtkCPExodusIIResultsArrayTemplate: public vtkMappedDataArray { public: + vtkAbstractTemplateTypeMacro(vtkCPExodusIIResultsArrayTemplate, + vtkMappedDataArray) vtkMappedDataArrayNewInstanceMacro(vtkCPExodusIIResultsArrayTemplate) static vtkCPExodusIIResultsArrayTemplate *New(); virtual void PrintSelf(ostream &os, vtkIndent indent); + typedef typename Superclass::ValueType ValueType; + // Description: // Set the arrays to be used and the number of tuples in each array. // The save option can be set to true to indicate that this class @@ -52,7 +53,7 @@ class vtkCPExodusIIResultsArrayTemplate: void GetTuples(vtkIdList *ptIds, vtkAbstractArray *output); void GetTuples(vtkIdType p1, vtkIdType p2, vtkAbstractArray *output); void Squeeze(); - vtkArrayIterator *NewIterator(); + VTK_NEWINSTANCE vtkArrayIterator *NewIterator(); vtkIdType LookupValue(vtkVariant value); void LookupValue(vtkVariant value, vtkIdList *ids); vtkVariant GetVariantValue(vtkIdType idx); @@ -61,9 +62,9 @@ class vtkCPExodusIIResultsArrayTemplate: void GetTuple(vtkIdType i, double *tuple); vtkIdType LookupTypedValue(Scalar value); void LookupTypedValue(Scalar value, vtkIdList *ids); - Scalar GetValue(vtkIdType idx); - Scalar& GetValueReference(vtkIdType idx); - void GetTupleValue(vtkIdType idx, Scalar *t); + ValueType GetValue(vtkIdType idx) const; + ValueType& GetValueReference(vtkIdType idx); + void GetTypedTuple(vtkIdType idx, Scalar *t) const; // Description: // This container is read only -- this method does nothing but print a @@ -95,9 +96,9 @@ class vtkCPExodusIIResultsArrayTemplate: void RemoveTuple(vtkIdType id); void RemoveFirstTuple(); void RemoveLastTuple(); - void SetTupleValue(vtkIdType i, const Scalar *t); - void InsertTupleValue(vtkIdType i, const Scalar *t); - vtkIdType InsertNextTupleValue(const Scalar *t); + void SetTypedTuple(vtkIdType i, const Scalar *t); + void InsertTypedTuple(vtkIdType i, const Scalar *t); + vtkIdType InsertNextTypedTuple(const Scalar *t); void SetValue(vtkIdType idx, Scalar value); vtkIdType InsertNextValue(Scalar v); void InsertValue(vtkIdType idx, Scalar v); diff --git a/IO/Exodus/vtkCPExodusIIResultsArrayTemplate.txx b/IO/Exodus/vtkCPExodusIIResultsArrayTemplate.txx index dc20b43b5d3..3725ecc02e4 100644 --- a/IO/Exodus/vtkCPExodusIIResultsArrayTemplate.txx +++ b/IO/Exodus/vtkCPExodusIIResultsArrayTemplate.txx @@ -238,15 +238,18 @@ template void vtkCPExodusIIResultsArrayTemplate } //------------------------------------------------------------------------------ -template Scalar vtkCPExodusIIResultsArrayTemplate -::GetValue(vtkIdType idx) +template +typename vtkCPExodusIIResultsArrayTemplate::ValueType +vtkCPExodusIIResultsArrayTemplate::GetValue(vtkIdType idx) const { - return this->GetValueReference(idx); + return const_cast*>( + this)->GetValueReference(idx); } //------------------------------------------------------------------------------ -template Scalar& vtkCPExodusIIResultsArrayTemplate -::GetValueReference(vtkIdType idx) +template +typename vtkCPExodusIIResultsArrayTemplate::ValueType& +vtkCPExodusIIResultsArrayTemplate::GetValueReference(vtkIdType idx) { const vtkIdType tuple = idx / this->NumberOfComponents; const vtkIdType comp = idx % this->NumberOfComponents; @@ -255,7 +258,7 @@ template Scalar& vtkCPExodusIIResultsArrayTemplate //------------------------------------------------------------------------------ template void vtkCPExodusIIResultsArrayTemplate -::GetTupleValue(vtkIdType tupleId, Scalar *tuple) +::GetTypedTuple(vtkIdType tupleId, Scalar *tuple) const { for (size_t comp = 0; comp < this->Arrays.size(); ++comp) { @@ -451,7 +454,7 @@ template void vtkCPExodusIIResultsArrayTemplate //------------------------------------------------------------------------------ template void vtkCPExodusIIResultsArrayTemplate -::SetTupleValue(vtkIdType, const Scalar*) +::SetTypedTuple(vtkIdType, const Scalar*) { vtkErrorMacro("Read only container.") return; @@ -459,7 +462,7 @@ template void vtkCPExodusIIResultsArrayTemplate //------------------------------------------------------------------------------ template void vtkCPExodusIIResultsArrayTemplate -::InsertTupleValue(vtkIdType, const Scalar*) +::InsertTypedTuple(vtkIdType, const Scalar*) { vtkErrorMacro("Read only container.") return; @@ -467,7 +470,7 @@ template void vtkCPExodusIIResultsArrayTemplate //------------------------------------------------------------------------------ template vtkIdType vtkCPExodusIIResultsArrayTemplate -::InsertNextTupleValue(const Scalar *) +::InsertNextTypedTuple(const Scalar *) { vtkErrorMacro("Read only container.") return -1; diff --git a/IO/Exodus/vtkExodusIICache.h b/IO/Exodus/vtkExodusIICache.h index 5be52923688..e08ac314221 100644 --- a/IO/Exodus/vtkExodusIICache.h +++ b/IO/Exodus/vtkExodusIICache.h @@ -29,7 +29,6 @@ #include // used for cache storage #include // use for LRU ordering -//BTX class VTKIOEXODUS_EXPORT vtkExodusIICacheKey { public: @@ -124,7 +123,6 @@ class VTKIOEXODUS_EXPORT vtkExodusIICacheEntry friend class vtkExodusIICache; }; -//ETX class VTKIOEXODUS_EXPORT vtkExodusIICache : public vtkObject { @@ -151,7 +149,6 @@ class VTKIOEXODUS_EXPORT vtkExodusIICache : public vtkObject */ int ReduceToSize( double newSize ); - //BTX /// Insert an entry into the cache (this can remove other cache entries to make space). void Insert( vtkExodusIICacheKey& key, vtkDataArray* value ); @@ -176,7 +173,6 @@ class VTKIOEXODUS_EXPORT vtkExodusIICache : public vtkObject * It is not an error to specify an empty range -- 0 will be returned if one is given. */ int Invalidate( vtkExodusIICacheKey key, vtkExodusIICacheKey pattern ); - //ETX protected: /// Default constructor @@ -195,7 +191,6 @@ class VTKIOEXODUS_EXPORT vtkExodusIICache : public vtkObject /// The current size of the cache (i.e., the size of the all the arrays it currently contains) in MiB. double Size; - //BTX /** A least-recently-used (LRU) cache to hold arrays. * During RequestData the cache may contain more than its maximum size since * the user may request more data than the cache can hold. However, the cache @@ -206,7 +201,6 @@ class VTKIOEXODUS_EXPORT vtkExodusIICache : public vtkObject /// The actual LRU list (indices into the cache ordered least to most recently used). vtkExodusIICacheLRU LRU; - //ETX private: vtkExodusIICache( const vtkExodusIICache& ); // Not implemented diff --git a/IO/Exodus/vtkExodusIIReader.cxx b/IO/Exodus/vtkExodusIIReader.cxx index a57598e3ff7..b71550e0e22 100644 --- a/IO/Exodus/vtkExodusIIReader.cxx +++ b/IO/Exodus/vtkExodusIIReader.cxx @@ -804,10 +804,20 @@ int vtkExodusIIReaderPrivate::AssembleOutputProceduralArrays( ( otyp == vtkExodusIIReader::SIDE_SET_CONN || otyp == vtkExodusIIReader::SIDE_SET ) ) { + vtkExodusIICacheKey ckey( -1, vtkExodusIIReader::ELEMENT_ID, 0, 0 ); + vtkIdTypeArray* src = 0; + + if ( vtkDataArray* elems = this->GetCacheOrRead( ckey ) ) + { + src = vtkIdTypeArray::New (); + src->DeepCopy (elems); + } + vtkExodusIICacheKey key( -1, vtkExodusIIReader::SIDE_SET_CONN, obj, 1 ); if ( vtkDataArray* arr = this->GetCacheOrRead( key ) ) { - vtkIdTypeArray* idarray = vtkIdTypeArray::SafeDownCast(arr); + + vtkIdTypeArray* idarray = vtkArrayDownCast(arr); vtkIdTypeArray* elementid = vtkIdTypeArray::New(); elementid->SetNumberOfTuples(idarray->GetNumberOfTuples()); elementid->SetName(vtkExodusIIReader::GetSideSetSourceElementIdArrayName()); @@ -815,10 +825,18 @@ int vtkExodusIIReaderPrivate::AssembleOutputProceduralArrays( elementside->SetNumberOfTuples(idarray->GetNumberOfTuples()); elementside->SetName(vtkExodusIIReader::GetSideSetSourceElementSideArrayName()); vtkIdType values[2]; + for(vtkIdType i=0;iGetNumberOfTuples();i++) { - idarray->GetTupleValue(i, values); - elementid->SetValue(i, values[0]-1); // switch to 0-based indexing + idarray->GetTypedTuple(i, values); + if (src == 0 || src->GetValue (values[0] - 1) <= 0) + { + elementid->SetValue(i, values[0] - 1); + } + else + { + elementid->SetValue(i, src->GetValue (values[0] - 1) - 1); // find the global element id + } // now we have to worry about mapping from exodus canonical side // ordering to vtk canonical side ordering for wedges and hexes. // Even if the element block isn't loaded that we still know what @@ -837,7 +855,7 @@ int vtkExodusIIReaderPrivate::AssembleOutputProceduralArrays( case VTK_HEXAHEDRON: { int hexMapping[6] = {2, 1, 3, 0, 4, 5}; - elementside->SetValue(i, hexMapping[ values[1]-1 ] ); + elementside->SetValue(i, hexMapping[ values[1]-1 ] ); break; } default: @@ -852,6 +870,11 @@ int vtkExodusIIReaderPrivate::AssembleOutputProceduralArrays( elementside->FastDelete(); status -= 2; } + + if (src != 0) + { + src->Delete (); + } } if ( this->GenerateGlobalElementIdArray && ! OBJTYPE_IS_SET( otyp ) ) @@ -1056,7 +1079,7 @@ int vtkExodusIIReaderPrivate::AssembleOutputPointMaps( vtkIdType timeStep, if ( ! mi->Status ) continue; // Skip arrays we don't want. - vtkIdTypeArray* src = vtkIdTypeArray::SafeDownCast( this->GetCacheOrRead( + vtkIdTypeArray* src = vtkArrayDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, vtkExodusIIReader::NODE_MAP, 0, midx ) ) ); if ( !src ) { @@ -1217,7 +1240,7 @@ void vtkExodusIIReaderPrivate::InsertBlockCells( if ( binfo->PointsPerCell == 0 ) { int arrId = (conn_type == vtkExodusIIReader::ELEM_BLOCK_ELEM_CONN ? 0 : 1); - ent = vtkIntArray::SafeDownCast( + ent = vtkArrayDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, vtkExodusIIReader::ENTITY_COUNTS, obj, arrId ))); @@ -1241,19 +1264,19 @@ void vtkExodusIIReaderPrivate::InsertBlockCells( if (binfo->CellType == VTK_POLYHEDRON) { vtkIntArray* efconn; - efconn = vtkIntArray::SafeDownCast( + efconn = vtkArrayDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, vtkExodusIIReader::ELEM_BLOCK_FACE_CONN, obj, 0 ))); if (efconn) efconn->Register(this); vtkIntArray* fconn; - fconn = vtkIntArray::SafeDownCast( + fconn = vtkArrayDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, vtkExodusIIReader::FACE_BLOCK_CONN, obj, 0 ))); if (fconn) fconn->Register(this); vtkIntArray* ptsPerFace = NULL; - ptsPerFace = vtkIntArray::SafeDownCast( + ptsPerFace = vtkArrayDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, vtkExodusIIReader::ENTITY_COUNTS, obj, 1 ))); @@ -1280,7 +1303,7 @@ void vtkExodusIIReaderPrivate::InsertBlockCells( } vtkIntArray* arr; - arr = vtkIntArray::SafeDownCast( + arr = vtkArrayDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, conn_type, obj, 0 ))); if ( ! arr ) @@ -1388,7 +1411,7 @@ void vtkExodusIIReaderPrivate::InsertSetCells( return; } - vtkIntArray* arr = vtkIntArray::SafeDownCast( + vtkIntArray* arr = vtkArrayDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, conn_type, obj, 0 ) ) ); if ( ! arr ) { @@ -1519,7 +1542,7 @@ void vtkExodusIIReaderPrivate::InsertSetCellCopies( } if ( loadNewBlk ) { - nconn = vtkIntArray::SafeDownCast( + nconn = vtkArrayDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, this->GetBlockConnTypeFromBlockType( otyp ), bnum, 0 ) ) ); if ( ! nconn ) @@ -2067,7 +2090,7 @@ vtkDataArray* vtkExodusIIReaderPrivate::GetCacheOrRead( vtkExodusIICacheKey key ckey.ObjectType = vtkExodusIIReader::ELEMENT_ID; break; } - vtkIdTypeArray* src = vtkIdTypeArray::SafeDownCast( this->GetCacheOrRead( ckey ) ); + vtkIdTypeArray* src = vtkArrayDownCast( this->GetCacheOrRead( ckey ) ); if ( ! src ) { arr = 0; @@ -2167,7 +2190,7 @@ vtkDataArray* vtkExodusIIReaderPrivate::GetCacheOrRead( vtkExodusIICacheKey key int otypidx = this->GetObjectTypeIndexFromObjectType( key.ObjectId ); int obj = key.ArrayId; BlockSetInfoType* bsinfop = (BlockSetInfoType*) this->GetObjectInfo( otypidx, obj ); - vtkIdTypeArray* src = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* src = vtkArrayDownCast( this->GetCacheOrRead( vtkExodusIICacheKey( -1, vtkExodusIIReader::NODE_ID, 0, 0 ) ) ); if ( this->SqueezePoints && src ) { @@ -2290,7 +2313,7 @@ vtkDataArray* vtkExodusIIReaderPrivate::GetCacheOrRead( vtkExodusIICacheKey key ktmp = vtkExodusIICacheKey( -1, vtkExodusIIReader::NODE_MAP, 0, 0 ); } // If there are no new-style maps, get the old-style map (which creates a default if nothing is stored on disk). - if ( nMaps < 1 || ! (iarr = vtkIdTypeArray::SafeDownCast(this->GetCacheOrRead( ktmp ))) ) + if ( nMaps < 1 || ! (iarr = vtkArrayDownCast(this->GetCacheOrRead( ktmp ))) ) { iarr = vtkIdTypeArray::New(); iarr->SetNumberOfComponents( 1 ); @@ -2626,7 +2649,7 @@ vtkDataArray* vtkExodusIIReaderPrivate::GetCacheOrRead( vtkExodusIICacheKey key { // we'll have to fix up the side indexing later // because Exodus and VTK have different canonical orderings for wedges and hexes. vtkIdType info[2] = {side_set_elem_list[i], side_set_side_list[i]}; - iarr->SetTupleValue(i, info); + iarr->SetTypedTuple(i, info); } arr = iarr; } @@ -2854,7 +2877,7 @@ vtkDataArray* vtkExodusIIReaderPrivate::GetCacheOrRead( vtkExodusIICacheKey key { for ( i = 0; i < num_info; ++i ) { - carr->InsertTupleValue( i, info[i] ); + carr->InsertTypedTuple( i, info[i] ); } arr = carr; } @@ -2917,7 +2940,7 @@ vtkDataArray* vtkExodusIIReaderPrivate::GetCacheOrRead( vtkExodusIICacheKey key { for ( j = 0; j < 4 ; ++j ) { - carr->InsertTupleValue( ( i * 4 ) + j, qa_record[i][j] ); + carr->InsertTypedTuple( ( i * 4 ) + j, qa_record[i][j] ); } } arr = carr; @@ -3817,6 +3840,7 @@ int vtkExodusIIReaderPrivate::UpdateTimeInformation() int exoid = this->Exoid; int itmp[5]; int num_timesteps; + int i; VTK_EXO_FUNC( ex_inquire( exoid, EX_INQ_TIME, itmp, 0, 0 ), "Inquire for EX_INQ_TIME failed" ); num_timesteps = itmp[0]; @@ -3825,7 +3849,16 @@ int vtkExodusIIReaderPrivate::UpdateTimeInformation() if ( num_timesteps > 0 ) { this->Times.resize( num_timesteps ); - VTK_EXO_FUNC( ex_get_all_times( this->Exoid, &this->Times[0] ), "Could not retrieve time values." ); + + int exo_err = ex_get_all_times( this->Exoid, &this->Times[0] ); + if ( exo_err < 0) + { + for ( i = 0; i < num_timesteps; ++i ) + { + this->Times[i] = i; + } + vtkWarningMacro("Could not retrieve time values, assuming times equal to timesteps"); + } } return 0; } diff --git a/IO/Exodus/vtkExodusIIReader.h b/IO/Exodus/vtkExodusIIReader.h index d28f7c7aacf..b7c4600ecc9 100644 --- a/IO/Exodus/vtkExodusIIReader.h +++ b/IO/Exodus/vtkExodusIIReader.h @@ -144,7 +144,6 @@ class VTKIOEXODUS_EXPORT vtkExodusIIReader : public vtkMultiBlockDataSetAlgorith virtual void SetFileId( int f ); int GetFileId(); -//BTX // Description: // Extra cell data array that can be generated. By default, this array // is off. The value of the array is the integer global id of the cell. @@ -212,7 +211,7 @@ class VTKIOEXODUS_EXPORT vtkExodusIIReader : public vtkMultiBlockDataSetAlgorith EDGE_ID = 106, //!< edge id map (old-style edge_num_map or first new-style edge map) array ENTITY_COUNTS = 109 //!< polyhedra per-entity count ex_get_block returns the sum for polyhedra }; -//ETX + static const char* GetGlobalElementIdArrayName() { return "GlobalElementId"; } static const char* GetPedigreeElementIdArrayName() { return "PedigreeElementId"; } static int GetGlobalElementID( vtkDataSet *data, int localID ); diff --git a/IO/Exodus/vtkExodusIIReaderParser.h b/IO/Exodus/vtkExodusIIReaderParser.h index b5be2cfdb5f..86356327cef 100644 --- a/IO/Exodus/vtkExodusIIReaderParser.h +++ b/IO/Exodus/vtkExodusIIReaderParser.h @@ -75,7 +75,7 @@ class VTKIOEXODUS_EXPORT vtkExodusIIReaderParser : public vtkXMLParser blockIdsSet.insert(iter->first); } } -//BTX + protected: vtkExodusIIReaderParser(); ~vtkExodusIIReaderParser(); @@ -162,7 +162,7 @@ class VTKIOEXODUS_EXPORT vtkExodusIIReaderParser : public vtkXMLParser private: vtkExodusIIReaderParser(const vtkExodusIIReaderParser&); // Not implemented void operator=(const vtkExodusIIReaderParser&); // Not implemented -//ETX + }; #endif diff --git a/IO/Exodus/vtkExodusIIWriter.cxx b/IO/Exodus/vtkExodusIIWriter.cxx index e89ff5628d5..712373c20a8 100644 --- a/IO/Exodus/vtkExodusIIWriter.cxx +++ b/IO/Exodus/vtkExodusIIWriter.cxx @@ -18,29 +18,32 @@ See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ +#include "vtkArrayIteratorIncludes.h" +#include "vtkCellArray.h" +#include "vtkCellData.h" +#include "vtkCompositeDataIterator.h" +#include "vtkCompositeDataSet.h" +#include "vtkDataObject.h" +#include "vtkDataObjectTreeIterator.h" +#include "vtkDoubleArray.h" #include "vtkExodusIIWriter.h" -#include "vtkObjectFactory.h" -#include "vtkModelMetadata.h" +#include "vtkFieldData.h" +#include "vtkFloatArray.h" +#include "vtkIdList.h" #include "vtkInformation.h" #include "vtkInformationVector.h" -#include "vtkStreamingDemandDrivenPipeline.h" -#include "vtkDoubleArray.h" -#include "vtkDataObject.h" -#include "vtkFieldData.h" -#include "vtkCompositeDataSet.h" -#include "vtkCompositeDataIterator.h" +#include "vtkIntArray.h" +#include "vtkModelMetadata.h" #include "vtkMultiBlockDataSet.h" -#include "vtkDataObjectTreeIterator.h" -#include "vtkUnstructuredGrid.h" -#include "vtkCellData.h" +#include "vtkNew.h" +#include "vtkObjectFactory.h" #include "vtkPointData.h" -#include "vtkIdList.h" +#include "vtkStdString.h" +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkStringArray.h" #include "vtkThreshold.h" -#include "vtkIntArray.h" -#include "vtkCellArray.h" -#include "vtkFloatArray.h" -#include "vtkArrayIteratorIncludes.h" #include "vtkToolkits.h" // for VTK_USE_PARALLEL +#include "vtkUnstructuredGrid.h" #include "vtk_exodusII.h" #include @@ -276,9 +279,10 @@ int vtkExodusIIWriter::GlobalContinueExecuting(int localContinueExecution) void vtkExodusIIWriter::WriteData () { this->NewFlattenedInput.clear (); + this->NewFlattenedNames.clear (); // Is it safe to assume this is the same? bool newHierarchy = false; - if (!this->FlattenHierarchy (this->OriginalInput, newHierarchy)) + if (!this->FlattenHierarchy (this->OriginalInput, 0, newHierarchy)) { vtkErrorMacro ( "vtkExodusIIWriter::WriteData Unable to flatten hierarchy"); @@ -301,6 +305,7 @@ void vtkExodusIIWriter::WriteData () // Copies over the new results data in the new objects this->FlattenedInput = this->NewFlattenedInput; + this->FlattenedNames = this->NewFlattenedNames; this->RemoveGhostCells (); @@ -435,7 +440,7 @@ void vtkExodusIIWriter::StringUppercase(std::string& str) } //---------------------------------------------------------------------------- -int vtkExodusIIWriter::FlattenHierarchy (vtkDataObject* input, bool& changed) +int vtkExodusIIWriter::FlattenHierarchy (vtkDataObject* input, const char *name, bool& changed) { if (input->IsA ("vtkMultiBlockDataSet")) { @@ -449,12 +454,12 @@ int vtkExodusIIWriter::FlattenHierarchy (vtkDataObject* input, bool& changed) !iter->IsDoneWithTraversal (); iter->GoToNextItem ()) { - const char *name = iter->GetCurrentMetaData()->Get (vtkCompositeDataSet::NAME()); + name = iter->GetCurrentMetaData()->Get (vtkCompositeDataSet::NAME()); if (name != 0 && strstr (name, "Sets") != 0) { continue; } - if (iter->GetCurrentDataObject () && !this->FlattenHierarchy (iter->GetCurrentDataObject (), changed)) + if (iter->GetCurrentDataObject () && !this->FlattenHierarchy (iter->GetCurrentDataObject (), name, changed)) { return 0; } @@ -476,7 +481,7 @@ int vtkExodusIIWriter::FlattenHierarchy (vtkDataObject* input, bool& changed) !iter->IsDoneWithTraversal (); iter->GoToNextItem ()) { - if (iter->GetCurrentDataObject () && !this->FlattenHierarchy (iter->GetCurrentDataObject (), changed)) + if (iter->GetCurrentDataObject () && !this->FlattenHierarchy (iter->GetCurrentDataObject (), name, changed)) { return 0; } @@ -535,6 +540,7 @@ int vtkExodusIIWriter::FlattenHierarchy (vtkDataObject* input, bool& changed) changed = true; } this->NewFlattenedInput.push_back (output); + this->NewFlattenedNames.push_back (name); } else { @@ -813,9 +819,13 @@ int vtkExodusIIWriter::CheckInputArrays () // Trying to find global element id vtkDataArray *da = cd->GetGlobalIds(); + if (!da) + { // try finding the array explicitly named + da = cd->GetArray ("GlobalElementId"); + } if (da) { - vtkIdTypeArray *ia = vtkIdTypeArray::SafeDownCast(da); + vtkIdTypeArray *ia = vtkArrayDownCast(da); if (!ia) { vtkWarningMacro(<< @@ -829,11 +839,16 @@ int vtkExodusIIWriter::CheckInputArrays () } } + // Trying to find global node id da = pd->GetGlobalIds(); + if (!da) + { // try finding the array explicitly named + da = pd->GetArray ("GlobalNodeId"); + } if (da) { - vtkIdTypeArray *ia = vtkIdTypeArray::SafeDownCast(da); + vtkIdTypeArray *ia = vtkArrayDownCast(da); if (!ia) { vtkWarningMacro(<< @@ -897,6 +912,7 @@ int vtkExodusIIWriter::ConstructBlockInfoMap () { this->CellToElementOffset[i][j] = 0; Block& b = this->BlockInfoMap[this->BlockIdList[i]->GetValue (j)];//CLM + b.Name = this->FlattenedNames[i].c_str(); b.Type = this->FlattenedInput[i]->GetCellType (j); b.NumElements = 1; b.ElementStartIndex = 0; @@ -1442,12 +1458,14 @@ int vtkExodusIIWriter::CreateSetsMetadata (vtkModelMetadata* em) { int numNodeSets = 0; int sumNodes = 0; + vtkNew nodeSetNames; vtkSmartPointer nodeSetIds = vtkSmartPointer::New (); vtkSmartPointer nodeSetSizes = vtkSmartPointer::New (); vtkSmartPointer nodeSetNumDF = vtkSmartPointer::New (); vtkSmartPointer nodeIds = vtkSmartPointer::New (); int numSideSets = 0; int sumSides = 0; + vtkNew sideSetNames; vtkSmartPointer sideSetIds = vtkSmartPointer::New (); vtkSmartPointer sideSetSizes = vtkSmartPointer::New (); vtkSmartPointer sideSetNumDF = vtkSmartPointer::New (); @@ -1481,10 +1499,17 @@ int vtkExodusIIWriter::CreateSetsMetadata (vtkModelMetadata* em) node_id = atoi (id_str); } nodeSetIds->InsertNextTuple1 (node_id); + + if (nodeSetNames->GetNumberOfValues() <= node_id) + { + nodeSetNames->SetNumberOfValues ((node_id + 1) * 2); + } + nodeSetNames->SetValue (node_id, name); + node_id ++; // Make sure the node_id is unique if id_str is invalid vtkUnstructuredGrid* grid = vtkUnstructuredGrid::SafeDownCast (iter->GetCurrentDataObject ()); vtkFieldData* field = grid->GetPointData (); - vtkIdTypeArray* globalIds = vtkIdTypeArray::SafeDownCast (field ? field->GetArray ("GlobalNodeId") : 0); + vtkIdTypeArray* globalIds = vtkArrayDownCast(field ? field->GetArray ("GlobalNodeId") : 0); if (globalIds) { int size = 0; @@ -1511,6 +1536,10 @@ int vtkExodusIIWriter::CreateSetsMetadata (vtkModelMetadata* em) } else if (isASideSet) { + int hexSides = 0; + int wedgeSides = 0; + int otherSides = 0; + int badSides = 0; numSideSets ++; const char* id_str = name != 0 ? strstr (name, "ID:") : 0; if (id_str != 0) @@ -1519,33 +1548,50 @@ int vtkExodusIIWriter::CreateSetsMetadata (vtkModelMetadata* em) side_id = atoi (id_str); } sideSetIds->InsertNextTuple1 (side_id); + if (sideSetNames->GetNumberOfValues () <= side_id) + { + sideSetNames->SetNumberOfValues((side_id + 1) * 2); + } + sideSetNames->SetValue (side_id, name); side_id ++; // Make sure the side_id is unique if id_str is invalid vtkUnstructuredGrid* grid = vtkUnstructuredGrid::SafeDownCast (iter->GetCurrentDataObject ()); vtkFieldData* field = grid->GetCellData (); - vtkIdTypeArray* sourceElement = vtkIdTypeArray::SafeDownCast (field ? field->GetArray ("SourceElementId") : 0); - vtkIntArray* sourceSide = vtkIntArray::SafeDownCast (field ? field->GetArray ("SourceElementSide") : 0); + int cells = grid->GetNumberOfCells (); + vtkIdTypeArray* sourceElement = vtkArrayDownCast(field ? field->GetArray ("SourceElementId") : 0); + vtkIntArray* sourceSide = vtkArrayDownCast(field ? field->GetArray ("SourceElementSide") : 0); if (sourceElement && sourceSide) { - int cells = grid->GetNumberOfCells (); for (int c = 0; c < cells; c ++) { sideSetElementList->InsertNextTuple1 (sourceElement->GetValue (c) + 1); switch (GetElementType (sourceElement->GetValue (c) + 1)) { + case -1: + { + badSides ++; + break; + } case VTK_WEDGE: { int wedgeMapping[5] = {3, 4, 0, 1, 2}; - sideSetSideList->InsertNextTuple1 (wedgeMapping[sourceSide->GetValue (c)] + 1); + int side = wedgeMapping[sourceSide->GetValue (c)] + 1; + sideSetSideList->InsertNextTuple1 (side); + wedgeSides ++; break; } case VTK_HEXAHEDRON: { int hexMapping[6] = {3, 1, 0, 2, 4, 5}; sideSetSideList->InsertNextTuple1 (hexMapping[sourceSide->GetValue (c)] + 1); + hexSides ++; break; } default: + { sideSetSideList->InsertNextTuple1 (sourceSide->GetValue (c) + 1); + otherSides ++; + break; + } } // TODO implement distribution factors sideSetNumDF->InsertNextTuple1 (0); @@ -1560,8 +1606,10 @@ int vtkExodusIIWriter::CreateSetsMetadata (vtkModelMetadata* em) } } + em->SetNumberOfNodeSets (numNodeSets); em->SetSumNodesPerNodeSet (sumNodes); + em->SetNodeSetNames (nodeSetNames.Get()); int *nodeSetIds_a = new int[nodeSetIds->GetNumberOfTuples ()]; memcpy (nodeSetIds_a, nodeSetIds->GetPointer (0), nodeSetIds->GetNumberOfTuples () * sizeof(int)); @@ -1581,6 +1629,7 @@ int vtkExodusIIWriter::CreateSetsMetadata (vtkModelMetadata* em) em->SetNumberOfSideSets (numSideSets); em->SetSumSidesPerSideSet (sumSides); + em->SetSideSetNames (sideSetNames.Get()); int *sideSetIds_a = new int[sideSetIds->GetNumberOfTuples ()]; memcpy (sideSetIds_a, sideSetIds->GetPointer (0), sideSetIds->GetNumberOfTuples() * sizeof(int)); @@ -1916,7 +1965,7 @@ int vtkExodusIIWriter::WriteBlockInformation() blockIter != this->BlockInfoMap.end (); blockIter ++) { - char *name = vtkExodusIIWriter::GetCellTypeName (blockIter->second.Type); + char *type_name = vtkExodusIIWriter::GetCellTypeName (blockIter->second.Type); if (blockIter->second.NodesPerElement == 0 && blockIter->second.NumElements > 0) { @@ -1924,7 +1973,7 @@ int vtkExodusIIWriter::WriteBlockInformation() int numPoints = blockIter->second.EntityNodeOffsets[numElts - 1] + blockIter->second.EntityCounts[numElts - 1]; rc = ex_put_elem_block(this->fid, blockIter->first, - name, + type_name, blockIter->second.NumElements, numPoints, blockIter->second.NumAttributes); @@ -1932,18 +1981,21 @@ int vtkExodusIIWriter::WriteBlockInformation() else { rc = ex_put_elem_block(this->fid, blockIter->first, - name, + type_name, blockIter->second.NumElements, blockIter->second.NodesPerElement, blockIter->second.NumAttributes); } - delete [] name; + delete [] type_name; + if (rc < 0) { vtkErrorMacro (<< "Problem adding block with id " << blockIter->first); continue; } + ex_put_name (this->fid, EX_ELEM_BLOCK, blockIter->first, blockIter->second.Name); + if (blockIter->second.NumElements > 0) { rc = ex_put_elem_conn(this->fid, blockIter->first, @@ -2503,17 +2555,25 @@ int vtkExodusIIWriter::WriteNodeSetInformation() emNumDF ++; } + int *node_ids = em->GetNodeSetIds(); + if (this->PassDoubles) { - rc = ex_put_concat_node_sets(this->fid, em->GetNodeSetIds(), + rc = ex_put_concat_node_sets(this->fid, node_ids, nsSize, nsNumDF, nsIdIdx, nsDFIdx, idBuf, dfBufD); } else { - rc = ex_put_concat_node_sets(this->fid, em->GetNodeSetIds(), + rc = ex_put_concat_node_sets(this->fid, node_ids, nsSize, nsNumDF, nsIdIdx, nsDFIdx, idBuf, dfBuf); } + for (i = 0; i < nnsets; i ++) { + vtkStdString name = em->GetNodeSetNames ()->GetValue (node_ids[i]); + ex_put_name (this->fid, EX_NODE_SET, node_ids[i], name.c_str()); + } + + delete [] nsSize; delete [] nsNumDF; delete [] nsIdIdx; @@ -2539,10 +2599,24 @@ vtkIdType vtkExodusIIWriter::GetElementLocalId(vtkIdType id) for (vtkIdType j=0; jGlobalElementIdList[i][j]; - int offset = this->CellToElementOffset[i][j]; - int start = this->BlockInfoMap[BlockIdList[i]->GetValue (j)].ElementStartIndex; + std::map::iterator mapit = this->LocalElementIdMap->find(gid); + if (mapit != this->LocalElementIdMap->end ()) + { + vtkErrorMacro ("Overlapping gids in the dataset"); + continue; + } + + std::map::const_iterator blockIter = + this->BlockInfoMap.find (this->BlockIdList[i]->GetValue (j)); + if (blockIter == this->BlockInfoMap.end ()) + { + vtkWarningMacro ("vtkExodusIIWriter: The block id map has come out of sync"); + continue; + } + + int index = blockIter->second.ElementStartIndex + CellToElementOffset[i][j]; this->LocalElementIdMap->insert( - std::map::value_type(gid, start + offset)); + std::map::value_type(gid, index)); } } } @@ -2674,7 +2748,7 @@ int vtkExodusIIWriter::WriteSideSetInformation() { ssSize[i]++; - idBuf[nextId] = lid+1; + idBuf[nextId] = lid + 1; sideBuf[nextId] = *sides; sides ++; @@ -2706,17 +2780,24 @@ int vtkExodusIIWriter::WriteSideSetInformation() } } + int *sids = em->GetSideSetIds (); + if (this->PassDoubles) { - rc = ex_put_concat_side_sets(this->fid, em->GetSideSetIds(), + rc = ex_put_concat_side_sets(this->fid, sids, ssSize, ssNumDF, ssIdIdx, ssDFIdx, idBuf, sideBuf, dfBufD); } else { - rc = ex_put_concat_side_sets(this->fid, em->GetSideSetIds(), + rc = ex_put_concat_side_sets(this->fid, sids, ssSize, ssNumDF, ssIdIdx, ssDFIdx, idBuf, sideBuf, dfBuf); } + for (i = 0; i < nssets; i ++) { + vtkStdString name = em->GetSideSetNames ()->GetValue (sids[i]); + ex_put_name (this->fid, EX_SIDE_SET, sids[i], name.c_str()); + } + delete [] ssSize; delete [] ssNumDF; delete [] ssIdIdx; @@ -2996,13 +3077,13 @@ int vtkExodusIIWriter::WriteGlobalData (int timestep, vtkDataArray *buffer) int rc; if (buffer->IsA ("vtkDoubleArray")) { - vtkDoubleArray *da = vtkDoubleArray::SafeDownCast (buffer); + vtkDoubleArray *da = vtkArrayDownCast(buffer); rc = ex_put_glob_vars (this->fid, timestep + 1, this->NumberOfScalarGlobalArrays, da->GetPointer (0)); } else /* (buffer->IsA ("vtkFloatArray")) */ { - vtkFloatArray *fa = vtkFloatArray::SafeDownCast (buffer); + vtkFloatArray *fa = vtkArrayDownCast(buffer); rc = ex_put_glob_vars (this->fid, timestep + 1, this->NumberOfScalarGlobalArrays, fa->GetPointer (0)); } @@ -3049,13 +3130,13 @@ int vtkExodusIIWriter::WriteCellData (int timestep, vtkDataArray *buffer) int rc; if (buffer->IsA ("vtkDoubleArray")) { - vtkDoubleArray *da = vtkDoubleArray::SafeDownCast (buffer); + vtkDoubleArray *da = vtkArrayDownCast(buffer); rc = ex_put_elem_var(this->fid, timestep + 1, varOutIndex + 1, id, numElts, da->GetPointer(start)); } else /* (buffer->IsA ("vtkFloatArray")) */ { - vtkFloatArray *fa = vtkFloatArray::SafeDownCast (buffer); + vtkFloatArray *fa = vtkArrayDownCast(buffer); rc = ex_put_elem_var(this->fid, timestep + 1, varOutIndex + 1, id, numElts, fa->GetPointer(start)); } @@ -3093,13 +3174,13 @@ int vtkExodusIIWriter::WritePointData (int timestep, vtkDataArray *buffer) int rc; if (buffer->IsA ("vtkDoubleArray")) { - vtkDoubleArray *da = vtkDoubleArray::SafeDownCast (buffer); + vtkDoubleArray *da = vtkArrayDownCast(buffer); rc = ex_put_nodal_var(this->fid, timestep + 1, varOutIndex + 1, this->NumPoints, da->GetPointer (0)); } else /* (buffer->IsA ("vtkFloatArray")) */ { - vtkFloatArray *fa = vtkFloatArray::SafeDownCast (buffer); + vtkFloatArray *fa = vtkArrayDownCast(buffer); rc = ex_put_nodal_var(this->fid, timestep + 1, varOutIndex + 1, this->NumPoints, fa->GetPointer (0)); } @@ -3223,7 +3304,7 @@ vtkIntArray* vtkExodusIIWriter::GetBlockIdArray ( } if (da) { - vtkIntArray *ia = vtkIntArray::SafeDownCast(da); + vtkIntArray *ia = vtkArrayDownCast(da); if (ia != 0 && vtkExodusIIWriter::SameTypeOfCells (ia, input)) { this->SetBlockIdArrayName(name); diff --git a/IO/Exodus/vtkExodusIIWriter.h b/IO/Exodus/vtkExodusIIWriter.h index 56b8aeda708..fe8f0bd5aff 100644 --- a/IO/Exodus/vtkExodusIIWriter.h +++ b/IO/Exodus/vtkExodusIIWriter.h @@ -188,17 +188,20 @@ class VTKIOEXODUS_EXPORT vtkExodusIIWriter : public vtkWriter int FileTimeOffset; bool TopologyChanged; -//BTX vtkDataObject *OriginalInput; std::vector< vtkSmartPointer > FlattenedInput; std::vector< vtkSmartPointer > NewFlattenedInput; + std::vector< vtkStdString > FlattenedNames; + std::vector< vtkStdString > NewFlattenedNames; + std::vector< vtkIntArray* > BlockIdList; struct Block { Block () { + this->Name = 0; this->Type = 0; this->NumElements = 0; this->ElementStartIndex = -1; @@ -210,6 +213,7 @@ class VTKIOEXODUS_EXPORT vtkExodusIIWriter : public vtkWriter this->NumAttributes = 0; this->BlockAttributes = 0; }; + const char *Name; int Type; int NumElements; int ElementStartIndex; @@ -227,11 +231,10 @@ class VTKIOEXODUS_EXPORT vtkExodusIIWriter : public vtkWriter std::vector GlobalElementIdList; std::vector GlobalNodeIdList; -//ETX + int AtLeastOneGlobalElementIdList; int AtLeastOneGlobalNodeIdList; -//BTX struct VariableInfo { int NumComponents; @@ -245,11 +248,9 @@ class VTKIOEXODUS_EXPORT vtkExodusIIWriter : public vtkWriter int NumberOfScalarGlobalArrays; int NumberOfScalarElementArrays; int NumberOfScalarNodeArrays; -//ETX -//BTX std::vector< std::vector > CellToElementOffset; -//ETX + // By BlockId, and within block ID by element variable, with variables // appearing in the same order in which they appear in OutputElementArrayNames @@ -258,10 +259,8 @@ class VTKIOEXODUS_EXPORT vtkExodusIIWriter : public vtkWriter int BlockVariableTruthValue(int blockIdx, int varIdx); -//BTX char *StrDupWithNew (const char *s); void StringUppercase (std::string& str); -//ETX int ProcessRequest (vtkInformation* request, vtkInformationVector** inputVector, @@ -283,7 +282,7 @@ class VTKIOEXODUS_EXPORT vtkExodusIIWriter : public vtkWriter void WriteData (); - int FlattenHierarchy (vtkDataObject* input, bool& changed); + int FlattenHierarchy (vtkDataObject* input, const char *name, bool& changed); int CreateNewExodusFile (); void CloseExodusFile (); @@ -308,7 +307,6 @@ class VTKIOEXODUS_EXPORT vtkExodusIIWriter : public vtkWriter int CreateBlockVariableMetadata (vtkModelMetadata* em); int CreateSetsMetadata (vtkModelMetadata* em); -//BTX void ConvertVariableNames (std::map& variableMap); char **FlattenOutVariableNames ( int nScalarArrays, @@ -319,7 +317,7 @@ class VTKIOEXODUS_EXPORT vtkExodusIIWriter : public vtkWriter std::map *LocalNodeIdMap; std::map *LocalElementIdMap; -//ETX + vtkIdType GetNodeLocalId(vtkIdType id); vtkIdType GetElementLocalId(vtkIdType id); int GetElementType(vtkIdType id); @@ -341,15 +339,12 @@ class VTKIOEXODUS_EXPORT vtkExodusIIWriter : public vtkWriter static bool SameTypeOfCells (vtkIntArray* cellToBlockId, vtkUnstructuredGrid* input); -//BTX double ExtractGlobalData (const char *name, int comp, int ts); int WriteGlobalData (int timestep, vtkDataArray *buffer); void ExtractCellData (const char *name, int comp, vtkDataArray *buffer); int WriteCellData (int timestep, vtkDataArray *buffer); void ExtractPointData (const char *name, int comp, vtkDataArray *buffer); int WritePointData (int timestep, vtkDataArray *buffer); -//ETX - private: vtkExodusIIWriter (const vtkExodusIIWriter&); // Not Implemented diff --git a/IO/Exodus/vtkModelMetadata.cxx b/IO/Exodus/vtkModelMetadata.cxx index c1b53047eb0..d4e3d2806e3 100644 --- a/IO/Exodus/vtkModelMetadata.cxx +++ b/IO/Exodus/vtkModelMetadata.cxx @@ -24,6 +24,7 @@ #include "vtkFieldData.h" #include "vtkCharArray.h" #include "vtkFloatArray.h" +#include "vtkStringArray.h" #include "vtkDataArray.h" #include "vtkIdTypeArray.h" #include "vtkIntArray.h" @@ -194,7 +195,9 @@ void vtkModelMetadata::FreeAllGlobalData() delete this->BlockIdIndex; this->BlockIdIndex = NULL; + this->SetNodeSetNames(NULL); this->SetNodeSetIds(NULL); + this->SetSideSetNames(NULL); this->SetSideSetIds(NULL); this->SetBlockPropertyNames(0, NULL); @@ -501,7 +504,6 @@ void vtkModelMetadata::SetNodeSetDistributionFactors(float *d) //------------------------------------------------- // side set calculations //------------------------------------------------- - void vtkModelMetadata::SetSideSetIds(int *s) { FREE(this->SideSetIds); @@ -1158,6 +1160,11 @@ void vtkModelMetadata::PrintSelf(ostream& os, vtkIndent indent) this->NumberOfBlocks << endl; os << indent << "NumberOfNodeSets: " << this->NumberOfNodeSets << endl; + os << indent << "NodeSetNames: "; + for(i=0; this->NodeSetNames && (iNodeSetNames->GetNumberOfValues()); i++) + { + os << this->NodeSetNames->GetValue (i) << " "; + } os << indent << "NodeSetIds: "; for(i=0;iNumberOfNodeSets;i++) { @@ -1189,6 +1196,11 @@ void vtkModelMetadata::PrintSelf(ostream& os, vtkIndent indent) os << endl; os << indent << "NumberOfSideSets: " << this->NumberOfSideSets << endl; + os << indent << "SideSetNames: "; + for(i=0;this->SideSetNames && (iSideSetNames->GetNumberOfValues()); i++) + { + os << this->SideSetNames->GetValue (i) << " "; + } os << indent << "SideSetIds: "; for(i=0;iNumberOfSideSets;i++) { diff --git a/IO/Exodus/vtkModelMetadata.h b/IO/Exodus/vtkModelMetadata.h index 4e4829c778d..33ff17ae923 100644 --- a/IO/Exodus/vtkModelMetadata.h +++ b/IO/Exodus/vtkModelMetadata.h @@ -71,13 +71,15 @@ #include "vtkIOExodusModule.h" // For export macro #include "vtkObject.h" - +#include "vtkSmartPointer.h" // for vtkSmartPointer +#include "vtkStringArray.h" // for vtkStringArray class vtkDataSet; class vtkCharArray; class vtkIdTypeArray; class vtkIntArray; class vtkFloatArray; class vtkIntArray; +class vtkStringArray; class vtkModelMetadataSTLCloak; class VTKIOEXODUS_EXPORT vtkModelMetadata : public vtkObject @@ -237,6 +239,10 @@ class VTKIOEXODUS_EXPORT vtkModelMetadata : public vtkObject vtkSetMacro(NumberOfNodeSets, int); int GetNumberOfNodeSets() const {return this->NumberOfNodeSets;} + // Description: + void SetNodeSetNames (vtkStringArray *names) { this->NodeSetNames = names; } + vtkStringArray* GetNodeSetNames() const { return this->NodeSetNames; } + // Description: // Set or get the list the IDs for each node set. // Length of list is the number of node sets. @@ -303,6 +309,10 @@ class VTKIOEXODUS_EXPORT vtkModelMetadata : public vtkObject vtkSetMacro(NumberOfSideSets, int); int GetNumberOfSideSets() const {return this->NumberOfSideSets;} + // Description: + void SetSideSetNames (vtkStringArray *names) { this->SideSetNames = names; } + vtkStringArray* GetSideSetNames() const { return this->SideSetNames; } + // Description: // Set or get a pointer to a list giving the ID of each side set. // We use your pointer, and free the memory when the object is freed. @@ -653,6 +663,8 @@ class VTKIOEXODUS_EXPORT vtkModelMetadata : public vtkObject int NumberOfNodeSets; // (G) + vtkSmartPointer NodeSetNames; + int *NodeSetIds; // NumberOfNodeSets (G) int *NodeSetSize; // NumberOfNodeSets (L) int *NodeSetNumberOfDistributionFactors; // NNS (L) (NSNDF[i] is 0 or NSS[i]) @@ -671,6 +683,8 @@ class VTKIOEXODUS_EXPORT vtkModelMetadata : public vtkObject int NumberOfSideSets; // (G) + vtkSmartPointer SideSetNames; + int *SideSetIds; // NumberOfSideSets (G) int *SideSetSize; // NumberOfSideSets (L) int *SideSetNumberOfDistributionFactors; // NSS (L) (SSNDF[i] = 0 or NumNodesInSide) diff --git a/IO/Export/vtkGL2PSExporter.h b/IO/Export/vtkGL2PSExporter.h index 3e763fdaa3b..eadc109492c 100644 --- a/IO/Export/vtkGL2PSExporter.h +++ b/IO/Export/vtkGL2PSExporter.h @@ -111,7 +111,6 @@ class VTKIOEXPORT_EXPORT vtkGL2PSExporter : public vtkExporter vtkSetStringMacro(Title); vtkGetStringMacro(Title); -//BTX enum OutputFormat { PS_FILE, @@ -120,7 +119,6 @@ class VTKIOEXPORT_EXPORT vtkGL2PSExporter : public vtkExporter TEX_FILE, SVG_FILE }; -//ETX // Description: // Configure the exporter to expect a painter-ordered 2D rendering, that is, @@ -153,14 +151,12 @@ class VTKIOEXPORT_EXPORT vtkGL2PSExporter : public vtkExporter {this->SetFileFormat(SVG_FILE);}; const char *GetFileFormatAsString(); -//BTX enum SortScheme { NO_SORT=0, SIMPLE_SORT=1, BSP_SORT=2 }; -//ETX // Description: // Set the the type of sorting algorithm to order primitives from diff --git a/IO/Export/vtkX3DExporter.cxx b/IO/Export/vtkX3DExporter.cxx index 50dbbf62613..c65d3234426 100644 --- a/IO/Export/vtkX3DExporter.cxx +++ b/IO/Export/vtkX3DExporter.cxx @@ -50,7 +50,7 @@ using namespace vtkX3D; // forward declarations -static bool vtkX3DExporterWriterUsingCellColors(vtkActor* anActor); +static bool vtkX3DExporterWriterUsingCellColors(vtkMapper* anActor); static bool vtkX3DExporterWriterRenderFaceSet( int cellType, int representation, @@ -484,8 +484,10 @@ void vtkX3DExporter::WriteAnActor(vtkActor *anActor, colors = mapper->MapScalars(255.0); - // Are we using cell colors. - bool cell_colors = vtkX3DExporterWriterUsingCellColors(anActor); + // Are we using cell colors? Pass the temporary mapper we created here since + // we're assured that that mapper only has vtkPolyData as input and hence + // don't run into issue when dealing with composite datasets. + bool cell_colors = vtkX3DExporterWriterUsingCellColors(mapper); normals = pntData->GetNormals(); @@ -880,10 +882,11 @@ int vtkX3DExporter::HasHeadLight(vtkRenderer* ren) return 0; } -static bool vtkX3DExporterWriterUsingCellColors(vtkActor* anActor) +// Determine if we're using cell data for scalar coloring. Returns true if +// that's the case. +static bool vtkX3DExporterWriterUsingCellColors(vtkMapper* mapper) { int cellFlag = 0; - vtkMapper* mapper = anActor->GetMapper(); vtkAbstractMapper::GetScalars( mapper->GetInput(), mapper->GetScalarMode(), @@ -1058,7 +1061,7 @@ static void vtkX3DExporterWriteData(vtkPoints *points, unsigned char c[4]; for (int i = 0; i < colors->GetNumberOfTuples(); i++) { - colors->GetTupleValue(i,c); + colors->GetTypedTuple(i,c); colorVec.push_back(c[0]/255.0); colorVec.push_back(c[1]/255.0); colorVec.push_back(c[2]/255.0); @@ -1124,11 +1127,11 @@ static bool vtkX3DExporterWriterRenderVerts( unsigned char color[4]; if (cell_colors) { - colors->GetTupleValue(cellId, color); + colors->GetTypedTuple(cellId, color); } else { - colors->GetTupleValue(indx[cc], color); + colors->GetTypedTuple(indx[cc], color); } colorVector.push_back(color[0]/255.0); @@ -1185,7 +1188,7 @@ static bool vtkX3DExporterWriterRenderPoints( // Get the color for this cell. unsigned char color[4]; - colors->GetTupleValue(cid, color); + colors->GetTypedTuple(cid, color); double dcolor[3]; dcolor[0] = color[0]/255.0; dcolor[1] = color[1]/255.0; @@ -1220,7 +1223,7 @@ static bool vtkX3DExporterWriterRenderPoints( if (colors) { unsigned char color[4]; - colors->GetTupleValue(pid, color); + colors->GetTypedTuple(pid, color); colorVec.push_back(color[0]/255.0); colorVec.push_back(color[1]/255.0); colorVec.push_back(color[2]/255.0); diff --git a/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion-rasterRef.png.md5 b/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion-rasterRef.png.md5 index 2240cf2b53c..8b8c2c6ed1e 100644 --- a/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion-rasterRef.png.md5 +++ b/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion-rasterRef.png.md5 @@ -1 +1 @@ -83561767d44807efad7c446bb70b3ae9 +c508c220fd21f8df796c8cccb3f2a0bb diff --git a/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion-rasterRef_1.png.md5 b/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion-rasterRef_1.png.md5 index 84abb5c108e..f2e1ab3481b 100644 --- a/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion-rasterRef_1.png.md5 +++ b/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion-rasterRef_1.png.md5 @@ -1 +1 @@ -b6cc53aad9c9524727ada6678ee7ab55 +05d42a8d16666524d9590aab4df569f2 diff --git a/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion.png.md5 b/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion.png.md5 index f83caa740ee..481db92f2bf 100644 --- a/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion.png.md5 +++ b/IO/ExportOpenGL/Testing/Data/Baseline/TestGL2PSExporterRasterExclusion.png.md5 @@ -1 +1 @@ -28392228daa6f2fff4e5f02b74295cea +17712695013e9f093d7a91dfb13ba2ec diff --git a/IO/FFMPEG/vtkFFMPEGWriter.cxx b/IO/FFMPEG/vtkFFMPEGWriter.cxx index d3fd4213a08..e6d06b7d7b0 100644 --- a/IO/FFMPEG/vtkFFMPEGWriter.cxx +++ b/IO/FFMPEG/vtkFFMPEGWriter.cxx @@ -43,6 +43,15 @@ extern "C" { #if LIBAVCODEC_VERSION_MAJOR < 55 # define AV_CODEC_ID_MJPEG CODEC_ID_MJPEG # define AV_CODEC_ID_RAWVIDEO CODEC_ID_RAWVIDEO +# define AV_PIX_FMT_BGR24 PIX_FMT_BGR24 +# define AV_PIX_FMT_RGB24 PIX_FMT_RGB24 +# define AV_PIX_FMT_YUVJ422P PIX_FMT_YUVJ422P +#endif + +#if LIBAVCODEC_VERSION_MAJOR < 56 || \ + LIBAVCODEC_VERSION_MAJOR == 55 && LIBAVCODEC_VERSION_MINOR < 28 || \ + LIBAVCODEC_VERSION_MAJOR == 55 && LIBAVCODEC_VERSION_MINOR == 28 && LIBAVCODEC_VERSION_MICRO < 1 +# define av_frame_alloc avcodec_alloc_frame #endif //--------------------------------------------------------------------------- @@ -191,11 +200,11 @@ int vtkFFMPEGWriterInternal::Start() c->height = this->Dim[1]; if (this->Writer->GetCompression()) { - c->pix_fmt = PIX_FMT_YUVJ422P; + c->pix_fmt = AV_PIX_FMT_YUVJ422P; } else { - c->pix_fmt = PIX_FMT_BGR24; + c->pix_fmt = AV_PIX_FMT_BGR24; } //to do playback at actual recorded rate, this will need more work see also below @@ -274,13 +283,13 @@ int vtkFFMPEGWriterInternal::Start() #endif //for the output of the writer's input... - this->rgbInput = avcodec_alloc_frame(); + this->rgbInput = av_frame_alloc(); if (!this->rgbInput) { vtkGenericWarningMacro (<< "Could not make rgbInput avframe." ); return 0; } - int RGBsize = avpicture_get_size(PIX_FMT_RGB24, c->width, c->height); + int RGBsize = avpicture_get_size(AV_PIX_FMT_RGB24, c->width, c->height); unsigned char *rgb = (unsigned char *)av_malloc(sizeof(unsigned char) * RGBsize); if (!rgb) { @@ -288,10 +297,10 @@ int vtkFFMPEGWriterInternal::Start() return 0; } //The rgb buffer should get deleted when this->rgbInput is. - avpicture_fill((AVPicture *)this->rgbInput, rgb, PIX_FMT_RGB24, c->width, c->height); + avpicture_fill((AVPicture *)this->rgbInput, rgb, AV_PIX_FMT_RGB24, c->width, c->height); //and for the output to the codec's input. - this->yuvOutput = avcodec_alloc_frame(); + this->yuvOutput = av_frame_alloc(); if (!this->yuvOutput) { vtkGenericWarningMacro (<< "Could not make yuvOutput avframe." ); @@ -323,7 +332,11 @@ int vtkFFMPEGWriterInternal::Start() #if LIBAVFORMAT_VERSION_MAJOR < 54 av_write_header(this->avFormatContext); #else - avformat_write_header(this->avFormatContext, NULL); + if (avformat_write_header(this->avFormatContext, NULL) < 0) + { + vtkGenericWarningMacro (<< "Could not allocate avcodec private data."); + return 0; + } #endif return 1; } @@ -349,12 +362,12 @@ int vtkFFMPEGWriterInternal::Write(vtkImageData *id) //convert that to YUV for input to the codec #ifdef VTK_FFMPEG_HAS_IMG_CONVERT img_convert((AVPicture *)this->yuvOutput, cc->pix_fmt, - (AVPicture *)this->rgbInput, PIX_FMT_RGB24, + (AVPicture *)this->rgbInput, AV_PIX_FMT_RGB24, cc->width, cc->height); #else //convert that to YUV for input to the codec SwsContext* convert_ctx = sws_getContext( - cc->width, cc->height, PIX_FMT_RGB24, + cc->width, cc->height, AV_PIX_FMT_RGB24, cc->width, cc->height, cc->pix_fmt, SWS_BICUBIC, NULL, NULL, NULL); diff --git a/IO/GDAL/Testing/Cxx/CMakeLists.txt b/IO/GDAL/Testing/Cxx/CMakeLists.txt index cc07838ac6a..03691ce4253 100644 --- a/IO/GDAL/Testing/Cxx/CMakeLists.txt +++ b/IO/GDAL/Testing/Cxx/CMakeLists.txt @@ -1,5 +1,14 @@ +set(TestGDALRasterNoDataValue_ARGS + -D DATA{../Data/Input/TestGDALRasterNoDataValue.tif} +) +set(TestGDALRasterPalette_ARGS + -D DATA{../Data/Input/TestGDALRasterPalette.tif} +) + vtk_add_test_cxx(${vtk-module}CxxTests tests TestGDALVectorReader.cxx TestGDALRasterReader.cxx + TestGDALRasterNoDataValue.cxx,NO_VALID,NO_OUTPUT + TestGDALRasterPalette.cxx ) vtk_test_cxx_executable(${vtk-module}CxxTests tests) diff --git a/IO/GDAL/Testing/Cxx/TestGDALRasterNoDataValue.cxx b/IO/GDAL/Testing/Cxx/TestGDALRasterNoDataValue.cxx new file mode 100644 index 00000000000..e56fb1773fc --- /dev/null +++ b/IO/GDAL/Testing/Cxx/TestGDALRasterNoDataValue.cxx @@ -0,0 +1,72 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestGDALRasterReader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include +#include +#include + +#include + +// Main program +int TestGDALRasterNoDataValue(int argc, char** argv) +{ + if (argc < 3) + { + std::cerr << "Expected TestName -D InputFile.tif" << std::endl; + return -1; + } + + std::string inputFileName(argv[2]); + + // Create reader to read shape file. + vtkNew reader; + reader->SetFileName(inputFileName.c_str()); + reader->Update(); + + vtkUniformGrid *rasterImage = vtkUniformGrid::SafeDownCast( + reader->GetOutput()); + + int numErrors = 0; + + if (!rasterImage->HasAnyBlankPoints()) + { + std::cerr << "Error image has no blank points" << std::endl; + ++numErrors; + } + + if (!rasterImage->HasAnyBlankCells()) + { + std::cerr << "Error image has no blank cells" << std::endl; + ++numErrors; + } + + double *scalarRange = rasterImage->GetScalarRange(); + + if ((scalarRange[0] < -888.5) || (scalarRange[0]) > -887.5) + { + std::cerr << "Error scalarRange[0] should be -888.0, not " + << scalarRange[0] << std::endl; + ++numErrors; + } + + if ((scalarRange[1] < 9998.5) || (scalarRange[1] > 9999.5)) + { + std::cerr << "Error scalarRange[1] should be 9999.0, not " + << scalarRange[1] << std::endl; + ++numErrors; + } + + //std::cout << "numErrors: " << numErrors << std::endl; + return numErrors; +} diff --git a/IO/GDAL/Testing/Cxx/TestGDALRasterPalette.cxx b/IO/GDAL/Testing/Cxx/TestGDALRasterPalette.cxx new file mode 100644 index 00000000000..88459ec95d5 --- /dev/null +++ b/IO/GDAL/Testing/Cxx/TestGDALRasterPalette.cxx @@ -0,0 +1,108 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestGDALRasterReader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// Main program +int TestGDALRasterPalette(int argc, char** argv) +{ + if (argc < 3) + { + std::cerr << "Expected TestName -D InputFile.tif" << std::endl; + return -1; + } + + std::string inputFileName(argv[2]); + + // Create reader to read shape file. + vtkNew reader; + reader->SetFileName(inputFileName.c_str()); + reader->Update(); + vtkUniformGrid *image = vtkUniformGrid::SafeDownCast(reader->GetOutput()); + + // Check that reader generated point scalars + if (image->GetPointData()->GetNumberOfArrays() < 1) + { + std::cerr << "ERROR: Missing point data scalars" << std::endl; + return 1; + } + if (image->GetPointData()->GetScalars()->GetSize() == 0) + { + std::cerr << "ERROR: Point data scalars empty" << std::endl; + return 1; + } + //image->GetPointData()->GetScalars()->Print(std::cout); + + // Check that reader generated color table + vtkLookupTable *colorTable = + image->GetPointData()->GetScalars()->GetLookupTable(); + if (!colorTable) + { + std::cerr << "ERROR: Missing color table" << std::endl; + return 1; + } + if (colorTable->GetNumberOfAvailableColors() != 256) + { + std::cerr << "ERROR: Color table does not have 256 colors." + << " Instead has " << colorTable->GetNumberOfAvailableColors() + << std::endl; + return 1; + } + //colorTable->Print(std::cout); + + // Create a renderer and actor + vtkNew renderer; + vtkNew actor; + actor->SetInputData(reader->GetOutput()); + actor->InterpolateOff(); + //actor->GetProperty()->SetInterpolationTypeToNearest(); + actor->GetProperty()->SetLookupTable(colorTable); + actor->GetProperty()->UseLookupTableScalarRangeOn(); + renderer->AddActor(actor.GetPointer()); + + // Create a render window, and an interactor + vtkNew renderWindow; + vtkNew renderWindowInteractor; + renderWindow->AddRenderer(renderer.GetPointer()); + renderWindowInteractor->SetRenderWindow(renderWindow.GetPointer()); + + //Add the actor to the scene + renderer->SetBackground(1.0, 1.0, 1.0); + renderWindow->SetSize(400, 400); + renderWindow->Render(); + renderer->ResetCamera(); + renderWindow->Render(); + + int retVal = vtkRegressionTestImage(renderWindow.GetPointer()); + if (retVal == vtkRegressionTester::DO_INTERACTOR) + { + renderWindowInteractor->Start(); + } + + return !retVal; +} diff --git a/IO/GDAL/Testing/Data/Baseline/TestGDALRasterPalette.png.md5 b/IO/GDAL/Testing/Data/Baseline/TestGDALRasterPalette.png.md5 new file mode 100644 index 00000000000..ef85ec463bd --- /dev/null +++ b/IO/GDAL/Testing/Data/Baseline/TestGDALRasterPalette.png.md5 @@ -0,0 +1 @@ +70aff17ba9e4a0d5c6cffb720f381d26 diff --git a/IO/GDAL/Testing/Data/Input/TestGDALRasterNoDataValue.tif.md5 b/IO/GDAL/Testing/Data/Input/TestGDALRasterNoDataValue.tif.md5 new file mode 100644 index 00000000000..068edb8e8e1 --- /dev/null +++ b/IO/GDAL/Testing/Data/Input/TestGDALRasterNoDataValue.tif.md5 @@ -0,0 +1 @@ +f73cb0b2de8941d9e491190d193f10a2 diff --git a/IO/GDAL/Testing/Data/Input/TestGDALRasterPalette.tif.md5 b/IO/GDAL/Testing/Data/Input/TestGDALRasterPalette.tif.md5 new file mode 100644 index 00000000000..f02894f0203 --- /dev/null +++ b/IO/GDAL/Testing/Data/Input/TestGDALRasterPalette.tif.md5 @@ -0,0 +1 @@ +cdffbf2b4f05e98cf0c0f10d34eb302a diff --git a/IO/GDAL/vtkGDALRasterReader.cxx b/IO/GDAL/vtkGDALRasterReader.cxx index 5d122e6e017..64f653503e0 100644 --- a/IO/GDAL/vtkGDALRasterReader.cxx +++ b/IO/GDAL/vtkGDALRasterReader.cxx @@ -24,6 +24,7 @@ #include "vtkInformationVector.h" #include "vtkInformation.h" #include "vtkIntArray.h" +#include "vtkLookupTable.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" @@ -44,6 +45,7 @@ // C/C++ includes #include #include +#include #include vtkStandardNewMacro(vtkGDALRasterReader); @@ -84,6 +86,9 @@ class vtkGDALRasterReader::vtkGDALRasterReaderInternal const double* GetGeoCornerPoints(); + void ReadColorTable( + GDALRasterBand *rasterBand, vtkLookupTable *colorTable) const; + int NumberOfBands; int NumberOfBytesPerPixel; @@ -101,6 +106,7 @@ class vtkGDALRasterReader::vtkGDALRasterReaderInternal // Upper left, lower left, upper right, lower right double CornerPoints[8]; + int HasNoDataValue; double NoDataValue; vtkIdType NumberOfPoints; @@ -277,17 +283,23 @@ void vtkGDALRasterReader::vtkGDALRasterReaderInternal::GenericReadData() // Pixel data. std::vector rawUniformGridData; + // Color table + vtkSmartPointer colorTable = + vtkSmartPointer::New(); + // Possible bands GDALRasterBand* redBand = 0; GDALRasterBand* greenBand = 0; GDALRasterBand* blueBand = 0; GDALRasterBand* alphaBand = 0; GDALRasterBand* greyBand = 0; + GDALRasterBand* paletteBand = 0; for (int i = 1; i <= this->NumberOfBands; ++i) { GDALRasterBand* rasterBand = this->GDALData->GetRasterBand(i); - NoDataValue = rasterBand->GetNoDataValue(); + this->HasNoDataValue = 0; + this->NoDataValue = rasterBand->GetNoDataValue(&this->HasNoDataValue); if (this->NumberOfBytesPerPixel == 0) { this->TargetDataType = rasterBand->GetRasterDataType(); @@ -328,6 +340,10 @@ void vtkGDALRasterReader::vtkGDALRasterReaderInternal::GenericReadData() { greyBand = rasterBand; } + else if (rasterBand->GetColorInterpretation() == GCI_PaletteIndex) + { + paletteBand = rasterBand; + } } const int& destWidth = this->Reader->TargetDimensions[0]; @@ -434,6 +450,20 @@ void vtkGDALRasterReader::vtkGDALRasterReaderInternal::GenericReadData() assert(err == CE_None); } } + else if (paletteBand) + { + // Read indexes + this->Reader->SetNumberOfScalarComponents(1); + rawUniformGridData.resize(destWidth * destHeight * pixelSpace); + err = paletteBand->RasterIO( + GF_Read, windowX, windowY, windowWidth, windowHeight, + static_cast(reinterpret_cast(&rawUniformGridData[0]) + + 0 * bandSpace), destWidth, destHeight, + this->TargetDataType, pixelSpace, lineSpace); + assert(err == CE_None); + + this->ReadColorTable(paletteBand, colorTable.GetPointer()); + } else { std::cerr << "Unknown raster band type \n"; @@ -451,6 +481,13 @@ void vtkGDALRasterReader::vtkGDALRasterReaderInternal::GenericReadData() this->UniformGridData->SetSpacing(geoSpacing[0], geoSpacing[1], geoSpacing[2]); this->UniformGridData->SetOrigin(d[0], d[1], 0); this->Convert(rawUniformGridData, destWidth, destHeight); + + if (paletteBand) + { + this->UniformGridData->GetPointData()->GetScalars()->SetName("Categories"); + this->UniformGridData->GetPointData()->GetScalars()->SetLookupTable( + colorTable); + } } //---------------------------------------------------------------------------- @@ -480,6 +517,12 @@ void vtkGDALRasterReader::vtkGDALRasterReaderInternal::Convert( scArr->SetNumberOfComponents(this->NumberOfBands); scArr->SetNumberOfTuples(targetWidth * targetHeight); + RAW_TYPE TNoDataValue = 0; + if (this->HasNoDataValue) + { + TNoDataValue = static_cast(this->NoDataValue); + } + for (int j = 0; j < targetHeight; ++j) { for (int i = 0; i < targetWidth; ++i) @@ -491,11 +534,18 @@ void vtkGDALRasterReader::vtkGDALRasterReaderInternal::Convert( j * targetWidth * NumberOfBands + bandIndex; sourceIndex = i + j * targetWidth + bandIndex * targetWidth * targetHeight; + RAW_TYPE tmp = rawUniformGridData[sourceIndex]; - if(tmp < min) min = tmp; - if(tmp > max) max = tmp; - if(tmp == NoDataValue) this->UniformGridData->BlankPoint(targetIndex); - else this->NumberOfPoints++; + if (this->HasNoDataValue && tmp == TNoDataValue) + { + this->UniformGridData->BlankPoint(targetIndex); + } + else + { + if(tmp < min) min = tmp; + if(tmp > max) max = tmp; + this->NumberOfPoints++; + } scArr->InsertValue(targetIndex, rawUniformGridData[sourceIndex]); } @@ -595,6 +645,53 @@ const double* vtkGDALRasterReader::vtkGDALRasterReaderInternal::GetGeoCornerPoin return this->CornerPoints; } +//----------------------------------------------------------------------------- +void vtkGDALRasterReader::vtkGDALRasterReaderInternal::ReadColorTable( + GDALRasterBand *rasterBand, vtkLookupTable *colorTable) const +{ + GDALColorTable *gdalTable = rasterBand->GetColorTable(); + if (gdalTable->GetPaletteInterpretation() != GPI_RGB) + { + std::cerr << "Color table palette type not supported " + << gdalTable->GetPaletteInterpretation() << std::endl; + return; + } + + char **categoryNames = rasterBand->GetCategoryNames(); + + colorTable->IndexedLookupOn(); + int numEntries = gdalTable->GetColorEntryCount(); + colorTable->SetNumberOfTableValues(numEntries); + std::stringstream ss; + for (int i=0; i< numEntries; ++i) + { + const GDALColorEntry *gdalEntry = gdalTable->GetColorEntry(i); + double r = static_cast(gdalEntry->c1) / 255.0; + double g = static_cast(gdalEntry->c2) / 255.0; + double b = static_cast(gdalEntry->c3) / 255.0; + double a = static_cast(gdalEntry->c4) / 255.0; + colorTable->SetTableValue(i, r, g, b, a); + + // Copy category name to lookup table annotation + if (categoryNames) + { + // Only use non-empty names + if (strlen(categoryNames[i]) > 0) + { + colorTable->SetAnnotation(vtkVariant(i), categoryNames[i]); + } + } + else + { + // Create default annotation + ss.str(""); + ss.clear(); + ss << "Category " << i; + colorTable->SetAnnotation(vtkVariant(i), ss.str()); + } + } +} + //----------------------------------------------------------------------------- void vtkGDALRasterReader::PrintSelf(std::ostream& os, vtkIndent indent) { diff --git a/IO/GDAL/vtkGDALRasterReader.h b/IO/GDAL/vtkGDALRasterReader.h index 92007095051..02500bdbc8c 100644 --- a/IO/GDAL/vtkGDALRasterReader.h +++ b/IO/GDAL/vtkGDALRasterReader.h @@ -67,21 +67,17 @@ class VTKIOGDAL_EXPORT vtkGDALRasterReader : public vtkImageReader2 // Get raster width and heigth vtkGetVector2Macro(RasterDimensions, int); - //BTX // Description: // Return metadata as reported by GDAL const std::vector& GetMetaData(); - //ETX // Description: // Return the invalid value for a pixel (for blanking purposes) double GetInvalidValue(); - //BTX // Description: // Return domain metadata std::vector GetDomainMetaData(const std::string& domain); - //ETX // Description: // Return driver name which was used to read the current data diff --git a/IO/GDAL/vtkGDALVectorReader.cxx b/IO/GDAL/vtkGDALVectorReader.cxx index e0b897632d1..4ebcbb1bd49 100644 --- a/IO/GDAL/vtkGDALVectorReader.cxx +++ b/IO/GDAL/vtkGDALVectorReader.cxx @@ -42,9 +42,16 @@ int vtkGDALVectorReader::OGRRegistered = 0; class vtkGDALVectorReader::Internal { public: - Internal( const char* srcName, int srcMode, int appendFeatures, int addFeatIds ) + Internal( const char* srcName, int appendFeatures, int addFeatIds ) { - this->Source = OGRSFDriverRegistrar::Open( srcName, srcMode, &this->Driver ); +#if GDAL_VERSION_MAJOR < 2 + OGRSFDriver* driver; + this->Source = OGRSFDriverRegistrar::Open( srcName, 0, &driver ); +#else + GDALAllRegister(); + this->Source = static_cast( + GDALOpenEx(srcName, GDAL_OF_VECTOR, NULL, NULL, NULL)); +#endif if ( ! this->Source ) { this->LastError = CPLGetLastErrorMsg(); @@ -61,7 +68,11 @@ class vtkGDALVectorReader::Internal { if ( this->Source ) { +#if GDAL_VERSION_MAJOR < 2 OGRDataSource::DestroyDataSource( this->Source ); +#else + GDALClose(this->Source); +#endif } } @@ -175,7 +186,7 @@ class vtkGDALVectorReader::Internal switch ( ffdef->GetType() ) { case OFTInteger: - iarr = vtkIntArray::SafeDownCast( fields[f] ); + iarr = vtkArrayDownCast( fields[f] ); ival = feat->GetFieldAsInteger( f ); for ( i = 0; i < nPoly; ++i ) { @@ -183,7 +194,7 @@ class vtkGDALVectorReader::Internal } break; case OFTReal: - rarr = vtkDoubleArray::SafeDownCast( fields[f] ); + rarr = vtkArrayDownCast( fields[f] ); rval = feat->GetFieldAsDouble( f ); for ( i = 0; i < nPoly; ++i ) { @@ -192,7 +203,7 @@ class vtkGDALVectorReader::Internal break; case OFTString: default: - sarr = vtkStringArray::SafeDownCast( fields[f] ); + sarr = vtkArrayDownCast( fields[f] ); sval = feat->GetFieldAsString( f ); for ( i = 0; i < nPoly; ++i ) { @@ -202,7 +213,7 @@ class vtkGDALVectorReader::Internal } if (this->AddFeatureIds) { - vtkIdTypeArray* idarr = vtkIdTypeArray::SafeDownCast(fields[numFields]); + vtkIdTypeArray* idarr = vtkArrayDownCast(fields[numFields]); for ( i = 0; i < nPoly; ++i ) { idarr->InsertNextValue(feat->GetFID()); @@ -302,13 +313,77 @@ class vtkGDALVectorReader::Internal case wkbNone: return 0; +#if GDAL_VERSION_MAJOR >= 2 + case wkbCircularString: + case wkbCircularStringZ: + case wkbCompoundCurve: + case wkbCompoundCurveZ: + case wkbCurvePolygon: + case wkbCurvePolygonZ: + case wkbMultiCurve: + case wkbMultiCurveZ: + case wkbMultiSurface: + case wkbMultiSurfaceZ: + return 0; +#endif +#if GDAL_VERSION_MAJOR >= 3 || \ + (GDAL_VERSION_MAJOR == 2 && GDAL_VERSION_MINOR > 0) + case wkbCircularStringM: + case wkbCircularStringZM: + case wkbCompoundCurveM: + case wkbCompoundCurveZM: + case wkbCurve: + case wkbCurveM: + case wkbCurvePolygonM: + case wkbCurvePolygonZM: + case wkbCurveZ: + case wkbCurveZM: + case wkbGeometryCollectionM: + case wkbGeometryCollectionZM: + case wkbLineStringM: + case wkbLineStringZM: + case wkbMultiCurveM: + case wkbMultiCurveZM: + case wkbMultiLineStringM: + case wkbMultiLineStringZM: + case wkbMultiPointM: + case wkbMultiPointZM: + case wkbMultiPolygonM: + case wkbMultiPolygonZM: + case wkbMultiSurfaceM: + case wkbMultiSurfaceZM: + case wkbPointM: + case wkbPointZM: + case wkbPolygonM: + case wkbPolygonZM: + case wkbPolyhedralSurface: + case wkbPolyhedralSurfaceM: + case wkbPolyhedralSurfaceZ: + case wkbPolyhedralSurfaceZM: + case wkbSurface: + case wkbSurfaceM: + case wkbSurfaceZ: + case wkbSurfaceZM: + case wkbTIN: + case wkbTINM: + case wkbTINZ: + case wkbTINZM: + case wkbTriangle: + case wkbTriangleM: + case wkbTriangleZ: + case wkbTriangleZM: + return 0; +#endif } return nCells; } +#if GDAL_VERSION_MAJOR < 2 OGRDataSource* Source; - OGRSFDriver* Driver; +#else + GDALDataset* Source; +#endif const char* LastError; int LayerIdx; int AppendFeatures; @@ -559,7 +634,7 @@ int vtkGDALVectorReader::InitializeInternal() if ( !this->Implementation ) { this->Implementation = new vtkGDALVectorReader::Internal( - this->FileName, 0 , + this->FileName, this->AppendFeatures, this->AddFeatureIds ); if ( ! this->Implementation || this->Implementation->LastError ) { diff --git a/IO/GDAL/vtkGDALVectorReader.h b/IO/GDAL/vtkGDALVectorReader.h index 810705a383b..0f6f5a86943 100644 --- a/IO/GDAL/vtkGDALVectorReader.h +++ b/IO/GDAL/vtkGDALVectorReader.h @@ -78,11 +78,9 @@ class VTKIOGDAL_EXPORT vtkGDALVectorReader : public vtkMultiBlockDataSetAlgorith vtkGetMacro(AppendFeatures, int); vtkBooleanMacro(AppendFeatures, int); - //BTX // Description: // Return projection string belong to each layer. std::map GetLayersProjection(); - //ETX // Description: // Return projection string belong to a layer. @@ -117,7 +115,6 @@ class VTKIOGDAL_EXPORT vtkGDALVectorReader : public vtkMultiBlockDataSetAlgorith int AppendFeatures; int AddFeatureIds; - //BTX class Internal; /// Private per-file metadata @@ -128,7 +125,6 @@ class VTKIOGDAL_EXPORT vtkGDALVectorReader : public vtkMultiBlockDataSetAlgorith /// Mapping of layer to projection. std::map LayersProjection; - //ETX private: vtkGDALVectorReader(const vtkGDALVectorReader&); // Not implemented. diff --git a/IO/GeoJSON/vtkGeoJSONFeature.cxx b/IO/GeoJSON/vtkGeoJSONFeature.cxx index b8aa97870ec..3228ae699ce 100644 --- a/IO/GeoJSON/vtkGeoJSONFeature.cxx +++ b/IO/GeoJSON/vtkGeoJSONFeature.cxx @@ -130,7 +130,7 @@ ExtractPoint(const Json::Value& coordinates, vtkPolyData *outputData) vtkAbstractArray *array = outputData->GetCellData()->GetAbstractArray("feature-id"); - vtkStringArray *ids = vtkStringArray::SafeDownCast(array); + vtkStringArray *ids = vtkArrayDownCast(array); ids->InsertNextValue(this->FeatureId); return outputData; @@ -154,7 +154,7 @@ ExtractMultiPoint(const Json::Value& coordinates, vtkPolyData *outputData) vtkAbstractArray *array = outputData->GetCellData()->GetAbstractArray("feature-id"); - vtkStringArray *ids = vtkStringArray::SafeDownCast(array); + vtkStringArray *ids = vtkArrayDownCast(array); const int PID_SIZE = coordinates.size(); vtkIdType* pids = new vtkIdType[ PID_SIZE ]; @@ -203,7 +203,7 @@ ExtractLineString(const Json::Value& coordinates, vtkPolyData *outputData) outputData->GetLines()->InsertNextCell(polyLine.GetPointer()); vtkAbstractArray *array = outputData->GetCellData()->GetAbstractArray("feature-id"); - vtkStringArray *ids = vtkStringArray::SafeDownCast(array); + vtkStringArray *ids = vtkArrayDownCast(array); ids->InsertNextValue(this->FeatureId); return outputData; @@ -245,7 +245,7 @@ ExtractPolygon(const Json::Value& coordinate, vtkPolyData *outputData) vtkPoints *points = outputData->GetPoints(); vtkAbstractArray *array = outputData->GetCellData()->GetAbstractArray("feature-id"); - vtkStringArray *ids = vtkStringArray::SafeDownCast(array); + vtkStringArray *ids = vtkArrayDownCast(array); // Output is either vtkPolygon or vtkPolyLine, // depending on OutputPolygons option. diff --git a/IO/GeoJSON/vtkGeoJSONReader.cxx b/IO/GeoJSON/vtkGeoJSONReader.cxx index 65fd87cda11..70ad976ec7f 100644 --- a/IO/GeoJSON/vtkGeoJSONReader.cxx +++ b/IO/GeoJSON/vtkGeoJSONReader.cxx @@ -353,19 +353,19 @@ GeoJSONReaderInternal::InsertFeatureProperties(vtkPolyData *polyData, switch (array->GetDataType()) { case VTK_BIT: - vtkBitArray::SafeDownCast(array)->InsertNextValue(value.ToChar()); + vtkArrayDownCast(array)->InsertNextValue(value.ToChar()); break; case VTK_DOUBLE: - vtkDoubleArray::SafeDownCast(array)->InsertNextValue(value.ToDouble()); + vtkArrayDownCast(array)->InsertNextValue(value.ToDouble()); break; case VTK_INT: - vtkIntArray::SafeDownCast(array)->InsertNextValue(value.ToInt()); + vtkArrayDownCast(array)->InsertNextValue(value.ToInt()); break; case VTK_STRING: - vtkStringArray::SafeDownCast(array)->InsertNextValue(value.ToString()); + vtkArrayDownCast(array)->InsertNextValue(value.ToString()); break; } } diff --git a/IO/Geometry/vtkAVSucdReader.h b/IO/Geometry/vtkAVSucdReader.h index 9a16c60c683..e579926a82f 100644 --- a/IO/Geometry/vtkAVSucdReader.h +++ b/IO/Geometry/vtkAVSucdReader.h @@ -145,7 +145,7 @@ class VTKIOGEOMETRY_EXPORT vtkAVSucdReader : public vtkUnstructuredGridAlgorithm int ByteOrder; int GetLabel(char *string, int number, char *label); - //BTX + enum { FILE_BIG_ENDIAN=0, @@ -169,7 +169,6 @@ class VTKIOGEOMETRY_EXPORT vtkAVSucdReader : public vtkUnstructuredGridAlgorithm float min[3]; // pre-calculated data minima (max size 3 for vectors) float max[3]; // pre-calculated data maxima (max size 3 for vectors) }; - //ETX DataInfo *NodeDataInfo; DataInfo *CellDataInfo; diff --git a/IO/Geometry/vtkChacoReader.cxx b/IO/Geometry/vtkChacoReader.cxx index a4cbadff83f..e74effebc60 100644 --- a/IO/Geometry/vtkChacoReader.cxx +++ b/IO/Geometry/vtkChacoReader.cxx @@ -258,7 +258,7 @@ int vtkChacoReader::BuildOutputGrid(vtkUnstructuredGrid *output) if (ncells && (this->NumberOfVertexWeights > 0)) { - vtkDoubleArray *da = vtkDoubleArray::SafeDownCast( + vtkDoubleArray *da = vtkArrayDownCast( this->DataCache->GetPointData()->GetArray(this->VarrayName[0])); haveVertexWeightArrays = (da != NULL); @@ -266,7 +266,7 @@ int vtkChacoReader::BuildOutputGrid(vtkUnstructuredGrid *output) if (ncells && (this->NumberOfEdgeWeights > 0)) { - vtkDoubleArray *da = vtkDoubleArray::SafeDownCast( + vtkDoubleArray *da = vtkArrayDownCast( this->DataCache->GetCellData()->GetArray(this->EarrayName[0])); haveEdgeWeightArrays = (da != NULL); @@ -336,7 +336,7 @@ int vtkChacoReader::BuildOutputGrid(vtkUnstructuredGrid *output) this->NumberOfCellWeightArrays = 0; } - vtkIntArray *ia = vtkIntArray::SafeDownCast( + vtkIntArray *ia = vtkArrayDownCast( this->DataCache->GetCellData()->GetArray(this->GetGlobalElementIdArrayName())); if (!ia && this->GenerateGlobalElementIdArray) @@ -348,7 +348,7 @@ int vtkChacoReader::BuildOutputGrid(vtkUnstructuredGrid *output) this->DataCache->GetCellData()->RemoveArray(this->GetGlobalElementIdArrayName()); } - ia = vtkIntArray::SafeDownCast( + ia = vtkArrayDownCast( this->DataCache->GetPointData()->GetArray(this->GetGlobalNodeIdArrayName())); if (!ia && this->GenerateGlobalNodeIdArray) diff --git a/IO/Geometry/vtkFLUENTReader.cxx b/IO/Geometry/vtkFLUENTReader.cxx index 2fecbd1593f..d72c256faa0 100644 --- a/IO/Geometry/vtkFLUENTReader.cxx +++ b/IO/Geometry/vtkFLUENTReader.cxx @@ -77,7 +77,7 @@ struct vtkFLUENTReader::Cell struct vtkFLUENTReader::Face { int type; - int zone; + unsigned int zone; std::vector< int > nodes; int c0; int c1; @@ -93,14 +93,14 @@ struct vtkFLUENTReader::Face struct vtkFLUENTReader::ScalarDataChunk { int subsectionId; - int zoneId; + unsigned int zoneId; std::vector< double > scalarData; }; struct vtkFLUENTReader::VectorDataChunk { int subsectionId; - int zoneId; + unsigned int zoneId; std::vector< double > iComponentData; std::vector< double > jComponentData; std::vector< double > kComponentData; @@ -2509,7 +2509,8 @@ void vtkFLUENTReader::GetNodesAscii() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int zoneId, firstIndex, lastIndex, type, nd; + unsigned int zoneId, firstIndex, lastIndex; + int type, nd; sscanf(info.c_str(), "%x %x %x %d %d", &zoneId, &firstIndex, &lastIndex, &type, &nd); @@ -2528,7 +2529,7 @@ void vtkFLUENTReader::GetNodesAscii() double x, y, z; if (this->GridDimension == 3) { - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { pdatastream >> x; pdatastream >> y; @@ -2538,7 +2539,7 @@ void vtkFLUENTReader::GetNodesAscii() } else { - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { pdatastream >> x; pdatastream >> y; @@ -2554,7 +2555,8 @@ void vtkFLUENTReader::GetNodesSinglePrecision() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int zoneId, firstIndex, lastIndex, type; + unsigned int zoneId, firstIndex, lastIndex; + int type; sscanf(info.c_str(), "%x %x %x %d", &zoneId, &firstIndex, &lastIndex, &type); size_t dstart = this->CaseBuffer->value.find('(', 7); @@ -2563,7 +2565,7 @@ void vtkFLUENTReader::GetNodesSinglePrecision() double x, y, z; if (this->GridDimension == 3) { - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { x = this->GetCaseBufferFloat( static_cast< int >(ptr) ); ptr = ptr + 4; @@ -2578,7 +2580,7 @@ void vtkFLUENTReader::GetNodesSinglePrecision() } else { - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { x = this->GetCaseBufferFloat( static_cast< int >(ptr) ); ptr = ptr + 4; @@ -2599,7 +2601,8 @@ void vtkFLUENTReader::GetNodesDoublePrecision() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int zoneId, firstIndex, lastIndex, type; + unsigned int zoneId, firstIndex, lastIndex; + int type; sscanf(info.c_str(), "%x %x %x %d", &zoneId, &firstIndex, &lastIndex, &type); size_t dstart = this->CaseBuffer->value.find('(', 7); @@ -2607,7 +2610,7 @@ void vtkFLUENTReader::GetNodesDoublePrecision() if (this->GridDimension == 3) { - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { double x = this->GetCaseBufferDouble( static_cast< int >(ptr) ); ptr = ptr + 8; @@ -2622,7 +2625,7 @@ void vtkFLUENTReader::GetNodesDoublePrecision() } else { - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { double x = this->GetCaseBufferDouble( static_cast< int >(ptr) ); ptr = ptr + 8; @@ -2643,7 +2646,8 @@ void vtkFLUENTReader::GetCellsAscii() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int zoneId, firstIndex, lastIndex, type; + unsigned int zoneId, firstIndex, lastIndex; + int type; sscanf(info.c_str(), "%x %x %x %d", &zoneId, &firstIndex, &lastIndex, &type); this->Cells->value.resize(lastIndex); @@ -2653,7 +2657,8 @@ void vtkFLUENTReader::GetCellsAscii() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int zoneId, firstIndex, lastIndex, type, elementType; + unsigned int zoneId, firstIndex, lastIndex; + int type, elementType; sscanf(info.c_str(), "%x %x %x %d %d", &zoneId, &firstIndex, &lastIndex, &type, &elementType); @@ -2664,7 +2669,7 @@ void vtkFLUENTReader::GetCellsAscii() std::string pdata = this->CaseBuffer-> value.substr(dstart+1, dend-start-1); std::stringstream pdatastream(pdata); - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { pdatastream >> this->Cells->value[i-1].type; this->Cells->value[i-1].zone = zoneId; @@ -2674,7 +2679,7 @@ void vtkFLUENTReader::GetCellsAscii() } else { - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { this->Cells->value[i-1].type = elementType; this->Cells->value[i-1].zone = zoneId; @@ -2691,7 +2696,7 @@ void vtkFLUENTReader::GetCellsBinary() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int zoneId, firstIndex, lastIndex, type, elementType; + unsigned int zoneId, firstIndex, lastIndex, type, elementType; sscanf(info.c_str(), "%x %x %x %x %x", &zoneId, &firstIndex, &lastIndex, &type, &elementType); @@ -2699,7 +2704,7 @@ void vtkFLUENTReader::GetCellsBinary() { size_t dstart = this->CaseBuffer->value.find('(', 7); size_t ptr = dstart + 1; - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { this->Cells->value[i-1].type = this->GetCaseBufferInt( static_cast< int >(ptr) ); @@ -2711,7 +2716,7 @@ void vtkFLUENTReader::GetCellsBinary() } else { - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { this->Cells->value[i-1].type = elementType; this->Cells->value[i-1].zone = zoneId; @@ -2730,7 +2735,7 @@ void vtkFLUENTReader::GetFacesAscii() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int zoneId, firstIndex, lastIndex, bcType; + unsigned int zoneId, firstIndex, lastIndex, bcType; sscanf(info.c_str(), "%x %x %x %x", &zoneId, &firstIndex, &lastIndex, &bcType); @@ -2741,7 +2746,7 @@ void vtkFLUENTReader::GetFacesAscii() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int zoneId, firstIndex, lastIndex, bcType, faceType; + unsigned int zoneId, firstIndex, lastIndex, bcType, faceType; sscanf(info.c_str(), "%x %x %x %x %x", &zoneId, &firstIndex, &lastIndex, &bcType, &faceType); @@ -2752,7 +2757,7 @@ void vtkFLUENTReader::GetFacesAscii() std::stringstream pdatastream(pdata); int numberOfNodesInFace = 0; - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { if (faceType == 0 || faceType == 5) { @@ -2799,13 +2804,13 @@ void vtkFLUENTReader::GetFacesBinary() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int zoneId, firstIndex, lastIndex, bcType, faceType; + unsigned int zoneId, firstIndex, lastIndex, bcType, faceType; sscanf(info.c_str(), "%x %x %x %x %x", &zoneId, &firstIndex, &lastIndex, &bcType, &faceType); size_t dstart = this->CaseBuffer->value.find('(', 7); int numberOfNodesInFace = 0; size_t ptr = dstart + 1; - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { if ((faceType == 0) || (faceType == 5)) { @@ -2861,7 +2866,7 @@ void vtkFLUENTReader::GetPeriodicShadowFacesAscii() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int firstIndex, lastIndex, periodicZone, shadowZone; + unsigned int firstIndex, lastIndex, periodicZone, shadowZone; sscanf(info.c_str(), "%x %x %x %x", &firstIndex, &lastIndex, &periodicZone, &shadowZone); @@ -2871,7 +2876,7 @@ void vtkFLUENTReader::GetPeriodicShadowFacesAscii() std::stringstream pdatastream(pdata); int faceIndex1, faceIndex2; - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { pdatastream >> hex >> faceIndex1; pdatastream >> hex >> faceIndex2; @@ -2885,7 +2890,7 @@ void vtkFLUENTReader::GetPeriodicShadowFacesBinary() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int firstIndex, lastIndex, periodicZone, shadowZone; + unsigned int firstIndex, lastIndex, periodicZone, shadowZone; sscanf(info.c_str(), "%x %x %x %x", &firstIndex, &lastIndex, &periodicZone, &shadowZone); @@ -2893,7 +2898,7 @@ void vtkFLUENTReader::GetPeriodicShadowFacesBinary() size_t ptr = dstart + 1; //int faceIndex1, faceIndex2; - for (int i = firstIndex; i <=lastIndex; i++) + for (unsigned int i = firstIndex; i <= lastIndex; i++) { //faceIndex1 = this->GetCaseBufferInt(ptr); this->GetCaseBufferInt( static_cast< int >(ptr) ); @@ -2910,7 +2915,7 @@ void vtkFLUENTReader::GetCellTreeAscii() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int cellId0, cellId1, parentZoneId, childZoneId; + unsigned int cellId0, cellId1, parentZoneId, childZoneId; sscanf(info.c_str(), "%x %x %x %x", &cellId0, &cellId1, &parentZoneId, &childZoneId); @@ -2920,7 +2925,7 @@ void vtkFLUENTReader::GetCellTreeAscii() std::stringstream pdatastream(pdata); int numberOfKids, kid; - for (int i = cellId0; i <=cellId1; i++) + for (unsigned int i = cellId0; i <= cellId1; i++) { this->Cells->value[i-1].parent = 1; pdatastream >> hex >> numberOfKids; @@ -2939,7 +2944,7 @@ void vtkFLUENTReader::GetCellTreeBinary() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int cellId0, cellId1, parentZoneId, childZoneId; + unsigned int cellId0, cellId1, parentZoneId, childZoneId; sscanf(info.c_str(), "%x %x %x %x", &cellId0, &cellId1, &parentZoneId, &childZoneId); @@ -2947,7 +2952,7 @@ void vtkFLUENTReader::GetCellTreeBinary() size_t ptr = dstart + 1; int numberOfKids, kid; - for (int i = cellId0; i <=cellId1; i++) + for (unsigned int i = cellId0; i <= cellId1; i++) { this->Cells->value[i-1].parent = 1; numberOfKids = this->GetCaseBufferInt( static_cast< int >(ptr) ); @@ -2967,7 +2972,7 @@ void vtkFLUENTReader::GetFaceTreeAscii() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int faceId0, faceId1, parentZoneId, childZoneId; + unsigned int faceId0, faceId1, parentZoneId, childZoneId; sscanf(info.c_str(), "%x %x %x %x", &faceId0, &faceId1, &parentZoneId, &childZoneId); @@ -2977,7 +2982,7 @@ void vtkFLUENTReader::GetFaceTreeAscii() std::stringstream pdatastream(pdata); int numberOfKids, kid; - for (int i = faceId0; i <=faceId1; i++) + for (unsigned int i = faceId0; i <= faceId1; i++) { this->Faces->value[i-1].parent = 1; pdatastream >> hex >> numberOfKids; @@ -2995,7 +3000,7 @@ void vtkFLUENTReader::GetFaceTreeBinary() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int faceId0, faceId1, parentZoneId, childZoneId; + unsigned int faceId0, faceId1, parentZoneId, childZoneId; sscanf(info.c_str(), "%x %x %x %x", &faceId0, &faceId1, &parentZoneId, &childZoneId); @@ -3003,7 +3008,7 @@ void vtkFLUENTReader::GetFaceTreeBinary() size_t ptr = dstart + 1; int numberOfKids, kid; - for (int i = faceId0; i <=faceId1; i++) + for (unsigned int i = faceId0; i <= faceId1; i++) { this->Faces->value[i-1].parent = 1; numberOfKids = this->GetCaseBufferInt( static_cast< int >(ptr) ); @@ -3023,7 +3028,7 @@ void vtkFLUENTReader::GetInterfaceFaceParentsAscii() size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int faceId0, faceId1; + unsigned int faceId0, faceId1; sscanf(info.c_str(), "%x %x", &faceId0, &faceId1); size_t dstart = this->CaseBuffer->value.find('(', 7); @@ -3032,7 +3037,7 @@ void vtkFLUENTReader::GetInterfaceFaceParentsAscii() std::stringstream pdatastream(pdata); int parentId0, parentId1; - for (int i = faceId0; i <=faceId1; i++) + for (unsigned int i = faceId0; i <= faceId1; i++) { pdatastream >> hex >> parentId0; pdatastream >> hex >> parentId1; @@ -3046,18 +3051,17 @@ void vtkFLUENTReader::GetInterfaceFaceParentsAscii() //---------------------------------------------------------------------------- void vtkFLUENTReader::GetInterfaceFaceParentsBinary() { - size_t start = this->CaseBuffer->value.find('(', 1); size_t end = this->CaseBuffer->value.find(')',1); std::string info = this->CaseBuffer->value.substr(start+1,end-start-1 ); - int faceId0, faceId1; + unsigned int faceId0, faceId1; sscanf(info.c_str(), "%x %x", &faceId0, &faceId1); size_t dstart = this->CaseBuffer->value.find('(', 7); size_t ptr = dstart + 1; int parentId0, parentId1; - for (int i = faceId0; i <=faceId1; i++) + for (unsigned int i = faceId0; i <= faceId1; i++) { parentId0 = this->GetCaseBufferInt( static_cast< int >(ptr) ); ptr = ptr + 4; diff --git a/IO/Geometry/vtkFacetWriter.h b/IO/Geometry/vtkFacetWriter.h index e5ad5b8f4db..36a653bce60 100644 --- a/IO/Geometry/vtkFacetWriter.h +++ b/IO/Geometry/vtkFacetWriter.h @@ -57,9 +57,7 @@ class VTKIOGEOMETRY_EXPORT vtkFacetWriter : public vtkPolyDataAlgorithm // Write data void Write(); - // BTX void WriteToStream(ostream* ost); - // ETX protected: vtkFacetWriter(); @@ -73,9 +71,7 @@ class VTKIOGEOMETRY_EXPORT vtkFacetWriter : public vtkPolyDataAlgorithm virtual int FillInputPortInformation(int, vtkInformation *); - // BTX int WriteDataToStream(ostream* ost, vtkPolyData* data); - // ETX char *FileName; ostream *OutputStream; diff --git a/IO/Geometry/vtkGAMBITReader.h b/IO/Geometry/vtkGAMBITReader.h index 2913d4e0fe2..c924c5e38c0 100644 --- a/IO/Geometry/vtkGAMBITReader.h +++ b/IO/Geometry/vtkGAMBITReader.h @@ -78,7 +78,6 @@ class VTKIOGEOMETRY_EXPORT vtkGAMBITReader : public vtkUnstructuredGridAlgorithm int NumberOfVelocityComponents; ifstream *FileStream; - //BTX enum GAMBITCellType { EDGE = 1, @@ -89,7 +88,6 @@ class VTKIOGEOMETRY_EXPORT vtkGAMBITReader : public vtkUnstructuredGridAlgorithm TETRA = 6, PYRAMID = 7 }; - //ETX private: void ReadFile(vtkUnstructuredGrid *output); diff --git a/IO/Geometry/vtkOpenFOAMReader.cxx b/IO/Geometry/vtkOpenFOAMReader.cxx index 2134fd7f281..2e81dd20ced 100644 --- a/IO/Geometry/vtkOpenFOAMReader.cxx +++ b/IO/Geometry/vtkOpenFOAMReader.cxx @@ -612,11 +612,12 @@ struct vtkFoamToken this->Type = STRING; this->String = new vtkStdString(value); } - void operator=(const vtkFoamToken& value) + vtkFoamToken& operator=(const vtkFoamToken& value) { this->Clear(); this->Type = value.Type; this->AssignData(value); + return *this; } bool operator==(const char value) const { @@ -5603,7 +5604,7 @@ void vtkOpenFOAMReaderPrivate::InsertCellsToGrid( else { nAdditionalCells++; - additionalCells->InsertNextTupleValue(cellPoints->GetPointer(0)); + additionalCells->InsertNextTypedTuple(cellPoints->GetPointer(0)); } } @@ -5633,7 +5634,7 @@ void vtkOpenFOAMReaderPrivate::InsertCellsToGrid( // set the 5th vertex number to -1 to distinguish a tetra cell cellPoints->SetId(4, -1); nAdditionalCells++; - additionalCells->InsertNextTupleValue(cellPoints->GetPointer(0)); + additionalCells->InsertNextTypedTuple(cellPoints->GetPointer(0)); } } } diff --git a/IO/Geometry/vtkOpenFOAMReader.h b/IO/Geometry/vtkOpenFOAMReader.h index 37c022a2e41..787cbfb7645 100644 --- a/IO/Geometry/vtkOpenFOAMReader.h +++ b/IO/Geometry/vtkOpenFOAMReader.h @@ -227,9 +227,7 @@ class VTKIOGEOMETRY_EXPORT vtkOpenFOAMReader : public vtkMultiBlockDataSetAlgori vtkDoubleArray *GetTimeValues(); int MakeMetaDataAtTimeStep(const bool); - //BTX friend class vtkOpenFOAMReaderPrivate; - //ETX protected: // refresh flag diff --git a/IO/Geometry/vtkPDBReader.cxx b/IO/Geometry/vtkPDBReader.cxx index 7995a099700..33670206764 100644 --- a/IO/Geometry/vtkPDBReader.cxx +++ b/IO/Geometry/vtkPDBReader.cxx @@ -103,7 +103,7 @@ void vtkPDBReader::ReadSpecificMolecule(FILE* fp) sscanf(&linebuf[32], "%c", &endChain); sscanf(&linebuf[33], "%d", &endResi); int tuple[4] = { startChain, startResi, endChain, endResi }; - Sheets->InsertNextTupleValue(tuple); + Sheets->InsertNextTypedTuple(tuple); } else if (command == "HELIX") { @@ -112,7 +112,7 @@ void vtkPDBReader::ReadSpecificMolecule(FILE* fp) sscanf(&linebuf[31], "%c", &endChain); sscanf(&linebuf[33], "%d", &endResi); int tuple[4] = { startChain, startResi, endChain, endResi }; - Helix->InsertNextTupleValue(tuple); + Helix->InsertNextTypedTuple(tuple); } } @@ -136,7 +136,7 @@ void vtkPDBReader::ReadSpecificMolecule(FILE* fp) for (j = 0; j < Sheets->GetNumberOfTuples(); j++) { int sheet[4]; - Sheets->GetTupleValue(j, sheet); + Sheets->GetTypedTuple(j, sheet); if (this->Chain->GetValue(i) != sheet[0]) continue; if (resi < sheet[1]) continue; if (resi > sheet[3]) continue; @@ -148,7 +148,7 @@ void vtkPDBReader::ReadSpecificMolecule(FILE* fp) for (j = 0; j < Helix->GetNumberOfTuples(); j++) { int helix[4]; - Helix->GetTupleValue(j, helix); + Helix->GetTypedTuple(j, helix); if (this->Chain->GetValue(i) != helix[0]) continue; if (resi < helix[1]) continue; if (resi > helix[3]) continue; diff --git a/IO/Geometry/vtkPTSReader.cxx b/IO/Geometry/vtkPTSReader.cxx index f3d1d714019..c532c956337 100644 --- a/IO/Geometry/vtkPTSReader.cxx +++ b/IO/Geometry/vtkPTSReader.cxx @@ -211,8 +211,7 @@ RequestData(vtkInformation *vtkNotUsed(request), // x y z intensity or // or x y z intensity r g b? int numValuesPerLine; - float intensity; - double rgb[3], pt[3]; + double irgb[4], pt[3]; if (numPts == -1) { @@ -230,13 +229,13 @@ RequestData(vtkInformation *vtkNotUsed(request), else { getline(file, buffer); - numValuesPerLine = sscanf(buffer.c_str(), "%lf %lf %lf %f %lf %lf %lf", + numValuesPerLine = sscanf(buffer.c_str(), "%lf %lf %lf %lf %lf %lf %lf", pt, pt+1, pt+2, - &intensity, rgb, rgb+1, rgb+2); + irgb, irgb+1, irgb+2, irgb+3); } - if (!((numValuesPerLine == 3) || (numValuesPerLine == 4) || + (numValuesPerLine == 6) || (numValuesPerLine == 7))) { // Unsupported line format! @@ -285,8 +284,8 @@ RequestData(vtkInformation *vtkNotUsed(request), output->SetVerts( newVerts.GetPointer() ); } - bool wantIntensities = (numValuesPerLine > 3); - if (numValuesPerLine == 7) + bool wantIntensities = ((numValuesPerLine == 4) || (numValuesPerLine == 7)); + if (numValuesPerLine > 4) { colors->SetNumberOfComponents(3); colors->SetName("Color"); @@ -298,7 +297,7 @@ RequestData(vtkInformation *vtkNotUsed(request), } } - if (wantIntensities && numValuesPerLine > 3) + if (wantIntensities) { intensities->SetName("Intensities"); intensities->SetNumberOfComponents(1); @@ -350,9 +349,9 @@ RequestData(vtkInformation *vtkNotUsed(request), if (floor(i*onRatio) > lastCount) { lastCount++; - sscanf(buffer.c_str(), "%lf %lf %lf %f %lf %lf %lf", + sscanf(buffer.c_str(), "%lf %lf %lf %lf %lf %lf %lf", pt, pt+1, pt+2, - &intensity, rgb, rgb+1, rgb+2); + irgb, irgb+1, irgb+2, irgb+3); // OK to process based on bounding box if ((!this->LimitReadToBounds) || this->ReadBBox.ContainsPoint(pt)) { @@ -362,13 +361,22 @@ RequestData(vtkInformation *vtkNotUsed(request), { pids[pid] = pid; } - if (wantIntensities && numValuesPerLine > 3) + if (wantIntensities) { - intensities->InsertNextValue(intensity); + intensities->InsertNextValue(irgb[0]); } - if (numValuesPerLine == 7) + if (numValuesPerLine > 4) { - colors->InsertNextTuple(rgb); + // if we have intensity then the color info starts with the second value in the array + // else it starts with the first + if(wantIntensities) + { + colors->InsertNextTuple(irgb+1); + } + else + { + colors->InsertNextTuple(irgb); + } } } } @@ -391,11 +399,11 @@ RequestData(vtkInformation *vtkNotUsed(request), if (newPts->GetNumberOfPoints() < targetNumPts) { newPts->Squeeze(); - if (wantIntensities && numValuesPerLine > 3) + if (wantIntensities) { intensities->Squeeze(); } - if (numValuesPerLine > 7) + if (numValuesPerLine > 4) { colors->Squeeze(); } diff --git a/IO/Geometry/vtkParticleReader.h b/IO/Geometry/vtkParticleReader.h index a3a9c25a46d..776db311319 100644 --- a/IO/Geometry/vtkParticleReader.h +++ b/IO/Geometry/vtkParticleReader.h @@ -151,7 +151,6 @@ class VTKIOGEOMETRY_EXPORT vtkParticleReader : public vtkPolyDataAlgorithm // Update of the progress. void DoProgressUpdate( size_t & bytesRead, size_t & fileLength ); - //BTX // Description: // Enumerate the supported file types. //
@@ -161,7 +160,6 @@ class VTKIOGEOMETRY_EXPORT vtkParticleReader : public vtkPolyDataAlgorithm
   // 
enum FILE_TYPE { FILE_TYPE_IS_UNKNOWN = 0, FILE_TYPE_IS_TEXT, FILE_TYPE_IS_BINARY }; - //ETX int HasScalar; // Description: diff --git a/IO/Geometry/vtkTecplotReader.cxx b/IO/Geometry/vtkTecplotReader.cxx index 8626ee8773b..f32a5d8eda4 100644 --- a/IO/Geometry/vtkTecplotReader.cxx +++ b/IO/Geometry/vtkTecplotReader.cxx @@ -76,10 +76,10 @@ class FileStreamReader protected: bool Open; bool Eof; - static const unsigned int BUFF_SIZE = 2048; + static const int BUFF_SIZE = 2048; char buff[BUFF_SIZE]; - unsigned int Pos; - unsigned int BuffEnd; + int Pos; + int BuffEnd; gzFile file; std::string FileName; @@ -414,17 +414,17 @@ class vtkTecplotReaderInternal // ---------------------------------------------------------------------------- static int GetCoord( const std::string & theToken ) { - if ( theToken == "X" || theToken == "x" || theToken == "I" ) + if ( theToken == "X" || theToken == "x" || theToken == "I" || theToken == "CoordinateX" ) { return 0; } - if ( theToken == "Y" || theToken == "y" || theToken == "J" ) + if ( theToken == "Y" || theToken == "y" || theToken == "J" || theToken == "CoordinateY" ) { return 1; } - if ( theToken == "Z" || theToken == "z" || theToken == "K" ) + if ( theToken == "Z" || theToken == "z" || theToken == "K" || theToken == "CoordinateZ" ) { return 2; } diff --git a/IO/Geometry/vtkTecplotReader.h b/IO/Geometry/vtkTecplotReader.h index 06f898500b6..d277d84c865 100644 --- a/IO/Geometry/vtkTecplotReader.h +++ b/IO/Geometry/vtkTecplotReader.h @@ -76,10 +76,8 @@ #include "vtkIOGeometryModule.h" // For export macro #include "vtkMultiBlockDataSetAlgorithm.h" -//BTX #include // STL Header; Required for vector #include // STL Header; Required for string -//ETX class vtkPoints; class vtkCellData; @@ -258,12 +256,10 @@ class VTKIOGEOMETRY_EXPORT vtkTecplotReader : public vtkMultiBlockDataSetAlgorit vtkDataArraySelection * DataArraySelection; vtkTecplotReaderInternal * Internal; - //BTX std::string DataTitle; std::vector< int > CellBased; std::vector< std::string > ZoneNames; std::vector< std::string > Variables; - //ETX private: diff --git a/IO/Geometry/vtkWindBladeReader.cxx b/IO/Geometry/vtkWindBladeReader.cxx index de943457238..9b2b2f92115 100644 --- a/IO/Geometry/vtkWindBladeReader.cxx +++ b/IO/Geometry/vtkWindBladeReader.cxx @@ -1691,37 +1691,18 @@ bool vtkWindBladeReader::SetUpGlobalData(const std::string &fileName, void vtkWindBladeReader::ProcessZCoords(float *topoData, float *zValues) { // Initial z coordinate processing - float* zedge = new float[this->Dimension[2] + 1]; - float* z = new float[this->Dimension[2]]; + std::vector z(this->Dimension[2]); float zb; - int ibctopbot = 1; - if (ibctopbot == 1) - { - for (int k = 0; k <= this->Dimension[2]; k++) - { - zedge[k] = k * this->Step[2]; - } - zb = zedge[this->Dimension[2]]; - for (int k = 0; k < this->Dimension[2]; k++) - { - z[k] = k * this->Step[2] + 0.5 * this->Step[2]; - } - } - - else + zb = this->Dimension[2] * this->Step[2]; + for (int k = 0; k < this->Dimension[2]; k++) { - for (int k = 0; k < this->Dimension[2]; k++) - { - z[k] = k * this->Step[2]; - } - zb = z[this->Dimension[2] - 1]; + z[k] = k * this->Step[2] + 0.5 * this->Step[2]; } // Use cubic spline or deformation to calculate z values int npoints = 31; - float* zdata = new float[npoints]; - float* zcoeff = new float[npoints]; + std::vector zdata(npoints), zcoeff(npoints); float zcrdata[] = { 0.0 , 2.00, 4.00, 6.00, 8.00, 10.00, 14.00, 18.00, 22.00, 26.00, @@ -1739,7 +1720,7 @@ void vtkWindBladeReader::ProcessZCoords(float *topoData, float *zValues) } // Call spline with zcoeff being the answer - this->Spline(zdata, zcrdata, npoints, 99.0e31, 99.0e31, zcoeff); + this->Spline(&zdata[0], zcrdata, npoints, 99.0e31, 99.0e31, &zcoeff[0]); } // Fill the zValues array depending on compression @@ -1760,7 +1741,7 @@ void vtkWindBladeReader::ProcessZCoords(float *topoData, float *zValues) { // Use spline interpolation float zinterp; - this->Splint(zdata, zcrdata, zcoeff, npoints, z[k], &zinterp, flag); + this->Splint(&zdata[0], zcrdata, &zcoeff[0], npoints, z[k], &zinterp, flag); zValues[index] = zinterp; } else @@ -1772,11 +1753,6 @@ void vtkWindBladeReader::ProcessZCoords(float *topoData, float *zValues) } } } - - delete [] zedge; - delete [] z; - delete [] zdata; - delete [] zcoeff; } //---------------------------------------------------------------------------- diff --git a/IO/Geometry/vtkWindBladeReader.h b/IO/Geometry/vtkWindBladeReader.h index 28047c45a46..dc3cd5a4dcd 100644 --- a/IO/Geometry/vtkWindBladeReader.h +++ b/IO/Geometry/vtkWindBladeReader.h @@ -78,7 +78,7 @@ class VTKIOGEOMETRY_EXPORT vtkWindBladeReader : public vtkStructuredGridAlgorith void EnableAllPointArrays(); protected: -//BTX + static float DRY_AIR_CONSTANT; static int NUM_PART_SIDES; // Blade parts rhombus const static int NUM_BASE_SIDES; // Base pyramid @@ -89,7 +89,6 @@ class VTKIOGEOMETRY_EXPORT vtkWindBladeReader : public vtkStructuredGridAlgorith static int VECTOR; static int FLOAT; static int INTEGER; -//ETX vtkWindBladeReader(); ~vtkWindBladeReader(); diff --git a/IO/Image/Testing/Cxx/TestTIFFReaderMultiple.cxx b/IO/Image/Testing/Cxx/TestTIFFReaderMultiple.cxx index 25f5487af57..ba00c7659eb 100644 --- a/IO/Image/Testing/Cxx/TestTIFFReaderMultiple.cxx +++ b/IO/Image/Testing/Cxx/TestTIFFReaderMultiple.cxx @@ -16,7 +16,7 @@ #include #include "vtkTestErrorObserver.h" -#ifndef WIN32 +#ifndef _WIN32 #include #endif @@ -28,7 +28,7 @@ int TestTIFFReaderMultiple(int argc, char *argv[]) return EXIT_FAILURE; } -#ifndef WIN32 +#ifndef _WIN32 // See how many file descriptors are in use int fdUsedBefore = 1; for (int i = 0; i < 1024; ++i) @@ -62,7 +62,7 @@ int TestTIFFReaderMultiple(int argc, char *argv[]) errorObserver->Clear(); } -#ifndef WIN32 +#ifndef _WIN32 // See how many file descriptors are in use int fdUsedAfter = 1; for (int i = 0; i < 1024; ++i) diff --git a/IO/Image/vtkBMPReader.h b/IO/Image/vtkBMPReader.h index 94a557ab1b7..d9cd9453e44 100644 --- a/IO/Image/vtkBMPReader.h +++ b/IO/Image/vtkBMPReader.h @@ -84,11 +84,9 @@ class VTKIOIMAGE_EXPORT vtkBMPReader : public vtkImageReader vtkGetObjectMacro(LookupTable, vtkLookupTable); -//BTX // Description: // Returns the color lut. vtkGetMacro(Colors,unsigned char *); -//ETX protected: vtkBMPReader(); diff --git a/IO/Image/vtkDEMReader.h b/IO/Image/vtkDEMReader.h index 3734bdbd5cf..7589819bb75 100644 --- a/IO/Image/vtkDEMReader.h +++ b/IO/Image/vtkDEMReader.h @@ -40,9 +40,7 @@ class VTKIOIMAGE_EXPORT vtkDEMReader : public vtkImageAlgorithm vtkSetStringMacro(FileName); vtkGetStringMacro(FileName); -//BTX enum {REFERENCE_SEA_LEVEL=0,REFERENCE_ELEVATION_BOUNDS}; -//ETX // Description: // Specify the elevation origin to use. By default, the elevation origin diff --git a/IO/Image/vtkDICOMImageReader.h b/IO/Image/vtkDICOMImageReader.h index 864f1364d36..abfc961e907 100644 --- a/IO/Image/vtkDICOMImageReader.h +++ b/IO/Image/vtkDICOMImageReader.h @@ -37,11 +37,9 @@ #include "vtkIOImageModule.h" // For export macro #include "vtkImageReader2.h" -//BTX class vtkDICOMImageReaderVector; class DICOMParser; class DICOMAppHelper; -//ETX class VTKIOIMAGE_EXPORT vtkDICOMImageReader : public vtkImageReader2 { diff --git a/IO/Image/vtkImageExport.h b/IO/Image/vtkImageExport.h index e9cdad3775e..95075d1c618 100644 --- a/IO/Image/vtkImageExport.h +++ b/IO/Image/vtkImageExport.h @@ -73,11 +73,9 @@ class VTKIOIMAGE_EXPORT vtkImageExport : public vtkImageAlgorithm double *GetDataOrigin(); void GetDataOrigin(double *ptr); -//BTX // Description: // Get the input object from the image pipeline. vtkImageData *GetInput(); -//ETX // Description: // Set/Get whether the data goes to the exported memory starting @@ -116,7 +114,6 @@ class VTKIOIMAGE_EXPORT vtkImageExport : public vtkImageAlgorithm // Get the user data that should be passed to the callback functions. void* GetCallbackUserData(); - //BTX // Description: // These are function pointer types for the pipeline connection // callbacks. See furhter documentation in vtkImageImport.h. @@ -145,7 +142,6 @@ class VTKIOIMAGE_EXPORT vtkImageExport : public vtkImageAlgorithm UpdateDataCallbackType GetUpdateDataCallback() const; DataExtentCallbackType GetDataExtentCallback() const; BufferPointerCallbackType GetBufferPointerCallback() const; - //ETX protected: vtkImageExport(); diff --git a/IO/Image/vtkImageImport.h b/IO/Image/vtkImageImport.h index 467cb4564b7..cb441d80768 100644 --- a/IO/Image/vtkImageImport.h +++ b/IO/Image/vtkImageImport.h @@ -132,7 +132,6 @@ class VTKIOIMAGE_EXPORT vtkImageImport : public vtkImageAlgorithm vtkSetStringMacro(ScalarArrayName); vtkGetStringMacro(ScalarArrayName); - //BTX // Description: // These are function pointer types for the pipeline connection // callbacks. See further documentation on each individual callback. @@ -238,8 +237,6 @@ class VTKIOIMAGE_EXPORT vtkImageImport : public vtkImageAlgorithm vtkSetMacro(CallbackUserData, void*); vtkGetMacro(CallbackUserData, void*); - //ETX - // Description: // Invoke the appropriate callbacks int InvokePipelineModifiedCallbacks(); @@ -270,7 +267,6 @@ class VTKIOIMAGE_EXPORT vtkImageImport : public vtkImageAlgorithm char *ScalarArrayName; void* CallbackUserData; - //BTX UpdateInformationCallbackType UpdateInformationCallback; PipelineModifiedCallbackType PipelineModifiedCallback; WholeExtentCallbackType WholeExtentCallback; @@ -282,7 +278,6 @@ class VTKIOIMAGE_EXPORT vtkImageImport : public vtkImageAlgorithm UpdateDataCallbackType UpdateDataCallback; DataExtentCallbackType DataExtentCallback; BufferPointerCallbackType BufferPointerCallback; - //ETX virtual void ExecuteDataWithInformation(vtkDataObject *d, vtkInformation* outInfo); diff --git a/IO/Image/vtkImageReader2.h b/IO/Image/vtkImageReader2.h index 03ff85c7d44..b9326d15992 100644 --- a/IO/Image/vtkImageReader2.h +++ b/IO/Image/vtkImageReader2.h @@ -191,10 +191,8 @@ class VTKIOIMAGE_EXPORT vtkImageReader2 : public vtkImageAlgorithm virtual int GetSwapBytes() {return this->SwapBytes;} vtkBooleanMacro(SwapBytes,int); -//BTX ifstream *GetFile() {return this->File;} vtkGetVectorMacro(DataIncrements,unsigned long,4); -//ETX virtual int OpenFile(); virtual void SeekFile(int i, int j, int k); diff --git a/IO/Image/vtkImageReader2Collection.h b/IO/Image/vtkImageReader2Collection.h index 15ba13d2699..dcf6013f29f 100644 --- a/IO/Image/vtkImageReader2Collection.h +++ b/IO/Image/vtkImageReader2Collection.h @@ -42,12 +42,10 @@ class VTKIOIMAGE_EXPORT vtkImageReader2Collection : public vtkCollection // Get the next image reader in the list. vtkImageReader2 *GetNextItem(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkImageReader2 *GetNextImageReader2(vtkCollectionSimpleIterator &cookie); - //ETX protected: vtkImageReader2Collection() {} diff --git a/IO/Image/vtkImageReader2Factory.h b/IO/Image/vtkImageReader2Factory.h index e2cbf2cd522..42127dbe236 100644 --- a/IO/Image/vtkImageReader2Factory.h +++ b/IO/Image/vtkImageReader2Factory.h @@ -56,6 +56,7 @@ class VTKIOIMAGE_EXPORT vtkImageReader2Factory : public vtkObject // open the image file, it is the callers responsibility to call // Delete on the returned object. If no reader is found, null // is returned. + VTK_NEWINSTANCE static vtkImageReader2* CreateImageReader2(const char* path); // Description: get a list of the currently registered readers. @@ -73,9 +74,9 @@ class VTKIOIMAGE_EXPORT vtkImageReader2Factory : public vtkObject static vtkImageReader2Collection* AvailableReaders; vtkImageReader2Factory(const vtkImageReader2Factory&); // Not implemented. void operator=(const vtkImageReader2Factory&); // Not implemented. -//BTX + friend class vtkImageReader2FactoryCleanup; -//ETX + }; #endif diff --git a/IO/Image/vtkImageWriter.h b/IO/Image/vtkImageWriter.h index e3083481073..7761e941c66 100644 --- a/IO/Image/vtkImageWriter.h +++ b/IO/Image/vtkImageWriter.h @@ -59,11 +59,9 @@ class VTKIOIMAGE_EXPORT vtkImageWriter : public vtkImageAlgorithm vtkSetMacro(FileDimensionality, int); vtkGetMacro(FileDimensionality, int); -//BTX // Description: // Set/Get the input object from the image pipeline. vtkImageData *GetInput(); -//ETX // Description: // The main interface which triggers the writer to start. diff --git a/IO/Image/vtkJSONImageWriter.cxx b/IO/Image/vtkJSONImageWriter.cxx index be7ed5bf701..df8603dae95 100644 --- a/IO/Image/vtkJSONImageWriter.cxx +++ b/IO/Image/vtkJSONImageWriter.cxx @@ -81,7 +81,7 @@ int vtkJSONImageWriter::RequestData( // Write this->InvokeEvent(vtkCommand::StartEvent); - vtkCharArray *validMask = vtkCharArray::SafeDownCast(input->GetPointData()->GetArray("vtkValidPointMask")); + vtkCharArray *validMask = vtkArrayDownCast(input->GetPointData()->GetArray("vtkValidPointMask")); ofstream file(this->FileName, ios::out); if (file.fail()) diff --git a/IO/Image/vtkMedicalImageProperties.h b/IO/Image/vtkMedicalImageProperties.h index b7d3b76588a..4aa46d4e4ce 100644 --- a/IO/Image/vtkMedicalImageProperties.h +++ b/IO/Image/vtkMedicalImageProperties.h @@ -352,13 +352,12 @@ class VTKIOIMAGE_EXPORT vtkMedicalImageProperties : public vtkObject // not found. int GetSliceIDFromInstanceUID(int &volumeidx, const char *uid); - //BTX typedef enum { AXIAL = 0, CORONAL, SAGITTAL } OrientationType; - //ETX + int GetOrientationType(int volumeidx); void SetOrientationType(int volumeidx, int orientation); static const char *GetStringFromOrientationType(unsigned int type); @@ -404,11 +403,9 @@ class VTKIOIMAGE_EXPORT vtkMedicalImageProperties : public vtkObject char *XRayTubeCurrent; double DirectionCosine[6]; - //BTX // Description: // PIMPL Encapsulation for STL containers vtkMedicalImagePropertiesInternals *Internals; - //ETX private: vtkMedicalImageProperties(const vtkMedicalImageProperties&); // Not implemented. diff --git a/IO/Image/vtkMetaImageReader.h b/IO/Image/vtkMetaImageReader.h index 59c38ac28eb..f212b2ed317 100644 --- a/IO/Image/vtkMetaImageReader.h +++ b/IO/Image/vtkMetaImageReader.h @@ -62,9 +62,7 @@ #include "vtkIOImageModule.h" // For export macro #include "vtkImageReader2.h" -//BTX namespace vtkmetaio { class MetaImage; } // forward declaration -//ETX class VTKIOIMAGE_EXPORT vtkMetaImageReader : public vtkImageReader2 { @@ -182,9 +180,7 @@ class VTKIOIMAGE_EXPORT vtkMetaImageReader : public vtkImageReader2 vtkMetaImageReader(const vtkMetaImageReader&); // Not implemented. void operator=(const vtkMetaImageReader&); // Not implemented. -//BTX vtkmetaio::MetaImage *MetaImagePtr; -//ETX double GantryAngle; char PatientName[255]; diff --git a/IO/Image/vtkMetaImageWriter.h b/IO/Image/vtkMetaImageWriter.h index b38ba9d0c5d..7783c069811 100644 --- a/IO/Image/vtkMetaImageWriter.h +++ b/IO/Image/vtkMetaImageWriter.h @@ -63,9 +63,7 @@ #include "vtkIOImageModule.h" // For export macro #include "vtkImageWriter.h" -//BTX namespace vtkmetaio { class MetaImage; } // forward declaration -//ETX class VTKIOIMAGE_EXPORT vtkMetaImageWriter : public vtkImageWriter { @@ -112,9 +110,7 @@ class VTKIOIMAGE_EXPORT vtkMetaImageWriter : public vtkImageWriter vtkMetaImageWriter(const vtkMetaImageWriter&); // Not implemented. void operator=(const vtkMetaImageWriter&); // Not implemented. -//BTX vtkmetaio::MetaImage * MetaImagePtr; -//ETX }; diff --git a/IO/Image/vtkSLCReader.cxx b/IO/Image/vtkSLCReader.cxx index 9e7cba43ff4..4c1591a9981 100644 --- a/IO/Image/vtkSLCReader.cxx +++ b/IO/Image/vtkSLCReader.cxx @@ -44,13 +44,12 @@ unsigned char* vtkSLCReader::Decode8BitData( unsigned char *in_ptr, unsigned char *return_ptr; unsigned char current_value; unsigned char remaining; - int done=0; curr_ptr = in_ptr; decode_ptr = return_ptr = new unsigned char[size]; - while( !done ) + while( true ) { current_value = *(curr_ptr++); diff --git a/IO/Image/vtkTIFFWriter.h b/IO/Image/vtkTIFFWriter.h index cb94c29f547..83bc8e4c4b7 100644 --- a/IO/Image/vtkTIFFWriter.h +++ b/IO/Image/vtkTIFFWriter.h @@ -38,7 +38,6 @@ class VTKIOIMAGE_EXPORT vtkTIFFWriter : public vtkImageWriter // The main interface which triggers the writer to start. virtual void Write(); -//BTX enum { // Compression types NoCompression, PackBits, @@ -46,7 +45,6 @@ class VTKIOIMAGE_EXPORT vtkTIFFWriter : public vtkImageWriter Deflate, LZW }; -//ETX // Description: // Set compression type. Sinze LZW compression is patented outside US, the diff --git a/IO/Image/vtkVolume16Reader.cxx b/IO/Image/vtkVolume16Reader.cxx index 350d90c2a14..0a75b38ca2f 100644 --- a/IO/Image/vtkVolume16Reader.cxx +++ b/IO/Image/vtkVolume16Reader.cxx @@ -167,7 +167,7 @@ int vtkVolume16Reader::RequestData( vtkImageData *output = this->AllocateOutputData(output_do, outInfo); vtkUnsignedShortArray *newScalars = - vtkUnsignedShortArray::SafeDownCast(output->GetPointData()->GetScalars()); + vtkArrayDownCast(output->GetPointData()->GetScalars()); // Validate instance variables if (this->FilePrefix == NULL) diff --git a/IO/Import/vtk3DSImporter.cxx b/IO/Import/vtk3DSImporter.cxx index 0de3598d9a6..05a712e9a9d 100644 --- a/IO/Import/vtk3DSImporter.cxx +++ b/IO/Import/vtk3DSImporter.cxx @@ -38,17 +38,21 @@ vtkStandardNewMacro(vtk3DSImporter); #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif -static vtk3DSColour Black = {0.0f, 0.0f, 0.0f}; -static char obj_name[80] = ""; -static vtk3DSColour fog_colour = {0.0f, 0.0f, 0.0f}; +// Wrap these globals in a namespace to prevent identifier collisions with +// inline code on MSVC2015: +namespace vtk3DS { +static vtk3DSColour black = {0.0f, 0.0f, 0.0f}; +static char objName[80] = ""; +static vtk3DSColour fogColour = {0.0f, 0.0f, 0.0f}; static vtk3DSColour col = {0.0f, 0.0f, 0.0f}; -static vtk3DSColour global_amb = {0.1f, 0.1f, 0.1f}; +static vtk3DSColour globalAmb = {0.1f, 0.1f, 0.1f}; static vtk3DSVector pos = {0.0, 0.0, 0.0}; static vtk3DSVector target = {0.0, 0.0, 0.0}; static float hotspot = -1; static float falloff = -1; + /* Default material property */ -static vtk3DSMatProp DefaultMaterial = +static vtk3DSMatProp defaultMaterial = { "Default", NULL, {1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}, {1.0, 1.0, 1.0}, 70.0, // shininess @@ -61,6 +65,8 @@ static vtk3DSMatProp DefaultMaterial = 0.0, // bump_strength NULL};// vtkProperty +} // end namespace vtk3DS + static void cleanup_name (char *); static void list_insert (vtk3DSList **root, vtk3DSList *new_node); static void *list_find (vtk3DSList **root, const char *name); @@ -149,7 +155,7 @@ int vtk3DSImporter::Read3DS () // create a vtk3DSMatProp and fill if in with default aMaterial = (vtk3DSMatProp *) malloc (sizeof (vtk3DSMatProp)); - *aMaterial = DefaultMaterial; + *aMaterial = vtk3DS::defaultMaterial; aMaterial->aProperty = vtkProperty::New (); VTK_LIST_INSERT (this->MatPropList, aMaterial); return 1; @@ -411,9 +417,9 @@ static vtk3DSMatProp *create_mprop() new_mprop = (vtk3DSMatProp *) malloc (sizeof(*new_mprop)); strcpy (new_mprop->name, ""); - new_mprop->ambient = Black; - new_mprop->diffuse = Black; - new_mprop->specular = Black; + new_mprop->ambient = vtk3DS::black; + new_mprop->diffuse = vtk3DS::black; + new_mprop->specular = vtk3DS::black; new_mprop->shininess = 0.0; new_mprop->transparency = 0.0; new_mprop->reflection = 0.0; @@ -530,7 +536,7 @@ static void parse_mdata (vtk3DSImporter *importer, vtk3DSChunk *mainchunk) { switch (chunk.tag) { - case 0x2100: parse_colour (importer, &global_amb); + case 0x2100: parse_colour (importer, &vtk3DS::globalAmb); break; case 0x1200: parse_colour (importer, &bgnd_colour); break; @@ -559,7 +565,7 @@ static void parse_fog (vtk3DSImporter *importer, vtk3DSChunk *mainchunk) (void) read_float(importer); (void)read_float(importer); - parse_colour (importer, &fog_colour); + parse_colour (importer, &vtk3DS::fogColour); do { @@ -677,8 +683,8 @@ static void parse_named_object (vtk3DSImporter *importer, vtk3DSChunk *mainchunk vtk3DSMesh *mesh; vtk3DSChunk chunk; - strcpy (obj_name, read_string(importer)); - cleanup_name (obj_name); + strcpy (vtk3DS::objName, read_string(importer)); + cleanup_name (vtk3DS::objName); mesh = NULL; @@ -718,7 +724,7 @@ static void parse_n_tri_object (vtk3DSImporter *importer, vtk3DSChunk *mainchunk vtk3DSMesh *mesh; vtk3DSChunk chunk; - mesh = create_mesh (obj_name, 0, 0); + mesh = create_mesh (vtk3DS::objName, 0, 0); do { @@ -840,8 +846,8 @@ static void parse_n_direct_light (vtk3DSImporter *importer, vtk3DSChunk *mainchu vtk3DSOmniLight *o; int spot_flag = 0; - read_point (importer, pos); - parse_colour (importer, &col); + read_point (importer, vtk3DS::pos); + parse_colour (importer, &vtk3DS::col); do { @@ -863,63 +869,63 @@ static void parse_n_direct_light (vtk3DSImporter *importer, vtk3DSChunk *mainchu if (!spot_flag) { - o = (vtk3DSOmniLight *) VTK_LIST_FIND (importer->OmniList, obj_name); + o = (vtk3DSOmniLight *) VTK_LIST_FIND (importer->OmniList, vtk3DS::objName); if (o != NULL) { - pos[0] = o->pos[0]; - pos[1] = o->pos[1]; - pos[2] = o->pos[2]; - col = o->col; + vtk3DS::pos[0] = o->pos[0]; + vtk3DS::pos[1] = o->pos[1]; + vtk3DS::pos[2] = o->pos[2]; + vtk3DS::col = o->col; } else { o = (vtk3DSOmniLight *) malloc (sizeof (*o)); - o->pos[0] = pos[0]; - o->pos[1] = pos[1]; - o->pos[2] = pos[2]; - o->col = col ; - strcpy (o->name, obj_name); + o->pos[0] = vtk3DS::pos[0]; + o->pos[1] = vtk3DS::pos[1]; + o->pos[2] = vtk3DS::pos[2]; + o->col = vtk3DS::col ; + strcpy (o->name, vtk3DS::objName); VTK_LIST_INSERT (importer->OmniList, o); } } else { - s = (vtk3DSSpotLight *) VTK_LIST_FIND (importer->SpotLightList, obj_name); + s = (vtk3DSSpotLight *) VTK_LIST_FIND (importer->SpotLightList, vtk3DS::objName); if (s != NULL) { - pos[0] = s->pos[0]; - pos[1] = s->pos[1]; - pos[2] = s->pos[2]; - target[0] = s->target[0]; - target[1] = s->target[1]; - target[2] = s->target[2]; - col = s->col; - hotspot = s->hotspot; - falloff = s->falloff; + vtk3DS::pos[0] = s->pos[0]; + vtk3DS::pos[1] = s->pos[1]; + vtk3DS::pos[2] = s->pos[2]; + vtk3DS::target[0] = s->target[0]; + vtk3DS::target[1] = s->target[1]; + vtk3DS::target[2] = s->target[2]; + vtk3DS::col = s->col; + vtk3DS::hotspot = s->hotspot; + vtk3DS::falloff = s->falloff; } else { - if (falloff <= 0.0) + if (vtk3DS::falloff <= 0.0) { - falloff = 180.0; + vtk3DS::falloff = 180.0; } - if (hotspot <= 0.0) + if (vtk3DS::hotspot <= 0.0) { - hotspot = 0.7*falloff; + vtk3DS::hotspot = 0.7*vtk3DS::falloff; } s = (vtk3DSSpotLight *) malloc (sizeof (*s)); - s->pos[0] = pos[0]; - s->pos[1] = pos[1]; - s->pos[2] = pos[2]; - s->target[0] = target[0]; - s->target[1] = target[1]; - s->target[2] = target[2]; - s->col = col ; - s->hotspot = hotspot; - s->falloff = falloff; - strcpy (s->name, obj_name); + s->pos[0] = vtk3DS::pos[0]; + s->pos[1] = vtk3DS::pos[1]; + s->pos[2] = vtk3DS::pos[2]; + s->target[0] = vtk3DS::target[0]; + s->target[1] = vtk3DS::target[1]; + s->target[2] = vtk3DS::target[2]; + s->col = vtk3DS::col ; + s->hotspot = vtk3DS::hotspot; + s->falloff = vtk3DS::falloff; + strcpy (s->name, vtk3DS::objName); VTK_LIST_INSERT (importer->SpotLightList, s); } } @@ -928,10 +934,10 @@ static void parse_n_direct_light (vtk3DSImporter *importer, vtk3DSChunk *mainchu static void parse_dl_spotlight(vtk3DSImporter *importer) { - read_point (importer, target); + read_point (importer, vtk3DS::target); - hotspot = read_float(importer); - falloff = read_float(importer); + vtk3DS::hotspot = read_float(importer); + vtk3DS::falloff = read_float(importer); } @@ -941,18 +947,18 @@ static void parse_n_camera(vtk3DSImporter *importer) float lens; vtk3DSCamera *c = (vtk3DSCamera *) malloc (sizeof (vtk3DSCamera)); - read_point (importer, pos); - read_point (importer, target); + read_point (importer, vtk3DS::pos); + read_point (importer, vtk3DS::target); bank = read_float(importer); lens = read_float(importer); - strcpy (c->name, obj_name); - c->pos[0] = pos[0]; - c->pos[1] = pos[1]; - c->pos[2] = pos[2]; - c->target[0] = target[0]; - c->target[1] = target[1]; - c->target[2] = target[2]; + strcpy (c->name, vtk3DS::objName); + c->pos[0] = vtk3DS::pos[0]; + c->pos[1] = vtk3DS::pos[1]; + c->pos[2] = vtk3DS::pos[2]; + c->target[0] = vtk3DS::target[0]; + c->target[1] = vtk3DS::target[1]; + c->target[2] = vtk3DS::target[2]; c->lens = lens; c->bank = bank; diff --git a/IO/Import/vtkVRMLImporter_Yacc.h b/IO/Import/vtkVRMLImporter_Yacc.h index f227d7d9866..2f46b905c5b 100644 --- a/IO/Import/vtkVRMLImporter_Yacc.h +++ b/IO/Import/vtkVRMLImporter_Yacc.h @@ -1702,7 +1702,7 @@ void vtkVRMLYaccData::expect(int type) #define FLEX_SCANNER -#ifdef WIN32 +#ifdef _WIN32 #include #else #include diff --git a/IO/Infovis/Testing/Cxx/TestPhyloXMLTreeReadWrite.cxx b/IO/Infovis/Testing/Cxx/TestPhyloXMLTreeReadWrite.cxx index cd497ccb8bd..6a98d0695b2 100644 --- a/IO/Infovis/Testing/Cxx/TestPhyloXMLTreeReadWrite.cxx +++ b/IO/Infovis/Testing/Cxx/TestPhyloXMLTreeReadWrite.cxx @@ -88,7 +88,7 @@ bool VerifyArrayAttribute(vtkTree *tree, const char *arrayName, //---------------------------------------------------------------------------- bool VerifyColor(vtkTree *tree, vtkIdType vertex, unsigned char r, unsigned char g, unsigned char b) { - vtkUnsignedCharArray *array = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray *array = vtkArrayDownCast( tree->GetVertexData()->GetAbstractArray("color")); if (!array) { diff --git a/IO/Infovis/Testing/Cxx/TestTulipReaderProperties.cxx b/IO/Infovis/Testing/Cxx/TestTulipReaderProperties.cxx index 80c9f15123f..b78bdc0ce49 100644 --- a/IO/Infovis/Testing/Cxx/TestTulipReaderProperties.cxx +++ b/IO/Infovis/Testing/Cxx/TestTulipReaderProperties.cxx @@ -56,7 +56,7 @@ int TestTulipReaderProperties(int argc, char* argv[]) int error_count = 0; // Test a sample of the node pedigree id property - vtkVariantArray *nodePedigree= vtkVariantArray::SafeDownCast( + vtkVariantArray *nodePedigree= vtkArrayDownCast( graph->GetVertexData()->GetPedigreeIds()); if (nodePedigree) { @@ -74,7 +74,7 @@ int TestTulipReaderProperties(int argc, char* argv[]) } // Test a sample of the node string property - vtkStringArray *nodeProperty1 = vtkStringArray::SafeDownCast( + vtkStringArray *nodeProperty1 = vtkArrayDownCast( graph->GetVertexData()->GetAbstractArray("Node Name")); if (nodeProperty1) { @@ -92,7 +92,7 @@ int TestTulipReaderProperties(int argc, char* argv[]) } // Test a sample of the node int property - vtkIntArray *nodeProperty2 = vtkIntArray::SafeDownCast( + vtkIntArray *nodeProperty2 = vtkArrayDownCast( graph->GetVertexData()->GetAbstractArray("Weight")); if (nodeProperty2) { @@ -110,7 +110,7 @@ int TestTulipReaderProperties(int argc, char* argv[]) } // Test a sample of the node double property - vtkDoubleArray *nodeProperty3 = vtkDoubleArray::SafeDownCast( + vtkDoubleArray *nodeProperty3 = vtkArrayDownCast( graph->GetVertexData()->GetAbstractArray("Betweenness Centrality")); if (nodeProperty3) { @@ -128,7 +128,7 @@ int TestTulipReaderProperties(int argc, char* argv[]) } // Test a sample of the edge string property - vtkStringArray *edgeProperty1 = vtkStringArray::SafeDownCast( + vtkStringArray *edgeProperty1 = vtkArrayDownCast( graph->GetEdgeData()->GetAbstractArray("Edge Name")); if (edgeProperty1) { @@ -146,7 +146,7 @@ int TestTulipReaderProperties(int argc, char* argv[]) } // Test a sample of the edge int property - vtkIntArray *edgeProperty2 = vtkIntArray::SafeDownCast( + vtkIntArray *edgeProperty2 = vtkArrayDownCast( graph->GetEdgeData()->GetAbstractArray("Weight")); if (edgeProperty2) { @@ -164,7 +164,7 @@ int TestTulipReaderProperties(int argc, char* argv[]) } // Test a sample of the edge pedigree id property - vtkVariantArray *edgePedigree= vtkVariantArray::SafeDownCast( + vtkVariantArray *edgePedigree= vtkArrayDownCast( graph->GetEdgeData()->GetPedigreeIds()); if (edgePedigree) { diff --git a/IO/Infovis/vtkDelimitedTextReader.cxx b/IO/Infovis/vtkDelimitedTextReader.cxx index c0607791616..3ebc31af237 100644 --- a/IO/Infovis/vtkDelimitedTextReader.cxx +++ b/IO/Infovis/vtkDelimitedTextReader.cxx @@ -292,13 +292,13 @@ class DelimitedTextIterator : public vtkTextCodec::OutputIterator if(this->UnicodeArrayOutput) { array->SetNumberOfTuples(this->CurrentRecordIndex + 1); - vtkUnicodeStringArray::SafeDownCast(array)->SetValue(this->CurrentRecordIndex, this->CurrentField); + vtkArrayDownCast(array)->SetValue(this->CurrentRecordIndex, this->CurrentField); } else { std::string s; this->CurrentField.utf8_str(s); - vtkStringArray::SafeDownCast(array)->InsertValue(this->CurrentRecordIndex, s); + vtkArrayDownCast(array)->InsertValue(this->CurrentRecordIndex, s); } } this->OutputTable->AddColumn(array); @@ -319,13 +319,13 @@ class DelimitedTextIterator : public vtkTextCodec::OutputIterator if(this->UnicodeArrayOutput) { - vtkUnicodeStringArray* uarray = vtkUnicodeStringArray::SafeDownCast(this->OutputTable->GetColumn(this->CurrentFieldIndex)); + vtkUnicodeStringArray* uarray = vtkArrayDownCast(this->OutputTable->GetColumn(this->CurrentFieldIndex)); uarray->SetNumberOfTuples(rec_index + 1); uarray->SetValue(rec_index, this->CurrentField); } else { - vtkStringArray* sarray = vtkStringArray::SafeDownCast(this->OutputTable->GetColumn(this->CurrentFieldIndex)); + vtkStringArray* sarray = vtkArrayDownCast(this->OutputTable->GetColumn(this->CurrentFieldIndex)); std::string s; this->CurrentField.utf8_str(s); sarray->InsertValue(rec_index,s); diff --git a/IO/Infovis/vtkDelimitedTextReader.h b/IO/Infovis/vtkDelimitedTextReader.h index 5c702c2f6df..1ea6c2ee9a8 100644 --- a/IO/Infovis/vtkDelimitedTextReader.h +++ b/IO/Infovis/vtkDelimitedTextReader.h @@ -254,7 +254,6 @@ class VTKIOINFOVIS_EXPORT vtkDelimitedTextReader : public vtkTableAlgorithm vtkSetMacro(ReplacementCharacter, vtkTypeUInt32); vtkGetMacro(ReplacementCharacter, vtkTypeUInt32); -//BTX protected: vtkDelimitedTextReader(); ~vtkDelimitedTextReader(); @@ -295,7 +294,7 @@ class VTKIOINFOVIS_EXPORT vtkDelimitedTextReader : public vtkTableAlgorithm private: vtkDelimitedTextReader(const vtkDelimitedTextReader&); // Not implemented void operator=(const vtkDelimitedTextReader&); // Not implemented -//ETX + }; #endif diff --git a/IO/Infovis/vtkPhyloXMLTreeReader.cxx b/IO/Infovis/vtkPhyloXMLTreeReader.cxx index ca2344e3c8f..ceee6e99135 100644 --- a/IO/Infovis/vtkPhyloXMLTreeReader.cxx +++ b/IO/Infovis/vtkPhyloXMLTreeReader.cxx @@ -704,7 +704,7 @@ void vtkPhyloXMLTreeReader::ReadColorElement(vtkXMLDataElement *element, } // store this color value in the array - vtkUnsignedCharArray *colorArray = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray *colorArray = vtkArrayDownCast( g->GetVertexData()->GetAbstractArray("color")); colorArray->SetTuple3(vertex, red, green, blue); this->ColoredVertices->SetValue(vertex, 1); @@ -718,7 +718,7 @@ void vtkPhyloXMLTreeReader::PropagateBranchColor(vtkTree *tree) return; } - vtkUnsignedCharArray *colorArray = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray *colorArray = vtkArrayDownCast( tree->GetVertexData()->GetAbstractArray("color")); if (!colorArray) { diff --git a/IO/Infovis/vtkPhyloXMLTreeWriter.cxx b/IO/Infovis/vtkPhyloXMLTreeWriter.cxx index 32d7f7bbb7d..71043421259 100644 --- a/IO/Infovis/vtkPhyloXMLTreeWriter.cxx +++ b/IO/Infovis/vtkPhyloXMLTreeWriter.cxx @@ -303,7 +303,7 @@ void vtkPhyloXMLTreeWriter::WriteColorElement(vtkTree* const input, vtkIdType vertex, vtkXMLDataElement *element) { - vtkUnsignedCharArray *colorArray = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray *colorArray = vtkArrayDownCast( input->GetVertexData()->GetAbstractArray("color")); if (!colorArray) { diff --git a/IO/Infovis/vtkXGMLReader.cxx b/IO/Infovis/vtkXGMLReader.cxx index 95db1f06c9e..cb6bf3309b5 100644 --- a/IO/Infovis/vtkXGMLReader.cxx +++ b/IO/Infovis/vtkXGMLReader.cxx @@ -314,7 +314,7 @@ int vtkXGMLReader::RequestData( if (property_table[i].Data->GetDataType() == VTK_INT) { assert(tok.Type == vtkXGMLReaderToken::INT); - vtkIntArray::SafeDownCast(property_table[i].Data)->SetValue(nodeIdMap[id], tok.IntValue); + vtkArrayDownCast(property_table[i].Data)->SetValue(nodeIdMap[id], tok.IntValue); } else if (property_table[i].Data->GetDataType() == VTK_DOUBLE) { @@ -324,12 +324,12 @@ int vtkXGMLReader::RequestData( d = (double)tok.IntValue; else vtkErrorMacro(<<"Expected double or int.\n"); - vtkDoubleArray::SafeDownCast(property_table[i].Data)->SetValue(nodeIdMap[id], d); + vtkArrayDownCast(property_table[i].Data)->SetValue(nodeIdMap[id], d); } else { assert(tok.Type == vtkXGMLReaderToken::TEXT); - vtkStringArray::SafeDownCast(property_table[i].Data)->SetValue(nodeIdMap[id], tok.StringValue); + vtkArrayDownCast(property_table[i].Data)->SetValue(nodeIdMap[id], tok.StringValue); } } vtkXGMLReaderNextToken(fin, tok); @@ -385,7 +385,7 @@ int vtkXGMLReader::RequestData( if (property_table[i].Data->GetDataType() == VTK_INT) { assert(tok.Type == vtkXGMLReaderToken::INT); - vtkIntArray::SafeDownCast(property_table[i].Data)->SetValue(edgeIdMap[id], tok.IntValue); + vtkArrayDownCast(property_table[i].Data)->SetValue(edgeIdMap[id], tok.IntValue); } else if (property_table[i].Data->GetDataType() == VTK_DOUBLE) { @@ -395,12 +395,12 @@ int vtkXGMLReader::RequestData( d = (double)tok.IntValue; else vtkErrorMacro(<<"Expected double or int.\n"); - vtkDoubleArray::SafeDownCast(property_table[i].Data)->SetValue(nodeIdMap[id], d); + vtkArrayDownCast(property_table[i].Data)->SetValue(nodeIdMap[id], d); } else { assert(tok.Type == vtkXGMLReaderToken::TEXT); - vtkStringArray::SafeDownCast(property_table[i].Data)->SetValue(edgeIdMap[id], tok.StringValue); + vtkArrayDownCast(property_table[i].Data)->SetValue(edgeIdMap[id], tok.StringValue); } } vtkXGMLReaderNextToken(fin, tok); diff --git a/IO/Infovis/vtkXMLTreeReader.cxx b/IO/Infovis/vtkXMLTreeReader.cxx index 3ff34d130b0..de81fff427f 100644 --- a/IO/Infovis/vtkXMLTreeReader.cxx +++ b/IO/Infovis/vtkXMLTreeReader.cxx @@ -91,7 +91,7 @@ static void vtkXMLTreeReaderProcessElement(vtkMutableDirectedGraph *tree, vtkIdType parent, xmlNode *node, int readCharData, int maskArrays) { vtkDataSetAttributes *data = tree->GetVertexData(); - vtkStringArray *nameArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(vtkXMLTreeReader::TagNameField)); + vtkStringArray *nameArr = vtkArrayDownCast(data->GetAbstractArray(vtkXMLTreeReader::TagNameField)); vtkStdString content; for (xmlNode *curNode = node; curNode; curNode = curNode->next) { @@ -128,11 +128,11 @@ static void vtkXMLTreeReaderProcessElement(vtkMutableDirectedGraph *tree, char *validName = new char[len+8]; strcpy(validName, ".valid."); strcat(validName, name); - vtkStringArray *stringArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(name)); + vtkStringArray *stringArr = vtkArrayDownCast(data->GetAbstractArray(name)); vtkBitArray *bitArr = 0; if (maskArrays) { - bitArr = vtkBitArray::SafeDownCast(data->GetAbstractArray(validName)); + bitArr = vtkArrayDownCast(data->GetAbstractArray(validName)); } if (!stringArr) { @@ -168,7 +168,7 @@ static void vtkXMLTreeReaderProcessElement(vtkMutableDirectedGraph *tree, if (readCharData && parent >= 0) { - vtkStringArray *charArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(vtkXMLTreeReader::CharDataField)); + vtkStringArray *charArr = vtkArrayDownCast(data->GetAbstractArray(vtkXMLTreeReader::CharDataField)); charArr->InsertValue(parent, content); } } @@ -228,7 +228,7 @@ int vtkXMLTreeReader::RequestData( // Make all the arrays the same size for (int i = 0; i < data->GetNumberOfArrays(); i++) { - vtkStringArray *stringArr = vtkStringArray::SafeDownCast(data->GetAbstractArray(i)); + vtkStringArray *stringArr = vtkArrayDownCast(data->GetAbstractArray(i)); if (stringArr && (stringArr->GetNumberOfTuples() < builder->GetNumberOfVertices())) { stringArr->InsertValue(builder->GetNumberOfVertices() - 1, vtkStdString("")); diff --git a/IO/LSDyna/private/LSDynaFamily.cxx b/IO/LSDyna/private/LSDynaFamily.cxx index 19bf9db4464..3dcb31c7143 100644 --- a/IO/LSDyna/private/LSDynaFamily.cxx +++ b/IO/LSDyna/private/LSDynaFamily.cxx @@ -36,7 +36,7 @@ namespace // Usually stat uses 32 bit fields, and stat64 (with underscores in Windows) uses 64 bit fields. // But on OS X and FreeBSD, stat uses 64 bit fields these days. #if (VTK_SIZEOF_ID_TYPE == 8) && !defined(_DARWIN_FEATURE_64_BIT_INODE) && !defined(__FreeBSD__) - #ifndef WIN32 + #ifndef _WIN32 #define USE_STAT_64 #else #define USE_WIN_STAT_64 @@ -64,7 +64,7 @@ namespace vtkLSDynaFile_t VTK_LSDYNA_OPENFILE(const char* fname) { -#ifndef WIN32 +#ifndef _WIN32 vtkLSDynaFile_t f = open(fname, O_RDONLY); return f; #else diff --git a/IO/LSDyna/private/LSDynaFamily.h b/IO/LSDyna/private/LSDynaFamily.h index 96c396a9c28..1cd99b90d19 100644 --- a/IO/LSDyna/private/LSDynaFamily.h +++ b/IO/LSDyna/private/LSDynaFamily.h @@ -42,7 +42,7 @@ //this is needs to be moved over to fseekpos and ftellpos //in the future -#ifndef WIN32 +#ifndef _WIN32 # include typedef off_t vtkLSDynaOff_t; // sanity typedef int vtkLSDynaFile_t; @@ -53,7 +53,7 @@ typedef int vtkLSDynaFile_t; # define VTK_LSDYNA_READ(fid,ptr,cnt) read(fid,ptr,cnt) # define VTK_LSDYNA_ISBADFILE(fid) (fid < 0) # define VTK_LSDYNA_CLOSEFILE(fid) close(fid) -#else // WIN32 +#else // _WIN32 typedef long vtkLSDynaOff_t; // insanity typedef FILE* vtkLSDynaFile_t; # define VTK_LSDYNA_BADFILE 0 diff --git a/IO/LSDyna/vtkLSDynaReader.cxx b/IO/LSDyna/vtkLSDynaReader.cxx index cf6104325fe..5067ebac72f 100644 --- a/IO/LSDyna/vtkLSDynaReader.cxx +++ b/IO/LSDyna/vtkLSDynaReader.cxx @@ -152,7 +152,7 @@ static const char* vtkLSDynaCellTypes[] = static void vtkLSGetLine( ifstream& deck, std::string& line ) { -#if !defined(_WIN32) && !defined(WIN32) && !defined(_MSC_VER) && !defined(__BORLANDC__) +#if !defined(_WIN32) && !defined(_MSC_VER) && !defined(__BORLANDC__) // One line implementation for everyone but Windows (MSVC6 and BCC32 are the troublemakers): std::getline( deck, line, '\n' ); #else @@ -3424,11 +3424,11 @@ int vtkLSDynaReader::ReadInputDeckKeywords( ifstream& deck ) { deckExt = ""; } -#ifndef WIN32 +#ifndef _WIN32 xmlSummary = deckDir + "/" + deckName + ".lsdyna"; #else xmlSummary = deckDir + "\\" + deckName + ".lsdyna"; -#endif // WIN32 +#endif // _WIN32 // As long as we don't kill the input deck, write the summary XML: if ( xmlSummary != this->InputDeck ) { @@ -3460,11 +3460,11 @@ int vtkLSDynaReader::WriteInputDeckSummary( const char* fname ) std::string dbName = this->P->Fam.GetDatabaseBaseName(); if ( this->IsDatabaseValid() && ! dbDir.empty() && ! dbName.empty() ) { -#ifndef WIN32 +#ifndef _WIN32 if ( dbDir[0] == '/' ) #else if ( dbDir[0] == '\\' ) -#endif // WIN32 +#endif // _WIN32 { // OK, we have an absolute path, so it should be safe to write it out. xmlSummary diff --git a/IO/Legacy/vtkCompositeDataReader.cxx b/IO/Legacy/vtkCompositeDataReader.cxx index 6482910a435..d1c5eebadac 100644 --- a/IO/Legacy/vtkCompositeDataReader.cxx +++ b/IO/Legacy/vtkCompositeDataReader.cxx @@ -415,7 +415,7 @@ bool vtkCompositeDataReader::ReadCompositeData(vtkOverlappingAMR* oamr) } vtkSmartPointer idata; - idata.TakeReference(vtkIntArray::SafeDownCast( + idata.TakeReference(vtkArrayDownCast( this->ReadArray("int", num_tuples, num_components))); if (!idata || idata->GetNumberOfComponents() != 6 || idata->GetNumberOfTuples() != static_cast(oamr->GetTotalNumberOfBlocks())) @@ -431,7 +431,7 @@ bool vtkCompositeDataReader::ReadCompositeData(vtkOverlappingAMR* oamr) for (unsigned int index=0; index < num_datasets; index++, metadata_index++) { int tuple[6]; - idata->GetTupleValue(metadata_index, tuple); + idata->GetTypedTuple(metadata_index, tuple); vtkAMRBox box; box.SetDimensions(&tuple[0], &tuple[3], description); diff --git a/IO/Legacy/vtkCompositeDataReader.h b/IO/Legacy/vtkCompositeDataReader.h index 1b4633f7d87..d45ba728cfb 100644 --- a/IO/Legacy/vtkCompositeDataReader.h +++ b/IO/Legacy/vtkCompositeDataReader.h @@ -45,7 +45,6 @@ class VTKIOLEGACY_EXPORT vtkCompositeDataReader : public vtkDataReader vtkCompositeDataSet *GetOutput(int idx); void SetOutput(vtkCompositeDataSet *output); -//BTX protected: vtkCompositeDataReader(); ~vtkCompositeDataReader(); @@ -83,7 +82,7 @@ class VTKIOLEGACY_EXPORT vtkCompositeDataReader : public vtkDataReader private: vtkCompositeDataReader(const vtkCompositeDataReader&); // Not implemented. void operator=(const vtkCompositeDataReader&); // Not implemented. -//ETX + }; #endif diff --git a/IO/Legacy/vtkCompositeDataWriter.cxx b/IO/Legacy/vtkCompositeDataWriter.cxx index 14adab842cb..94937cb17e4 100644 --- a/IO/Legacy/vtkCompositeDataWriter.cxx +++ b/IO/Legacy/vtkCompositeDataWriter.cxx @@ -263,7 +263,7 @@ bool vtkCompositeDataWriter::WriteCompositeData( const vtkAMRBox& box = oamr->GetAMRBox(level,index); int tuple[6]; box.Serialize(tuple); - idata->SetTupleValue(metadata_index, tuple); + idata->SetTypedTuple(metadata_index, tuple); } } *fp << "AMRBOXES " diff --git a/IO/Legacy/vtkCompositeDataWriter.h b/IO/Legacy/vtkCompositeDataWriter.h index 662d6bc9533..d447aea6b40 100644 --- a/IO/Legacy/vtkCompositeDataWriter.h +++ b/IO/Legacy/vtkCompositeDataWriter.h @@ -47,7 +47,6 @@ class VTKIOLEGACY_EXPORT vtkCompositeDataWriter : public vtkDataWriter vtkCompositeDataSet* GetInput(); vtkCompositeDataSet* GetInput(int port); -//BTX protected: vtkCompositeDataWriter(); ~vtkCompositeDataWriter(); @@ -67,7 +66,7 @@ class VTKIOLEGACY_EXPORT vtkCompositeDataWriter : public vtkDataWriter private: vtkCompositeDataWriter(const vtkCompositeDataWriter&); // Not implemented void operator=(const vtkCompositeDataWriter&); // Not implemented -//ETX + }; #endif diff --git a/IO/Legacy/vtkDataReader.cxx b/IO/Legacy/vtkDataReader.cxx index d320c54319a..f4445523070 100644 --- a/IO/Legacy/vtkDataReader.cxx +++ b/IO/Legacy/vtkDataReader.cxx @@ -1882,7 +1882,7 @@ int vtkDataReader::ReadPoints(vtkPointSet *ps, int numPts) return 0; } - data = vtkDataArray::SafeDownCast( + data = vtkArrayDownCast( this->ReadArray(line, numPts, 3)); if ( data != NULL ) { @@ -1916,7 +1916,7 @@ int vtkDataReader::ReadPoints(vtkGraph *g, int numPts) return 0; } - data = vtkDataArray::SafeDownCast( + data = vtkArrayDownCast( this->ReadArray(line, numPts, 3)); if ( data != NULL ) { @@ -1953,7 +1953,7 @@ int vtkDataReader::ReadCoordinates(vtkRectilinearGrid *rg, int axes, return 0; } - data = vtkDataArray::SafeDownCast( + data = vtkArrayDownCast( this->ReadArray(line, numCoords, 1)); if ( !data ) { @@ -2046,7 +2046,7 @@ int vtkDataReader::ReadScalarData(vtkDataSetAttributes *a, int numPts) } // Read the data - data = vtkDataArray::SafeDownCast( + data = vtkArrayDownCast( this->ReadArray(line, numPts, numComp)); if ( data != NULL ) { @@ -2095,7 +2095,7 @@ int vtkDataReader::ReadVectorData(vtkDataSetAttributes *a, int numPts) skipVector = 1; } - data = vtkDataArray::SafeDownCast( + data = vtkArrayDownCast( this->ReadArray(line, numPts, 3)); if ( data != NULL ) { @@ -2145,7 +2145,7 @@ int vtkDataReader::ReadNormalData(vtkDataSetAttributes *a, int numPts) skipNormal = 1; } - data = vtkDataArray::SafeDownCast( + data = vtkArrayDownCast( this->ReadArray(line, numPts, 3)); if ( data != NULL ) { @@ -2194,7 +2194,7 @@ int vtkDataReader::ReadTensorData(vtkDataSetAttributes *a, int numPts) skipTensor = 1; } - data = vtkDataArray::SafeDownCast( + data = vtkArrayDownCast( this->ReadArray(line, numPts, 9)); if ( data != NULL ) { @@ -2348,7 +2348,7 @@ int vtkDataReader::ReadTCoordsData(vtkDataSetAttributes *a, int numPts) skipTCoord = 1; } - data = vtkDataArray::SafeDownCast( + data = vtkArrayDownCast( this->ReadArray(line, numPts, dim)); if ( data != NULL ) { @@ -2397,7 +2397,7 @@ int vtkDataReader::ReadGlobalIds(vtkDataSetAttributes *a, int numPts) skipGlobalIds = 1; } - data = vtkDataArray::SafeDownCast( + data = vtkArrayDownCast( this->ReadArray(line, numPts, 1)); if ( data != NULL ) { @@ -2728,7 +2728,7 @@ int vtkDataReader::ReadCells(int size, int *data, void vtkDataReader::ConvertGhostLevelsToGhostType( FieldType fieldType, vtkAbstractArray *data) const { - vtkUnsignedCharArray* ucData = vtkUnsignedCharArray::SafeDownCast(data); + vtkUnsignedCharArray* ucData = vtkArrayDownCast(data); const char* name = data->GetName(); int numComp = data->GetNumberOfComponents(); if (this->FileMajorVersion < 4 && ucData && diff --git a/IO/Legacy/vtkDataReader.h b/IO/Legacy/vtkDataReader.h index 401ec3487a0..f1072272074 100644 --- a/IO/Legacy/vtkDataReader.h +++ b/IO/Legacy/vtkDataReader.h @@ -298,7 +298,6 @@ class VTKIOLEGACY_EXPORT vtkDataReader : public vtkAlgorithm vtkGetMacro(FileMajorVersion, int); vtkGetMacro(FileMinorVersion, int); -//BTX // Description: // Internal function to read in a value. Returns zero if there was an // error. @@ -314,13 +313,11 @@ class VTKIOLEGACY_EXPORT vtkDataReader : public vtkAlgorithm int Read(unsigned long long *result); int Read(float *); int Read(double *); -//ETX // Description: // Close the vtk file. void CloseVTKFile(); -//BTX // Description: // Internal function to read in a line up to 256 characters. // Returns zero if there was an error. @@ -338,7 +335,6 @@ class VTKIOLEGACY_EXPORT vtkDataReader : public vtkAlgorithm // Description: // Return the istream being used to read in the data. istream *GetIStream() {return this->IS;}; -//ETX // Description: // Read the meta information from the file. This needs to be public to it diff --git a/IO/Legacy/vtkGenericDataObjectReader.h b/IO/Legacy/vtkGenericDataObjectReader.h index 91adbd3fbcb..f16a270d0bb 100644 --- a/IO/Legacy/vtkGenericDataObjectReader.h +++ b/IO/Legacy/vtkGenericDataObjectReader.h @@ -81,7 +81,7 @@ class VTKIOLEGACY_EXPORT vtkGenericDataObjectReader : public vtkDataReader // See vtkAlgorithm for information. virtual int ProcessRequest(vtkInformation *, vtkInformationVector **, vtkInformationVector *); -//BTX + protected: vtkGenericDataObjectReader(); ~vtkGenericDataObjectReader(); @@ -102,7 +102,7 @@ class VTKIOLEGACY_EXPORT vtkGenericDataObjectReader : public vtkDataReader void ReadData(const char* dataClass, vtkDataObject* output); vtkSetStringMacro(Header); -//ETX + }; #endif diff --git a/IO/Legacy/vtkGraphReader.cxx b/IO/Legacy/vtkGraphReader.cxx index 8ac05cc4cc3..65ea3d61a00 100644 --- a/IO/Legacy/vtkGraphReader.cxx +++ b/IO/Legacy/vtkGraphReader.cxx @@ -124,8 +124,7 @@ int vtkGraphReader::RequestData( builder = undir_builder; } - int done = 0; - while(!done) + while(true) { if(!this->ReadString(line)) { diff --git a/IO/Legacy/vtkStructuredGridReader.cxx b/IO/Legacy/vtkStructuredGridReader.cxx index a4848148cea..b33539e5ef9 100644 --- a/IO/Legacy/vtkStructuredGridReader.cxx +++ b/IO/Legacy/vtkStructuredGridReader.cxx @@ -249,7 +249,7 @@ int vtkStructuredGridReader::RequestData( return 1; } - vtkUnsignedCharArray *data = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray *data = vtkArrayDownCast( this->ReadArray(line, numPts, 1)); if ( data != NULL ) diff --git a/IO/Legacy/vtkTableReader.cxx b/IO/Legacy/vtkTableReader.cxx index 9e7040c464c..9854ba0defb 100644 --- a/IO/Legacy/vtkTableReader.cxx +++ b/IO/Legacy/vtkTableReader.cxx @@ -139,8 +139,7 @@ int vtkTableReader::RequestData( vtkTable* const output = vtkTable::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); - int done = 0; - while(!done) + while(true) { if(!this->ReadString(line)) { diff --git a/IO/Legacy/vtkTreeReader.cxx b/IO/Legacy/vtkTreeReader.cxx index d9f3f833f87..91233408f89 100644 --- a/IO/Legacy/vtkTreeReader.cxx +++ b/IO/Legacy/vtkTreeReader.cxx @@ -144,8 +144,7 @@ int vtkTreeReader::RequestData( vtkSmartPointer builder = vtkSmartPointer::New(); - int done = 0; - while(!done) + while(true) { if(!this->ReadString(line)) { diff --git a/IO/MINC/vtkMINCImageAttributes.cxx b/IO/MINC/vtkMINCImageAttributes.cxx index da8e2ba24fb..783c8a81e8a 100644 --- a/IO/MINC/vtkMINCImageAttributes.cxx +++ b/IO/MINC/vtkMINCImageAttributes.cxx @@ -71,6 +71,10 @@ POSSIBILITY OF SUCH DAMAGES. #include #include +#if defined(_MSC_VER) && (_MSC_VER < 1900) +#define snprintf _snprintf +#endif + //------------------------------------------------------------------------- // A container for mapping attribute names to arrays class vtkMINCImageAttributeMap @@ -259,8 +263,8 @@ void vtkMINCImageAttributes::AddDimension(const char *dimension, vtkIdType length) { // Check for duplicates - int n = this->DimensionNames->GetNumberOfValues(); - for (int i = 0; i < n; i++) + vtkIdType n = this->DimensionNames->GetNumberOfValues(); + for (vtkIdType i = 0; i < n; i++) { if (strcmp(dimension, this->DimensionNames->GetValue(i)) == 0) { @@ -294,19 +298,33 @@ void vtkMINCImageAttributes::AddDimension(const char *dimension, const char *vtkMINCImageAttributes::ConvertDataArrayToString( vtkDataArray *array) { - int dataType = array->GetDataType(); + const char *result = ""; + vtkIdType n = array->GetNumberOfTuples(); + if (n == 0) + { + return result; + } + int dataType = array->GetDataType(); if (dataType == VTK_CHAR) { - vtkCharArray *charArray = vtkCharArray::SafeDownCast(array); - return charArray->GetPointer(0); + vtkCharArray *charArray = vtkArrayDownCast(array); + if (charArray) + { + result = charArray->GetPointer(0); + // Check to see if string has a terminal null (the null might be + // part of the attribute, or stored in the following byte) + if ((n > 0 && result[n-1] == '\0') || + (charArray->GetSize() > n && result[n] == '\0')) + { + return result; + } + } } std::ostringstream os; - int n = array->GetNumberOfTuples(); - int i = 0; - for (i = 0; i < n; i++) + for (vtkIdType i = 0; i < n; i++) { double val = array->GetComponent(i, 0); if (dataType == VTK_DOUBLE || dataType == VTK_FLOAT) @@ -315,11 +333,11 @@ const char *vtkMINCImageAttributes::ConvertDataArrayToString( char storage[128]; if (dataType == VTK_DOUBLE) { - sprintf(storage, "%0.15g", val); + snprintf(storage, 128, "%0.15g", val); } else { - sprintf(storage, "%0.7g", val); + snprintf(storage, 128, "%0.7g", val); } // Add a decimal if there isn't one, to distinguish from int for (char *cp = storage; *cp != '.'; cp++) @@ -333,43 +351,47 @@ const char *vtkMINCImageAttributes::ConvertDataArrayToString( } os << storage; } + else if (dataType == VTK_CHAR) + { + os.put(static_cast(val)); + } else { os << val; } - if (i < n-1) + if (i < n-1 && dataType != VTK_CHAR) { os << ", "; } } - // Store the string - std::string str = os.str(); - const char *result = 0; + // Store the string + std::string str = os.str(); - if (this->StringStore == 0) - { - this->StringStore = vtkStringArray::New(); - } + if (this->StringStore == 0) + { + this->StringStore = vtkStringArray::New(); + } - // See if the string is already stored - n = this->StringStore->GetNumberOfValues(); - for (i = 0; i < n; i++) - { - result = this->StringStore->GetValue(i); - if (strcmp(str.c_str(), result) == 0) - { - break; - } - } - // If not, add it to the array. - if (i == n) + // See if the string is already stored + vtkIdType m = this->StringStore->GetNumberOfValues(); + vtkIdType j; + for (j = 0; j < m; j++) + { + result = this->StringStore->GetValue(j); + if (strcmp(str.c_str(), result) == 0) { - i = this->StringStore->InsertNextValue(str.c_str()); - result = this->StringStore->GetValue(i); + break; } + } + // If not, add it to the array. + if (j == m) + { + j = this->StringStore->InsertNextValue(str.c_str()); + result = this->StringStore->GetValue(j); + } - return result; + return result; } //------------------------------------------------------------------------- @@ -417,12 +439,12 @@ void vtkMINCImageAttributes::PrintFileHeader(ostream &os) os << "netcdf " << name << " {\n"; os << "dimensions:\n"; - int ndim = 0; + vtkIdType ndim = 0; if (this->DimensionNames) { ndim = this->DimensionNames->GetNumberOfValues(); } - for (int idim = 0; idim < ndim; idim++) + for (vtkIdType idim = 0; idim < ndim; idim++) { os << "\t" << this->DimensionNames->GetValue(idim) << " = " << this->DimensionLengths->GetValue(idim) << " ;\n"; @@ -430,8 +452,8 @@ void vtkMINCImageAttributes::PrintFileHeader(ostream &os) os << "variables:\n"; - int nvar = 0; - int ivar = 0; + vtkIdType nvar = 0; + vtkIdType ivar = 0; if (this->VariableNames) { nvar = this->VariableNames->GetNumberOfValues(); @@ -450,8 +472,7 @@ void vtkMINCImageAttributes::PrintFileHeader(ostream &os) strcmp(varname, MIimagemax) == 0 || strcmp(varname, MIimagemin) == 0) { - os << "\t" << imageDataType << " " << varname; - int nvardim = this->DimensionNames->GetNumberOfValues(); + vtkIdType nvardim = this->DimensionNames->GetNumberOfValues(); // If this is image-min or image-max, only print the // dimensions for these variables if (varname[5] == '-') @@ -460,6 +481,11 @@ void vtkMINCImageAttributes::PrintFileHeader(ostream &os) { nvardim = this->NumberOfImageMinMaxDimensions; } + os << "\tdouble " << varname; + } + else + { + os << "\t" << imageDataType << " " << varname; } if (nvardim > 0) @@ -486,8 +512,8 @@ void vtkMINCImageAttributes::PrintFileHeader(ostream &os) this->AttributeNames->GetStringArray(varname); if (attArray) { - int natt = attArray->GetNumberOfValues(); - for (int iatt = 0; iatt < natt; iatt++) + vtkIdType natt = attArray->GetNumberOfValues(); + for (vtkIdType iatt = 0; iatt < natt; iatt++) { const char *attname = attArray->GetValue(iatt); vtkDataArray *array = @@ -495,11 +521,9 @@ void vtkMINCImageAttributes::PrintFileHeader(ostream &os) os << "\t\t" << varname << ":" << attname << " = "; if (array->GetDataType() == VTK_CHAR) { - vtkCharArray *charArray = - vtkCharArray::SafeDownCast(array); os << "\""; - const char *cp = charArray->GetPointer(0); - const char *endcp = cp + charArray->GetNumberOfTuples(); + const char *cp = this->ConvertDataArrayToString(array); + const char *endcp = cp + strlen(cp); char text[512]; text[0] = '\0'; while (cp < endcp) @@ -694,7 +718,7 @@ const char *vtkMINCImageAttributes::GetAttributeValueAsString( return 0; } - // Convert any other array to a a string. + // Convert any other array to a string. return this->ConvertDataArrayToString(array); } @@ -714,8 +738,8 @@ int vtkMINCImageAttributes::GetAttributeValueAsInt( if (array->GetDataType() == VTK_CHAR) { - char *text = vtkCharArray::SafeDownCast(array)->GetPointer(0); - char *endp = text; + const char *text = this->ConvertDataArrayToString(array); + char *endp = const_cast(text); long result = strtol(text, &endp, 10); // Check for complete conversion if (*endp == '\0' && *text != '\0') @@ -763,8 +787,8 @@ double vtkMINCImageAttributes::GetAttributeValueAsDouble( if (array->GetDataType() == VTK_CHAR) { - char *text = vtkCharArray::SafeDownCast(array)->GetPointer(0); - char *endp = text; + const char *text = this->ConvertDataArrayToString(array); + char *endp = const_cast(text); double result = strtod(text, &endp); // Check for complete conversion if (*endp == '\0' && *text != '\0') @@ -812,8 +836,8 @@ void vtkMINCImageAttributes::SetAttributeValueAsArray( this->AttributeValues->AddArray(array); // Add to variable to VariableNames - int n = this->VariableNames->GetNumberOfValues(); - int i = 0; + vtkIdType n = this->VariableNames->GetNumberOfValues(); + vtkIdType i = 0; for (i = 0; i < n; i++) { if (strcmp(this->VariableNames->GetValue(i), variable) == 0) @@ -869,12 +893,14 @@ void vtkMINCImageAttributes::SetAttributeValueAsString( const char *attribute, const char *value) { - size_t length = strlen(value)+1; + size_t length = strlen(value); vtkCharArray *array = vtkCharArray::New(); - array->SetNumberOfValues(length); - strcpy(array->GetPointer(0), value); - + // Allocate an extra byte to store a null terminator. + array->Resize(length + 1); + char *dest = array->WritePointer(0, length); + strncpy(dest, value, length); + dest[length] = '\0'; this->SetAttributeValueAsArray(variable, attribute, array); array->Delete(); @@ -1403,8 +1429,8 @@ void vtkMINCImageAttributes::FindValidRange(double range[2]) if (this->DataType == VTK_FLOAT) { // use float precision if VTK_FLOAT - range[0] = (float)range[0]; - range[1] = (float)range[1]; + range[0] = static_cast(range[0]); + range[1] = static_cast(range[1]); } } else @@ -1509,8 +1535,8 @@ void vtkMINCImageAttributes::ShallowCopy(vtkMINCImageAttributes *source) this->AttributeNames->Clear(); vtkStringArray *varnames = source->GetVariableNames(); - int nvar = varnames->GetNumberOfValues(); - for (int ivar = 0; ivar <= nvar; ivar++) + vtkIdType nvar = varnames->GetNumberOfValues(); + for (vtkIdType ivar = 0; ivar <= nvar; ivar++) { // set varname to emtpy last time around to get global attributes const char *varname = MI_EMPTY_STRING; @@ -1519,8 +1545,8 @@ void vtkMINCImageAttributes::ShallowCopy(vtkMINCImageAttributes *source) varname = varnames->GetValue(ivar); } vtkStringArray *attnames = source->GetAttributeNames(varname); - int natt = attnames->GetNumberOfValues(); - for (int iatt = 0; iatt < natt; iatt++) + vtkIdType natt = attnames->GetNumberOfValues(); + for (vtkIdType iatt = 0; iatt < natt; iatt++) { const char *attname = attnames->GetValue(iatt); this->SetAttributeValueAsArray( @@ -1533,4 +1559,3 @@ void vtkMINCImageAttributes::ShallowCopy(vtkMINCImageAttributes *source) this->StringStore->Reset(); } } - diff --git a/IO/MINC/vtkMINCImageReader.cxx b/IO/MINC/vtkMINCImageReader.cxx index 1c2cd29a9e1..2e996fc4eec 100644 --- a/IO/MINC/vtkMINCImageReader.cxx +++ b/IO/MINC/vtkMINCImageReader.cxx @@ -379,10 +379,7 @@ int vtkMINCImageReader::ReadMINCFileAttributes() this->DirectionCosines->Identity(); // Orientation set tells us which direction cosines were found - int orientationSet[3]; - orientationSet[0] = 0; - orientationSet[1] = 0; - orientationSet[2] = 0; + int orientationSet[3] = {0, 0, 0}; this->ImageAttributes->Reset(); @@ -484,11 +481,10 @@ int vtkMINCImageReader::ReadMINCFileAttributes() vtkCharArray *charArray = vtkCharArray::New(); // The netcdf standard doesn't enforce null-termination // of string attributes, so we add a null here. - charArray->SetNumberOfValues(attlength+1); - charArray->SetValue(attlength, 0); - charArray->SetNumberOfValues(attlength); - nc_get_att_text(ncid, varid, attname, - charArray->GetPointer(0)); + charArray->Resize(attlength + 1); + char *dest = charArray->WritePointer(0, attlength); + nc_get_att_text(ncid, varid, attname, dest); + dest[attlength] = '\0'; dataArray = charArray; } break; @@ -586,7 +582,7 @@ int vtkMINCImageReader::ReadMINCFileAttributes() { // Set the orientation matrix from the direction_cosines vtkDoubleArray *doubleArray = - vtkDoubleArray::SafeDownCast( + vtkArrayDownCast( this->ImageAttributes->GetAttributeValueAsArray( dimname, MIdirection_cosines)); if (doubleArray && doubleArray->GetNumberOfTuples() == 3) @@ -703,7 +699,7 @@ int vtkMINCImageReader::ReadMINCFileAttributes() // Get the name from the file name by removing the path and // the extension. const char *fileName = this->FileName; - char name[128]; + char name[4096]; name[0] = '\0'; int startChar = 0; int endChar = static_cast(strlen(fileName)); @@ -835,16 +831,11 @@ void vtkMINCImageReader::ExecuteInformation() } // Set the VTK information from the MINC information. - int dataExtent[6]; - dataExtent[0] = dataExtent[1] = 0; - dataExtent[2] = dataExtent[3] = 0; - dataExtent[4] = dataExtent[5] = 0; + int dataExtent[6] = {0, 0, 0, 0, 0, 0}; - double dataSpacing[3]; - dataSpacing[0] = dataSpacing[1] = dataSpacing[2] = 1.0; + double dataSpacing[3] = {1.0, 1.0, 1.0}; - double dataOrigin[3]; - dataOrigin[0] = dataOrigin[1] = dataOrigin[2] = 0.0; + double dataOrigin[3] = {0.0, 0.0, 0.0}; int numberOfComponents = 1; @@ -895,8 +886,8 @@ void vtkMINCImageReader::ExecuteInformation() vtkIdTypeArray *dimensionLengths = this->ImageAttributes->GetDimensionLengths(); - int numberOfDimensions = dimensionNames->GetNumberOfValues(); - for (int i = 0; i < numberOfDimensions; i++) + unsigned int numberOfDimensions = dimensionNames->GetNumberOfValues(); + for (unsigned int i = 0; i < numberOfDimensions; i++) { const char *dimName = dimensionNames->GetValue(i); vtkIdType dimLength = dimensionLengths->GetValue(i); diff --git a/IO/MINC/vtkMINCImageWriter.cxx b/IO/MINC/vtkMINCImageWriter.cxx index 4fdb8d05137..43dcd3df564 100644 --- a/IO/MINC/vtkMINCImageWriter.cxx +++ b/IO/MINC/vtkMINCImageWriter.cxx @@ -87,6 +87,10 @@ POSSIBILITY OF SUCH DAMAGES. #include #include +#if defined(_MSC_VER) && (_MSC_VER < 1900) +#define snprintf _snprintf +#endif + #define VTK_MINC_MAX_DIMS 8 //-------------------------------------------------------------------------- @@ -437,7 +441,7 @@ std::string vtkMINCImageWriterCreateIdentString() #else int processId = getpid(); #endif - sprintf(buf, "%i%s%i", processId, itemsep, identx++); + snprintf(buf, 1024, "%i%s%i", processId, itemsep, identx++); ident.append(buf); return ident; @@ -494,11 +498,15 @@ nc_type vtkMINCImageWriterConvertVTKTypeToMINCType( } //------------------------------------------------------------------------- -// These macro is only for use in WriteMINCFileAttributes +// These macros are only for use in WriteMINCFileAttributes. + +// Note: Until VTK 7.0, this macro added a terminating null byte to all +// text attributes. As of VTK 7.1, it does not. The attribute length +// should be the string length, not the string length "plus one". #define vtkMINCImageWriterPutAttributeTextMacro(name, text) \ if (status == NC_NOERR) \ { \ - status = nc_put_att_text(ncid, varid, name, strlen(text)+1, text); \ + status = nc_put_att_text(ncid, varid, name, strlen(text), text); \ } #define vtkMINCImageWriterPutAttributeDoubleMacro(name, count, ptr) \ @@ -967,7 +975,7 @@ int vtkMINCImageWriter::CreateMINCVariables( // Don't set valid_range if the default is suitable if (this->ComputeValidRangeFromScalarRange || (this->ImageAttributes && - vtkDoubleArray::SafeDownCast( + vtkArrayDownCast( this->ImageAttributes->GetAttributeValueAsArray( MIimage, MIvalid_range)))) { @@ -1231,7 +1239,7 @@ void vtkMINCImageWriter::FindMINCValidRange(double range[2]) vtkDoubleArray *rangearray = 0; if (this->ImageAttributes) { - rangearray = vtkDoubleArray::SafeDownCast( + rangearray = vtkArrayDownCast( this->ImageAttributes->GetAttributeValueAsArray( MIimage, MIvalid_range)); } diff --git a/IO/MINC/vtkMNIObjectWriter.cxx b/IO/MINC/vtkMNIObjectWriter.cxx index 6a2ce476ef6..096f1fdde34 100644 --- a/IO/MINC/vtkMNIObjectWriter.cxx +++ b/IO/MINC/vtkMNIObjectWriter.cxx @@ -647,7 +647,7 @@ int vtkMNIObjectWriter::WriteColors( rgba[3] = 255; } - newScalars->SetTupleValue(0, rgba); + newScalars->SetTypedTuple(0, rgba); scalars = newScalars; } diff --git a/IO/MINC/vtkMNITagPointReader.cxx b/IO/MINC/vtkMNITagPointReader.cxx index f2f6aa71917..1b26265cb3e 100644 --- a/IO/MINC/vtkMNITagPointReader.cxx +++ b/IO/MINC/vtkMNITagPointReader.cxx @@ -189,7 +189,8 @@ int vtkMNITagPointReader::ReadLineAfterComments( { delete [] this->Comments; this->Comments = new char[comments.length() + 1]; - strcpy(this->Comments, comments.c_str()); + strncpy(this->Comments, comments.c_str(), comments.length()); + this->Comments[comments.length()] = '\0'; return 1; } @@ -661,7 +662,7 @@ vtkStringArray *vtkMNITagPointReader::GetLabelText() if (output) { - return vtkStringArray::SafeDownCast( + return vtkArrayDownCast( output->GetPointData()->GetAbstractArray("LabelText")); } @@ -678,7 +679,7 @@ vtkDoubleArray *vtkMNITagPointReader::GetWeights() if (output) { - return vtkDoubleArray::SafeDownCast( + return vtkArrayDownCast( output->GetPointData()->GetArray("Weights")); } @@ -695,7 +696,7 @@ vtkIntArray *vtkMNITagPointReader::GetStructureIds() if (output) { - return vtkIntArray::SafeDownCast( + return vtkArrayDownCast( output->GetPointData()->GetArray("StructureIds")); } @@ -712,7 +713,7 @@ vtkIntArray *vtkMNITagPointReader::GetPatientIds() if (output) { - return vtkIntArray::SafeDownCast( + return vtkArrayDownCast( output->GetPointData()->GetArray("PatientIds")); } diff --git a/IO/MINC/vtkMNITagPointWriter.cxx b/IO/MINC/vtkMNITagPointWriter.cxx index eb9bbdc8e07..74707b3a8ba 100644 --- a/IO/MINC/vtkMNITagPointWriter.cxx +++ b/IO/MINC/vtkMNITagPointWriter.cxx @@ -237,7 +237,7 @@ void vtkMNITagPointWriter::WriteData(vtkPointSet *inputs[2]) { points[ii] = inputs[ii]->GetPoints(); - vtkStringArray *stringArray = vtkStringArray::SafeDownCast( + vtkStringArray *stringArray = vtkArrayDownCast( inputs[ii]->GetPointData()->GetAbstractArray("LabelText")); if (stringArray) { diff --git a/IO/MINC/vtkMNITransformReader.cxx b/IO/MINC/vtkMNITransformReader.cxx index 283b802a205..f569240e88c 100644 --- a/IO/MINC/vtkMNITransformReader.cxx +++ b/IO/MINC/vtkMNITransformReader.cxx @@ -205,7 +205,8 @@ int vtkMNITransformReader::ReadLineAfterComments( { delete [] this->Comments; this->Comments = new char[comments.length() + 1]; - strcpy(this->Comments, comments.c_str()); + strncpy(this->Comments, comments.c_str(), comments.length()); + this->Comments[comments.length()] = '\0'; return 1; } } diff --git a/IO/MPIImage/vtkPNrrdReader.cxx b/IO/MPIImage/vtkPNrrdReader.cxx index f9c4d879abf..a78a9da7f37 100644 --- a/IO/MPIImage/vtkPNrrdReader.cxx +++ b/IO/MPIImage/vtkPNrrdReader.cxx @@ -26,6 +26,7 @@ #include "vtkObjectFactory.h" #include "vtkStringArray.h" +#include #include #include #include @@ -308,16 +309,25 @@ void vtkPNrrdReader::ReadSlice(int slice, const int extent[6], void *buffer) length *= extent[3]-extent[2]+1; if (this->GetFileDimensionality() == 3) length *= extent[5]-extent[4]+1; - if (length > VTK_INT_MAX) + vtkIdType pos = 0; + while (length > pos) { - vtkErrorMacro(<< "Cannot read more than " << VTK_INT_MAX - << " bytes at a time."); + MPI_Status stat; + // we know this will fit in an int because it can't exceed VTK_INT_MAX. + const int remaining = std::min(static_cast(length - pos), + static_cast(VTK_INT_MAX)); + MPICall(MPI_File_read(file.Handle, (static_cast(buffer)) + pos, remaining, + MPI_BYTE, &stat)); + int rd = 0; + MPICall(MPI_Get_elements(&stat, MPI_BYTE, &rd)); + if (MPI_UNDEFINED == rd) + { + vtkErrorMacro("Error obtaining number of values read in " << remaining << + "-byte read."); + } + pos += static_cast(rd); } - // Do the read. This is a coordinated parallel operation for efficiency. - MPICall(MPI_File_read_all(file.Handle, buffer, static_cast(length), - MPI_BYTE, MPI_STATUS_IGNORE)); - MPICall(MPI_File_close(&file.Handle)); } #else // VTK_USE_MPI_IO diff --git a/IO/MPIParallel/vtkMPIMultiBlockPLOT3DReader.cxx b/IO/MPIParallel/vtkMPIMultiBlockPLOT3DReader.cxx index 4740e3871a5..c76232fdb23 100644 --- a/IO/MPIParallel/vtkMPIMultiBlockPLOT3DReader.cxx +++ b/IO/MPIParallel/vtkMPIMultiBlockPLOT3DReader.cxx @@ -15,18 +15,21 @@ #include "vtkMPIMultiBlockPLOT3DReader.h" #include "vtkByteSwap.h" -#include "vtkDataArrayDispatcher.h" +#include "vtkDoubleArray.h" #include "vtkErrorCode.h" +#include "vtkFloatArray.h" +#include "vtkIntArray.h" #include "vtkMPICommunicator.h" #include "vtkMPIController.h" #include "vtkMPI.h" #include "vtkMultiBlockPLOT3DReaderInternals.h" #include "vtkObjectFactory.h" #include "vtkStructuredData.h" - #include #include + + #define DEFINE_MPI_TYPE(ctype, mpitype) \ template <> struct mpi_type { static MPI_Datatype type() { return mpitype; } }; @@ -51,132 +54,121 @@ namespace { }; - class SetupFileViewFunctor + template + class vtkMPIPLOT3DArrayReader { - vtkMPICommunicatorOpaqueComm& Communicator; - vtkMPIOpaqueFileHandle& Handle; - int Extent[6]; - int WExtent[6]; - vtkTypeUInt64 Offset; - int ByteOrder; - public: - SetupFileViewFunctor( - vtkMPICommunicatorOpaqueComm& comm, - vtkMPIOpaqueFileHandle& handle, - const int extent[6], const int wextent[6], vtkTypeUInt64 offset, int byteOrder) - : Communicator(comm), Handle(handle), Offset(offset), ByteOrder(byteOrder) + vtkMPIPLOT3DArrayReader() : ByteOrder( + vtkMultiBlockPLOT3DReader::FILE_BIG_ENDIAN) { - std::copy(extent, extent+6, this->Extent); - std::copy(wextent, wextent+6, this->WExtent); } - template - void operator()(vtkDataArrayDispatcherPointer array) const - { - int array_of_sizes[3]; - int array_of_subsizes[3]; - int array_of_starts[3]; - for (int cc=0; cc < 3; ++cc) + vtkIdType ReadScalar(void* vfp, + vtkTypeUInt64 offset, + vtkIdType preskip, + vtkIdType n, + vtkIdType vtkNotUsed(postskip), + DataType* scalar, + const vtkMultiBlockPLOT3DReaderRecord& record = vtkMultiBlockPLOT3DReaderRecord()) { - array_of_sizes[cc] = this->WExtent[cc*2+1] - this->WExtent[cc*2] + 1; - array_of_subsizes[cc] = this->Extent[cc*2+1] - this->Extent[cc*2] + 1; - array_of_starts[cc] = this->Extent[cc*2]; - } + vtkMPIOpaqueFileHandle* fp = reinterpret_cast(vfp); + assert(fp); - // Define the file type for this process. - MPI_Datatype filetype; - if (MPI_Type_create_subarray(3, - array_of_sizes, - array_of_subsizes, - array_of_starts, - MPI_ORDER_FORTRAN, - mpi_type::type(), - &filetype) != MPI_SUCCESS) - { - throw MPIPlot3DException(); - } - MPI_Type_commit(&filetype); + // skip preskip if we're setting over subrecord separators. + offset += record.GetLengthWithSeparators(offset, preskip*sizeof(DataType)); - // For each component. - const vtkIdType valuesToRead = vtkStructuredData::GetNumberOfPoints( - const_cast(this->Extent)); - const vtkIdType valuesTotal = vtkStructuredData::GetNumberOfPoints( - const_cast(this->WExtent)); + // Let's see if we encounter markers while reading the data from current + // position. + std::vector > chunks = + record.GetChunksToRead(offset, sizeof(DataType) * n); - const int _INT_MAX = 2e9 / sizeof(T); /// XXX: arbitrary limit that seems - /// to work when reading large files. + const int dummy_INT_MAX = 2e9; /// XXX: arbitrary limit that seems + /// to work when reading large files. + vtkIdType bytesread = 0; + for (size_t cc=0; cc < chunks.size(); cc++) + { + vtkTypeUInt64 start = chunks[cc].first; + vtkTypeUInt64 length = chunks[cc].second; + while (length > 0) + { + int segment = length > static_cast(dummy_INT_MAX)? + (length - dummy_INT_MAX) : static_cast(length); - int numIterations = static_cast(valuesToRead/_INT_MAX) + 1; - int maxNumIterations; - if (MPI_Allreduce(&numIterations, &maxNumIterations, 1, mpi_type::type(), - MPI_MAX, *this->Communicator.GetHandle()) != MPI_SUCCESS) - { - throw MPIPlot3DException(); - } + MPI_Status status; + if (MPI_File_read_at(fp->Handle, start, + reinterpret_cast(scalar) + bytesread, + segment, MPI_UNSIGNED_CHAR, &status) != MPI_SUCCESS) + { + return 0; // let's assume nothing was read. + } + start += segment; + length -= segment; + bytesread += segment; + } + } - vtkTypeUInt64 byteOffset = this->Offset; - // simply use the VTK array for scalars. - T *buffer = array.NumberOfComponents == 1? array.RawPointer : new T[valuesToRead]; - try - { - for (int comp=0; comp < array.NumberOfComponents; ++comp) + if (this->ByteOrder == vtkMultiBlockPLOT3DReader::FILE_LITTLE_ENDIAN) { - // Define the view. - if (MPI_File_set_view(this->Handle.Handle, byteOffset, mpi_type::type(), - filetype, const_cast("native"), MPI_INFO_NULL) != MPI_SUCCESS) + if (sizeof(DataType) == 4) { - throw MPIPlot3DException(); + vtkByteSwap::Swap4LERange(scalar, n); } - - // Read contents from the file in 2GB chunks. - vtkIdType valuesRead = 0; - for (int iteration = 0; iteration < maxNumIterations; ++iteration) + else { - vtkIdType valuesToReadInIteration = - std::min((valuesToRead - valuesRead), static_cast(_INT_MAX)); - if (MPI_File_read_all(this->Handle.Handle, buffer + valuesRead, - static_cast(valuesToReadInIteration), - mpi_type::type(), MPI_STATUS_IGNORE) != MPI_SUCCESS) - { - throw MPIPlot3DException(); - } - valuesRead += valuesToReadInIteration; + vtkByteSwap::Swap8LERange(scalar, n); } - if (buffer != array.RawPointer) + } + else + { + if (sizeof(DataType) == 4) { - for (vtkIdType i=0; i < valuesToRead; ++i) - { - array.RawPointer[array.NumberOfComponents*i + comp] = buffer[i]; - } + vtkByteSwap::Swap4BERange(scalar, n); + } + else + { + vtkByteSwap::Swap8BERange(scalar, n); } - byteOffset += valuesTotal * sizeof(T); } + return bytesread / sizeof(DataType); } - catch (MPIPlot3DException) + + vtkIdType ReadVector(void* vfp, + vtkTypeUInt64 offset, + int extent[6], int wextent[6], + int numDims, DataType* vector, + const vtkMultiBlockPLOT3DReaderRecord &record) { - if (buffer != array.RawPointer) + vtkIdType n = vtkStructuredData::GetNumberOfPoints(extent); + vtkIdType totalN = vtkStructuredData::GetNumberOfPoints(wextent); + + // Setting to 0 in case numDims == 0. We still need to + // populate an array with 3 components but the code below + // does not read the 3rd component (it doesn't exist + // in the file) + memset(vector, 0, n*3*sizeof(DataType)); + + vtkIdType retVal = 0; + DataType* buffer = new DataType[n]; + for (int component = 0; component < numDims; component++) { - delete [] buffer; + vtkIdType preskip, postskip; + vtkMultiBlockPLOT3DReaderInternals::CalculateSkips(extent, wextent, preskip, postskip); + vtkIdType valread = this->ReadScalar(vfp, offset, preskip, n, postskip, buffer, record); + if (valread != n) + { + return 0; // failed. + } + retVal += valread; + for (vtkIdType i=0; iByteOrder == vtkMultiBlockPLOT3DReader::FILE_LITTLE_ENDIAN) - { - vtkByteSwap::SwapLERange(array.RawPointer, array.NumberOfComponents*array.NumberOfTuples); - } - else - { - vtkByteSwap::SwapBERange(array.RawPointer, array.NumberOfComponents*array.NumberOfTuples); - } - } + int ByteOrder; }; } @@ -254,76 +246,92 @@ void vtkMPIMultiBlockPLOT3DReader::CloseFile(void* vfp) //---------------------------------------------------------------------------- int vtkMPIMultiBlockPLOT3DReader::ReadIntScalar( void* vfp, int extent[6], int wextent[6], - vtkDataArray* scalar, vtkTypeUInt64 offset) + vtkDataArray* scalar, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& record) + { if (!this->CanUseMPIIO()) { - return this->Superclass::ReadIntScalar(vfp, extent, wextent, scalar, offset); + return this->Superclass::ReadIntScalar(vfp, extent, wextent, scalar, offset, record); } - return this->ReadScalar(vfp, extent, wextent, scalar, offset); + vtkIdType n = vtkStructuredData::GetNumberOfPoints(extent); + vtkMPIPLOT3DArrayReader arrayReader; + arrayReader.ByteOrder = this->Internal->Settings.ByteOrder; + vtkIdType preskip, postskip; + vtkMultiBlockPLOT3DReaderInternals::CalculateSkips(extent, wextent, preskip, postskip); + vtkIntArray* intArray = static_cast(scalar); + return arrayReader.ReadScalar( + vfp, offset, preskip, n, postskip, intArray->GetPointer(0), record) == n; } //---------------------------------------------------------------------------- int vtkMPIMultiBlockPLOT3DReader::ReadScalar( - void* vfp, - int extent[6], int wextent[6], - vtkDataArray* scalar, vtkTypeUInt64 offset) + void* vfp, + int extent[6], int wextent[6], + vtkDataArray* scalar, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& record) { if (!this->CanUseMPIIO()) { - return this->Superclass::ReadScalar(vfp, extent, wextent, scalar, offset); + return this->Superclass::ReadScalar(vfp, extent, wextent, scalar, offset, record); } - vtkMPIOpaqueFileHandle* handle = reinterpret_cast(vfp); - assert(handle); - - vtkMPICommunicatorOpaqueComm* comm = - vtkMPICommunicator::SafeDownCast(this->Controller->GetCommunicator())->GetMPIComm(); - assert(comm); - - SetupFileViewFunctor work(*comm, *handle, extent, wextent, offset, this->Internal->Settings.ByteOrder); - vtkDataArrayDispatcher dispatcher(work); - try + vtkIdType n = vtkStructuredData::GetNumberOfPoints(extent); + if (this->Internal->Settings.Precision == 4) { - dispatcher.Go(scalar); + vtkMPIPLOT3DArrayReader arrayReader; + arrayReader.ByteOrder = this->Internal->Settings.ByteOrder; + vtkIdType preskip, postskip; + vtkMultiBlockPLOT3DReaderInternals::CalculateSkips(extent, wextent, preskip, postskip); + vtkFloatArray* floatArray = static_cast(scalar); + return arrayReader.ReadScalar( + vfp, offset, preskip, n, postskip, floatArray->GetPointer(0), + record) == n; } - catch (MPIPlot3DException) + else { - return 0; + vtkMPIPLOT3DArrayReader arrayReader; + arrayReader.ByteOrder = this->Internal->Settings.ByteOrder; + vtkIdType preskip, postskip; + vtkMultiBlockPLOT3DReaderInternals::CalculateSkips(extent, wextent, preskip, postskip); + vtkDoubleArray* doubleArray = static_cast(scalar); + return arrayReader.ReadScalar( + vfp, offset, preskip, n, postskip, doubleArray->GetPointer(0), + record) == n; } - return 1; } //---------------------------------------------------------------------------- int vtkMPIMultiBlockPLOT3DReader::ReadVector( void* vfp, int extent[6], int wextent[6], - int numDims, vtkDataArray* vector, vtkTypeUInt64 offset) + int numDims, vtkDataArray* vector, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& record) { if (!this->CanUseMPIIO()) { - return this->Superclass::ReadVector(vfp, extent, wextent, numDims, vector, offset); + return this->Superclass::ReadVector(vfp, extent, wextent, numDims, vector, offset, record); } - vtkMPIOpaqueFileHandle* handle = reinterpret_cast(vfp); - assert(handle); - - vtkMPICommunicatorOpaqueComm* comm = - vtkMPICommunicator::SafeDownCast(this->Controller->GetCommunicator())->GetMPIComm(); - assert(comm); - - SetupFileViewFunctor work(*comm, *handle, extent, wextent, offset, this->Internal->Settings.ByteOrder); - vtkDataArrayDispatcher dispatcher(work); - try + vtkIdType n = vtkStructuredData::GetNumberOfPoints(extent); + vtkIdType nValues = n*numDims; + if (this->Internal->Settings.Precision == 4) { - dispatcher.Go(vector); + vtkMPIPLOT3DArrayReader arrayReader; + arrayReader.ByteOrder = this->Internal->Settings.ByteOrder; + vtkFloatArray* floatArray = static_cast(vector); + return arrayReader.ReadVector( + vfp, offset, extent, wextent, numDims, floatArray->GetPointer(0), record) == nValues; } - catch (MPIPlot3DException) + else { - return 0; + vtkMPIPLOT3DArrayReader arrayReader; + arrayReader.ByteOrder = this->Internal->Settings.ByteOrder; + vtkDoubleArray* doubleArray = static_cast(vector); + return arrayReader.ReadVector( + vfp, offset, extent, wextent, numDims, doubleArray->GetPointer(0), record) == nValues; } - return 1; } //---------------------------------------------------------------------------- diff --git a/IO/MPIParallel/vtkMPIMultiBlockPLOT3DReader.h b/IO/MPIParallel/vtkMPIMultiBlockPLOT3DReader.h index 4692d5ba49c..91420c9b16d 100644 --- a/IO/MPIParallel/vtkMPIMultiBlockPLOT3DReader.h +++ b/IO/MPIParallel/vtkMPIMultiBlockPLOT3DReader.h @@ -54,16 +54,18 @@ class VTKIOMPIPARALLEL_EXPORT vtkMPIMultiBlockPLOT3DReader : public vtkMultiBloc virtual int ReadIntScalar( void* vfp, int extent[6], int wextent[6], - vtkDataArray* scalar, vtkTypeUInt64 offset); + vtkDataArray* scalar, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& currentRecord); virtual int ReadScalar( void* vfp, int extent[6], int wextent[6], - vtkDataArray* scalar, vtkTypeUInt64 offset); + vtkDataArray* scalar, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& currentRecord); virtual int ReadVector( void* vfp, int extent[6], int wextent[6], - int numDims, vtkDataArray* vector, vtkTypeUInt64 offset); - + int numDims, vtkDataArray* vector, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& currentRecord); bool UseMPIIO; private: vtkMPIMultiBlockPLOT3DReader(const vtkMPIMultiBlockPLOT3DReader&); // Not implemented. diff --git a/IO/Movie/vtkGenericMovieWriter.h b/IO/Movie/vtkGenericMovieWriter.h index 4f4148c86e3..e0dc51bea66 100644 --- a/IO/Movie/vtkGenericMovieWriter.h +++ b/IO/Movie/vtkGenericMovieWriter.h @@ -56,7 +56,6 @@ class VTKIOMOVIE_EXPORT vtkGenericMovieWriter : public vtkImageAlgorithm // Converts vtkErrorCodes and vtkGenericMovieWriter errors to strings. static const char *GetStringFromErrorCode(unsigned long event); - //BTX enum MovieWriterErrorIds { UserError = 40000, //must match vtkErrorCode::UserError InitError, @@ -65,7 +64,6 @@ class VTKIOMOVIE_EXPORT vtkGenericMovieWriter : public vtkImageAlgorithm CanNotFormat, ChangedResolutionError }; - //ETX protected: vtkGenericMovieWriter(); diff --git a/IO/MySQL/vtkMySQLDatabase.h b/IO/MySQL/vtkMySQLDatabase.h index f533b614ffb..1148d7a5387 100644 --- a/IO/MySQL/vtkMySQLDatabase.h +++ b/IO/MySQL/vtkMySQLDatabase.h @@ -43,9 +43,8 @@ class vtkMySQLDatabasePrivate; class VTKIOMYSQL_EXPORT vtkMySQLDatabase : public vtkSQLDatabase { -//BTX + friend class vtkMySQLQuery; -//ETX public: vtkTypeMacro(vtkMySQLDatabase, vtkSQLDatabase); @@ -201,9 +200,7 @@ class VTKIOMYSQL_EXPORT vtkMySQLDatabase : public vtkSQLDatabase int ServerPort; int Reconnect; -//BTX vtkMySQLDatabasePrivate* const Private; -//ETX vtkMySQLDatabase(const vtkMySQLDatabase &); // Not implemented. void operator=(const vtkMySQLDatabase &); // Not implemented. diff --git a/IO/MySQL/vtkMySQLQuery.cxx b/IO/MySQL/vtkMySQLQuery.cxx index a97b5891dfc..b4e6b62a454 100644 --- a/IO/MySQL/vtkMySQLQuery.cxx +++ b/IO/MySQL/vtkMySQLQuery.cxx @@ -25,7 +25,7 @@ #include -#if defined(WIN32) +#if defined(_WIN32) # include # include # define LOWERCASE_COMPARE _stricmp diff --git a/IO/MySQL/vtkMySQLQuery.h b/IO/MySQL/vtkMySQLQuery.h index e522e379828..454c61e09fa 100644 --- a/IO/MySQL/vtkMySQLQuery.h +++ b/IO/MySQL/vtkMySQLQuery.h @@ -43,9 +43,8 @@ class vtkMySQLQueryInternals; class VTKIOMYSQL_EXPORT vtkMySQLQuery : public vtkSQLQuery { -//BTX + friend class vtkMySQLDatabase; -//ETX public: vtkTypeMacro(vtkMySQLQuery, vtkSQLQuery); @@ -106,21 +105,21 @@ class VTKIOMYSQL_EXPORT vtkMySQLQuery : public vtkSQLQuery // further explanation. The driver makes internal copies of string // and BLOB parameters so you don't need to worry about keeping them // in scope until the query finishes executing. -//BTX + using vtkSQLQuery::BindParameter; bool BindParameter(int index, unsigned char value); bool BindParameter(int index, signed char value); bool BindParameter(int index, unsigned short value); bool BindParameter(int index, signed short value); bool BindParameter(int index, unsigned int value); -//ETX + bool BindParameter(int index, int value); -//BTX + bool BindParameter(int index, unsigned long value); bool BindParameter(int index, signed long value); bool BindParameter(int index, vtkTypeUInt64 value); bool BindParameter(int index, vtkTypeInt64 value); -//ETX + bool BindParameter(int index, float value); bool BindParameter(int index, double value); // Description: diff --git a/IO/NetCDF/vtkMPASReader.cxx b/IO/NetCDF/vtkMPASReader.cxx index 0af22e7eed8..be7950847b4 100644 --- a/IO/NetCDF/vtkMPASReader.cxx +++ b/IO/NetCDF/vtkMPASReader.cxx @@ -2381,7 +2381,7 @@ void vtkMPASReader::LoadTimeFieldData(vtkUnstructuredGrid *dataset) if (vtkDataArray *da = fd->GetArray("Time")) { - if (!(array = vtkStringArray::SafeDownCast(da))) + if (!(array = vtkArrayDownCast(da))) { vtkWarningMacro("Not creating \"Time\" field data array: a data array " "with this name already exists."); diff --git a/IO/NetCDF/vtkNetCDFCFReader.h b/IO/NetCDF/vtkNetCDFCFReader.h index e93c16436bb..0177a66ee69 100644 --- a/IO/NetCDF/vtkNetCDFCFReader.h +++ b/IO/NetCDF/vtkNetCDFCFReader.h @@ -115,15 +115,12 @@ class VTKIONETCDF_EXPORT vtkNetCDFCFReader : public vtkNetCDFReader vtkInformationVector **inputVector, vtkInformationVector *outputVector); -//BTX // Description: // Interprets the special conventions of COARDS. virtual int ReadMetaData(int ncFD); virtual int IsTimeDimension(int ncFD, int dimId); virtual vtkSmartPointer GetTimeValues(int ncFD, int dimId); -//ETX -//BTX class vtkDimensionInfo { public: vtkDimensionInfo() { }; @@ -202,7 +199,6 @@ class VTKIONETCDF_EXPORT vtkNetCDFCFReader : public vtkNetCDFReader // Finds the dependent dimension information for the given set of dimensions. // Returns NULL if no information has been recorded. vtkDependentDimensionInfo *FindDependentDimensionInfo(vtkIntArray *dims); -//ETX // Description: // Given the list of dimensions, identify the longitude, latitude, and diff --git a/IO/NetCDF/vtkNetCDFReader.cxx b/IO/NetCDF/vtkNetCDFReader.cxx index c9f115931fc..2f57cdba146 100644 --- a/IO/NetCDF/vtkNetCDFReader.cxx +++ b/IO/NetCDF/vtkNetCDFReader.cxx @@ -242,22 +242,33 @@ int vtkNetCDFReader::RequestInformation( compositeTimeValues->SetNumberOfComponents(1); while ((oldTime < oldTimeEnd) || (newTime < newTimeEnd)) { + double nextTimeValue; if ( (newTime >= newTimeEnd) || ((oldTime < oldTimeEnd) && (*oldTime < *newTime)) ) { - compositeTimeValues->InsertNextTuple1(*oldTime); + nextTimeValue = *oldTime; oldTime++; } else if ((oldTime >= oldTimeEnd) || (*newTime < *oldTime)) { - compositeTimeValues->InsertNextTuple1(*newTime); + nextTimeValue = *newTime; newTime++; } else // *oldTime == *newTime { - compositeTimeValues->InsertNextTuple1(*oldTime); + nextTimeValue = *oldTime; oldTime++; newTime++; } + compositeTimeValues->InsertNextTuple1(nextTimeValue); + + // Obviously, time values should be monotonically increasing. If they + // are not, that is indicative of an error. Often this means just a + // garbage time slice. Because we still want to see the other time + // slices, just dump those with bad time values. + while ((newTime < newTimeEnd) && (*newTime <= nextTimeValue)) + { + newTime++; + } } timeValues = compositeTimeValues; diff --git a/IO/NetCDF/vtkNetCDFReader.h b/IO/NetCDF/vtkNetCDFReader.h index 0b9fe2ab527..32290d0184a 100644 --- a/IO/NetCDF/vtkNetCDFReader.h +++ b/IO/NetCDF/vtkNetCDFReader.h @@ -133,7 +133,6 @@ class VTKIONETCDF_EXPORT vtkNetCDFReader : public vtkDataObjectAlgorithm vtkTimeStamp FileNameMTime; vtkTimeStamp MetaDataMTime; -//BTX // Description: // The dimension ids of the arrays being loaded into the data. vtkSmartPointer LoadingDimensions; @@ -149,7 +148,6 @@ class VTKIONETCDF_EXPORT vtkNetCDFReader : public vtkDataObjectAlgorithm // Description: // Placeholder for structure returned from GetAllDimensions(). vtkStringArray *AllDimensions; -//ETX int ReplaceFillValueWithNan; @@ -193,7 +191,6 @@ class VTKIONETCDF_EXPORT vtkNetCDFReader : public vtkDataObjectAlgorithm // a given file. virtual int IsTimeDimension(int ncFD, int dimId); -//BTX // Description: // Given a dimension already determined to be a time dimension (via a call to // IsTimeDimension) returns an array with time values. The default @@ -201,7 +198,6 @@ class VTKIONETCDF_EXPORT vtkNetCDFReader : public vtkDataObjectAlgorithm // should override this function if there is a convention that identifies time // values. This method returns 0 on error, 1 otherwise. virtual vtkSmartPointer GetTimeValues(int ncFD, int dimId); -//ETX // Description: // Called internally to determine whether a variable with the given set of diff --git a/IO/NetCDF/vtkSLACReader.cxx b/IO/NetCDF/vtkSLACReader.cxx index 70992b9ed45..24195ba8494 100644 --- a/IO/NetCDF/vtkSLACReader.cxx +++ b/IO/NetCDF/vtkSLACReader.cxx @@ -246,12 +246,13 @@ class vtkSLACReaderAutoCloseNetCDF (*this->ReferenceCount)++; } - void operator=(const vtkSLACReaderAutoCloseNetCDF &src) + vtkSLACReaderAutoCloseNetCDF& operator=(const vtkSLACReaderAutoCloseNetCDF &src) { this->UnReference(); this->FileDescriptor = src.FileDescriptor; this->ReferenceCount = src.ReferenceCount; (*this->ReferenceCount)++; + return *this; } operator int() const { return this->FileDescriptor; } @@ -1280,7 +1281,7 @@ int vtkSLACReader::ReadConnectivity(int meshFD, // winding, but it should be consistent through the mesh. The invertTets // flag set earlier indicates whether we need to invert the tetrahedra. vtkIdType tetInfo[NumPerTetInt]; - connectivity->GetTupleValue(i, tetInfo); + connectivity->GetTypedTuple(i, tetInfo); if (invertTets) std::swap(tetInfo[1], tetInfo[2]); vtkUnstructuredGrid *ugrid = AllocateGetBlock(volumeOutput, tetInfo[0], IS_INTERNAL_VOLUME()); @@ -1300,7 +1301,7 @@ int vtkSLACReader::ReadConnectivity(int meshFD, // when the face is internal. Other flags separate faces in a multiblock // data set. vtkIdType tetInfo[NumPerTetExt]; - connectivity->GetTupleValue(i, tetInfo); + connectivity->GetTypedTuple(i, tetInfo); if (invertTets) { std::swap(tetInfo[1], tetInfo[2]); // Invert point indices diff --git a/IO/NetCDF/vtkSLACReader.h b/IO/NetCDF/vtkSLACReader.h index 860032b454a..fe4911c4b79 100644 --- a/IO/NetCDF/vtkSLACReader.h +++ b/IO/NetCDF/vtkSLACReader.h @@ -126,7 +126,6 @@ class VTKIONETCDF_EXPORT vtkSLACReader : public vtkMultiBlockDataSetAlgorithm static vtkInformationObjectBaseKey *POINTS(); static vtkInformationObjectBaseKey *POINT_DATA(); -//BTX // Description: // Simple class used internally to define an edge based on the endpoints. The // endpoints are canonically identified by the lower and higher values. @@ -176,13 +175,11 @@ class VTKIONETCDF_EXPORT vtkSLACReader : public vtkMultiBlockDataSetAlgorithm VOLUME_OUTPUT = 1, NUM_OUTPUTS = 2 }; -//ETX protected: vtkSLACReader(); ~vtkSLACReader(); -//BTX class vtkInternal; vtkInternal *Internal; @@ -208,8 +205,6 @@ class VTKIONETCDF_EXPORT vtkSLACReader : public vtkMultiBlockDataSetAlgorithm // True if mode files describe vibrating fields. bool FrequencyModes; -//ETX - virtual int RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector); @@ -250,22 +245,17 @@ class VTKIONETCDF_EXPORT vtkSLACReader : public vtkMultiBlockDataSetAlgorithm virtual int ReadTetrahedronExteriorArray(int meshFD, vtkIdTypeArray *connectivity); -//BTX // Description: // Reads point data arrays. Called by ReadCoordinates and ReadFieldData. virtual vtkSmartPointer ReadPointDataArray(int ncFD, int varId); -//ETX -//BTX // Description: // Helpful constants equal to the amount of identifiers per tet. enum { NumPerTetInt = 5, NumPerTetExt = 9 }; -//ETX -//BTX // Description: // Manages a map from edges to midpoint coordinates. class VTKIONETCDF_EXPORT MidpointCoordinateMap @@ -328,7 +318,6 @@ class VTKIONETCDF_EXPORT vtkSLACReader : public vtkMultiBlockDataSetAlgorithm MidpointIdMap(const MidpointIdMap &); void operator=(const MidpointIdMap &); }; -//ETX // Description: // Read in the point coordinate data from the mesh file. Returns 1 on diff --git a/IO/ODBC/vtkODBCDatabase.h b/IO/ODBC/vtkODBCDatabase.h index d5609135646..8229d96182c 100644 --- a/IO/ODBC/vtkODBCDatabase.h +++ b/IO/ODBC/vtkODBCDatabase.h @@ -76,9 +76,8 @@ class vtkODBCInternals; class VTKIOODBC_EXPORT vtkODBCDatabase : public vtkSQLDatabase { -//BTX + friend class vtkODBCQuery; -//ETX public: vtkTypeMacro(vtkODBCDatabase, vtkSQLDatabase); diff --git a/IO/ODBC/vtkODBCQuery.h b/IO/ODBC/vtkODBCQuery.h index 4014d3f3c5f..ce84f0d7439 100644 --- a/IO/ODBC/vtkODBCQuery.h +++ b/IO/ODBC/vtkODBCQuery.h @@ -44,9 +44,8 @@ class vtkODBCQueryInternals; class VTKIOODBC_EXPORT vtkODBCQuery : public vtkSQLQuery { -//BTX + friend class vtkODBCDatabase; -//ETX public: vtkTypeMacro(vtkODBCQuery, vtkSQLQuery); @@ -106,21 +105,21 @@ class VTKIOODBC_EXPORT vtkODBCQuery : public vtkSQLQuery // further explanation. The driver makes internal copies of string // and BLOB parameters so you don't need to worry about keeping them // in scope until the query finishes executing. -//BTX + using vtkSQLQuery::BindParameter; bool BindParameter(int index, unsigned char value); bool BindParameter(int index, signed char value); bool BindParameter(int index, unsigned short value); bool BindParameter(int index, signed short value); bool BindParameter(int index, unsigned int value); -//ETX + bool BindParameter(int index, int value); -//BTX + bool BindParameter(int index, unsigned long value); bool BindParameter(int index, signed long value); bool BindParameter(int index, vtkTypeUInt64 value); bool BindParameter(int index, vtkTypeInt64 value); -//ETX + bool BindParameter(int index, float value); bool BindParameter(int index, double value); // Description: diff --git a/IO/PLY/Testing/Cxx/TestPLYWriter.cxx b/IO/PLY/Testing/Cxx/TestPLYWriter.cxx index 3bdf86d1d7b..15944ac5251 100644 --- a/IO/PLY/Testing/Cxx/TestPLYWriter.cxx +++ b/IO/PLY/Testing/Cxx/TestPLYWriter.cxx @@ -103,8 +103,8 @@ int TestPLYWriter(int argc, char *argv[]) return EXIT_FAILURE; } - vtkFloatArray * inputArray = vtkFloatArray::SafeDownCast(data->GetPointData()->GetTCoords()); - vtkFloatArray * outputArray = vtkFloatArray::SafeDownCast(tCoords); + vtkFloatArray * inputArray = vtkArrayDownCast(data->GetPointData()->GetTCoords()); + vtkFloatArray * outputArray = vtkArrayDownCast(tCoords); if (!inputArray || !outputArray) { std::cout << "Texture coordinates are not of float type." << std::endl; diff --git a/IO/PLY/vtkPLYWriter.cxx b/IO/PLY/vtkPLYWriter.cxx index 3f1bc956e0e..43aa369195a 100644 --- a/IO/PLY/vtkPLYWriter.cxx +++ b/IO/PLY/vtkPLYWriter.cxx @@ -305,7 +305,7 @@ unsigned char *vtkPLYWriter::GetColors(vtkIdType num, { return NULL; } - else if ( (rgbArray=vtkUnsignedCharArray::SafeDownCast(da)) != NULL && + else if ( (rgbArray=vtkArrayDownCast(da)) != NULL && numComp == 3 ) {//have unsigned char array of three components, copy it colors = c = new unsigned char[3*num]; @@ -318,6 +318,21 @@ unsigned char *vtkPLYWriter::GetColors(vtkIdType num, } return colors; } + else if ( (rgbArray=vtkArrayDownCast(da)) != NULL && + numComp == 4 ) + {//have unsigned char array of four components (RGBA), copy it without the `A`. + colors = c = new unsigned char[3*num]; + const unsigned char *rgba = rgbArray->GetPointer(0); + for (i=0; iLookupTable != NULL ) {//use the data array mapped through lookup table colors = c = new unsigned char[3*num]; @@ -346,7 +361,7 @@ const float *vtkPLYWriter::GetTextureCoordinates(vtkIdType num, vtkDataSetAttrib return NULL; vtkFloatArray *textureArray; - if ( (textureArray = vtkFloatArray::SafeDownCast(tCoords)) == NULL ) + if ( (textureArray = vtkArrayDownCast(tCoords)) == NULL ) vtkErrorMacro(<< "PLY writer only supports float texture coordinates"); return textureArray->GetPointer(0); diff --git a/IO/PLY/vtkPLYWriter.h b/IO/PLY/vtkPLYWriter.h index 72bab0eb7e5..7e8bafeab38 100644 --- a/IO/PLY/vtkPLYWriter.h +++ b/IO/PLY/vtkPLYWriter.h @@ -20,7 +20,7 @@ // As for PointData and CellData, vtkPLYWriter cannot handle normals or // vectors. It only handles RGB PointData and CellData. You need to set the // name of the array (using SetName for the array and SetArrayName for the -// writer). If the array is not a vtkUnsignedCharArray with 3 components, +// writer). If the array is not a vtkUnsignedCharArray with 3 or 4 components, // you need to specify a vtkLookupTable to map the scalars to RGB. // .SECTION Caveats @@ -77,7 +77,9 @@ class VTKIOPLY_EXPORT vtkPLYWriter : public vtkWriter // output file. The default behavior is as follows. The user provides the // name of an array and a component number. If the type of the array is // three components, unsigned char, then the data is written as three - // separate "red", "green" and "blue" properties. If the type is not + // separate "red", "green" and "blue" properties. If the type of the array is + // four components, unsigned char, then the data is written as three separate + // "red", "green" and "blue" properties, dropping the "alpha". If the type is not // unsigned char, and a lookup table is provided, then the array/component // are mapped through the table to generate three separate "red", "green" // and "blue" properties in the PLY file. The user can also set the diff --git a/IO/Parallel/vtkEnSightWriter.cxx b/IO/Parallel/vtkEnSightWriter.cxx index 71b3693aafc..46562620a9e 100644 --- a/IO/Parallel/vtkEnSightWriter.cxx +++ b/IO/Parallel/vtkEnSightWriter.cxx @@ -355,16 +355,7 @@ void vtkEnSightWriter::WriteData() this->WriteStringToFile("part",fd); this->WriteIntToFile(part,fd); //cout << "part is " << part << endl; - int exodusIndex=-1; - if (exodusIndex!=-1) - { - sprintf(charBuffer,"Exodus-%s-%d",blockNames[exodusIndex],part); - this->WriteStringToFile(charBuffer,fd); - } - else - { - this->WriteStringToFile("VTK Part",fd); - } + this->WriteStringToFile("VTK Part",fd); this->WriteStringToFile("coordinates",fd); } diff --git a/IO/Parallel/vtkMultiBlockPLOT3DReader.cxx b/IO/Parallel/vtkMultiBlockPLOT3DReader.cxx index 7995f8cc05e..2d8191dedb7 100644 --- a/IO/Parallel/vtkMultiBlockPLOT3DReader.cxx +++ b/IO/Parallel/vtkMultiBlockPLOT3DReader.cxx @@ -34,23 +34,10 @@ #include "vtkCellData.h" #include "vtkMultiProcessController.h" #include "vtkDummyController.h" - #include "vtkNew.h" #include "vtkMultiBlockPLOT3DReaderInternals.h" -#include - -#ifdef _WIN64 -# define vtk_fseek _fseeki64 -# define vtk_ftell _ftelli64 -# define vtk_off_t __int64 -#else -# define vtk_fseek fseek -# define vtk_ftell ftell -# define vtk_off_t long -#endif - vtkObjectFactoryNewMacro(vtkMultiBlockPLOT3DReader); vtkCxxSetObjectMacro(vtkMultiBlockPLOT3DReader, @@ -62,6 +49,25 @@ vtkCxxSetObjectMacro(vtkMultiBlockPLOT3DReader, #define VTK_PINF ((VTK_RHOINF*VTK_CINF) * (VTK_RHOINF*VTK_CINF) / this->Gamma) #define VTK_CV (this->R / (this->Gamma-1.0)) +namespace +{ +// helper class used to keep a FILE handle to close when the instance goes out +// of scope. +class vtkPlot3DCFile +{ + FILE* Handle; + bool CloseOnDelete; +public: + vtkPlot3DCFile(FILE* handle=NULL) : Handle(handle), CloseOnDelete(true) {} + ~vtkPlot3DCFile() { if (this->Handle && this->CloseOnDelete) { fclose(this->Handle); } } + operator FILE*&() { return this->Handle; } + // This may be needed to tell vtkPlot3DCFile not to close on delete, instead + // we're taking over the calling close on the file. + void DisableClose() { this->CloseOnDelete = false; } +}; + +} + template class vtkPLOT3DArrayReader { @@ -75,15 +81,51 @@ class vtkPLOT3DArrayReader vtkIdType preskip, vtkIdType n, vtkIdType postskip, - DataType* scalar) + DataType* scalar, + const vtkMultiBlockPLOT3DReaderRecord& record = vtkMultiBlockPLOT3DReaderRecord()) { - if (preskip > 0) + vtkMultiBlockPLOT3DReaderRecord::SubRecordSeparators separators = + record.GetSubRecordSeparators(vtk_ftell(fp), preskip); + + vtk_fseek(fp, + preskip*sizeof(DataType) + + separators.size() * vtkMultiBlockPLOT3DReaderRecord::SubRecordSeparatorWidth, + SEEK_CUR); + + // Let's see if we encounter markers while reading the data from current + // position. + separators = record.GetSubRecordSeparators(vtk_ftell(fp), sizeof(DataType) * n); + + vtkIdType retVal; + if (separators.size() == 0) { - vtk_fseek(fp, preskip*sizeof(DataType), SEEK_CUR); + // no record separators will be encountered, yay! Just read the block. + retVal = static_cast(fread(scalar, sizeof(DataType), n, fp)); } - vtkIdType retVal = static_cast( - fread(scalar, sizeof(DataType), n, fp)); - vtk_fseek(fp, postskip*sizeof(DataType), SEEK_CUR); + else + { + // need to read in chunks to skip separators. + vtkTypeUInt64 pos = vtk_ftell(fp); + std::vector > chunks = + record.GetChunksToRead(pos, sizeof(DataType) * n, separators); + + vtkTypeUInt64 bytesread = 0; + for (size_t cc=0; cc < chunks.size(); ++cc) + { + vtk_fseek(fp, chunks[cc].first, SEEK_SET); + bytesread += static_cast( + fread(reinterpret_cast(scalar) + bytesread, 1, chunks[cc].second, fp)); + } + retVal = static_cast(bytesread / sizeof(DataType)); + } + + // Let's count markers we encounter while postskipping. If any, we'll need + // to step over them as well. + separators = record.GetSubRecordSeparators(vtk_ftell(fp), sizeof(DataType)*postskip); + vtk_fseek(fp, + postskip*sizeof(DataType) + + separators.size() * vtkMultiBlockPLOT3DReaderRecord::SubRecordSeparatorWidth, + SEEK_CUR); if (this->ByteOrder == vtkMultiBlockPLOT3DReader::FILE_LITTLE_ENDIAN) { if (sizeof(DataType) == 4) @@ -109,17 +151,10 @@ class vtkPLOT3DArrayReader return retVal; } - void CalculateSkips(int extent[6], int wextent[6], - vtkIdType& preskip, vtkIdType& postskip) - { - vtkIdType nPtsInPlane = static_cast(wextent[1]+1)*(wextent[3]+1); - preskip = nPtsInPlane * extent[4]; - postskip = nPtsInPlane * (wextent[5] - extent[5]); - } - vtkIdType ReadVector(FILE* fp, int extent[6], int wextent[6], - int numDims, DataType* vector) + int numDims, DataType* vector, + const vtkMultiBlockPLOT3DReaderRecord &record) { vtkIdType n = vtkStructuredData::GetNumberOfPoints(extent); @@ -134,15 +169,14 @@ class vtkPLOT3DArrayReader for (int component = 0; component < numDims; component++) { vtkIdType preskip, postskip; - this->CalculateSkips(extent, wextent, preskip, postskip); - retVal += this->ReadScalar(fp, preskip, n, postskip, buffer); + vtkMultiBlockPLOT3DReaderInternals::CalculateSkips(extent, wextent, preskip, postskip); + retVal += this->ReadScalar(fp, preskip, n, postskip, buffer, record); for (vtkIdType i=0; i(vfp); vtkIdType n = vtkStructuredData::GetNumberOfPoints(extent); if (this->Internal->Settings.BinaryFile) { + // precond: we assume the offset has been updated properly to step over + // sub-record markers, if any. if (vtk_fseek(fp, offset, SEEK_SET) != 0) { return 0; @@ -537,10 +574,10 @@ int vtkMultiBlockPLOT3DReader::ReadIntScalar( vtkPLOT3DArrayReader arrayReader; arrayReader.ByteOrder = this->Internal->Settings.ByteOrder; vtkIdType preskip, postskip; - arrayReader.CalculateSkips(extent, wextent, preskip, postskip); + vtkMultiBlockPLOT3DReaderInternals::CalculateSkips(extent, wextent, preskip, postskip); vtkIntArray* intArray = static_cast(scalar); return arrayReader.ReadScalar( - fp, preskip, n, postskip, intArray->GetPointer(0)) == n; + fp, preskip, n, postskip, intArray->GetPointer(0), record) == n; } else { @@ -551,7 +588,8 @@ int vtkMultiBlockPLOT3DReader::ReadIntScalar( int vtkMultiBlockPLOT3DReader::ReadScalar( void* vfp, int extent[6], int wextent[6], - vtkDataArray* scalar, vtkTypeUInt64 offset) + vtkDataArray* scalar, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& record) { vtkIdType n = vtkStructuredData::GetNumberOfPoints(extent); @@ -559,6 +597,8 @@ int vtkMultiBlockPLOT3DReader::ReadScalar( if (this->Internal->Settings.BinaryFile) { + // precond: we assume the offset has been updated properly to step over + // sub-record markers, if any. if (vtk_fseek(fp, offset, SEEK_SET) != 0) { return 0; @@ -569,20 +609,22 @@ int vtkMultiBlockPLOT3DReader::ReadScalar( vtkPLOT3DArrayReader arrayReader; arrayReader.ByteOrder = this->Internal->Settings.ByteOrder; vtkIdType preskip, postskip; - arrayReader.CalculateSkips(extent, wextent, preskip, postskip); + vtkMultiBlockPLOT3DReaderInternals::CalculateSkips(extent, wextent, preskip, postskip); vtkFloatArray* floatArray = static_cast(scalar); return arrayReader.ReadScalar( - fp, preskip, n, postskip, floatArray->GetPointer(0)) == n; + fp, preskip, n, postskip, floatArray->GetPointer(0), + record) == n; } else { vtkPLOT3DArrayReader arrayReader; arrayReader.ByteOrder = this->Internal->Settings.ByteOrder; vtkIdType preskip, postskip; - arrayReader.CalculateSkips(extent, wextent, preskip, postskip); + vtkMultiBlockPLOT3DReaderInternals::CalculateSkips(extent, wextent, preskip, postskip); vtkDoubleArray* doubleArray = static_cast(scalar); return arrayReader.ReadScalar( - fp, preskip, n, postskip, doubleArray->GetPointer(0)) == n; + fp, preskip, n, postskip, doubleArray->GetPointer(0), + record) == n; } } else @@ -632,7 +674,8 @@ int vtkMultiBlockPLOT3DReader::ReadScalar( int vtkMultiBlockPLOT3DReader::ReadVector( void* vfp, int extent[6], int wextent[6], - int numDims, vtkDataArray* vector, vtkTypeUInt64 offset) + int numDims, vtkDataArray* vector, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& record) { vtkIdType n = vtkStructuredData::GetNumberOfPoints(extent); vtkIdType nValues = n*numDims; @@ -641,6 +684,8 @@ int vtkMultiBlockPLOT3DReader::ReadVector( if (this->Internal->Settings.BinaryFile) { + // precond: we assume the offset has been updated properly to step over + // sub-record markers, if any. if (vtk_fseek(fp, offset, SEEK_SET) != 0) { return 0; @@ -651,7 +696,7 @@ int vtkMultiBlockPLOT3DReader::ReadVector( arrayReader.ByteOrder = this->Internal->Settings.ByteOrder; vtkFloatArray* floatArray = static_cast(vector); return arrayReader.ReadVector( - fp, extent, wextent, numDims, floatArray->GetPointer(0)) == nValues; + fp, extent, wextent, numDims, floatArray->GetPointer(0), record) == nValues; } else { @@ -659,7 +704,7 @@ int vtkMultiBlockPLOT3DReader::ReadVector( arrayReader.ByteOrder = this->Internal->Settings.ByteOrder; vtkDoubleArray* doubleArray = static_cast(vector); return arrayReader.ReadVector( - fp, extent, wextent, numDims, doubleArray->GetPointer(0)) == nValues; + fp, extent, wextent, numDims, doubleArray->GetPointer(0), record) == nValues; } } else @@ -1002,13 +1047,6 @@ void vtkMultiBlockPLOT3DReader::RemoveFunction(int fnum) } } -namespace -{ -class Plot3DException : public std::exception -{ -}; -} - int vtkMultiBlockPLOT3DReader::RequestInformation( vtkInformation*, vtkInformationVector**, @@ -1036,10 +1074,9 @@ int vtkMultiBlockPLOT3DReader::RequestInformation( (this->Internal->NeedToCheckXYZFile || this->Internal->Blocks.size() == 0)) { - FILE* xyzFp; + vtkPlot3DCFile xyzFp; if ( this->CheckGeometryFile(xyzFp) != VTK_OK) { - fclose(xyzFp); throw Plot3DException(); } @@ -1047,18 +1084,16 @@ int vtkMultiBlockPLOT3DReader::RequestInformation( if (!this->AutoDetectionCheck(xyzFp)) { - fclose(xyzFp); throw Plot3DException(); } this->Internal->NeedToCheckXYZFile = false; - fclose(xyzFp); } // We report time from the Q file for meta-type readers that // might support file series of Q files. if (this->QFileName && this->QFileName[0] != '\0') { - FILE* qFp; + vtkPlot3DCFile qFp; if ( this->CheckSolutionFile(qFp) != VTK_OK) { throw Plot3DException(); @@ -1066,7 +1101,6 @@ int vtkMultiBlockPLOT3DReader::RequestInformation( int nq, nqc, overflow; if (this->ReadQHeader(qFp, false, nq, nqc, overflow) != VTK_OK) { - fclose(qFp); throw Plot3DException(); } @@ -1086,7 +1120,6 @@ int vtkMultiBlockPLOT3DReader::RequestInformation( vtkErrorMacro("Encountered premature end-of-file while reading " "the q file (or the file is corrupt)."); this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError); - fclose(qFp); properties->Delete(); throw Plot3DException(); } @@ -1095,7 +1128,6 @@ int vtkMultiBlockPLOT3DReader::RequestInformation( hasTime = true; properties->Delete(); } - fclose(qFp); } } catch (Plot3DException&) @@ -1217,7 +1249,7 @@ int vtkMultiBlockPLOT3DReader::RequestData( et->SetNumberOfPieces(size); et->SetSplitModeToZSlab(); - FILE* xyzFp = 0; + vtkPlot3DCFile xyzFp(0); // Don't read the geometry if we already have it! if ( numBlocks == 0 ) @@ -1242,7 +1274,6 @@ int vtkMultiBlockPLOT3DReader::RequestData( if ( this->ReadGeometryHeader(xyzFp) != VTK_OK ) { vtkErrorMacro("Error reading geometry file."); - fclose(xyzFp); throw Plot3DException(); } @@ -1252,7 +1283,6 @@ int vtkMultiBlockPLOT3DReader::RequestData( if (this->Internal->Settings.BinaryFile) { offset = vtk_ftell(xyzFp); - fclose(xyzFp); } } catch (Plot3DException&) @@ -1293,12 +1323,29 @@ int vtkMultiBlockPLOT3DReader::RequestData( // For ASCII files, the first rank keeps reading without // worrying about offsets and such. xyzFp2 = xyzFp; + xyzFp.DisableClose(); } this->Internal->Blocks.resize(numBlocks); for(int i=0; iInternal->Settings, this->Controller)) + { + vtkErrorMacro("Encountered premature end-of-file while reading " + "the geometry file (or the file is corrupt)."); + this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError); + this->CloseFile(xyzFp2); + this->ClearGeometryCache(); + return 0; + } + + // we now have determined how many (sub)records are part of this block. + assert(record.AtStart(offset)); + offset += this->GetByteCountSize(); // Read the geometry of this grid. @@ -1335,7 +1382,8 @@ int vtkMultiBlockPLOT3DReader::RequestData( extent, wextent, this->Internal->Settings.NumberOfDimensions, pointArray, - offset) == 0) + offset, + record) == 0) { vtkErrorMacro("Encountered premature end-of-file while reading " "the geometry file (or the file is corrupt)."); @@ -1346,15 +1394,15 @@ int vtkMultiBlockPLOT3DReader::RequestData( } // Increment the offset for next read. This points to the // beginning of next block. - offset += this->Internal->Settings.NumberOfDimensions* - nTotalPts*this->Internal->Settings.Precision; + offset += record.GetLengthWithSeparators(offset, + this->Internal->Settings.NumberOfDimensions* nTotalPts*this->Internal->Settings.Precision); if (this->Internal->Settings.IBlanking) { vtkIntArray* iblank = vtkIntArray::New(); iblank->SetName("IBlank"); iblank->SetNumberOfTuples(npts); - if ( this->ReadIntScalar(xyzFp2, extent, wextent, iblank, offset) == 0) + if ( this->ReadIntScalar(xyzFp2, extent, wextent, iblank, offset, record) == 0) { vtkErrorMacro("Encountered premature end-of-file while reading " "the xyz file (or the file is corrupt)."); @@ -1367,7 +1415,7 @@ int vtkMultiBlockPLOT3DReader::RequestData( int* ib = iblank->GetPointer(0); nthOutput->GetPointData()->AddArray(iblank); iblank->Delete(); - offset += nTotalPts*sizeof(int); + offset += record.GetLengthWithSeparators(offset, nTotalPts*sizeof(int)); vtkUnsignedCharArray *ghosts = vtkUnsignedCharArray::New(); ghosts->SetNumberOfValues(nthOutput->GetNumberOfCells()); @@ -1405,6 +1453,8 @@ int vtkMultiBlockPLOT3DReader::RequestData( } offset += this->GetByteCountSize(); + assert(record.AtEnd(offset)); + //**************** RECORD END ********************************* } this->CloseFile(xyzFp2); @@ -1429,7 +1479,7 @@ int vtkMultiBlockPLOT3DReader::RequestData( // Now read the solution. if (this->QFileName && this->QFileName[0] != '\0') { - FILE* qFp = 0; + vtkPlot3DCFile qFp(NULL); int nq=0, nqc=0, isOverflow=0; int error = 0; @@ -1444,7 +1494,6 @@ int vtkMultiBlockPLOT3DReader::RequestData( if ( this->ReadQHeader(qFp, true, nq, nqc, isOverflow) != VTK_OK ) { - fclose(qFp); throw Plot3DException(); } } @@ -1481,6 +1530,7 @@ int vtkMultiBlockPLOT3DReader::RequestData( // offsets and let the file move forward while reading // from the original file handle. qFp2 = qFp; + qFp.DisableClose(); } for(int i=0; iSetErrorCode(vtkErrorCode::PrematureEndOfFileError); - fclose(qFp); properties->Delete(); throw Plot3DException(); } @@ -1536,7 +1585,6 @@ int vtkMultiBlockPLOT3DReader::RequestData( vtkErrorMacro("Encountered premature end-of-file while reading " "the q file (or the file is corrupt)."); this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError); - fclose(qFp); properties->Delete(); throw Plot3DException(); } @@ -1554,7 +1602,6 @@ int vtkMultiBlockPLOT3DReader::RequestData( vtkErrorMacro("Encountered premature end-of-file while reading " "the q file (or the file is corrupt)."); this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError); - fclose(qFp); properties->Delete(); throw Plot3DException(); } @@ -1595,24 +1642,39 @@ int vtkMultiBlockPLOT3DReader::RequestData( et->PieceToExtent(); et->GetExtent(extent); + int ldims[3]; + vtkStructuredData::GetDimensionsFromExtent(extent, ldims); + vtkIdType npts = vtkStructuredData::GetNumberOfPoints(extent); vtkIdType nTotalPts = (vtkIdType)dims[0]*dims[1]*dims[2]; + //**************** RECORD START ********************************* + // precond: offset is at start of a record in the file. + vtkMultiBlockPLOT3DReaderRecord record; + if (!record.Initialize(qFp, offset, this->Internal->Settings, this->Controller)) + { + vtkErrorMacro("Encountered premature end-of-file while reading " + "the q file (or the file is corrupt)."); + this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError); + this->CloseFile(qFp2); + this->ClearGeometryCache(); + return 0; + } + + // we now have determined how many (sub)records are part of this block. + assert(record.AtStart(offset)); + offset += this->GetByteCountSize(); vtkDataArray* density = this->NewFloatArray(); density->SetNumberOfComponents(1); density->SetNumberOfTuples( npts ); density->SetName("Density"); - if ( this->ReadScalar(qFp2, extent, wextent, density, offset) == 0) + if ( this->ReadScalar(qFp2, extent, wextent, density, offset, record) == 0) { vtkErrorMacro("Encountered premature end-of-file while reading " "the q file (or the file is corrupt)."); this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError); - if (rank == 0 && this->Internal->Settings.BinaryFile) - { - fclose(qFp); - } this->CloseFile(qFp2); density->Delete(); this->ClearGeometryCache(); @@ -1620,7 +1682,7 @@ int vtkMultiBlockPLOT3DReader::RequestData( } nthOutput->GetPointData()->AddArray(density); density->Delete(); - offset += nTotalPts*this->Internal->Settings.Precision; + offset += record.GetLengthWithSeparators(offset, nTotalPts*this->Internal->Settings.Precision); vtkDataArray* momentum = this->NewFloatArray(); momentum->SetNumberOfComponents(3); @@ -1630,15 +1692,12 @@ int vtkMultiBlockPLOT3DReader::RequestData( extent, wextent, this->Internal->Settings.NumberOfDimensions, momentum, - offset) == 0) + offset, + record) == 0) { vtkErrorMacro("Encountered premature end-of-file while reading " "the q file (or the file is corrupt)."); this->SetErrorCode(vtkErrorCode::PrematureEndOfFileError); - if (rank == 0 && this->Internal->Settings.BinaryFile) - { - fclose(qFp); - } this->CloseFile(qFp2); momentum->Delete(); this->ClearGeometryCache(); @@ -1646,21 +1705,17 @@ int vtkMultiBlockPLOT3DReader::RequestData( } nthOutput->GetPointData()->AddArray(momentum); momentum->Delete(); - offset += this->Internal->Settings.NumberOfDimensions* - nTotalPts*this->Internal->Settings.Precision; + offset += record.GetLengthWithSeparators(offset, + this->Internal->Settings.NumberOfDimensions* nTotalPts*this->Internal->Settings.Precision); vtkDataArray* se = this->NewFloatArray(); se->SetNumberOfComponents(1); se->SetNumberOfTuples( npts ); se->SetName("StagnationEnergy"); - if ( this->ReadScalar(qFp2, extent, wextent, se, offset) == 0) + if ( this->ReadScalar(qFp2, extent, wextent, se, offset, record) == 0) { vtkErrorMacro("Encountered premature end-of-file while reading " "the q file (or the file is corrupt)."); - if (rank == 0 && this->Internal->Settings.BinaryFile) - { - fclose(qFp); - } this->CloseFile(qFp2); se->Delete(); this->ClearGeometryCache(); @@ -1668,7 +1723,7 @@ int vtkMultiBlockPLOT3DReader::RequestData( } nthOutput->GetPointData()->AddArray(se); se->Delete(); - offset += nTotalPts*this->Internal->Settings.Precision; + offset += record.GetLengthWithSeparators(offset, nTotalPts*this->Internal->Settings.Precision); if (isOverflow) { @@ -1678,14 +1733,10 @@ int vtkMultiBlockPLOT3DReader::RequestData( gamma->SetNumberOfComponents(1); gamma->SetNumberOfTuples(npts); gamma->SetName("Gamma"); - if (this->ReadScalar(qFp2, extent, wextent, gamma, offset) == 0) + if (this->ReadScalar(qFp2, extent, wextent, gamma, offset, record) == 0) { vtkErrorMacro("Encountered premature end-of-file while reading " "the q file (or the file is corrupt)."); - if (rank == 0 && this->Internal->Settings.BinaryFile) - { - fclose(qFp); - } this->CloseFile(qFp2); gamma->Delete(); this->ClearGeometryCache(); @@ -1693,7 +1744,7 @@ int vtkMultiBlockPLOT3DReader::RequestData( } nthOutput->GetPointData()->AddArray(gamma); gamma->Delete(); - offset += nTotalPts*this->Internal->Settings.Precision; + offset += record.GetLengthWithSeparators(offset, nTotalPts*this->Internal->Settings.Precision); } /// end of new char res[100]; @@ -1706,21 +1757,17 @@ int vtkMultiBlockPLOT3DReader::RequestData( int k = j+1; sprintf(res, "Species Density #%d", k); temp->SetName(res); - if (this->ReadScalar(qFp2, extent, wextent, temp, offset) == 0) + if (this->ReadScalar(qFp2, extent, wextent, temp, offset, record) == 0) { vtkErrorMacro("Encountered premature end-of-file while reading " "the q file (or the file is corrupt)."); - if (rank == 0 && this->Internal->Settings.BinaryFile) - { - fclose(qFp); - } this->CloseFile(qFp2); temp->Delete(); this->ClearGeometryCache(); return 0; } nthOutput->GetPointData()->AddArray(temp); - offset += nTotalPts*this->Internal->Settings.Precision; + offset += record.GetLengthWithSeparators(offset, nTotalPts*this->Internal->Settings.Precision); temp->Delete(); } float d, r; @@ -1732,7 +1779,7 @@ int vtkMultiBlockPLOT3DReader::RequestData( vtkDataArray* spec = outputPD->GetArray(res); vtkDataArray* dens = outputPD->GetArray("Density"); rat->SetNumberOfComponents(1); - rat->SetNumberOfTuples(dims[0]*dims[1]*dims[2]); + rat->SetNumberOfTuples(ldims[0]*ldims[1]*ldims[2]); sprintf(res, "Spec Dens #%d / rho", v+1); rat->SetName(res); for(int w=0; wNewFloatArray(); temp->SetNumberOfComponents(1); - temp->SetNumberOfTuples(dims[0]*dims[1]*dims[2]); + temp->SetNumberOfTuples(ldims[0]*ldims[1]*ldims[2]); int k = a+1; sprintf(res, "Turb Field Quant #%d", k); temp->SetName(res); - if (this->ReadScalar(qFp2, extent, wextent, temp, offset) == 0) + if (this->ReadScalar(qFp2, extent, wextent, temp, offset, record) == 0) { vtkErrorMacro("Encountered premature end-of-file while reading " "the q file (or the file is corrupt)."); - if (rank == 0 && this->Internal->Settings.BinaryFile) - { - fclose(qFp); - } this->CloseFile(qFp2); temp->Delete(); this->ClearGeometryCache(); return 0; } nthOutput->GetPointData()->AddArray(temp); - offset += nTotalPts*this->Internal->Settings.Precision; + offset += record.GetLengthWithSeparators(offset, nTotalPts*this->Internal->Settings.Precision); temp->Delete(); } } offset += this->GetByteCountSize(); + assert(record.AtEnd(offset)); + //**************** RECORD END ********************************* if (rank == 0 && this->Internal->Settings.BinaryFile) { @@ -1795,10 +1840,6 @@ int vtkMultiBlockPLOT3DReader::RequestData( this->AssignAttribute(this->VectorFunctionNumber, nthOutput, vtkDataSetAttributes::VECTORS); } - if (rank == 0 && this->Internal->Settings.BinaryFile) - { - fclose(qFp); - } this->CloseFile(qFp2); } @@ -1807,7 +1848,7 @@ int vtkMultiBlockPLOT3DReader::RequestData( { vtkTypeUInt64 offset = 0; - FILE* fFp = 0; + vtkPlot3DCFile fFp(NULL); std::vector nFunctions(numBlocks); int error = 0; @@ -1822,11 +1863,9 @@ int vtkMultiBlockPLOT3DReader::RequestData( if ( this->ReadFunctionHeader(fFp, &nFunctions[0]) != VTK_OK ) { - fclose(fFp); throw Plot3DException(); } offset = vtk_ftell(fFp); - fclose(fFp); } catch (Plot3DException&) { @@ -1853,6 +1892,7 @@ int vtkMultiBlockPLOT3DReader::RequestData( else { fFp2 = fFp; + fFp.DisableClose(); } for(int i=0; iInternal->Settings, this->Controller)) + { + vtkErrorMacro("Encountered premature end-of-file while reading " + "the function file (or the file is corrupt)."); + this->CloseFile(fFp2); + this->ClearGeometryCache(); + return 0; + } + + // we now have determined how many (sub)records are part of this block. + assert(record.AtStart(offset)); + offset += this->GetByteCountSize(); for (int j=0; jSetName(functionName); - if (this->ReadScalar(fFp2, extent, wextent, functionArray, offset) == 0) + if (this->ReadScalar(fFp2, extent, wextent, functionArray, offset, record) == 0) { vtkErrorMacro("Encountered premature end-of-file while reading " "the function file (or the file is corrupt)."); @@ -1888,12 +1943,14 @@ int vtkMultiBlockPLOT3DReader::RequestData( this->ClearGeometryCache(); return 0; } - offset += nTotalPts*this->Internal->Settings.Precision; + offset += record.GetLengthWithSeparators(offset, nTotalPts*this->Internal->Settings.Precision); nthOutput->GetPointData()->AddArray(functionArray); functionArray->Delete(); } offset += this->GetByteCountSize(); + assert(record.AtEnd(offset)); + //**************** RECORD END ********************************* } this->CloseFile(fFp2); } diff --git a/IO/Parallel/vtkMultiBlockPLOT3DReader.h b/IO/Parallel/vtkMultiBlockPLOT3DReader.h index 0efa31758ee..bc156bce8a5 100644 --- a/IO/Parallel/vtkMultiBlockPLOT3DReader.h +++ b/IO/Parallel/vtkMultiBlockPLOT3DReader.h @@ -91,7 +91,7 @@ class vtkUnsignedCharArray; class vtkIntArray; class vtkStructuredGrid; class vtkMultiProcessController; - +class vtkMultiBlockPLOT3DReaderRecord; struct vtkMultiBlockPLOT3DReaderInternals; class VTKIOPARALLEL_EXPORT vtkMultiBlockPLOT3DReader : public vtkMultiBlockDataSetAlgorithm @@ -239,13 +239,11 @@ class VTKIOPARALLEL_EXPORT vtkMultiBlockPLOT3DReader : public vtkMultiBlockDataS void SetController(vtkMultiProcessController *c); vtkGetObjectMacro(Controller, vtkMultiProcessController); -//BTX enum { FILE_BIG_ENDIAN=0, FILE_LITTLE_ENDIAN=1 }; -//ETX protected: vtkMultiBlockPLOT3DReader(); @@ -269,15 +267,18 @@ class VTKIOPARALLEL_EXPORT vtkMultiBlockPLOT3DReader : public vtkMultiBlockDataS virtual int ReadIntScalar( void* vfp, int extent[6], int wextent[6], - vtkDataArray* scalar, vtkTypeUInt64 offset); + vtkDataArray* scalar, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& currentRecord); virtual int ReadScalar( void* vfp, int extent[6], int wextent[6], - vtkDataArray* scalar, vtkTypeUInt64 offset); + vtkDataArray* scalar, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& currentRecord); virtual int ReadVector( void* vfp, int extent[6], int wextent[6], - int numDims, vtkDataArray* vector, vtkTypeUInt64 offset); + int numDims, vtkDataArray* vector, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderRecord& currentRecord); virtual int OpenFileForDataRead(void*& fp, const char* fname); virtual void CloseFile(void* fp); diff --git a/IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.cxx b/IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.cxx index 7747bc8ffc5..946905d9976 100644 --- a/IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.cxx +++ b/IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.cxx @@ -15,6 +15,9 @@ =========================================================================*/ #include "vtkMultiBlockPLOT3DReaderInternals.h" +#include "vtkMultiProcessController.h" +#include + int vtkMultiBlockPLOT3DReaderInternals::ReadInts(FILE* fp, int n, int* val) { int retVal = static_cast(fread(val, sizeof(int), n, fp)); @@ -409,3 +412,162 @@ size_t vtkMultiBlockPLOT3DReaderInternals::CalculateFileSizeForBlock(int precisi } return size; } + +//----------------------------------------------------------------------------- +bool vtkMultiBlockPLOT3DReaderRecord::Initialize( + FILE* fp, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderInternals::InternalSettings& settings, + vtkMultiProcessController* controller) +{ + this->SubRecords.clear(); + if (!settings.BinaryFile || !settings.HasByteCount) + { + return true; + } + const int rank = controller? controller->GetLocalProcessId() : 0; + int error = 0; + if (rank == 0) + { + vtkTypeUInt64 pos = vtk_ftell(fp); + unsigned int leadingLengthField; + int signBit = 0; + try + { + do + { + vtkSubRecord subrecord; + subrecord.HeaderOffset = offset; + vtkTypeUInt64 dataOffset = subrecord.HeaderOffset + sizeof(int); + vtk_fseek(fp, offset, SEEK_SET); + if (fread(&leadingLengthField, sizeof(unsigned int), 1, fp) != 1) + { + throw Plot3DException(); + } + signBit = (0x80000000 & leadingLengthField)? 1 : 0; + if (signBit) + { + unsigned int length = 0xffffffff ^ (leadingLengthField - 1); + subrecord.FooterOffset = dataOffset + length; + } + else + { + subrecord.FooterOffset = dataOffset + leadingLengthField; + } + this->SubRecords.push_back(subrecord); + offset = subrecord.FooterOffset + sizeof(int); + } + while (signBit == 1); + } + catch (Plot3DException&) + { + error = 1; + } + vtk_fseek(fp, pos, SEEK_SET); + } + + if (controller == NULL) + { + if (error) + { + this->SubRecords.clear(); + } + return error == 0; + } + + // Communicate record information to all ranks. + controller->Broadcast(&error, 1, 0); + if (error) + { + this->SubRecords.clear(); + return false; + } + if (rank == 0) + { + int count = static_cast(this->SubRecords.size()); + controller->Broadcast(&count, 1, 0); + if (count > 0) + { + controller->Broadcast( + reinterpret_cast(&this->SubRecords[0]), count * 2, 0); + } + } + else + { + int count; + controller->Broadcast(&count, 1, 0); + this->SubRecords.resize(count); + if (count > 0) + { + controller->Broadcast( + reinterpret_cast(&this->SubRecords[0]), count * 2, 0); + } + } + return true; +} + +//----------------------------------------------------------------------------- +vtkMultiBlockPLOT3DReaderRecord::SubRecordSeparators +vtkMultiBlockPLOT3DReaderRecord::GetSubRecordSeparators( + vtkTypeUInt64 startOffset, vtkTypeUInt64 length) const +{ + vtkMultiBlockPLOT3DReaderRecord::SubRecordSeparators markers; + if (this->SubRecords.size() <= 1) + { + return markers; + } + + // locate the sub-record in which startOffset begins. + VectorOfSubRecords::const_iterator sr_start = this->SubRecords.begin(); + while (sr_start != this->SubRecords.end() + && sr_start->FooterOffset < startOffset) + { + sr_start++; + } + assert(sr_start != this->SubRecords.end()); + + vtkTypeUInt64 endOffset = startOffset + length; + + VectorOfSubRecords::const_iterator sr_end = sr_start; + while (sr_end != this->SubRecords.end() + && sr_end->FooterOffset < endOffset) + { + markers.push_back(sr_end->FooterOffset); + sr_end++; + assert(sr_end != this->SubRecords.end()); + endOffset += vtkMultiBlockPLOT3DReaderRecord::SubRecordSeparatorWidth; + } + assert(sr_end != this->SubRecords.end()); + return markers; +} + +//----------------------------------------------------------------------------- +std::vector > +vtkMultiBlockPLOT3DReaderRecord::GetChunksToRead( + vtkTypeUInt64 start, vtkTypeUInt64 length, const std::vector &markers) +{ + std::vector > chunks; + for (size_t cc=0; cc < markers.size(); ++cc) + { + if (start < markers[cc]) + { + vtkTypeUInt64 chunksize = (markers[cc] - start); + chunks.push_back(std::pair(start, chunksize)); + length -= chunksize; + } + start = markers[cc] + vtkMultiBlockPLOT3DReaderRecord::SubRecordSeparatorWidth; + } + if (length > 0) + { + chunks.push_back(std::pair(start, length)); + } + return chunks; +} + +//----------------------------------------------------------------------------- +vtkTypeUInt64 vtkMultiBlockPLOT3DReaderRecord::GetLengthWithSeparators( + vtkTypeUInt64 start, vtkTypeUInt64 length) const +{ + return this->GetSubRecordSeparators(start, length).size() + * vtkMultiBlockPLOT3DReaderRecord::SubRecordSeparatorWidth + + length; +} diff --git a/IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.h b/IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.h index 2d85ceced29..d2d72fab47d 100644 --- a/IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.h +++ b/IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.h @@ -15,13 +15,27 @@ #ifndef vtkMultiBlockPLOT3DReaderInternals_h #define vtkMultiBlockPLOT3DReaderInternals_h +#include "vtkIOParallelModule.h" // For export macro #include "vtkByteSwap.h" #include "vtkMultiBlockPLOT3DReader.h" #include "vtkSmartPointer.h" #include "vtkStructuredGrid.h" +#include #include +class vtkMultiProcessController; + +#ifdef _WIN64 +# define vtk_fseek _fseeki64 +# define vtk_ftell _ftelli64 +# define vtk_off_t __int64 +#else +# define vtk_fseek fseek +# define vtk_ftell ftell +# define vtk_off_t long +#endif + struct vtkMultiBlockPLOT3DReaderInternals { struct Dims @@ -87,6 +101,113 @@ struct vtkMultiBlockPLOT3DReaderInternals int ndims, int hasByteCount, int* gridDims); + + static void CalculateSkips(const int extent[6], const int wextent[6], + vtkIdType& preskip, vtkIdType& postskip) + { + vtkIdType nPtsInPlane = static_cast(wextent[1]+1)*(wextent[3]+1); + preskip = nPtsInPlane * extent[4]; + postskip = nPtsInPlane * (wextent[5] - extent[5]); + } +}; + +namespace +{ +class Plot3DException : public std::exception +{ +}; +} + +// Description: +// vtkMultiBlockPLOT3DReaderRecord represents a data record in the file. For +// binary Plot3D files with record separators (i.e. leading and trailing length +// field per record see: https://software.intel.com/en-us/node/525311), if the +// record length is greater than 2,147,483,639 bytes, the record get split into +// multiple records. This class allows use to manage that. +// It corresponds to a complete record i.e. including all the records when split +// among multiple records due to length limit. +class VTKIOPARALLEL_EXPORT vtkMultiBlockPLOT3DReaderRecord +{ + struct vtkSubRecord + { + vtkTypeUInt64 HeaderOffset; + vtkTypeUInt64 FooterOffset; + }; + + typedef std::vector VectorOfSubRecords; + VectorOfSubRecords SubRecords; + +public: + // Description: + // A type for collection of sub-record separators i.e. separators encountered + // within a record when the record length is greater than 2,147,483,639 bytes. + typedef std::vector SubRecordSeparators; + + // Description: + // Since a sub-record separator is made up of the trailing length field of a + // sub-record and the leading length field of the next sub-record, it's length + // is two ints. + static const int SubRecordSeparatorWidth = sizeof(int) * 2; + + // Description: + // Initialize metadata about the record located at the given offset. + // This reads the file on the root node to populate record information, + // seeking and marching forward through the file if the record comprises of + // multiple sub-records. The file is reset back to the original starting + // position when done. + // + // This method has no effect for non-binary files or files that don't have + // record separators i.e. HasByteCount == 0. + bool Initialize(FILE* fp, vtkTypeUInt64 offset, + const vtkMultiBlockPLOT3DReaderInternals::InternalSettings& settings, + vtkMultiProcessController* controller); + + // Description: + // Returns true if: + // 1. file doesn't comprise of records i.e. ASCII or doesn't have byte-count markers. + // 2. offset is same as the start offset for this record. + bool AtStart(vtkTypeUInt64 offset) + { + return (this->SubRecords.size()==0 || this->SubRecords.front().HeaderOffset == offset); + } + + // Description: + // Returns true if: + // 1. file doesn't comprise of records i.e. ASCII or doesn't have byte-count markers. + // 2. offset is at the end of this record i.e. the start of the next record. + bool AtEnd(vtkTypeUInt64 offset) + { + return (this->SubRecords.size()==0 || + (this->SubRecords.back().FooterOffset + sizeof(int) == offset)); + } + + // Description: + // Returns the location of SubRecordSeparators (bad two 4-byte ints) between startOffset and + // (startOffset + length). + SubRecordSeparators GetSubRecordSeparators(vtkTypeUInt64 startOffset, vtkTypeUInt64 length) const; + + // Description: + // When reading between file offsets \c start and \c (start + length) from the file, if it has any + // sub-record separators, this method splits the read into chunks so that it + // skips the sub-record separators. The returned value is a vector of pairs + // (offset, length-in-bytes). + static std::vector > GetChunksToRead( + vtkTypeUInt64 start, vtkTypeUInt64 length, const std::vector &markers); + + // Description: + // If the block in file (start, start+length) steps over sub-record separators + // within this record, then this method will return a new length that includes + // the bytes for the separators to be skipped. Otherwise, simply returns the + // length. + vtkTypeUInt64 GetLengthWithSeparators(vtkTypeUInt64 start, vtkTypeUInt64 length) const; + + std::vector > GetChunksToRead( + vtkTypeUInt64 start, vtkTypeUInt64 length) const + { + return this->GetChunksToRead(start, length, this->GetSubRecordSeparators(start, length)); + } + }; + #endif // VTK-HeaderTest-Exclude: vtkMultiBlockPLOT3DReaderInternals.h diff --git a/IO/Parallel/vtkPDataSetReader.h b/IO/Parallel/vtkPDataSetReader.h index 6297a06e695..dcbbb45d24f 100644 --- a/IO/Parallel/vtkPDataSetReader.h +++ b/IO/Parallel/vtkPDataSetReader.h @@ -88,9 +88,8 @@ class VTKIOPARALLEL_EXPORT vtkPDataSetReader : public vtkDataSetAlgorithm vtkDataSet *CheckOutput(); void SetNumberOfPieces(int num); -//BTX ifstream *OpenFile(const char *); -//ETX + int ReadXML(ifstream *file, char **block, char **param, char **value); void SkipFieldData(ifstream *file); diff --git a/IO/Parallel/vtkPDataSetWriter.h b/IO/Parallel/vtkPDataSetWriter.h index 446be6d64d2..b847cd2aa03 100644 --- a/IO/Parallel/vtkPDataSetWriter.h +++ b/IO/Parallel/vtkPDataSetWriter.h @@ -90,7 +90,6 @@ class VTKIOPARALLEL_EXPORT vtkPDataSetWriter : public vtkDataSetWriter vtkPDataSetWriter(); ~vtkPDataSetWriter(); -//BTX ostream *OpenFile(); int WriteUnstructuredMetaData(vtkDataSet *input, char *root, char *str, ostream *fptr); @@ -100,7 +99,6 @@ class VTKIOPARALLEL_EXPORT vtkPDataSetWriter : public vtkDataSetWriter char *root, char *str, ostream *fptr); int WriteStructuredGridMetaData(vtkStructuredGrid *input, char *root, char *str, ostream *fptr); -//ETX int StartPiece; int EndPiece; diff --git a/IO/Parallel/vtkPOpenFOAMReader.h b/IO/Parallel/vtkPOpenFOAMReader.h index 1d801eef10c..2eff08432ba 100644 --- a/IO/Parallel/vtkPOpenFOAMReader.h +++ b/IO/Parallel/vtkPOpenFOAMReader.h @@ -36,9 +36,9 @@ class vtkMultiProcessController; class VTKIOPARALLEL_EXPORT vtkPOpenFOAMReader : public vtkOpenFOAMReader { public: - //BTX + enum caseType { DECOMPOSED_CASE = 0, RECONSTRUCTED_CASE = 1 }; - //ETX + static vtkPOpenFOAMReader *New(); vtkTypeMacro(vtkPOpenFOAMReader, vtkOpenFOAMReader); diff --git a/IO/Parallel/vtkPSLACReader.cxx b/IO/Parallel/vtkPSLACReader.cxx index 9f4a55a92a8..be7df8897a5 100644 --- a/IO/Parallel/vtkPSLACReader.cxx +++ b/IO/Parallel/vtkPSLACReader.cxx @@ -763,7 +763,7 @@ int vtkPSLACReader::ReadConnectivity(int meshFD, vtkIdType ids[2]; ids[0] = edgesNeeded[i].GetMinEndPoint(); ids[1] = edgesNeeded[i].GetMaxEndPoint(); - edgeLists[process]->InsertNextTupleValue(static_cast(ids)); + edgeLists[process]->InsertNextTypedTuple(static_cast(ids)); } for (int process = 0; process < this->NumberOfPieces; process ++) { @@ -1062,12 +1062,25 @@ int vtkPSLACReader::ReadMidpointCoordinates ( start /= this->Internal->EdgesToSendToProcesses->GetNumberOfComponents(); end /= this->Internal->EdgesToSendToProcesses->GetNumberOfComponents(); + // FIXME: There seems to be a bug somewhere that results in the + // EdgesToSendToProcesses array to be empty, while the corresponding + // Offsets and Lengths arrays are not. This only happens on some processes, + // and the PSLAC unit tests still pass. The bit below prevents invalid + // memory accesses when this occurs. + if (this->Internal->EdgesToSendToProcesses->GetNumberOfTuples() == 0 && + this->Internal->EdgesToSendToProcessesOffsets->GetNumberOfTuples() != 0) + { + vtkWarningMacro("Inconsistent reader state detected. Skipping midpoint " + "sync."); + end = start = 0; + } + midpointListsType midpointsToSend; for (vtkIdType i = start; i < end; i ++) { MidpointsAvailableType::const_iterator iter; vtkIdType e[2]; - this->Internal->EdgesToSendToProcesses->GetTupleValue(i, e); + this->Internal->EdgesToSendToProcesses->GetTypedTuple(i, e); iter = MidpointsAvailable.find(EdgeEndpoints(e[0], e[1])); if (iter != MidpointsAvailable.end ()) { @@ -1108,7 +1121,7 @@ int vtkPSLACReader::ReadMidpointCoordinates ( vtkIdType index; if (iter == localMap.end()) { - index = this->Internal->LocalToGlobalIds->InsertNextTupleValue( + index = this->Internal->LocalToGlobalIds->InsertNextTypedTuple( &topIter->globalId); localMap[topIter->globalId] = index; } @@ -1147,7 +1160,7 @@ int vtkPSLACReader::ReadMidpointData(int meshFD, vtkMultiBlockDataSet *output, vtkIdType end = start + pointsAdded; for (vtkIdType i = start; i < end; i ++) { - this->Internal->LocalToGlobalIds->InsertNextTupleValue (&i); + this->Internal->LocalToGlobalIds->InsertNextTypedTuple (&i); } return 1; diff --git a/IO/Parallel/vtkPSLACReader.h b/IO/Parallel/vtkPSLACReader.h index 9c5d65d6089..8c5882aa97f 100644 --- a/IO/Parallel/vtkPSLACReader.h +++ b/IO/Parallel/vtkPSLACReader.h @@ -89,16 +89,12 @@ class VTKIOPARALLEL_EXPORT vtkPSLACReader : public vtkSLACReader virtual int MeshUpToDate(); -//BTX // Description: // Reads point data arrays. Called by ReadCoordinates and ReadFieldData. virtual vtkSmartPointer ReadPointDataArray(int ncFD, int varId); -//ETX -//BTX class vtkInternal; vtkInternal *Internal; -//ETX // Description: // The number of pieces and the requested piece to load. Synonymous with diff --git a/IO/Parallel/vtkPlot3DMetaReader.h b/IO/Parallel/vtkPlot3DMetaReader.h index 0cabecf52e3..3b39bd4f13f 100644 --- a/IO/Parallel/vtkPlot3DMetaReader.h +++ b/IO/Parallel/vtkPlot3DMetaReader.h @@ -76,9 +76,7 @@ #include "vtkIOParallelModule.h" // For export macro #include "vtkMultiBlockDataSetAlgorithm.h" -//BTX struct vtkPlot3DMetaReaderInternals; -//ETX class vtkMultiBlockPLOT3DReader; diff --git a/IO/ParallelExodus/Testing/Cxx/TestExodusImplicitArrays.cxx b/IO/ParallelExodus/Testing/Cxx/TestExodusImplicitArrays.cxx index 3eff0e7e716..1b9b64babb4 100644 --- a/IO/ParallelExodus/Testing/Cxx/TestExodusImplicitArrays.cxx +++ b/IO/ParallelExodus/Testing/Cxx/TestExodusImplicitArrays.cxx @@ -45,9 +45,9 @@ int TestExodusImplicitArrays(int argc, char *argv[]) { return 1; } - vtkIdTypeArray *ie = vtkIdTypeArray::SafeDownCast ( + vtkIdTypeArray *ie = vtkArrayDownCast( obj->GetAttributes (vtkDataSet::CELL)->GetAbstractArray ("ImplicitElementId")); - vtkIdTypeArray *in = vtkIdTypeArray::SafeDownCast ( + vtkIdTypeArray *in = vtkArrayDownCast( obj->GetAttributes (vtkDataSet::POINT)->GetAbstractArray ("ImplicitNodeId")); if (!ie || !in) { diff --git a/IO/ParallelExodus/vtkPExodusIIReader.h b/IO/ParallelExodus/vtkPExodusIIReader.h index fb522e33219..09f9fc8535c 100644 --- a/IO/ParallelExodus/vtkPExodusIIReader.h +++ b/IO/ParallelExodus/vtkPExodusIIReader.h @@ -148,11 +148,10 @@ class VTKIOPARALLELEXODUS_EXPORT vtkPExodusIIReader : public vtkExodusIIReader int NumberOfFiles; char **FileNames; int NumberOfFileNames; -//BTX + std::vector ReaderList; std::vector NumberOfPointsPerFile; std::vector NumberOfCellsPerFile; -//ETX int LastCommonTimeStep; diff --git a/IO/ParallelXML/Testing/Python/CMakeLists.txt b/IO/ParallelXML/Testing/Python/CMakeLists.txt index 1abf5e5ece6..32bbf38a291 100644 --- a/IO/ParallelXML/Testing/Python/CMakeLists.txt +++ b/IO/ParallelXML/Testing/Python/CMakeLists.txt @@ -1,3 +1,4 @@ vtk_add_test_python_mpi( testParallelXMLWriters.py,NO_VALID + testParallelMultiBlockWriter.py,NO_VALID ) diff --git a/IO/ParallelXML/Testing/Python/testParallelMultiBlockWriter.py b/IO/ParallelXML/Testing/Python/testParallelMultiBlockWriter.py new file mode 100644 index 00000000000..01d9a0f9819 --- /dev/null +++ b/IO/ParallelXML/Testing/Python/testParallelMultiBlockWriter.py @@ -0,0 +1,110 @@ +from __future__ import print_function +import shutil, os + +import vtk + +from vtk.test import Testing +from vtk.util.misc import vtkGetTempDir +VTK_TEMP_DIR = vtkGetTempDir() + +contr = vtk.vtkMultiProcessController.GetGlobalController() +if not contr: + nranks = 1 + rank = 0 +else: + nranks = contr.GetNumberOfProcesses() + rank = contr.GetLocalProcessId() + +# Let's create a simple multiblock with non-empty blocks as indicated below. +# is a multiblock dataset. +# [] is a leaf node where the number indicates the ranks on which it is +# non-null +# () is a leaf node where the number indicates the ranks on which it is +# non-empty + +# +# | +# |-- # level where a block is non-null on only 1 rank +# | | +# | |-- [0](0) +# | |-- [1](1) +# | |-- [2](2) +# | ... (up to total number of ranks) +# | +# |-- # level where block is non-null on all ranks, but non-empty only on 1 +# | | +# | |-- [0,1,..nranks](0) +# | |-- [0,1,..nranks](1) +# | |-- [0,1,..nranks](2) +# | ... (up to total number of ranks) +# | +# |-- # level where block is non-null, non-empty on all ranks. +# | | +# | |-- [0,1,..nranks](0,1,...nranks) +# | |-- [0,1,..nranks](0,1,...nranks) +# | |-- [0,1,..nranks](0,1,...nranks) +# | ... (up to total number of ranks) + + +def createDataSet(empty): + if not empty: + s = vtk.vtkSphereSource() + s.Update() + clone = s.GetOutputDataObject(0).NewInstance() + clone.ShallowCopy(s.GetOutputDataObject(0)) + return clone + else: + return vtk.vtkPolyData() + +def createData(non_null_ranks, non_empty_ranks, num_ranks): + mb = vtk.vtkMultiBlockDataSet() + mb.SetNumberOfBlocks(num_ranks) + for i in non_null_ranks: + mb.SetBlock(i, createDataSet(i not in non_empty_ranks)) + return mb + +def createMB(piece, num_pieces): + output = vtk.vtkMultiBlockDataSet() + output.SetNumberOfBlocks(3) + output.SetBlock(0, createData([piece], [piece], num_pieces)) + output.SetBlock(1, createData(range(num_pieces), [piece], num_pieces)) + output.SetBlock(2, createData(range(num_pieces), range(num_pieces), num_pieces)) + return output + +writer = vtk.vtkXMLPMultiBlockDataWriter() +prefix =VTK_TEMP_DIR + "/testParallelXMLWriters" +fname = prefix + ".vtm" + +if rank == 0: + try: + os.remove(fname) + except OSError: pass + try: + shutil.rmtree(prefix) + except OSError: pass + print("Output: %s" % fname) + +# put a barrier here to make sure that the files are deleted by process 0 +# before going further with the test +if contr: + contr.Barrier() + +writer.SetFileName(fname) +writer.SetInputDataObject(createMB(rank, nranks)) +writer.Write() + +if contr: + contr.Barrier() + +if rank == 0: + reader = vtk.vtkXMLMultiBlockDataReader() + reader.SetFileName(fname) + reader.Update() + + # since verifying the md structure won't reveal if we have written the write + # set of files, let's just look at the files we wrote out. + files = os.listdir(prefix) + + expected_file_count = nranks + nranks + (nranks*nranks) + print ("Expecting %d files for the leaf nodes" % expected_file_count) + assert (len(files) == expected_file_count) diff --git a/IO/ParallelXML/vtkXMLPDataSetWriter.h b/IO/ParallelXML/vtkXMLPDataSetWriter.h index 6b8d92e3a53..cba11ca69bd 100644 --- a/IO/ParallelXML/vtkXMLPDataSetWriter.h +++ b/IO/ParallelXML/vtkXMLPDataSetWriter.h @@ -36,11 +36,9 @@ class VTKIOPARALLELXML_EXPORT vtkXMLPDataSetWriter : public vtkXMLPDataWriter void PrintSelf(ostream& os, vtkIndent indent); static vtkXMLPDataSetWriter* New(); - //BTX // Description: // Get/Set the writer's input. vtkDataSet* GetInput(); - //ETX protected: vtkXMLPDataSetWriter(); diff --git a/IO/ParallelXML/vtkXMLPImageDataWriter.h b/IO/ParallelXML/vtkXMLPImageDataWriter.h index 7b2c51b115c..98a67894767 100644 --- a/IO/ParallelXML/vtkXMLPImageDataWriter.h +++ b/IO/ParallelXML/vtkXMLPImageDataWriter.h @@ -38,11 +38,9 @@ class VTKIOPARALLELXML_EXPORT vtkXMLPImageDataWriter : public vtkXMLPStructuredD vtkTypeMacro(vtkXMLPImageDataWriter,vtkXMLPStructuredDataWriter); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Get/Set the writer's input. vtkImageData* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/ParallelXML/vtkXMLPMultiBlockDataWriter.cxx b/IO/ParallelXML/vtkXMLPMultiBlockDataWriter.cxx index d65b9bf572a..ad728680bc3 100644 --- a/IO/ParallelXML/vtkXMLPMultiBlockDataWriter.cxx +++ b/IO/ParallelXML/vtkXMLPMultiBlockDataWriter.cxx @@ -263,8 +263,8 @@ int vtkXMLPMultiBlockDataWriter::WriteComposite( curDO, datasetXML, currentFileIndex) ) { retVal = 1; + parentXML->AddNestedElement(datasetXML); } - parentXML->AddNestedElement(datasetXML); currentFileIndex++; datasetXML->Delete(); } @@ -325,14 +325,16 @@ int vtkXMLPMultiBlockDataWriter::ParallelWriteNonCompositeData( } } } - if(dObj) + + const int* datatypes_ptr = this->GetDataTypesPointer(); + if(dObj && datatypes_ptr[currentFileIndex] != -1) { vtkStdString fName = this->CreatePieceFileName( - currentFileIndex, myProcId, this->GetDataTypesPointer()[currentFileIndex]); + currentFileIndex, myProcId, datatypes_ptr[currentFileIndex]); return this->Superclass::WriteNonCompositeData( dObj, NULL, currentFileIndex, fName.c_str()); } - return 0; + return 1; } //---------------------------------------------------------------------------- @@ -342,41 +344,15 @@ vtkStdString vtkXMLPMultiBlockDataWriter::CreatePieceFileName( std::string fname; std::string extension; - switch (dataSetType) - { - case VTK_POLY_DATA: - { - extension = "vtp"; - break; - } - case VTK_STRUCTURED_POINTS: - case VTK_IMAGE_DATA: - case VTK_UNIFORM_GRID: - { - extension = "vti"; - break; - } - case VTK_UNSTRUCTURED_GRID: + if (const char* cext = this->GetDefaultFileExtensionForDataSet(dataSetType)) { - extension = "vtu"; - break; + extension = cext; } - case VTK_STRUCTURED_GRID: - { - extension = "vts"; - break; - } - case VTK_RECTILINEAR_GRID: - { - extension = "vtr"; - break; - } - default: + else { vtkErrorMacro(<Controller->GetLocalProcessId() << " Unknown data set type."); return fname; } - } std::ostringstream fn_with_warning_C4701; fn_with_warning_C4701 diff --git a/IO/ParallelXML/vtkXMLPMultiBlockDataWriter.h b/IO/ParallelXML/vtkXMLPMultiBlockDataWriter.h index 1f053aedd18..ce21fbeac6f 100644 --- a/IO/ParallelXML/vtkXMLPMultiBlockDataWriter.h +++ b/IO/ParallelXML/vtkXMLPMultiBlockDataWriter.h @@ -66,7 +66,6 @@ class VTKIOPARALLELXML_EXPORT vtkXMLPMultiBlockDataWriter : public vtkXMLMultiBl vtkInformationVector**, vtkInformationVector*); -//BTX protected: vtkXMLPMultiBlockDataWriter(); ~vtkXMLPMultiBlockDataWriter(); @@ -130,7 +129,7 @@ class VTKIOPARALLELXML_EXPORT vtkXMLPMultiBlockDataWriter : public vtkXMLMultiBl class vtkInternal; vtkInternal* Internal; -//ETX + }; #endif diff --git a/IO/ParallelXML/vtkXMLPPolyDataWriter.h b/IO/ParallelXML/vtkXMLPPolyDataWriter.h index 070e4fd86eb..1ab08a4b2e0 100644 --- a/IO/ParallelXML/vtkXMLPPolyDataWriter.h +++ b/IO/ParallelXML/vtkXMLPPolyDataWriter.h @@ -38,11 +38,9 @@ class VTKIOPARALLELXML_EXPORT vtkXMLPPolyDataWriter : public vtkXMLPUnstructured vtkTypeMacro(vtkXMLPPolyDataWriter,vtkXMLPUnstructuredDataWriter); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Get/Set the writer's input. vtkPolyData* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/ParallelXML/vtkXMLPRectilinearGridWriter.h b/IO/ParallelXML/vtkXMLPRectilinearGridWriter.h index 0adf700baa3..b7263a38792 100644 --- a/IO/ParallelXML/vtkXMLPRectilinearGridWriter.h +++ b/IO/ParallelXML/vtkXMLPRectilinearGridWriter.h @@ -39,11 +39,9 @@ class VTKIOPARALLELXML_EXPORT vtkXMLPRectilinearGridWriter : public vtkXMLPStruc vtkTypeMacro(vtkXMLPRectilinearGridWriter,vtkXMLPStructuredDataWriter); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Get/Set the writer's input. vtkRectilinearGrid* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/ParallelXML/vtkXMLPStructuredGridWriter.h b/IO/ParallelXML/vtkXMLPStructuredGridWriter.h index 7484d8dd23d..dfb38f5caa8 100644 --- a/IO/ParallelXML/vtkXMLPStructuredGridWriter.h +++ b/IO/ParallelXML/vtkXMLPStructuredGridWriter.h @@ -39,11 +39,9 @@ class VTKIOPARALLELXML_EXPORT vtkXMLPStructuredGridWriter : public vtkXMLPStruct vtkTypeMacro(vtkXMLPStructuredGridWriter,vtkXMLPStructuredDataWriter); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Get/Set the writer's input. vtkStructuredGrid* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/ParallelXML/vtkXMLPUniformGridAMRWriter.h b/IO/ParallelXML/vtkXMLPUniformGridAMRWriter.h index eb72aeeaeed..f21cbfd0852 100644 --- a/IO/ParallelXML/vtkXMLPUniformGridAMRWriter.h +++ b/IO/ParallelXML/vtkXMLPUniformGridAMRWriter.h @@ -53,7 +53,6 @@ class VTKIOPARALLELXML_EXPORT vtkXMLPUniformGridAMRWriter : public vtkXMLUniform // WriteMetaFile set to 0 by default. virtual void SetWriteMetaFile(int flag); -//BTX protected: vtkXMLPUniformGridAMRWriter(); ~vtkXMLPUniformGridAMRWriter(); @@ -66,7 +65,7 @@ class VTKIOPARALLELXML_EXPORT vtkXMLPUniformGridAMRWriter : public vtkXMLUniform private: vtkXMLPUniformGridAMRWriter(const vtkXMLPUniformGridAMRWriter&); // Not implemented. void operator=(const vtkXMLPUniformGridAMRWriter&); // Not implemented. -//ETX + }; #endif diff --git a/IO/ParallelXML/vtkXMLPUnstructuredGridWriter.h b/IO/ParallelXML/vtkXMLPUnstructuredGridWriter.h index 3b361b1563b..3514f563616 100644 --- a/IO/ParallelXML/vtkXMLPUnstructuredGridWriter.h +++ b/IO/ParallelXML/vtkXMLPUnstructuredGridWriter.h @@ -39,11 +39,9 @@ class VTKIOPARALLELXML_EXPORT vtkXMLPUnstructuredGridWriter : public vtkXMLPUnst vtkTypeMacro(vtkXMLPUnstructuredGridWriter,vtkXMLPUnstructuredDataWriter); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Get/Set the writer's input. vtkUnstructuredGridBase* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/PostgreSQL/vtkPostgreSQLDatabase.h b/IO/PostgreSQL/vtkPostgreSQLDatabase.h index d94b33e78e8..7df0432fc45 100644 --- a/IO/PostgreSQL/vtkPostgreSQLDatabase.h +++ b/IO/PostgreSQL/vtkPostgreSQLDatabase.h @@ -53,10 +53,9 @@ struct PQconn; class VTKIOPOSTGRESQL_EXPORT vtkPostgreSQLDatabase : public vtkSQLDatabase { - //BTX + friend class vtkPostgreSQLQuery; friend class vtkPostgreSQLQueryPrivate; - //ETX public: vtkTypeMacro(vtkPostgreSQLDatabase, vtkSQLDatabase); diff --git a/IO/PostgreSQL/vtkPostgreSQLQuery.h b/IO/PostgreSQL/vtkPostgreSQLQuery.h index c19806aafa1..9490463226d 100644 --- a/IO/PostgreSQL/vtkPostgreSQLQuery.h +++ b/IO/PostgreSQL/vtkPostgreSQLQuery.h @@ -117,9 +117,7 @@ class VTKIOPOSTGRESQL_EXPORT vtkPostgreSQLQuery : public vtkSQLQuery void DeleteQueryResults(); - //BTX friend class vtkPostgreSQLDatabase; - //ETX private: vtkPostgreSQLQuery( const vtkPostgreSQLQuery& ); // Not implemented. diff --git a/IO/SQL/vtkDatabaseToTableReader.h b/IO/SQL/vtkDatabaseToTableReader.h index 73ba98633b8..eeb3effa1b4 100644 --- a/IO/SQL/vtkDatabaseToTableReader.h +++ b/IO/SQL/vtkDatabaseToTableReader.h @@ -54,9 +54,9 @@ class VTKIOSQL_EXPORT vtkDatabaseToTableReader : public vtkTableAlgorithm int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *) = 0; vtkSQLDatabase *Database; - //BTX + std::string TableName; - //ETX + private: vtkDatabaseToTableReader(const vtkDatabaseToTableReader&); // Not implemented. void operator=(const vtkDatabaseToTableReader&); // Not implemented. diff --git a/IO/SQL/vtkSQLDatabase.h b/IO/SQL/vtkSQLDatabase.h index ad516555bbc..6955f7fcc1f 100644 --- a/IO/SQL/vtkSQLDatabase.h +++ b/IO/SQL/vtkSQLDatabase.h @@ -101,7 +101,7 @@ class VTKIOSQL_EXPORT vtkSQLDatabase : public vtkObject // Description: // Return an empty query on this database. - virtual vtkSQLQuery* GetQueryInstance() = 0; + virtual VTK_NEWINSTANCE vtkSQLQuery* GetQueryInstance() = 0; // Description: // Did the last operation generate an error @@ -187,17 +187,15 @@ class VTKIOSQL_EXPORT vtkSQLDatabase : public vtkObject // Create a the proper subclass given a URL. // The URL format for SQL databases is a true URL of the form: // 'protocol://'[[username[':'password]'@']hostname[':'port]]'/'[dbname] . - static vtkSQLDatabase* CreateFromURL( const char* URL ); + static VTK_NEWINSTANCE vtkSQLDatabase* CreateFromURL( const char* URL ); // Description: // Effect a database schema. virtual bool EffectSchema( vtkSQLDatabaseSchema*, bool dropIfExists = false ); -//BTX // Description: // Type for CreateFromURL callback. typedef vtkSQLDatabase* (*CreateFunction)(const char* URL); -//ETX // Description: // Provides mechanism to register/unregister additional callbacks to create @@ -216,7 +214,6 @@ class VTKIOSQL_EXPORT vtkSQLDatabase : public vtkObject // information (full text)for specific documents. static vtkInformationObjectBaseKey* DATABASE(); -//BTX protected: vtkSQLDatabase(); ~vtkSQLDatabase(); @@ -235,7 +232,7 @@ class VTKIOSQL_EXPORT vtkSQLDatabase : public vtkObject // Datastructure used to store registered callbacks. class vtkCallbackVector; static vtkCallbackVector* Callbacks; -//ETX + }; #endif // vtkSQLDatabase_h diff --git a/IO/SQL/vtkSQLDatabaseGraphSource.h b/IO/SQL/vtkSQLDatabaseGraphSource.h index 2484c7bebe2..5ac92cb2ec9 100644 --- a/IO/SQL/vtkSQLDatabaseGraphSource.h +++ b/IO/SQL/vtkSQLDatabaseGraphSource.h @@ -101,10 +101,8 @@ class VTKIOSQL_EXPORT vtkSQLDatabaseGraphSource : public vtkGraphAlgorithm // and re-emits them as if they came from this class. vtkEventForwarderCommand *EventForwarder; -//BTX class implementation; implementation* const Implementation; -//ETX bool Directed; diff --git a/IO/SQL/vtkSQLDatabaseSchema.h b/IO/SQL/vtkSQLDatabaseSchema.h index 91adfa9ea96..790d17a22df 100644 --- a/IO/SQL/vtkSQLDatabaseSchema.h +++ b/IO/SQL/vtkSQLDatabaseSchema.h @@ -62,7 +62,6 @@ class VTKIOSQL_EXPORT vtkSQLDatabaseSchema : public vtkObject void PrintSelf(ostream& os, vtkIndent indent); static vtkSQLDatabaseSchema* New(); - //BTX // Description: // Basic data types for database columns enum DatabaseColumnType @@ -101,7 +100,6 @@ class VTKIOSQL_EXPORT vtkSQLDatabaseSchema : public vtkObject BEFORE_DELETE = 4, // Just before a row is deleted AFTER_DELETE = 5 // Just after a row is deleted }; - //ETX // Description: // Add a preamble to the schema @@ -332,7 +330,6 @@ class VTKIOSQL_EXPORT vtkSQLDatabaseSchema : public vtkObject vtkSetStringMacro(Name); vtkGetStringMacro(Name); - //BTX // Tokens passed to AddTable to indicate the type of data that follows. Random integers chosen to prevent mishaps. enum VarargTokens { @@ -374,16 +371,14 @@ class VTKIOSQL_EXPORT vtkSQLDatabaseSchema : public vtkObject // return 0; // } int AddTableMultipleArguments( const char* tblName, ... ); - //ETX protected: vtkSQLDatabaseSchema(); ~vtkSQLDatabaseSchema(); char* Name; -//BTX + class vtkSQLDatabaseSchemaInternals* Internals; -//ETX private: vtkSQLDatabaseSchema(const vtkSQLDatabaseSchema &); // Not implemented. diff --git a/IO/SQL/vtkSQLDatabaseTableSource.h b/IO/SQL/vtkSQLDatabaseTableSource.h index c07b1b7bd84..9979efb18ca 100644 --- a/IO/SQL/vtkSQLDatabaseTableSource.h +++ b/IO/SQL/vtkSQLDatabaseTableSource.h @@ -82,10 +82,9 @@ class VTKIOSQL_EXPORT vtkSQLDatabaseTableSource : public vtkTableAlgorithm // and re-emits them as if they came from this class. vtkEventForwarderCommand *EventForwarder; -//BTX class implementation; implementation* const Implementation; -//ETX + }; #endif diff --git a/IO/SQL/vtkSQLQuery.h b/IO/SQL/vtkSQLQuery.h index 223002ba4d5..6673ad288bc 100644 --- a/IO/SQL/vtkSQLQuery.h +++ b/IO/SQL/vtkSQLQuery.h @@ -99,7 +99,6 @@ class VTKIOSQL_EXPORT vtkSQLQuery : public vtkRowQuery // Return the database associated with the query. vtkGetObjectMacro(Database, vtkSQLDatabase); -//BTX // Description: // Bind a parameter to a placeholder in a query. A full discussion // of this feature is beyond the scope of this header file, but in @@ -137,13 +136,13 @@ class VTKIOSQL_EXPORT vtkSQLQuery : public vtkRowQuery // types are signed unless otherwise specified. virtual bool BindParameter(int index, signed char value); virtual bool BindParameter(int index, short value); -//ETX + virtual bool BindParameter(int index, int value); -//BTX + virtual bool BindParameter(int index, long value); virtual bool BindParameter(int index, vtkTypeUInt64 value); virtual bool BindParameter(int index, vtkTypeInt64 value); -//ETX + virtual bool BindParameter(int index, float value); virtual bool BindParameter(int index, double value); // Description: @@ -152,9 +151,9 @@ class VTKIOSQL_EXPORT vtkSQLQuery : public vtkRowQuery // Description: // Bind a string value by specifying an array and a size virtual bool BindParameter(int index, const char *stringValue, size_t length); -//BTX + virtual bool BindParameter(int index, const vtkStdString &string); -//ETX + virtual bool BindParameter(int index, vtkVariant var); // Description: // Bind a blob value. Not all databases support blobs as a data @@ -165,7 +164,6 @@ class VTKIOSQL_EXPORT vtkSQLQuery : public vtkRowQuery // Reset all parameter bindings to NULL. virtual bool ClearParameterBindings(); -//BTX // Description: // Escape a string for inclusion into an SQL query. // If \a addSurroundingQuotes is true, then quotation marks appropriate to the @@ -176,7 +174,6 @@ class VTKIOSQL_EXPORT vtkSQLQuery : public vtkRowQuery // database backends that do not provde a way to escape // strings for use inside queries. virtual vtkStdString EscapeString( vtkStdString s, bool addSurroundingQuotes = true ); -//ETX // Description: // Escape a string for inclusion into an SQL query. diff --git a/IO/SQL/vtkSQLiteDatabase.h b/IO/SQL/vtkSQLiteDatabase.h index 640355ad49d..8fd9f54b33d 100644 --- a/IO/SQL/vtkSQLiteDatabase.h +++ b/IO/SQL/vtkSQLiteDatabase.h @@ -53,23 +53,20 @@ struct vtk_sqlite3; class VTKIOSQL_EXPORT vtkSQLiteDatabase : public vtkSQLDatabase { - //BTX + friend class vtkSQLiteQuery; - //ETX public: vtkTypeMacro(vtkSQLiteDatabase, vtkSQLDatabase); void PrintSelf(ostream& os, vtkIndent indent); static vtkSQLiteDatabase *New(); - //BTX enum { USE_EXISTING, USE_EXISTING_OR_CREATE, CREATE_OR_CLEAR, CREATE }; - //ETX // Description: // Open a new connection to the database. You need to set the diff --git a/IO/SQL/vtkSQLiteQuery.h b/IO/SQL/vtkSQLiteQuery.h index bfab39a3ca9..68820d3937a 100644 --- a/IO/SQL/vtkSQLiteQuery.h +++ b/IO/SQL/vtkSQLiteQuery.h @@ -51,9 +51,8 @@ struct vtk_sqlite3_stmt; class VTKIOSQL_EXPORT vtkSQLiteQuery : public vtkSQLQuery { - //BTX + friend class vtkSQLiteDatabase; - //ETX public: vtkTypeMacro(vtkSQLiteQuery, vtkSQLQuery); @@ -111,21 +110,21 @@ class VTKIOSQL_EXPORT vtkSQLiteQuery : public vtkSQLQuery // further explanation. The driver makes internal copies of string // and BLOB parameters so you don't need to worry about keeping them // in scope until the query finishes executing. -//BTX + using vtkSQLQuery::BindParameter; bool BindParameter(int index, unsigned char value); bool BindParameter(int index, signed char value); bool BindParameter(int index, unsigned short value); bool BindParameter(int index, short value); bool BindParameter(int index, unsigned int value); -//ETX + bool BindParameter(int index, int value); -//BTX + bool BindParameter(int index, unsigned long value); bool BindParameter(int index, long value); bool BindParameter(int index, vtkTypeUInt64 value); bool BindParameter(int index, vtkTypeInt64 value); -//ETX + bool BindParameter(int index, float value); bool BindParameter(int index, double value); // Description: @@ -134,9 +133,9 @@ class VTKIOSQL_EXPORT vtkSQLiteQuery : public vtkSQLQuery // Description: // Bind a string value by specifying an array and a size bool BindParameter(int index, const char *stringValue, size_t length); -//BTX + bool BindParameter(int index, const vtkStdString &string); -//ETX + bool BindParameter(int index, vtkVariant value); // Description: // Bind a blob value. Not all databases support blobs as a data diff --git a/IO/SQL/vtkTableToDatabaseWriter.h b/IO/SQL/vtkTableToDatabaseWriter.h index 6d441fa734d..06bcda16432 100644 --- a/IO/SQL/vtkTableToDatabaseWriter.h +++ b/IO/SQL/vtkTableToDatabaseWriter.h @@ -65,9 +65,8 @@ class VTKIOSQL_EXPORT vtkTableToDatabaseWriter : public vtkWriter vtkSQLDatabase *Database; vtkTable *Input; - //BTX + std::string TableName; - //ETX private: vtkTableToDatabaseWriter(const vtkTableToDatabaseWriter&); // Not implemented. diff --git a/IO/TecplotTable/CMakeLists.txt b/IO/TecplotTable/CMakeLists.txt new file mode 100644 index 00000000000..152e8f533d7 --- /dev/null +++ b/IO/TecplotTable/CMakeLists.txt @@ -0,0 +1,5 @@ +set(Module_SRCS + vtkTecplotTableReader.cxx + ) + +vtk_module_library(vtkIOTecplotTable ${Module_SRCS}) diff --git a/IO/TecplotTable/Testing/Cxx/CMakeLists.txt b/IO/TecplotTable/Testing/Cxx/CMakeLists.txt new file mode 100644 index 00000000000..102cb223d5e --- /dev/null +++ b/IO/TecplotTable/Testing/Cxx/CMakeLists.txt @@ -0,0 +1,13 @@ + +vtk_add_test_cxx(${vtk-module}CxxTests tests + NO_VALID + TestTecplotTableReader.cxx + ) + +ExternalData_add_test(VTKData + NAME TestTecplotTableReader + COMMAND ${vtk-module}CxxTests TestTecplotTableReader + -D DATA{../Data/residuals.dat} + ) + +vtk_test_cxx_executable(${vtk-module}CxxTests tests) diff --git a/IO/TecplotTable/Testing/Cxx/TestTecplotTableReader.cxx b/IO/TecplotTable/Testing/Cxx/TestTecplotTableReader.cxx new file mode 100644 index 00000000000..717733a5b4a --- /dev/null +++ b/IO/TecplotTable/Testing/Cxx/TestTecplotTableReader.cxx @@ -0,0 +1,52 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestDelimitedTextReader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include +#include +#include + +// This tests the ability to read a Tecplot table. The test file contains residuals from a CFD calculation. +int TestTecplotTableReader(int argc, char *argv[]) +{ + //------------ test the reader with an input file----------------- + if (argc != 3) return 0; // for some reason we get called twice, once with 5 arguments that are not pointing to the file + + char* filename = argv[2]; + std::cout << filename << std::endl; + vtkTecplotTableReader *reader = vtkTecplotTableReader::New(); + reader->SetFileName(filename); + reader->OutputPedigreeIdsOn(); + reader->Update(); + + vtkTable* table = reader->GetOutput(); + table->Dump(); + cout << "Printing reader info..." << endl; + reader->Print(cout); + + if (table->GetNumberOfRows() != 171) + { + cout << "ERROR: Wrong number of rows: " << table->GetNumberOfRows()<GetNumberOfColumns() != 11 + 1) // one extra for pedigree ids + { + cout << "ERROR: Wrong number of columns: " << table->GetNumberOfColumns()<Delete(); + + return 0; +} diff --git a/IO/TecplotTable/Testing/Data/residuals.dat.md5 b/IO/TecplotTable/Testing/Data/residuals.dat.md5 new file mode 100644 index 00000000000..e055eb08444 --- /dev/null +++ b/IO/TecplotTable/Testing/Data/residuals.dat.md5 @@ -0,0 +1 @@ +ad064f17d0cf8231239690b0e0c412ed diff --git a/IO/TecplotTable/module.cmake b/IO/TecplotTable/module.cmake new file mode 100644 index 00000000000..722c6adac78 --- /dev/null +++ b/IO/TecplotTable/module.cmake @@ -0,0 +1,11 @@ +vtk_module(vtkIOTecplotTable + GROUPS + StandAlone + DEPENDS + vtkCommonExecutionModel + TEST_DEPENDS + vtkTestingCore + PRIVATE_DEPENDS + vtksys + vtkIOCore + ) diff --git a/IO/TecplotTable/vtkTecplotTableReader.cxx b/IO/TecplotTable/vtkTecplotTableReader.cxx new file mode 100644 index 00000000000..f416dd453c6 --- /dev/null +++ b/IO/TecplotTable/vtkTecplotTableReader.cxx @@ -0,0 +1,510 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkTecplotTableReader.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/*------------------------------------------------------------------------- + Copyright 2016 Menno Deij - van Rijswijk (MARIN) +-------------------------------------------------------------------------*/ + +#include "vtkTecplotTableReader.h" +#include "vtkCommand.h" +#include "vtkDataSetAttributes.h" +#include "vtkIdTypeArray.h" +#include "vtkInformation.h" +#include "vtkInformationVector.h" +#include "vtkObjectFactory.h" +#include "vtkSmartPointer.h" +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkTable.h" +#include "vtkDoubleArray.h" + +#include "vtkTextCodec.h" +#include "vtkTextCodecFactory.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +//////////////////////////////////////////////////////////////////////////////// +// DelimitedTextIterator + +/// Output iterator object that parses a stream of Unicode characters into records and +/// fields, inserting them into a vtkTable. Based on the iterator from +/// vtkIOInfoVis::DelimitedTextReader but tailored to Tecplot table files + +namespace { + +class DelimitedTextIterator : public vtkTextCodec::OutputIterator +{ +public: + typedef std::forward_iterator_tag iterator_category; + typedef vtkUnicodeStringValueType value_type; + typedef std::string::difference_type difference_type; + typedef value_type* pointer; + typedef value_type& reference; + + DelimitedTextIterator( + vtkTable* const outputTable, + const vtkIdType maxRecords, + const vtkIdType headerLines, + const vtkIdType columnHeadersOnLine, + const vtkIdType skipColumnNames + ): + MaxRecords(maxRecords), + MaxRecordIndex(maxRecords + headerLines), // first two lines are title + column names + WhiteSpaceOnlyString(true), + OutputTable(outputTable), + CurrentRecordIndex(0), + CurrentFieldIndex(0), + HeaderLines(headerLines), + ColumnNamesOnLine(columnHeadersOnLine), + SkipColumnNames(skipColumnNames), + RecordAdjacent(true), + MergeConsDelims(true), + ProcessEscapeSequence(false), + UseStringDelimiter(true), + WithinString(0) + { + // how records (e.g. lines) are separated + RecordDelimiters.insert('\n'); + RecordDelimiters.insert('\r'); + + // how fields (e.g. entries) are separated + FieldDelimiters.insert(' '); + FieldDelimiters.insert('\t'); + + // how string entries are separated + StringDelimiters.insert('"'); + StringDelimiters.insert(' '); + + // what is whitespace + Whitespace.insert(' '); + Whitespace.insert('\t'); + } + + ~DelimitedTextIterator() + { + // Ensure that all table columns have the same length ... + for(vtkIdType i = 0; i != this->OutputTable->GetNumberOfColumns(); ++i) + { + if(this->OutputTable->GetColumn(i)->GetNumberOfTuples() != + this->OutputTable->GetColumn(0)->GetNumberOfTuples()) + { + this->OutputTable->GetColumn(i) + ->Resize(this->OutputTable->GetColumn(0)->GetNumberOfTuples()); + } + } + } + + DelimitedTextIterator& operator++(int) + { + return *this; + } + + DelimitedTextIterator& operator*() + { + return *this; + } + + // Handle windows files that do not have a carriage return line feed on the last line of the file ... + void ReachedEndOfInput() + { + if(this->CurrentField.empty()) + { + return; + } + vtkUnicodeString::value_type value = + this->CurrentField[this->CurrentField.character_count()-1]; + if(!this->RecordDelimiters.count(value) && !this->Whitespace.count(value)) + { + this->InsertField(); + } + } + + DelimitedTextIterator& operator=(const vtkUnicodeString::value_type value) + { + // If we've already read our maximum number of records, we're done ... + if(this->MaxRecords && this->CurrentRecordIndex == this->MaxRecordIndex) + { + return *this; + } + + // Strip adjacent record delimiters and whitespace... + if(this->RecordAdjacent && (this->RecordDelimiters.count(value) || + this->Whitespace.count(value))) + { + return *this; + } + else + { + this->RecordAdjacent = false; + } + + // Look for record delimiters ... + if(this->RecordDelimiters.count(value)) + { + // keep skipping until column names line + if (this->CurrentRecordIndex < ColumnNamesOnLine) + { + this->CurrentRecordIndex += 1; + return *this; + } + + this->InsertField(); + this->CurrentRecordIndex += 1; + this->CurrentFieldIndex = 0; + this->CurrentField.clear(); + this->RecordAdjacent = true; + this->WithinString = 0; + this->WhiteSpaceOnlyString = true; + return *this; + } + + if (this->CurrentRecordIndex < ColumnNamesOnLine) + { + return *this; // keep skipping until column names line + } + + // Look for field delimiters unless we're in a string ... + if(!this->WithinString && this->FieldDelimiters.count(value)) + { + // Handle special case of merging consective delimiters ... + if( !(this->CurrentField.empty() && this->MergeConsDelims) ) + { + if (!(this->CurrentFieldIndex < SkipColumnNames && this->CurrentRecordIndex == ColumnNamesOnLine)) + //if (!(this->CurrentFieldIndex == 0 && this->CurrentRecordIndex == 1)) + { + this->InsertField(); + } + this->CurrentFieldIndex += 1; + this->CurrentField.clear(); + } + return *this; + } + + // Check for start of escape sequence ... + if(!this->ProcessEscapeSequence && this->EscapeDelimiter.count(value)) + { + this->ProcessEscapeSequence = true; + return *this; + } + + // Process escape sequence ... + if(this->ProcessEscapeSequence) + { + vtkUnicodeString curr_char; + curr_char += value; + if(curr_char == vtkUnicodeString::from_utf8("0")) + { + this->CurrentField += vtkUnicodeString::from_utf8("\0"); + } + else if(curr_char == vtkUnicodeString::from_utf8("a")) + { + this->CurrentField += vtkUnicodeString::from_utf8("\a"); + } + else if(curr_char == vtkUnicodeString::from_utf8("b")) + { + this->CurrentField += vtkUnicodeString::from_utf8("\b"); + } + else if(curr_char == vtkUnicodeString::from_utf8("t")) + { + this->CurrentField += vtkUnicodeString::from_utf8("\t"); + } + else if(curr_char == vtkUnicodeString::from_utf8("n")) + { + this->CurrentField += vtkUnicodeString::from_utf8("\n"); + } + else if(curr_char == vtkUnicodeString::from_utf8("v")) + { + this->CurrentField += vtkUnicodeString::from_utf8("\v"); + } + else if(curr_char == vtkUnicodeString::from_utf8("f")) + { + this->CurrentField += vtkUnicodeString::from_utf8("\f"); + } + else if(curr_char == vtkUnicodeString::from_utf8("r")) + { + this->CurrentField += vtkUnicodeString::from_utf8("\r"); + } + else if(curr_char == vtkUnicodeString::from_utf8("\\")) + { + this->CurrentField += vtkUnicodeString::from_utf8("\\"); + } + else + { + this->CurrentField += value; + } + this->ProcessEscapeSequence = false; + return *this; + } + + // Start a string ... + if(!this->WithinString && this->StringDelimiters.count(value) && + this->UseStringDelimiter) + { + this->WithinString = value; + this->CurrentField.clear(); + return *this; + } + + // End a string ... + if(this->WithinString && (this->WithinString == value) && + this->UseStringDelimiter) + { + this->WithinString = 0; + return *this; + } + + if(!this->Whitespace.count(value)) + { + this->WhiteSpaceOnlyString = false; + } + // Keep growing the current field ... + this->CurrentField += value; + return *this; + } + +private: + void InsertField() + { + vtkIdType fieldIndex = this->CurrentFieldIndex; + if (this->CurrentRecordIndex == ColumnNamesOnLine) + { + fieldIndex -= SkipColumnNames; + } + + if(fieldIndex >= this->OutputTable->GetNumberOfColumns() && ColumnNamesOnLine == this->CurrentRecordIndex) + { + vtkDoubleArray* array = vtkDoubleArray::New(); + + array->SetName(this->CurrentField.utf8_str()); + this->OutputTable->AddColumn(array); + array->Delete(); + } + else if(fieldIndex < this->OutputTable->GetNumberOfColumns()) + { + // Handle case where input file has header information ... + vtkIdType recordIndex; + recordIndex = this->CurrentRecordIndex - HeaderLines; + vtkDoubleArray* array = vtkArrayDownCast(this->OutputTable->GetColumn(fieldIndex)); + + vtkStdString str; + str = this->CurrentField.utf8_str(); + bool ok; + double doubleValue = vtkVariant(str).ToDouble(&ok); + if (ok) + { + array->InsertValue(recordIndex, doubleValue); + } + else + { + array->InsertValue(recordIndex, std::numeric_limits::quiet_NaN()); + } + } + } + + vtkIdType MaxRecords; + vtkIdType MaxRecordIndex; + std::set RecordDelimiters; + std::set FieldDelimiters; + std::set StringDelimiters; + std::set Whitespace; + std::set EscapeDelimiter; + + bool WhiteSpaceOnlyString; + vtkTable* OutputTable; + vtkIdType CurrentRecordIndex; + vtkIdType CurrentFieldIndex; + vtkUnicodeString CurrentField; + + vtkIdType HeaderLines; + vtkIdType ColumnNamesOnLine; + vtkIdType SkipColumnNames; + + + bool RecordAdjacent; + bool MergeConsDelims; + bool ProcessEscapeSequence; + bool UseStringDelimiter; + vtkUnicodeString::value_type WithinString; +}; + +} // End anonymous namespace + +///////////////////////////////////////////////////////////////////////////////////////// +// vtkTecplotTableReader + +vtkStandardNewMacro(vtkTecplotTableReader); + +vtkTecplotTableReader::vtkTecplotTableReader() : + FileName(0), + MaxRecords(0), + HeaderLines(2), + ColumnNamesOnLine(1), + SkipColumnNames(1) +{ + this->SetNumberOfInputPorts(0); + this->SetNumberOfOutputPorts(1); + this->PedigreeIdArrayName = NULL; + this->SetPedigreeIdArrayName("id"); + this->GeneratePedigreeIds = false; + this->OutputPedigreeIds = false; +} + +vtkTecplotTableReader::~vtkTecplotTableReader() +{ + this->SetPedigreeIdArrayName(0); + this->SetFileName(0); +} + +void vtkTecplotTableReader::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "FileName: " + << (this->FileName ? this->FileName : "(none)") << endl; + os << indent << "MaxRecords: " << this->MaxRecords + << endl; + os << indent << "GeneratePedigreeIds: " + << this->GeneratePedigreeIds << endl; + os << indent << "PedigreeIdArrayName: " + << this->PedigreeIdArrayName << endl; + os << indent << "OutputPedigreeIds: " + << (this->OutputPedigreeIds? "true" : "false") << endl; +} + +vtkStdString vtkTecplotTableReader::GetLastError() +{ + return this->LastError; +} + +int vtkTecplotTableReader::RequestData( + vtkInformation*, + vtkInformationVector**, + vtkInformationVector* outputVector) +{ + vtkTable* const output_table = vtkTable::GetData(outputVector); + + this->LastError = ""; + + try + { + // We only retrieve one piece ... + vtkInformation* const outInfo = outputVector->GetInformationObject(0); + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) && + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) + { + return 1; + } + + if (!this->PedigreeIdArrayName) + { + vtkErrorMacro(<<"You must specify a pedigree id array name"); + return 0; + } + + istream* input_stream_pt = NULL; + ifstream file_stream; + + // If the filename hasn't been specified, we're done ... + if(!this->FileName) + { + return 1; + } + // Get the total size of the input file in bytes + file_stream.open(this->FileName, ios::binary); + if(!file_stream.good()) + { + vtkErrorMacro(<<"Unable to open input file" << std::string(this->FileName)); + return 0; + } + + file_stream.seekg(0, ios::end); + file_stream.seekg(0, ios::beg); + + input_stream_pt = dynamic_cast(&file_stream); + vtkTextCodec* transCodec = vtkTextCodecFactory::CodecToHandle(*input_stream_pt); + + if (NULL == transCodec) + { + // should this use the locale instead?? + return 1; + } + + DelimitedTextIterator iterator( + output_table, + this->MaxRecords, + this->HeaderLines, + this->ColumnNamesOnLine, + this->SkipColumnNames); + + vtkTextCodec::OutputIterator& outIter = iterator; + + transCodec->ToUnicode(*input_stream_pt, outIter); + iterator.ReachedEndOfInput(); + transCodec->Delete(); + + if(this->OutputPedigreeIds) + { + vtkAbstractArray *arr = + output_table->GetColumnByName(this->PedigreeIdArrayName); + + if (this->GeneratePedigreeIds || !arr) + { + vtkSmartPointer pedigreeIds = + vtkSmartPointer::New(); + vtkIdType numRows = output_table->GetNumberOfRows(); + pedigreeIds->SetNumberOfTuples(numRows); + pedigreeIds->SetName(this->PedigreeIdArrayName); + for (vtkIdType i = 0; i < numRows; ++i) + { + pedigreeIds->InsertValue(i, i); + } + output_table->GetRowData()->SetPedigreeIds(pedigreeIds); + } + else + { + if (arr) + { + output_table->GetRowData()->SetPedigreeIds(arr); + } + else + { + vtkErrorMacro(<< "Could not find pedigree id array: " << std::string(this->PedigreeIdArrayName)); + return 0; + } + } + } + } + catch(std::exception& e) + { + vtkErrorMacro(<< "caught exception: " << e.what()); + this->LastError = e.what(); + output_table->Initialize(); + return 0; + } + catch(...) + { + vtkErrorMacro(<< "caught unknown exception."); + this->LastError = "Unknown exception."; + output_table->Initialize(); + return 0; + } + + return 1; +} diff --git a/IO/TecplotTable/vtkTecplotTableReader.h b/IO/TecplotTable/vtkTecplotTableReader.h new file mode 100644 index 00000000000..cfd99e0a3c5 --- /dev/null +++ b/IO/TecplotTable/vtkTecplotTableReader.h @@ -0,0 +1,124 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkTecplotTableReader.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +/*------------------------------------------------------------------------- + Copyright 2016 Menno Deij - van Rijswijk (MARIN) +-------------------------------------------------------------------------*/ + + +// .NAME vtkTecplotTableReader - reads in Tecplot tabular data +// and outputs a vtkTable data structure. +// +// .SECTION Description +// vtkTecplotTableReader is an interface for reading tabulat data in Tecplot +// ascii format. +// +// .SECTION Thanks +// Thanks to vtkDelimitedTextReader authors. +// + +#ifndef vtkTecplotTableReader_h +#define vtkTecplotTableReader_h + +#include "vtkIOTecplotTableModule.h" // For export macro +#include "vtkTableAlgorithm.h" +#include "vtkUnicodeString.h" // Needed for vtkUnicodeString +#include "vtkStdString.h" // Needed for vtkStdString + +class VTKIOTECPLOTTABLE_EXPORT vtkTecplotTableReader : public vtkTableAlgorithm +{ +public: + static vtkTecplotTableReader* New(); + vtkTypeMacro(vtkTecplotTableReader, vtkTableAlgorithm); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Specifies the delimited text file to be loaded. + vtkGetStringMacro(FileName); + vtkSetStringMacro(FileName); + + // Description: + // Specifies the maximum number of records to read from the file. Limiting the + // number of records to read is useful for previewing the contents of a file. + vtkGetMacro(MaxRecords, vtkIdType); + vtkSetMacro(MaxRecords, vtkIdType); + + // Description: + // Specifies the number of lines that form the header of the file. Default is 2. + vtkGetMacro(HeaderLines, vtkIdType); + vtkSetMacro(HeaderLines, vtkIdType); + + // Description: + // Specifies the line number that holds the column names. Default is 1. + vtkGetMacro(ColumnNamesOnLine, vtkIdType); + vtkSetMacro(ColumnNamesOnLine, vtkIdType); + + // Description + // Specifies the number of fields to skip while reading the column names. Default is 1. + vtkGetMacro(SkipColumnNames, vtkIdType); + vtkSetMacro(SkipColumnNames, vtkIdType); + + + + // Description: + // The name of the array for generating or assigning pedigree ids + // (default "id"). + vtkSetStringMacro(PedigreeIdArrayName); + vtkGetStringMacro(PedigreeIdArrayName); + + // Description: + // If on (default), generates pedigree ids automatically. + // If off, assign one of the arrays to be the pedigree id. + vtkSetMacro(GeneratePedigreeIds, bool); + vtkGetMacro(GeneratePedigreeIds, bool); + vtkBooleanMacro(GeneratePedigreeIds, bool); + + // Description: + // If on, assigns pedigree ids to output. Defaults to off. + vtkSetMacro(OutputPedigreeIds, bool); + vtkGetMacro(OutputPedigreeIds, bool); + vtkBooleanMacro(OutputPedigreeIds, bool); + + // Description: + // Returns a human-readable description of the most recent error, if any. + // Otherwise, returns an empty string. Note that the result is only valid + // after calling Update(). + vtkStdString GetLastError(); + +protected: + vtkTecplotTableReader(); + ~vtkTecplotTableReader(); + + int RequestData( + vtkInformation*, + vtkInformationVector**, + vtkInformationVector*); + + char* FileName; + vtkIdType MaxRecords; + vtkIdType HeaderLines; + vtkIdType ColumnNamesOnLine; + vtkIdType SkipColumnNames; + char* PedigreeIdArrayName; + bool GeneratePedigreeIds; + bool OutputPedigreeIds; + vtkStdString LastError; + +private: + vtkTecplotTableReader(const vtkTecplotTableReader&); // Not implemented + void operator=(const vtkTecplotTableReader&); // Not implemented + +}; + +#endif diff --git a/IO/VPIC/vtkVPICReader.h b/IO/VPIC/vtkVPICReader.h index d11576217ae..0c596b3f09d 100644 --- a/IO/VPIC/vtkVPICReader.h +++ b/IO/VPIC/vtkVPICReader.h @@ -36,10 +36,10 @@ class vtkFloatArray; class vtkStdString; class vtkMultiProcessController; class vtkInformation; -//BTX + class VPICDataSet; class GridExchange; -//ETX + class VTKIOVPIC_EXPORT vtkVPICReader : public vtkImageAlgorithm { public: diff --git a/IO/XML/Testing/Cxx/CMakeLists.txt b/IO/XML/Testing/Cxx/CMakeLists.txt index c9973dd1224..a8013579851 100644 --- a/IO/XML/Testing/Cxx/CMakeLists.txt +++ b/IO/XML/Testing/Cxx/CMakeLists.txt @@ -7,6 +7,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestXMLUnstructuredGridReader.cxx TestXML.cxx,NO_DATA,NO_VALID,NO_OUTPUT TestXMLToString.cxx,NO_DATA,NO_VALID,NO_OUTPUT + TestXMLWriterWithDataArrayFallback.cxx,NO_VALID TestDataObjectXMLIO.cxx,NO_VALID ) @@ -28,3 +29,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests ) vtk_test_cxx_executable(${vtk-module}CxxTests tests) + +add_executable(TestXMLCInterface MACOSX_BUNDLE TestXMLCInterface.c) +target_link_libraries(TestXMLCInterface LINK_PRIVATE vtkIOXML) +add_test(NAME TestXMLCInterface COMMAND TestXMLCInterface) diff --git a/IO/XML/Testing/Cxx/TestXMLCInterface.c b/IO/XML/Testing/Cxx/TestXMLCInterface.c index 75a68a37e6f..93be603fa81 100644 --- a/IO/XML/Testing/Cxx/TestXMLCInterface.c +++ b/IO/XML/Testing/Cxx/TestXMLCInterface.c @@ -21,6 +21,7 @@ int main() { int i,j; + { vtkXMLWriterC* writer = vtkXMLWriterC_New(); const char filename[] = "cube.vtu"; float points[3*NPOINTS] = {0, 0, 0, @@ -62,6 +63,6 @@ int main() } vtkXMLWriterC_Stop(writer); vtkXMLWriterC_Delete(writer); - + } return 0; } diff --git a/IO/XML/Testing/Cxx/TestXMLWriterWithDataArrayFallback.cxx b/IO/XML/Testing/Cxx/TestXMLWriterWithDataArrayFallback.cxx new file mode 100644 index 00000000000..8f0cbcc0200 --- /dev/null +++ b/IO/XML/Testing/Cxx/TestXMLWriterWithDataArrayFallback.cxx @@ -0,0 +1,93 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestXMLWriterWithDataArrayFallback.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME Test of vtkXMLWriter with data array dispatch fallback +// .SECTION Description +// + +#include "vtkImageData.h" +#include "vtkIntArray.h" +#include "vtkNew.h" +#include "vtkPointData.h" +#include "vtkTestDataArray.h" +#include "vtkTestUtilities.h" +#include "vtkXMLImageDataReader.h" +#include "vtkXMLImageDataWriter.h" + +#include + +int TestXMLWriterWithDataArrayFallback(int argc, char *argv[]) +{ + char* temp_dir_c = + vtkTestUtilities::GetArgOrEnvOrDefault("-T", argc, argv, + "VTK_TEMP_DIR", + "Testing/Temporary"); + std::string temp_dir = std::string(temp_dir_c); + delete [] temp_dir_c; + + if (temp_dir.empty()) + { + cerr << "Could not determine temporary directory." << endl; + return EXIT_FAILURE; + } + + std::string filename = temp_dir + "/testXMLWriterWithDataArrayFallback.vti"; + + { + vtkNew imageData; + imageData->SetDimensions(2,3,1); + + vtkNew > data; + data->SetName("test_data"); + data->SetNumberOfTuples(6); + for (vtkIdType i = 0; i < 6; i++) + { + data->SetValue(i,static_cast(i)); + } + + imageData->GetPointData()->AddArray(data.GetPointer()); + + vtkNew writer; + writer->SetFileName(filename.c_str()); + writer->SetInputData(imageData.GetPointer()); + writer->Write(); + } + + { + vtkNew reader; + reader->SetFileName(filename.c_str()); + reader->Update(); + + vtkImageData* imageData = reader->GetOutput(); + vtkIntArray* data = vtkIntArray::SafeDownCast( + imageData->GetPointData()->GetArray("test_data")); + + if (!data || data->GetNumberOfTuples() != 6) + { + cerr << "Could not read data array." << endl; + return EXIT_FAILURE; + } + + for (vtkIdType i = 0; i < data->GetNumberOfTuples(); i++) + { + if (data->GetValue(i) != i) + { + cerr << "Incorrect value from data array." << endl; + return EXIT_FAILURE; + } + } + } + + return EXIT_SUCCESS; +} diff --git a/IO/XML/vtkXMLCompositeDataReader.h b/IO/XML/vtkXMLCompositeDataReader.h index 70193f814db..140963e1643 100644 --- a/IO/XML/vtkXMLCompositeDataReader.h +++ b/IO/XML/vtkXMLCompositeDataReader.h @@ -32,9 +32,8 @@ class vtkCompositeDataSet; class vtkInformationIntegerKey; class vtkInformationIntegerVectorKey; -//BTX + struct vtkXMLCompositeDataReaderInternals; -//ETX class VTKIOXML_EXPORT vtkXMLCompositeDataReader : public vtkXMLReader { diff --git a/IO/XML/vtkXMLCompositeDataWriter.cxx b/IO/XML/vtkXMLCompositeDataWriter.cxx index 329c83c1a93..91c45db3d07 100644 --- a/IO/XML/vtkXMLCompositeDataWriter.cxx +++ b/IO/XML/vtkXMLCompositeDataWriter.cxx @@ -17,6 +17,7 @@ #include "vtkCallbackCommand.h" #include "vtkCompositeDataPipeline.h" #include "vtkCompositeDataSet.h" +#include "vtkDataObjectTreeIterator.h" #include "vtkErrorCode.h" #include "vtkExecutive.h" #include "vtkGarbageCollector.h" @@ -33,14 +34,10 @@ #include "vtkStructuredGrid.h" #include "vtkUnstructuredGrid.h" #include "vtkXMLDataElement.h" -#include "vtkXMLImageDataWriter.h" -#include "vtkXMLPolyDataWriter.h" -#include "vtkXMLRectilinearGridWriter.h" -#include "vtkXMLStructuredGridWriter.h" -#include "vtkXMLUnstructuredGridWriter.h" -#include "vtkXMLWriter.h" -#include "vtkDataObjectTreeIterator.h" +#include "vtkXMLDataSetWriter.h" + #include +#include #include #include #include @@ -49,12 +46,39 @@ class vtkXMLCompositeDataWriterInternals { + // These are used to by GetDefaultFileExtension(). This helps us avoid + // creating new instances repeatedly for the same dataset type. + std::map > TmpWriters; + public: std::vector< vtkSmartPointer > Writers; std::string FilePath; std::string FilePrefix; vtkSmartPointer Root; std::vector DataTypes; + + // Get the default extension for the dataset_type. Will return NULL if an + // extension cannot be determined. + const char* GetDefaultFileExtensionForDataSet(int dataset_type) + { + std::map >::iterator iter + = this->TmpWriters.find(dataset_type); + if (iter == this->TmpWriters.end()) + { + vtkSmartPointer writer; + writer.TakeReference(vtkXMLDataSetWriter::NewWriter(dataset_type)); + if (writer) + { + std::pair > pair(dataset_type, writer); + iter = this->TmpWriters.insert(pair).first; + } + } + if (iter != this->TmpWriters.end()) + { + return iter->second->GetDefaultFileExtension(); + } + return NULL; + } }; //---------------------------------------------------------------------------- @@ -79,6 +103,12 @@ vtkXMLCompositeDataWriter::~vtkXMLCompositeDataWriter() delete this->Internal; } +//---------------------------------------------------------------------------- +const char* vtkXMLCompositeDataWriter::GetDefaultFileExtensionForDataSet(int dataset_type) +{ + return this->Internal->GetDefaultFileExtensionForDataSet(dataset_type); +} + //---------------------------------------------------------------------------- unsigned int vtkXMLCompositeDataWriter::GetNumberOfDataTypes() { @@ -370,9 +400,10 @@ void vtkXMLCompositeDataWriter::FillDataTypes(vtkCompositeDataSet* hdInput) this->Internal->DataTypes.clear(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { - vtkDataSet* ds = vtkDataSet::SafeDownCast( - iter->GetCurrentDataObject()); - if (ds) + vtkDataSet* ds = vtkDataSet::SafeDownCast(iter->GetCurrentDataObject()); + // BUG #0015942: Datasets with no cells or points are considered empty and + // we'll skip then in our serialization code. + if (ds && (ds->GetNumberOfPoints() > 0 || ds->GetNumberOfCells() > 0)) { this->Internal->DataTypes.push_back(ds->GetDataObjectType()); } @@ -403,95 +434,35 @@ void vtkXMLCompositeDataWriter::CreateWriters(vtkCompositeDataSet* hdInput) this->Internal->Writers.resize(numDatasets); int i = 0; - for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) + for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem(), ++i) { - this->Internal->Writers[i] = NULL; - vtkDataSet* ds = vtkDataSet::SafeDownCast( - iter->GetCurrentDataObject()); - if (ds) + vtkSmartPointer& writer = this->Internal->Writers[i]; + vtkDataSet* ds = vtkDataSet::SafeDownCast(iter->GetCurrentDataObject()); + if (ds == NULL) { - // Create a writer based on the type of this input. - switch (this->Internal->DataTypes[i]) - { - case VTK_POLY_DATA: - if (!this->Internal->Writers[i].GetPointer() || - (strcmp(this->Internal->Writers[i]->GetClassName(), - "vtkXMLPolyDataWriter") != 0)) - { - vtkXMLPolyDataWriter* w = vtkXMLPolyDataWriter::New(); - this->Internal->Writers[i] = w; - w->Delete(); - } - vtkXMLPolyDataWriter::SafeDownCast(this->Internal->Writers[i].GetPointer()) - ->SetInputData(ds); - break; - case VTK_STRUCTURED_POINTS: - case VTK_IMAGE_DATA: - case VTK_UNIFORM_GRID: - if (!this->Internal->Writers[i].GetPointer() || - (strcmp(this->Internal->Writers[i]->GetClassName(), - "vtkXMLImageDataWriter") != 0)) - { - vtkXMLImageDataWriter* w = vtkXMLImageDataWriter::New(); - this->Internal->Writers[i] = w; - w->Delete(); - } - vtkXMLImageDataWriter::SafeDownCast(this->Internal->Writers[i].GetPointer()) - ->SetInputData(ds); - break; - case VTK_UNSTRUCTURED_GRID: - if (!this->Internal->Writers[i].GetPointer() || - (strcmp(this->Internal->Writers[i]->GetClassName(), - "vtkXMLUnstructuredGridWriter") != 0)) - { - vtkXMLUnstructuredGridWriter* w = vtkXMLUnstructuredGridWriter::New(); - this->Internal->Writers[i] = w; - w->Delete(); - } - vtkXMLUnstructuredGridWriter::SafeDownCast( - this->Internal->Writers[i].GetPointer())->SetInputData(ds); - break; - case VTK_STRUCTURED_GRID: - if (!this->Internal->Writers[i].GetPointer() || - (strcmp(this->Internal->Writers[i]->GetClassName(), - "vtkXMLStructuredGridWriter") != 0)) - { - vtkXMLStructuredGridWriter* w = vtkXMLStructuredGridWriter::New(); - this->Internal->Writers[i] = w; - w->Delete(); - } - vtkXMLStructuredGridWriter::SafeDownCast( - this->Internal->Writers[i].GetPointer())->SetInputData(ds); - break; - case VTK_RECTILINEAR_GRID: - if (!this->Internal->Writers[i].GetPointer() || - (strcmp(this->Internal->Writers[i]->GetClassName(), - "vtkXMLRectilinearGridWriter") != 0)) - { - vtkXMLRectilinearGridWriter* w = vtkXMLRectilinearGridWriter::New(); - this->Internal->Writers[i] = w; - w->Delete(); - } - vtkXMLRectilinearGridWriter::SafeDownCast( - this->Internal->Writers[i].GetPointer())->SetInputData(ds); - break; - default: - this->Internal->Writers[i] = 0; - } + writer = NULL; + continue; + } + // Create a writer based on the type of this input. We just instantiate + // vtkXMLDataSetWriter. That internally creates the write type of writer + // based on the data type. + writer.TakeReference(vtkXMLDataSetWriter::NewWriter(this->Internal->DataTypes[i])); + if (writer) + { // Copy settings to the writer. - if (vtkXMLWriter* w = this->Internal->Writers[i].GetPointer()) - { - w->SetDebug(this->GetDebug()); - w->SetByteOrder(this->GetByteOrder()); - w->SetCompressor(this->GetCompressor()); - w->SetBlockSize(this->GetBlockSize()); - w->SetDataMode(this->GetDataMode()); - w->SetEncodeAppendedData(this->GetEncodeAppendedData()); - w->SetHeaderType(this->GetHeaderType()); - } + writer->SetDebug(this->GetDebug()); + writer->SetByteOrder(this->GetByteOrder()); + writer->SetCompressor(this->GetCompressor()); + writer->SetBlockSize(this->GetBlockSize()); + writer->SetDataMode(this->GetDataMode()); + writer->SetEncodeAppendedData(this->GetEncodeAppendedData()); + writer->SetHeaderType(this->GetHeaderType()); + writer->SetIdType(this->GetIdType()); + + // Pass input. + writer->SetInputDataObject(ds); } - i++; } } @@ -593,33 +564,9 @@ vtkStdString vtkXMLCompositeDataWriter::CreatePieceFileName( stream << this->Internal->FilePrefix.c_str() << "/" << this->Internal->FilePrefix.c_str() << "_" << piece << "."; - switch (this->Internal->DataTypes[piece]) - { - case VTK_POLY_DATA: - stream << "vtp"; - break; - - case VTK_STRUCTURED_POINTS: - case VTK_IMAGE_DATA: - case VTK_UNIFORM_GRID: - stream << "vti"; - break; - - case VTK_UNSTRUCTURED_GRID: - stream << "vtu"; - break; - - case VTK_STRUCTURED_GRID: - stream << "vts"; - break; - - case VTK_RECTILINEAR_GRID: - stream << "vtr"; - break; - - default: - return ""; - } + const char* ext = this->GetDefaultFileExtensionForDataSet( + this->Internal->DataTypes[piece]); + stream << (ext? ext : ""); return stream.str(); } diff --git a/IO/XML/vtkXMLCompositeDataWriter.h b/IO/XML/vtkXMLCompositeDataWriter.h index 0b3e22b33ba..808248fa181 100644 --- a/IO/XML/vtkXMLCompositeDataWriter.h +++ b/IO/XML/vtkXMLCompositeDataWriter.h @@ -113,6 +113,11 @@ class VTKIOXML_EXPORT vtkXMLCompositeDataWriter : public vtkXMLWriter const char* GetFilePrefix(); const char* GetFilePath(); + // Description: + // Returns the default extension to use for the given dataset type. + // Returns NULL if an extension cannot be determined. + const char* GetDefaultFileExtensionForDataSet(int dataset_type); + // Description: // Write the collection file if it is requested. // This is overridden in parallel writers to communicate the hierarchy to the diff --git a/IO/XML/vtkXMLDataReader.cxx b/IO/XML/vtkXMLDataReader.cxx index c0d50bde049..566cada75ae 100644 --- a/IO/XML/vtkXMLDataReader.cxx +++ b/IO/XML/vtkXMLDataReader.cxx @@ -696,7 +696,7 @@ void vtkXMLDataReader::ConvertGhostLevelsToGhostType( FieldType fieldType, vtkAbstractArray* data, vtkIdType startIndex, vtkIdType numValues) { - vtkUnsignedCharArray* ucData = vtkUnsignedCharArray::SafeDownCast(data); + vtkUnsignedCharArray* ucData = vtkArrayDownCast(data); int numComp = data->GetNumberOfComponents(); const char* name = data->GetName(); if (this->GetFileMajorVersion() < 2 && ucData && diff --git a/IO/XML/vtkXMLDataSetWriter.cxx b/IO/XML/vtkXMLDataSetWriter.cxx index 43cf9edbe95..4e154c15415 100644 --- a/IO/XML/vtkXMLDataSetWriter.cxx +++ b/IO/XML/vtkXMLDataSetWriter.cxx @@ -14,6 +14,7 @@ =========================================================================*/ #include "vtkXMLDataSetWriter.h" +#include "vtkAlgorithmOutput.h" #include "vtkCallbackCommand.h" #include "vtkDataSet.h" #include "vtkHyperOctree.h" @@ -22,6 +23,7 @@ #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkRectilinearGrid.h" +#include "vtkSmartPointer.h" #include "vtkStructuredGrid.h" #include "vtkUnstructuredGrid.h" #include "vtkXMLHyperOctreeWriter.h" @@ -30,7 +32,6 @@ #include "vtkXMLRectilinearGridWriter.h" #include "vtkXMLStructuredGridWriter.h" #include "vtkXMLUnstructuredGridWriter.h" -#include "vtkAlgorithmOutput.h" vtkStandardNewMacro(vtkXMLDataSetWriter); @@ -62,82 +63,65 @@ vtkDataSet* vtkXMLDataSetWriter::GetInput() } //---------------------------------------------------------------------------- -int vtkXMLDataSetWriter::WriteInternal() +vtkXMLWriter* vtkXMLDataSetWriter::NewWriter(int dataset_type) { - vtkAlgorithmOutput* input = this->GetInputConnection(0, 0); - vtkXMLWriter* writer = 0; - // Create a writer based on the data set type. - switch (this->GetInput()->GetDataObjectType()) + switch (dataset_type) { case VTK_UNIFORM_GRID: case VTK_IMAGE_DATA: case VTK_STRUCTURED_POINTS: - { - vtkXMLImageDataWriter* w = vtkXMLImageDataWriter::New(); - w->SetInputConnection(input); - writer = w; - } break; + return vtkXMLImageDataWriter::New(); case VTK_STRUCTURED_GRID: - { - vtkXMLStructuredGridWriter* w = vtkXMLStructuredGridWriter::New(); - w->SetInputConnection(input); - writer = w; - } break; + return vtkXMLStructuredGridWriter::New(); case VTK_RECTILINEAR_GRID: - { - vtkXMLRectilinearGridWriter* w = vtkXMLRectilinearGridWriter::New(); - w->SetInputConnection(input); - writer = w; - } break; + return vtkXMLRectilinearGridWriter::New(); case VTK_UNSTRUCTURED_GRID: - { - vtkXMLUnstructuredGridWriter* w = vtkXMLUnstructuredGridWriter::New(); - w->SetInputConnection(input); - writer = w; - } break; + return vtkXMLUnstructuredGridWriter::New(); case VTK_POLY_DATA: - { - vtkXMLPolyDataWriter* w = vtkXMLPolyDataWriter::New(); - w->SetInputConnection(input); - writer = w; - } break; + return vtkXMLPolyDataWriter::New(); case VTK_HYPER_OCTREE: - { - vtkXMLHyperOctreeWriter* w = vtkXMLHyperOctreeWriter::New(); - w->SetInputConnection(input); - writer = w; - } break; + return vtkXMLHyperOctreeWriter::New(); } + return NULL; +} - // Make sure we got a valid writer for the data set. - if (!writer) +//---------------------------------------------------------------------------- +int vtkXMLDataSetWriter::WriteInternal() +{ + // Create a writer based on the data set type. + vtkXMLWriter* writer = + vtkXMLDataSetWriter::NewWriter(this->GetInput()->GetDataObjectType()); + if (writer) { - vtkErrorMacro("Cannot write dataset type: " - << this->GetInput()->GetDataObjectType() << " which is a " - << this->GetInput()->GetClassName()); - return 0; + writer->SetInputConnection(this->GetInputConnection(0, 0)); + + // Copy the settings to the writer. + writer->SetDebug(this->GetDebug()); + writer->SetFileName(this->GetFileName()); + writer->SetByteOrder(this->GetByteOrder()); + writer->SetCompressor(this->GetCompressor()); + writer->SetBlockSize(this->GetBlockSize()); + writer->SetDataMode(this->GetDataMode()); + writer->SetEncodeAppendedData(this->GetEncodeAppendedData()); + writer->SetHeaderType(this->GetHeaderType()); + writer->SetIdType(this->GetIdType()); + writer->AddObserver(vtkCommand::ProgressEvent, this->ProgressObserver); + + // Try to write. + int result = writer->Write(); + + // Cleanup. + writer->RemoveObserver(this->ProgressObserver); + writer->Delete(); + return result; } - // Copy the settings to the writer. - writer->SetDebug(this->GetDebug()); - writer->SetFileName(this->GetFileName()); - writer->SetByteOrder(this->GetByteOrder()); - writer->SetCompressor(this->GetCompressor()); - writer->SetBlockSize(this->GetBlockSize()); - writer->SetDataMode(this->GetDataMode()); - writer->SetEncodeAppendedData(this->GetEncodeAppendedData()); - writer->SetHeaderType(this->GetHeaderType()); - writer->SetIdType(this->GetIdType()); - writer->AddObserver(vtkCommand::ProgressEvent, this->ProgressObserver); - - // Try to write. - int result = writer->Write(); - - // Cleanup. - writer->RemoveObserver(this->ProgressObserver); - writer->Delete(); - return result; + // Make sure we got a valid writer for the data set. + vtkErrorMacro("Cannot write dataset type: " + << this->GetInput()->GetDataObjectType() << " which is a " + << this->GetInput()->GetClassName()); + return 0; } //---------------------------------------------------------------------------- diff --git a/IO/XML/vtkXMLDataSetWriter.h b/IO/XML/vtkXMLDataSetWriter.h index e700ef2be8b..e675a72a561 100644 --- a/IO/XML/vtkXMLDataSetWriter.h +++ b/IO/XML/vtkXMLDataSetWriter.h @@ -38,11 +38,16 @@ class VTKIOXML_EXPORT vtkXMLDataSetWriter : public vtkXMLWriter void PrintSelf(ostream& os, vtkIndent indent); static vtkXMLDataSetWriter* New(); - //BTX // Description: // Get/Set the writer's input. vtkDataSet* GetInput(); - //ETX + + // Description: + // Creates a writer for the given dataset type. May return NULL for + // unsupported/unrecognized dataset types. Returns a new instance. The caller + // is responsible of calling vtkObject::Delete() or vtkObject::UnRegister() on + // it when done. + static vtkXMLWriter* NewWriter(int dataset_type); protected: vtkXMLDataSetWriter(); @@ -67,6 +72,7 @@ class VTKIOXML_EXPORT vtkXMLDataSetWriter : public vtkXMLWriter // The observer to report progress from the internal writer. vtkCallbackCommand* ProgressObserver; + private: vtkXMLDataSetWriter(const vtkXMLDataSetWriter&); // Not implemented. void operator=(const vtkXMLDataSetWriter&); // Not implemented. diff --git a/IO/XML/vtkXMLHierarchicalBoxDataFileConverter.h b/IO/XML/vtkXMLHierarchicalBoxDataFileConverter.h index c6affe92bd4..2140e758948 100644 --- a/IO/XML/vtkXMLHierarchicalBoxDataFileConverter.h +++ b/IO/XML/vtkXMLHierarchicalBoxDataFileConverter.h @@ -48,7 +48,6 @@ class VTKIOXML_EXPORT vtkXMLHierarchicalBoxDataFileConverter : public vtkObject // Converts the input file to new format and writes out the output file. bool Convert(); -//BTX protected: vtkXMLHierarchicalBoxDataFileConverter(); ~vtkXMLHierarchicalBoxDataFileConverter(); @@ -67,7 +66,7 @@ class VTKIOXML_EXPORT vtkXMLHierarchicalBoxDataFileConverter : public vtkObject private: vtkXMLHierarchicalBoxDataFileConverter(const vtkXMLHierarchicalBoxDataFileConverter&); // Not implemented. void operator=(const vtkXMLHierarchicalBoxDataFileConverter&); // Not implemented. -//ETX + }; #endif diff --git a/IO/XML/vtkXMLHierarchicalBoxDataWriter.h b/IO/XML/vtkXMLHierarchicalBoxDataWriter.h index 80afaa91a7d..2a4ff113ed3 100644 --- a/IO/XML/vtkXMLHierarchicalBoxDataWriter.h +++ b/IO/XML/vtkXMLHierarchicalBoxDataWriter.h @@ -36,7 +36,6 @@ class VTKIOXML_EXPORT vtkXMLHierarchicalBoxDataWriter : public vtkXMLUniformGrid virtual const char* GetDefaultFileExtension() { return "vth"; } -//BTX protected: vtkXMLHierarchicalBoxDataWriter(); ~vtkXMLHierarchicalBoxDataWriter(); @@ -44,7 +43,7 @@ class VTKIOXML_EXPORT vtkXMLHierarchicalBoxDataWriter : public vtkXMLUniformGrid private: vtkXMLHierarchicalBoxDataWriter(const vtkXMLHierarchicalBoxDataWriter&); // Not implemented. void operator=(const vtkXMLHierarchicalBoxDataWriter&); // Not implemented. -//ETX + }; #endif diff --git a/IO/XML/vtkXMLHyperOctreeReader.cxx b/IO/XML/vtkXMLHyperOctreeReader.cxx index 6c8dd142649..10eb5479add 100644 --- a/IO/XML/vtkXMLHyperOctreeReader.cxx +++ b/IO/XML/vtkXMLHyperOctreeReader.cxx @@ -207,7 +207,7 @@ void vtkXMLHyperOctreeReader::ReadTopology(vtkXMLDataElement *elem) // Since topology is a vtkIntArray. vtkAbstractArray* a = this->CreateArray(tElem); - vtkDataArray *tda = vtkDataArray::SafeDownCast(a); + vtkDataArray *tda = vtkArrayDownCast(a); if (!tda) { if (a) @@ -234,7 +234,7 @@ void vtkXMLHyperOctreeReader::ReadTopology(vtkXMLDataElement *elem) return; } - vtkIntArray *ta = vtkIntArray::SafeDownCast(tda); + vtkIntArray *ta = vtkArrayDownCast(tda); if (!ta) { tda->Delete(); diff --git a/IO/XML/vtkXMLHyperOctreeWriter.h b/IO/XML/vtkXMLHyperOctreeWriter.h index 74667e68b45..95f4bdf9d80 100644 --- a/IO/XML/vtkXMLHyperOctreeWriter.h +++ b/IO/XML/vtkXMLHyperOctreeWriter.h @@ -40,11 +40,9 @@ class VTKIOXML_EXPORT vtkXMLHyperOctreeWriter : public vtkXMLWriter void PrintSelf(ostream& os, vtkIndent indent); static vtkXMLHyperOctreeWriter* New(); - //BTX // Description: // Get/Set the writer's input. vtkHyperOctree* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/XML/vtkXMLImageDataWriter.h b/IO/XML/vtkXMLImageDataWriter.h index 3f5429c20dc..1683364764d 100644 --- a/IO/XML/vtkXMLImageDataWriter.h +++ b/IO/XML/vtkXMLImageDataWriter.h @@ -38,11 +38,9 @@ class VTKIOXML_EXPORT vtkXMLImageDataWriter : public vtkXMLStructuredDataWriter vtkTypeMacro(vtkXMLImageDataWriter,vtkXMLStructuredDataWriter); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Get/Set the writer's input. vtkImageData* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/XML/vtkXMLMultiBlockDataWriter.h b/IO/XML/vtkXMLMultiBlockDataWriter.h index f6bcfa5e5bc..7239c3a87ef 100644 --- a/IO/XML/vtkXMLMultiBlockDataWriter.h +++ b/IO/XML/vtkXMLMultiBlockDataWriter.h @@ -34,7 +34,6 @@ class VTKIOXML_EXPORT vtkXMLMultiBlockDataWriter : public vtkXMLCompositeDataWri virtual const char* GetDefaultFileExtension() { return "vtm"; } -//BTX protected: vtkXMLMultiBlockDataWriter(); ~vtkXMLMultiBlockDataWriter(); @@ -49,7 +48,7 @@ class VTKIOXML_EXPORT vtkXMLMultiBlockDataWriter : public vtkXMLCompositeDataWri private: vtkXMLMultiBlockDataWriter(const vtkXMLMultiBlockDataWriter&); // Not implemented. void operator=(const vtkXMLMultiBlockDataWriter&); // Not implemented. -//ETX + }; #endif diff --git a/IO/XML/vtkXMLPRectilinearGridReader.cxx b/IO/XML/vtkXMLPRectilinearGridReader.cxx index 3a6a0e6e1a6..7ef1edbc0ac 100644 --- a/IO/XML/vtkXMLPRectilinearGridReader.cxx +++ b/IO/XML/vtkXMLPRectilinearGridReader.cxx @@ -147,9 +147,9 @@ void vtkXMLPRectilinearGridReader::SetupOutputData() vtkAbstractArray* ay = this->CreateArray(yc); vtkAbstractArray* az = this->CreateArray(zc); - vtkDataArray* x = vtkDataArray::SafeDownCast(ax); - vtkDataArray* y = vtkDataArray::SafeDownCast(ay); - vtkDataArray* z = vtkDataArray::SafeDownCast(az); + vtkDataArray* x = vtkArrayDownCast(ax); + vtkDataArray* y = vtkArrayDownCast(ay); + vtkDataArray* z = vtkArrayDownCast(az); if(x && y && z) { x->SetNumberOfTuples(this->PointDimensions[0]); diff --git a/IO/XML/vtkXMLPStructuredGridReader.cxx b/IO/XML/vtkXMLPStructuredGridReader.cxx index 4a81d3637de..b60006e3690 100644 --- a/IO/XML/vtkXMLPStructuredGridReader.cxx +++ b/IO/XML/vtkXMLPStructuredGridReader.cxx @@ -135,7 +135,7 @@ void vtkXMLPStructuredGridReader::SetupOutputData() // Non-zero volume. vtkAbstractArray* aa = this->CreateArray(this->PPointsElement->GetNestedElement(0)); - vtkDataArray* a = vtkDataArray::SafeDownCast(aa); + vtkDataArray* a = vtkArrayDownCast(aa); if(a) { a->SetNumberOfTuples(this->GetNumberOfPoints()); diff --git a/IO/XML/vtkXMLPUnstructuredDataReader.cxx b/IO/XML/vtkXMLPUnstructuredDataReader.cxx index d1e5cf51f95..4d534dc423d 100644 --- a/IO/XML/vtkXMLPUnstructuredDataReader.cxx +++ b/IO/XML/vtkXMLPUnstructuredDataReader.cxx @@ -157,7 +157,7 @@ void vtkXMLPUnstructuredDataReader::SetupOutputData() { vtkAbstractArray* aa = this->CreateArray( this->PPointsElement->GetNestedElement(0)); - vtkDataArray* a = vtkDataArray::SafeDownCast(aa); + vtkDataArray* a = vtkArrayDownCast(aa); if (a) { a->SetNumberOfTuples(this->GetNumberOfPoints()); diff --git a/IO/XML/vtkXMLPUnstructuredGridReader.cxx b/IO/XML/vtkXMLPUnstructuredGridReader.cxx index 5120baa4ad5..e4cc092f88e 100644 --- a/IO/XML/vtkXMLPUnstructuredGridReader.cxx +++ b/IO/XML/vtkXMLPUnstructuredGridReader.cxx @@ -160,7 +160,41 @@ int vtkXMLPUnstructuredGridReader::ReadPieceData() outLocs[i] = inLocs[i] + startLoc; } - // Copy the cooresponding cell types. + // Copy Faces and FaceLocations with offset adjustment if they exist + if(vtkIdTypeArray* inputFaces = input->GetFaces()) + { + vtkIdTypeArray* inputFaceLocations = input->GetFaceLocations(); + vtkIdTypeArray* outputFaces = output->GetFaces(); + if(!outputFaces) + { + output->InitializeFacesRepresentation(0); + outputFaces = output->GetFaces(); + } + vtkIdTypeArray* outputFaceLocations = output->GetFaceLocations(); + for (vtkIdType i = 0;i < numCells; ++i) + { + outputFaceLocations->InsertNextValue(outputFaces->GetMaxId() + 1); + vtkIdType location = inputFaceLocations->GetValue(i); + vtkIdType numFaces = inputFaces->GetValue(location); + location++; + outputFaces->InsertNextValue(numFaces); + for (vtkIdType f = 0;f < numFaces; f++) + { + vtkIdType numPoints = inputFaces->GetValue(location); + outputFaces->InsertNextValue(numPoints); + location++; + for (vtkIdType p = 0;p < numPoints; p++) + { + // only the point ids get the offset + outputFaces->InsertNextValue( + inputFaces->GetValue(location)+this->StartPoint); + location++; + } + } + } + } + + // Copy the corresponding cell types. vtkUnsignedCharArray* inTypes = input->GetCellTypesArray(); vtkUnsignedCharArray* outTypes = output->GetCellTypesArray(); vtkIdType components = outTypes->GetNumberOfComponents(); @@ -204,3 +238,17 @@ int vtkXMLPUnstructuredGridReader::FillOutputPortInformation( info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkUnstructuredGrid"); return 1; } + +//---------------------------------------------------------------------------- +void vtkXMLPUnstructuredGridReader::SqueezeOutputArrays(vtkDataObject* output) +{ + vtkUnstructuredGrid* grid = vtkUnstructuredGrid::SafeDownCast(output); + if(vtkIdTypeArray* outputFaces = grid->GetFaces()) + { + outputFaces->Squeeze(); + } + if(vtkIdTypeArray* outputFaceLocations = grid->GetFaceLocations()) + { + outputFaceLocations->Squeeze(); + } +} diff --git a/IO/XML/vtkXMLPUnstructuredGridReader.h b/IO/XML/vtkXMLPUnstructuredGridReader.h index 4db9344fad7..47c2f9fe6f6 100644 --- a/IO/XML/vtkXMLPUnstructuredGridReader.h +++ b/IO/XML/vtkXMLPUnstructuredGridReader.h @@ -59,6 +59,8 @@ class VTKIOXML_EXPORT vtkXMLPUnstructuredGridReader : public vtkXMLPUnstructured vtkXMLDataReader* CreatePieceReader(); virtual int FillOutputPortInformation(int, vtkInformation*); + virtual void SqueezeOutputArrays(vtkDataObject*); + // The index of the cell in the output where the current piece // begins. vtkIdType StartCell; diff --git a/IO/XML/vtkXMLPolyDataWriter.h b/IO/XML/vtkXMLPolyDataWriter.h index 8584c355504..129a17439c0 100644 --- a/IO/XML/vtkXMLPolyDataWriter.h +++ b/IO/XML/vtkXMLPolyDataWriter.h @@ -39,11 +39,9 @@ class VTKIOXML_EXPORT vtkXMLPolyDataWriter : public vtkXMLUnstructuredDataWriter void PrintSelf(ostream& os, vtkIndent indent); static vtkXMLPolyDataWriter* New(); - //BTX // Description: // Get/Set the writer's input. vtkPolyData* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/XML/vtkXMLReader.cxx b/IO/XML/vtkXMLReader.cxx index ec8a24c155b..e4c9f721ca0 100644 --- a/IO/XML/vtkXMLReader.cxx +++ b/IO/XML/vtkXMLReader.cxx @@ -622,6 +622,8 @@ int vtkXMLReader::RequestData(vtkInformation *vtkNotUsed(request), this->TimeStepWasReadOnce = 1; } + this->SqueezeOutputArrays(output); + this->CurrentOutput = 0; return 1; } diff --git a/IO/XML/vtkXMLReader.h b/IO/XML/vtkXMLReader.h index e091c72f003..91ac2382c6a 100644 --- a/IO/XML/vtkXMLReader.h +++ b/IO/XML/vtkXMLReader.h @@ -49,10 +49,10 @@ class VTKIOXML_EXPORT vtkXMLReader : public vtkAlgorithm vtkGetStringMacro(FileName); // Description: - // Enable writing to an InputString instead of the default, a file. - vtkSetMacro(ReadFromInputString,int); - vtkGetMacro(ReadFromInputString,int); - vtkBooleanMacro(ReadFromInputString,int); + // Enable reading from an InputString instead of the default, a file. + vtkSetMacro(ReadFromInputString, int); + vtkGetMacro(ReadFromInputString, int); + vtkBooleanMacro(ReadFromInputString, int); void SetInputString(std::string s) { this->InputString = s; } // Description: @@ -125,13 +125,13 @@ class VTKIOXML_EXPORT vtkXMLReader : public vtkAlgorithm // Set/get the ErrorObserver for the internal reader // This is useful for applications that want to catch error messages. void SetReaderErrorObserver(vtkCommand *); - vtkGetObjectMacro(ReaderErrorObserver,vtkCommand); + vtkGetObjectMacro(ReaderErrorObserver, vtkCommand); // Description: // Set/get the ErrorObserver for the internal xml parser // This is useful for applications that want to catch error messages. void SetParserErrorObserver(vtkCommand *); - vtkGetObjectMacro(ParserErrorObserver,vtkCommand); + vtkGetObjectMacro(ParserErrorObserver, vtkCommand); protected: vtkXMLReader(); @@ -217,10 +217,8 @@ class VTKIOXML_EXPORT vtkXMLReader : public vtkAlgorithm void SetDataArraySelections(vtkXMLDataElement* eDSA, vtkDataArraySelection* sel); -//BTX int SetFieldDataInfo(vtkXMLDataElement *eDSA, int association, int numTuples, vtkInformationVector *(&infoVector)); -//ETX // Check whether the given array element is an enabled array. int PointDataArrayIsEnabled(vtkXMLDataElement* ePDA); @@ -230,6 +228,10 @@ class VTKIOXML_EXPORT vtkXMLReader : public vtkAlgorithm static void SelectionModifiedCallback(vtkObject* caller, unsigned long eid, void* clientdata, void* calldata); + // Give concrete classes an option to squeeze any output arrays + // at the end of RequestData. + virtual void SqueezeOutputArrays(vtkDataObject*) {} + // The vtkXMLDataParser instance used to hide XML reading details. vtkXMLDataParser* XMLParser; diff --git a/IO/XML/vtkXMLRectilinearGridReader.cxx b/IO/XML/vtkXMLRectilinearGridReader.cxx index 29722f7b29e..be67e4d38b3 100644 --- a/IO/XML/vtkXMLRectilinearGridReader.cxx +++ b/IO/XML/vtkXMLRectilinearGridReader.cxx @@ -147,9 +147,9 @@ void vtkXMLRectilinearGridReader::SetupOutputData() vtkAbstractArray* ya = this->CreateArray(yc); vtkAbstractArray* za = this->CreateArray(zc); - vtkDataArray* x = vtkDataArray::SafeDownCast(xa); - vtkDataArray* y = vtkDataArray::SafeDownCast(ya); - vtkDataArray* z = vtkDataArray::SafeDownCast(za); + vtkDataArray* x = vtkArrayDownCast(xa); + vtkDataArray* y = vtkArrayDownCast(ya); + vtkDataArray* z = vtkArrayDownCast(za); if (x && y && z) { x->SetNumberOfTuples(this->PointDimensions[0]); diff --git a/IO/XML/vtkXMLRectilinearGridWriter.h b/IO/XML/vtkXMLRectilinearGridWriter.h index ca59688558f..6345e08991e 100644 --- a/IO/XML/vtkXMLRectilinearGridWriter.h +++ b/IO/XML/vtkXMLRectilinearGridWriter.h @@ -38,11 +38,9 @@ class VTKIOXML_EXPORT vtkXMLRectilinearGridWriter : public vtkXMLStructuredDataW vtkTypeMacro(vtkXMLRectilinearGridWriter,vtkXMLStructuredDataWriter); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Get/Set the writer's input. vtkRectilinearGrid* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/XML/vtkXMLStructuredGridReader.cxx b/IO/XML/vtkXMLStructuredGridReader.cxx index 33e2adc08e2..8fa7c2bde1b 100644 --- a/IO/XML/vtkXMLStructuredGridReader.cxx +++ b/IO/XML/vtkXMLStructuredGridReader.cxx @@ -133,7 +133,7 @@ void vtkXMLStructuredGridReader::SetupOutputData() { // Non-zero volume. vtkAbstractArray* aa = this->CreateArray(ePoints->GetNestedElement(0)); - vtkDataArray* a = vtkDataArray::SafeDownCast(aa); + vtkDataArray* a = vtkArrayDownCast(aa); if (a) { // Allocate the points array. diff --git a/IO/XML/vtkXMLStructuredGridWriter.h b/IO/XML/vtkXMLStructuredGridWriter.h index 043f8c03463..9d43a9e9eef 100644 --- a/IO/XML/vtkXMLStructuredGridWriter.h +++ b/IO/XML/vtkXMLStructuredGridWriter.h @@ -38,11 +38,9 @@ class VTKIOXML_EXPORT vtkXMLStructuredGridWriter : public vtkXMLStructuredDataWr vtkTypeMacro(vtkXMLStructuredGridWriter,vtkXMLStructuredDataWriter); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Get/Set the writer's input. vtkStructuredGrid* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/XML/vtkXMLUniformGridAMRWriter.h b/IO/XML/vtkXMLUniformGridAMRWriter.h index a7d1cffe67b..1fa918e1366 100644 --- a/IO/XML/vtkXMLUniformGridAMRWriter.h +++ b/IO/XML/vtkXMLUniformGridAMRWriter.h @@ -36,7 +36,6 @@ class VTKIOXML_EXPORT vtkXMLUniformGridAMRWriter : public vtkXMLCompositeDataWri virtual const char* GetDefaultFileExtension() { return "vth"; } -//BTX protected: vtkXMLUniformGridAMRWriter(); ~vtkXMLUniformGridAMRWriter(); @@ -58,7 +57,7 @@ class VTKIOXML_EXPORT vtkXMLUniformGridAMRWriter : public vtkXMLCompositeDataWri private: vtkXMLUniformGridAMRWriter(const vtkXMLUniformGridAMRWriter&); // Not implemented. void operator=(const vtkXMLUniformGridAMRWriter&); // Not implemented. -//ETX + }; #endif diff --git a/IO/XML/vtkXMLUnstructuredDataReader.cxx b/IO/XML/vtkXMLUnstructuredDataReader.cxx index 7abc7c0f4dd..00ea6619240 100644 --- a/IO/XML/vtkXMLUnstructuredDataReader.cxx +++ b/IO/XML/vtkXMLUnstructuredDataReader.cxx @@ -108,7 +108,7 @@ vtkIdTypeArray* vtkXMLUnstructuredDataReader::ConvertToIdTypeArray(vtkDataArray* a) { // If it is already a vtkIdTypeArray, just return it. - vtkIdTypeArray* ida = vtkIdTypeArray::SafeDownCast(a); + vtkIdTypeArray* ida = vtkArrayDownCast(a); if(ida) { return ida; @@ -141,7 +141,7 @@ vtkUnsignedCharArray* vtkXMLUnstructuredDataReader::ConvertToUnsignedCharArray(vtkDataArray* a) { // If it is already a vtkUnsignedCharArray, just return it. - vtkUnsignedCharArray* uca = vtkUnsignedCharArray::SafeDownCast(a); + vtkUnsignedCharArray* uca = vtkArrayDownCast(a); if(uca) { return uca; @@ -386,7 +386,7 @@ void vtkXMLUnstructuredDataReader::SetupOutputData() { // Non-zero volume. vtkAbstractArray* aa = this->CreateArray(ePoints->GetNestedElement(0)); - vtkDataArray* a = vtkDataArray::SafeDownCast(aa); + vtkDataArray* a = vtkArrayDownCast(aa); if (a) { // Allocate the points array. @@ -569,7 +569,7 @@ int vtkXMLUnstructuredDataReader::ReadCellArray(vtkIdType numberOfCells, return 0; } vtkAbstractArray* ac1 = this->CreateArray(eOffsets); - vtkDataArray* c1 = vtkDataArray::SafeDownCast(ac1); + vtkDataArray* c1 = vtkArrayDownCast(ac1); if(!c1 || (c1->GetNumberOfComponents() != 1)) { vtkErrorMacro("Cannot read cell offsets from " << eCells->GetName() @@ -635,7 +635,7 @@ int vtkXMLUnstructuredDataReader::ReadCellArray(vtkIdType numberOfCells, return 0; } vtkAbstractArray* ac0 = this->CreateArray(eConn); - vtkDataArray* c0 = vtkDataArray::SafeDownCast(ac0); + vtkDataArray* c0 = vtkArrayDownCast(ac0); if(!c0 || (c0->GetNumberOfComponents() != 1)) { vtkErrorMacro("Cannot read cell connectivity from " << eCells->GetName() @@ -748,7 +748,7 @@ int vtkXMLUnstructuredDataReader::ReadFaceArray(vtkIdType numberOfCells, return 0; } vtkAbstractArray* ac1 = this->CreateArray(efaceOffsets); - vtkDataArray* c1 = vtkDataArray::SafeDownCast(ac1); + vtkDataArray* c1 = vtkArrayDownCast(ac1); if(!c1 || (c1->GetNumberOfComponents() != 1)) { vtkErrorMacro("Cannot read face offsets from " << eCells->GetName() @@ -820,7 +820,7 @@ int vtkXMLUnstructuredDataReader::ReadFaceArray(vtkIdType numberOfCells, return 0; } vtkAbstractArray* ac0 = this->CreateArray(efaces); - vtkDataArray* c0 = vtkDataArray::SafeDownCast(ac0); + vtkDataArray* c0 = vtkArrayDownCast(ac0); if(!c0 || (c0->GetNumberOfComponents() != 1)) { vtkErrorMacro("Cannot read faces from " << eCells->GetName() diff --git a/IO/XML/vtkXMLUnstructuredGridReader.cxx b/IO/XML/vtkXMLUnstructuredGridReader.cxx index cc089c2e848..0ac870c0119 100644 --- a/IO/XML/vtkXMLUnstructuredGridReader.cxx +++ b/IO/XML/vtkXMLUnstructuredGridReader.cxx @@ -316,7 +316,7 @@ int vtkXMLUnstructuredGridReader::ReadPieceData() return 0; } vtkAbstractArray* ac2 = this->CreateArray(eTypes); - vtkDataArray* c2 = vtkDataArray::SafeDownCast(ac2); + vtkDataArray* c2 = vtkArrayDownCast(ac2); if(!c2 || (c2->GetNumberOfComponents() != 1)) { vtkErrorMacro("Cannot read cell types from " << eCells->GetName() diff --git a/IO/XML/vtkXMLUnstructuredGridWriter.h b/IO/XML/vtkXMLUnstructuredGridWriter.h index 2c7f00efbe3..147b667b124 100644 --- a/IO/XML/vtkXMLUnstructuredGridWriter.h +++ b/IO/XML/vtkXMLUnstructuredGridWriter.h @@ -40,11 +40,9 @@ class VTKIOXML_EXPORT vtkXMLUnstructuredGridWriter : public vtkXMLUnstructuredDa void PrintSelf(ostream& os, vtkIndent indent); static vtkXMLUnstructuredGridWriter* New(); - //BTX // Description: // Get/Set the writer's input. vtkUnstructuredGridBase* GetInput(); - //ETX // Description: // Get the default file extension for files written by this writer. diff --git a/IO/XML/vtkXMLWriter.cxx b/IO/XML/vtkXMLWriter.cxx index 0b7cb4bece5..eabfb140c62 100644 --- a/IO/XML/vtkXMLWriter.cxx +++ b/IO/XML/vtkXMLWriter.cxx @@ -14,13 +14,14 @@ =========================================================================*/ #include "vtkXMLWriter.h" +#include "vtkArrayDispatch.h" #include "vtkArrayIteratorIncludes.h" +#include "vtkAOSDataArrayTemplate.h" #include "vtkBase64OutputStream.h" #include "vtkByteSwap.h" #include "vtkCellData.h" #include "vtkCommand.h" #include "vtkDataArray.h" -#include "vtkDataArrayIteratorMacro.h" #include "vtkDataSet.h" #include "vtkErrorCode.h" #include "vtkInformation.h" @@ -87,118 +88,209 @@ class vtkXMLWriterHelper } }; -//---------------------------------------------------------------------------- -// Specialize for cases where IterType is ValueType* (common case for -// vtkDataArrayTemplate subclasses). The last arg is to help less-robust -// compilers decide between the various overloads by making a unfavorable -// int-to-long conversion in the IterType overload, making this next -// overload more favorable when the iterator is a ValueType*. -template -int vtkXMLWriterWriteBinaryDataBlocks(vtkXMLWriter* writer, - ValueType* iter, int wordType, size_t memWordSize, size_t outWordSize, - size_t numWords, int) -{ - // generic implementation for fixed component length arrays. - size_t blockWords = writer->GetBlockSize()/outWordSize; - size_t memBlockSize = blockWords*memWordSize; - - // Prepare a pointer and counter to move through the data. - unsigned char* ptr = reinterpret_cast(iter); - size_t wordsLeft = numWords; +namespace { + +struct WriteBinaryDataBlockWorker +{ + vtkXMLWriter *Writer; + int WordType; + size_t MemWordSize; + size_t OutWordSize; + size_t NumWords; + bool Result; + + WriteBinaryDataBlockWorker(vtkXMLWriter *writer, int wordType, + size_t memWordSize, size_t outWordSize, + size_t numWords) + : Writer(writer), WordType(wordType), + MemWordSize(memWordSize), OutWordSize(outWordSize), NumWords(numWords), + Result(false) + {} + + //---------------------------------------------------------------------------- + // Specialize for AoS arrays. + template + void operator()(vtkAOSDataArrayTemplate* array) + { + // Get the raw pointer to the array data: + ValueType *iter = array->GetPointer(0); + + // generic implementation for fixed component length arrays. + size_t blockWords = this->Writer->GetBlockSize() / this->OutWordSize; + size_t memBlockSize = blockWords * this->MemWordSize; + + // Prepare a pointer and counter to move through the data. + unsigned char *ptr = reinterpret_cast(iter); + size_t wordsLeft = this->NumWords; + + // Do the complete blocks. + vtkXMLWriterHelper::SetProgressPartial(this->Writer, 0); + this->Result = true; + while (this->Result && (wordsLeft >= blockWords)) + { + if (!vtkXMLWriterHelper::WriteBinaryDataBlock(this->Writer, ptr, + blockWords, this->WordType)) + { + this->Result = false; + } + ptr += memBlockSize; + wordsLeft -= blockWords; + vtkXMLWriterHelper::SetProgressPartial( + this->Writer, + static_cast(this->NumWords - wordsLeft) / this->NumWords); + } - // Do the complete blocks. - vtkXMLWriterHelper::SetProgressPartial(writer, 0); - int result = 1; - while(result && (wordsLeft >= blockWords)) - { - if (!vtkXMLWriterHelper::WriteBinaryDataBlock(writer, ptr, blockWords, wordType)) + // Do the last partial block if any. + if (this->Result && (wordsLeft > 0)) { - result = 0; + if (!vtkXMLWriterHelper::WriteBinaryDataBlock(this->Writer, ptr, + wordsLeft, this->WordType)) + { + this->Result = 0; + } } - ptr += memBlockSize; - wordsLeft -= blockWords; - vtkXMLWriterHelper::SetProgressPartial(writer, - static_cast(numWords - wordsLeft) / numWords); - } + vtkXMLWriterHelper::SetProgressPartial(this->Writer, 1); + } - // Do the last partial block if any. - if (result && (wordsLeft > 0)) - { - if (!vtkXMLWriterHelper::WriteBinaryDataBlock(writer, ptr, wordsLeft, wordType)) + //---------------------------------------------------------------------------- + // Specialize for non-AoS generic arrays: + template + void operator()(ArrayT *array) + { + typedef typename ArrayT::ValueType ValueType; + + // generic implementation for fixed component length arrays. + size_t blockWords = this->Writer->GetBlockSize() / this->OutWordSize; + + // Prepare a buffer to move through the data. + std::vector buffer(blockWords * this->MemWordSize); + size_t wordsLeft = this->NumWords; + + if (buffer.empty()) { - result = 0; + // No data -- bail here, since the calls to buffer[0] below will segfault. + this->Result = false; + return; } - } - vtkXMLWriterHelper::SetProgressPartial(writer, 1); - return result; -} - -//---------------------------------------------------------------------------- -// Specialize for cases where IterType is some other type with iterator -// semantics (e.g. vtkMappedDataArray iterators): -template -int vtkXMLWriterWriteBinaryDataBlocks(vtkXMLWriter* writer, - IterType iter, int wordType, size_t memWordSize, size_t outWordSize, - size_t numWords, long) -{ - // generic implementation for fixed component length arrays. - size_t blockWords = writer->GetBlockSize()/outWordSize; - // Prepare a buffer to move through the data. - std::vector buffer(blockWords * memWordSize); - size_t wordsLeft = numWords; + // Do the complete blocks. + vtkXMLWriterHelper::SetProgressPartial(this->Writer, 0); + this->Result = true; + vtkIdType valueIdx = 0; + while (this->Result && (wordsLeft >= blockWords)) + { + // Copy data to contiguous buffer: + ValueType* bufferIter = reinterpret_cast(&buffer[0]); + for (size_t i = 0; i < blockWords; ++i, ++valueIdx) + { + *bufferIter++ = array->GetValue(valueIdx); + } - if (buffer.empty()) - { - // No data -- bail here, since the calls to buffer[0] below will segfault. - return 1; - } + if (!vtkXMLWriterHelper::WriteBinaryDataBlock(this->Writer, &buffer[0], + blockWords, this->WordType)) + { + this->Result = false; + } + wordsLeft -= blockWords; + vtkXMLWriterHelper::SetProgressPartial( + this->Writer, + static_cast(this->NumWords - wordsLeft) / this->NumWords); + } - // Do the complete blocks. - vtkXMLWriterHelper::SetProgressPartial(writer, 0); - int result = 1; - while(result && (wordsLeft >= blockWords)) - { - // Copy data to contiguous buffer: - IterType blockEnd = iter + blockWords; - ValueType* bufferIter = reinterpret_cast(&buffer[0]); - while (iter != blockEnd) + // Do the last partial block if any. + if (this->Result && (wordsLeft > 0)) { - *bufferIter++ = *iter++; + ValueType* bufferIter = reinterpret_cast(&buffer[0]); + for (size_t i = 0; i < wordsLeft; ++i, ++valueIdx) + { + *bufferIter++ = array->GetValue(valueIdx); + } + + if (!vtkXMLWriterHelper::WriteBinaryDataBlock(this->Writer, &buffer[0], + wordsLeft, this->WordType)) + { + this->Result = false; + } } - if (!vtkXMLWriterHelper::WriteBinaryDataBlock(writer, &buffer[0], blockWords, - wordType)) + vtkXMLWriterHelper::SetProgressPartial(this->Writer, 1); + } + +}; // End WriteBinaryDataBlockWorker + +namespace +{ + //---------------------------------------------------------------------------- + // Specialize for vtkDataArrays, which implicitly cast everything to double: + template + void WriteDataArrayFallback(ValueType*, vtkDataArray *array, + WriteBinaryDataBlockWorker& worker) + { + // generic implementation for fixed component length arrays. + size_t blockWords = worker.Writer->GetBlockSize() / worker.OutWordSize; + + // Prepare a buffer to move through the data. + std::vector buffer(blockWords * worker.MemWordSize); + size_t wordsLeft = worker.NumWords; + + if (buffer.empty()) { - result = 0; + // No data -- bail here, since the calls to buffer[0] below will segfault. + worker.Result = false; + return; } - wordsLeft -= blockWords; - vtkXMLWriterHelper::SetProgressPartial(writer, - float(numWords-wordsLeft)/numWords); - } - // Do the last partial block if any. - if (result && (wordsLeft > 0)) - { - // Copy data to contiguous buffer: - IterType blockEnd = iter + wordsLeft; - ValueType* bufferIter = reinterpret_cast(&buffer[0]); - while (iter != blockEnd) + vtkIdType nComponents = array->GetNumberOfComponents(); + + // Do the complete blocks. + vtkXMLWriterHelper::SetProgressPartial(worker.Writer, 0); + worker.Result = true; + vtkIdType valueIdx = 0; + while (worker.Result && (wordsLeft >= blockWords)) { - *bufferIter++ = *iter++; + // Copy data to contiguous buffer: + ValueType* bufferIter = reinterpret_cast(&buffer[0]); + for (size_t i = 0; i < blockWords; ++i, ++valueIdx) + { + *bufferIter++ = static_cast( + array->GetComponent(valueIdx/nComponents,valueIdx%nComponents)); + } + + if (!vtkXMLWriterHelper::WriteBinaryDataBlock(worker.Writer, &buffer[0], + blockWords, worker.WordType)) + { + worker.Result = false; + } + wordsLeft -= blockWords; + vtkXMLWriterHelper::SetProgressPartial( + worker.Writer, + static_cast(worker.NumWords - wordsLeft) / worker.NumWords); } - if (!vtkXMLWriterHelper::WriteBinaryDataBlock(writer, &buffer[0], wordsLeft, - wordType)) + // Do the last partial block if any. + if (worker.Result && (wordsLeft > 0)) { - result = 0; + ValueType* bufferIter = reinterpret_cast(&buffer[0]); + for (size_t i = 0; i < wordsLeft; ++i, ++valueIdx) + { + *bufferIter++ = static_cast( + array->GetComponent(valueIdx/nComponents,valueIdx%nComponents)); + } + + if (!vtkXMLWriterHelper::WriteBinaryDataBlock(worker.Writer, &buffer[0], + wordsLeft, worker.WordType)) + { + worker.Result = false; + } } - } - vtkXMLWriterHelper::SetProgressPartial(writer, 1); - return result; + + vtkXMLWriterHelper::SetProgressPartial(worker.Writer, 1); + } + } //---------------------------------------------------------------------------- +// Specialize for string arrays: static int vtkXMLWriterWriteBinaryDataBlocks( vtkXMLWriter* writer, vtkArrayIteratorTemplate* iter, int wordType, size_t outWordSize, size_t numStrings, int) @@ -284,6 +376,8 @@ static int vtkXMLWriterWriteBinaryDataBlocks( vtkXMLWriterHelper::SetProgressPartial(writer, 1); return result; } + +} // end anon namespace //***************************************************************************** vtkCxxSetObjectMacro(vtkXMLWriter, Compressor, vtkDataCompressor); @@ -1246,33 +1340,62 @@ int vtkXMLWriter::WriteBinaryDataInternal(vtkAbstractArray* a) size_t numValues = static_cast(a->GetNumberOfComponents() * a->GetNumberOfTuples()); - switch (wordType) + + if (wordType == VTK_STRING) { - vtkDataArrayIteratorMacro(a, - ret = vtkXMLWriterWriteBinaryDataBlocks( - this, vtkDABegin, wordType, memWordSize, outWordSize, numValues, 1) - ); - case VTK_STRING: + vtkArrayIterator *aiter = a->NewIterator(); + vtkArrayIteratorTemplate *iter = + vtkArrayIteratorTemplate::SafeDownCast(aiter); + if (iter) { - vtkArrayIterator *aiter = a->NewIterator(); - vtkArrayIteratorTemplate *iter = - vtkArrayIteratorTemplate::SafeDownCast(aiter); - if (iter) - { - ret = vtkXMLWriterWriteBinaryDataBlocks( - this, iter, wordType, outWordSize, numValues, 1); - } - else + ret = vtkXMLWriterWriteBinaryDataBlocks( + this, iter, wordType, outWordSize, numValues, 1); + } + else + { + vtkWarningMacro("Unsupported iterator for data type : " << wordType); + ret = 0; + } + aiter->Delete(); + } + else if (vtkDataArray *da = vtkArrayDownCast(a)) + { + WriteBinaryDataBlockWorker worker(this, wordType, memWordSize, outWordSize, + numValues); + if (!vtkArrayDispatch::Dispatch::Execute(da, worker)) + { + switch (wordType) + { + case VTK___INT64: + case VTK_UNSIGNED___INT64: + case VTK_LONG_LONG: + case VTK_UNSIGNED_LONG_LONG: +#ifdef VTK_USE_64BIT_IDS + case VTK_ID_TYPE: +#endif + vtkWarningMacro("Using legacy vtkDataArray API, which may result " + "in precision loss"); + break; + default: + break; + } + + switch (wordType) { - vtkWarningMacro("Unsupported iterator for data type : " << wordType); - ret = 0; + vtkTemplateMacro(WriteDataArrayFallback(static_cast(0), + da,worker)); + default: + vtkWarningMacro("Unsupported data type: " << wordType); + break; } - aiter->Delete(); } - break; - default: - vtkWarningMacro("Cannot write binary data of type : " << wordType); - ret = 0; + ret = worker.Result ? 1 : 0; + } + else + { + vtkWarningMacro("Not writing array '" << a->GetName() << "': Unsupported " + "array type: " << a->GetClassName()); + ret = 0; } // Free the byte swap buffer if it was allocated. @@ -1885,7 +2008,7 @@ void vtkXMLWriter::WriteArrayAppended( this->WriteArrayHeader(a,indent,alternateName, writeNumTuples, timestep); int shortFormatTag = 1; // close with: /> // - if (vtkDataArray::SafeDownCast(a)) + if (vtkArrayDownCast(a)) { // write the scalar range of this data array, we reserver space because we // don't actually have the data at this point @@ -1960,7 +2083,7 @@ void vtkXMLWriter::WriteArrayHeader(vtkAbstractArray* a, vtkIndent indent, int timestep) { ostream& os = *(this->Stream); - if (vtkDataArray::SafeDownCast(a)) + if (vtkArrayDownCast(a)) { os << indent << "(a); os << indent << (da ? "" : "") << "\n"; } // Force write and check for errors. @@ -2077,7 +2200,7 @@ void vtkXMLWriter::WriteArrayInline( // Write the header WriteArrayHeader(a, indent, alternateName, writeNumTuples, 0); // - vtkDataArray* da = vtkDataArray::SafeDownCast(a); + vtkDataArray* da = vtkArrayDownCast(a); if (da) { // write the range @@ -2392,7 +2515,7 @@ void vtkXMLWriter::WritePointDataAppendedData(vtkPointData* pd, int timestep, (pdManager->GetElement(i).GetPosition(timestep), pdManager->GetElement(i).GetOffsetValue(timestep), "offset"); } - vtkDataArray* d = vtkDataArray::SafeDownCast(a); + vtkDataArray* d = vtkArrayDownCast(a); if (d) { // ranges are only written in case of Data Arrays. @@ -2487,7 +2610,7 @@ void vtkXMLWriter::WriteCellDataAppendedData(vtkCellData* cd, int timestep, cdManager->GetElement(i).GetOffsetValue(timestep), "offset"); } - vtkDataArray* d = vtkDataArray::SafeDownCast(a); + vtkDataArray* d = vtkArrayDownCast(a); if (d) { double *range = d->GetRange(-1); @@ -2855,7 +2978,7 @@ void vtkXMLWriter::WritePPoints(vtkPoints* points, vtkIndent indent) void vtkXMLWriter::WritePArray(vtkAbstractArray* a, vtkIndent indent, const char* alternateName) { - vtkDataArray* d = vtkDataArray::SafeDownCast(a); + vtkDataArray* d = vtkArrayDownCast(a); ostream& os = *(this->Stream); if (d) { diff --git a/IO/XML/vtkXMLWriter.h b/IO/XML/vtkXMLWriter.h index 170c80cfe60..167eba4f516 100644 --- a/IO/XML/vtkXMLWriter.h +++ b/IO/XML/vtkXMLWriter.h @@ -28,9 +28,9 @@ class vtkAbstractArray; class vtkArrayIterator; -//BTX + template class vtkArrayIteratorTemplate; -//ETX + class vtkCellData; class vtkDataArray; class vtkDataCompressor; @@ -41,35 +41,29 @@ class vtkPointData; class vtkPoints; class vtkFieldData; class vtkXMLDataHeader; -//BTX + class vtkStdString; class OffsetsManager; // one per piece/per time class OffsetsManagerGroup; // array of OffsetsManager class OffsetsManagerArray; // array of OffsetsManagerGroup -//ETX class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm { public: - vtkTypeMacro(vtkXMLWriter,vtkAlgorithm); + vtkTypeMacro(vtkXMLWriter, vtkAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Enumerate big and little endian byte order settings. enum { BigEndian, LittleEndian }; - //ETX - //BTX // Description: // Enumerate the supported data modes. // Ascii = Inline ascii data. // Binary = Inline binary data (base64 encoded, possibly compressed). // Appended = Appended binary data (possibly compressed and/or base64). enum { Ascii, Binary, Appended }; - //ETX - //BTX // Description: // Enumerate the supported vtkIdType bit lengths. // Int32 = File stores 32-bit values for vtkIdType. @@ -81,7 +75,6 @@ class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm // UInt32 = File stores 32-bit binary data header elements. // UInt64 = File stores 64-bit binary data header elements. enum { UInt32=32, UInt64=64 }; - //ETX // Description: // Get/Set the byte order of data written to the file. The default @@ -114,9 +107,9 @@ class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm // Description: // Enable writing to an OutputString instead of the default, a file. - vtkSetMacro(WriteToOutputString,int); - vtkGetMacro(WriteToOutputString,int); - vtkBooleanMacro(WriteToOutputString,int); + vtkSetMacro(WriteToOutputString, int); + vtkGetMacro(WriteToOutputString, int); + vtkBooleanMacro(WriteToOutputString, int); std::string GetOutputString() { return this->OutputString; } // Description: @@ -125,13 +118,11 @@ class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm virtual void SetCompressor(vtkDataCompressor*); vtkGetObjectMacro(Compressor, vtkDataCompressor); -//BTX enum CompressorType { NONE, ZLIB }; -//ETX // Description: // Convenience functions to set the compressor to certain known types. @@ -180,7 +171,7 @@ class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm void SetInputData(vtkDataObject *); void SetInputData(int, vtkDataObject*); vtkDataObject *GetInput(int port); - vtkDataObject *GetInput() { return this->GetInput(0); }; + vtkDataObject *GetInput() { return this->GetInput(0); } // Description: // Get the default file extension for files written by this writer. @@ -198,8 +189,8 @@ class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm // Description: // Set the number of time steps - vtkGetMacro(NumberOfTimeSteps,int); - vtkSetMacro(NumberOfTimeSteps,int); + vtkGetMacro(NumberOfTimeSteps, int); + vtkSetMacro(NumberOfTimeSteps, int); // Description: // API to interface an outside the VTK pipeline control @@ -254,7 +245,6 @@ class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm // appended data offsets for field data OffsetsManagerGroup *FieldDataOM; //one per array - //BTX // We need a 32 bit signed integer type to which vtkIdType will be // converted if Int32 is specified for the IdType parameter to this // writer. @@ -267,7 +257,6 @@ class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm # else # error "No native data type can represent a signed 32-bit integer." # endif - //ETX // Buffer for vtkIdType conversion. Int32IdType* Int32IdTypeBuffer; @@ -295,7 +284,7 @@ class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm // Method defined by subclasses to write data. Return 1 for // success, 0 for failure. - virtual int WriteData() {return 1;}; + virtual int WriteData() { return 1; } // Method defined by subclasses to specify the data set's type name. virtual const char* GetDataSetName()=0; @@ -457,9 +446,8 @@ class VTKIOXML_EXPORT vtkXMLWriter : public vtkAlgorithm bool UsePreviousVersion; vtkTypeInt64 *NumberOfTimeValues; //one per piece / per timestep - //BTX + friend class vtkXMLWriterHelper; - //ETX private: vtkXMLWriter(const vtkXMLWriter&); // Not implemented. diff --git a/IO/XMLParser/vtkXMLDataParser.h b/IO/XMLParser/vtkXMLDataParser.h index 9e0258195d0..b5cc4d2acad 100644 --- a/IO/XMLParser/vtkXMLDataParser.h +++ b/IO/XMLParser/vtkXMLDataParser.h @@ -44,7 +44,6 @@ class VTKIOXMLPARSER_EXPORT vtkXMLDataParser : public vtkXMLParser // Get the root element from the XML document. vtkXMLDataElement* GetRootElement(); - //BTX // Description: // Enumerate big and little endian byte order settings. enum { BigEndian, LittleEndian }; @@ -84,7 +83,6 @@ class VTKIOXMLPARSER_EXPORT vtkXMLDataParser : public vtkXMLParser // stream. Returns the number of words read. size_t ReadBinaryData(void* buffer, vtkTypeUInt64 startWord, size_t maxWords, int wordType); - //ETX // Description: // Get/Set the compressor used to decompress binary and appended data diff --git a/IO/XMLParser/vtkXMLParser.h b/IO/XMLParser/vtkXMLParser.h index 27c30dc881f..8b741218736 100644 --- a/IO/XMLParser/vtkXMLParser.h +++ b/IO/XMLParser/vtkXMLParser.h @@ -42,7 +42,6 @@ class VTKIOXMLPARSER_EXPORT vtkXMLParser : public vtkObject static vtkXMLParser* New(); - //BTX // Description: // Get/Set the input stream. vtkSetMacro(Stream, istream*); @@ -54,7 +53,6 @@ class VTKIOXMLPARSER_EXPORT vtkXMLParser : public vtkObject // work-around stream bugs on various platforms. vtkTypeInt64 TellG(); void SeekG(vtkTypeInt64 position); - //ETX // Description: // Parse the XML input. @@ -178,11 +176,9 @@ class VTKIOXMLPARSER_EXPORT vtkXMLParser : public vtkObject // routine. static int IsSpace(char c); - //BTX friend void vtkXMLParserStartElement(void*, const char*, const char**); friend void vtkXMLParserEndElement(void*, const char*); friend void vtkXMLParserCharacterDataHandler(void*, const char*, int); - //ETX int IgnoreCharacterData; diff --git a/IO/XMLParser/vtkXMLUtilities.h b/IO/XMLParser/vtkXMLUtilities.h index 401053f6aea..3b567efba80 100644 --- a/IO/XMLParser/vtkXMLUtilities.h +++ b/IO/XMLParser/vtkXMLUtilities.h @@ -51,7 +51,6 @@ class VTKIOXMLPARSER_EXPORT vtkXMLUtilities : public vtkObject ostream&, const char *sep = 0); - //BTX // Description: // Flatten a vtkXMLDataElement to a stream, i.e. output a textual stream // corresponding to that XML element, its attributes and its @@ -73,9 +72,7 @@ class VTKIOXMLPARSER_EXPORT vtkXMLUtilities : public vtkObject static int WriteElementToFile(vtkXMLDataElement*, const char *filename, vtkIndent *indent = 0); - //ETX - //BTX // Description: // Read a vtkXMLDataElement from a stream, string or file. // The 'encoding' parameter will be used to set the internal encoding of the @@ -92,7 +89,6 @@ class VTKIOXMLPARSER_EXPORT vtkXMLUtilities : public vtkObject const char *str, int encoding = VTK_ENCODING_NONE); static vtkXMLDataElement* ReadElementFromFile( const char *filename, int encoding = VTK_ENCODING_NONE); - //ETX // Description: // Sets attributes of an element from an array of encoded attributes. @@ -106,7 +102,6 @@ class VTKIOXMLPARSER_EXPORT vtkXMLUtilities : public vtkObject const char** atts, int encoding); - //BTX // Description: // Find all elements in 'tree' that are similar to 'elem' (using the // vtkXMLDataElement::IsEqualTo() predicate). @@ -117,7 +112,6 @@ class VTKIOXMLPARSER_EXPORT vtkXMLUtilities : public vtkObject static int FindSimilarElements(vtkXMLDataElement *elem, vtkXMLDataElement *tree, vtkXMLDataElement ***results); - //ETX // Description: // Factor and unfactor a tree. This operation looks for duplicate elements diff --git a/IO/Xdmf2/vtkSILBuilder.h b/IO/Xdmf2/vtkSILBuilder.h index b83efe399c9..28e9db751fa 100644 --- a/IO/Xdmf2/vtkSILBuilder.h +++ b/IO/Xdmf2/vtkSILBuilder.h @@ -57,7 +57,6 @@ class VTKIOXDMF2_EXPORT vtkSILBuilder : public vtkObject // Returns the vertex id for the root vertex. vtkGetMacro(RootVertex, vtkIdType); -//BTX protected: vtkSILBuilder(); ~vtkSILBuilder(); @@ -71,7 +70,7 @@ class VTKIOXDMF2_EXPORT vtkSILBuilder : public vtkObject private: vtkSILBuilder(const vtkSILBuilder&); // Not implemented. void operator=(const vtkSILBuilder&); // Not implemented. -//ETX + }; #endif diff --git a/IO/Xdmf2/vtkXdmfDataArray.cxx b/IO/Xdmf2/vtkXdmfDataArray.cxx index 2e2f80ed694..e4f76a7b250 100644 --- a/IO/Xdmf2/vtkXdmfDataArray.cxx +++ b/IO/Xdmf2/vtkXdmfDataArray.cxx @@ -219,7 +219,7 @@ vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : { - vtkCharArray *chara = vtkCharArray::SafeDownCast(this->vtkArray); + vtkCharArray *chara = vtkArrayDownCast(this->vtkArray); if(!chara){ XdmfErrorMessage("Cannot downcast data array"); return(0); @@ -229,7 +229,7 @@ vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, break; case XDMF_UINT8_TYPE : { - vtkUnsignedCharArray *uchara = vtkUnsignedCharArray::SafeDownCast(this->vtkArray); + vtkUnsignedCharArray *uchara = vtkArrayDownCast(this->vtkArray); if(!uchara){ XdmfErrorMessage("Cannot downcast ucharata array"); return(0); @@ -239,7 +239,7 @@ vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, break; case XDMF_INT16_TYPE : { - vtkShortArray *shorta = vtkShortArray::SafeDownCast(this->vtkArray); + vtkShortArray *shorta = vtkArrayDownCast(this->vtkArray); if(!shorta){ XdmfErrorMessage("Cannot downcast data array"); return(0); @@ -249,7 +249,7 @@ vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, break; case XDMF_UINT16_TYPE : { - vtkUnsignedShortArray *ushorta = vtkUnsignedShortArray::SafeDownCast(this->vtkArray); + vtkUnsignedShortArray *ushorta = vtkArrayDownCast(this->vtkArray); if(!ushorta){ XdmfErrorMessage("Cannot downcast ushortata array"); return(0); @@ -259,7 +259,7 @@ vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, break; case XDMF_INT32_TYPE : { - vtkIntArray *inta = vtkIntArray::SafeDownCast(this->vtkArray); + vtkIntArray *inta = vtkArrayDownCast(this->vtkArray); if(!inta){ XdmfErrorMessage("Cannot downcast intata array"); return(0); @@ -269,7 +269,7 @@ vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, break; case XDMF_UINT32_TYPE : { - vtkUnsignedIntArray *uinta = vtkUnsignedIntArray::SafeDownCast(this->vtkArray); + vtkUnsignedIntArray *uinta = vtkArrayDownCast(this->vtkArray); if(!uinta){ XdmfErrorMessage("Cannot downcast uintata array"); return(0); @@ -279,7 +279,7 @@ vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, break; case XDMF_INT64_TYPE : { - vtkLongArray *longa = vtkLongArray::SafeDownCast(this->vtkArray); + vtkLongArray *longa = vtkArrayDownCast(this->vtkArray); if(!longa){ XdmfErrorMessage("Cannot downcast longa array"); return(0); @@ -289,7 +289,7 @@ vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, break; case XDMF_FLOAT32_TYPE : { - vtkFloatArray *floata = vtkFloatArray::SafeDownCast(this->vtkArray); + vtkFloatArray *floata = vtkArrayDownCast(this->vtkArray); if(!floata){ XdmfErrorMessage("Cannot downcast floatata array"); return(0); @@ -299,7 +299,7 @@ vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, break; case XDMF_FLOAT64_TYPE : { - vtkDoubleArray *doublea = vtkDoubleArray::SafeDownCast(this->vtkArray); + vtkDoubleArray *doublea = vtkArrayDownCast(this->vtkArray); if(!doublea){ XdmfErrorMessage("Cannot downcast doubleata array"); return(0); diff --git a/IO/Xdmf2/vtkXdmfHeavyData.cxx b/IO/Xdmf2/vtkXdmfHeavyData.cxx index a12d85c82d0..d48cce0ff29 100644 --- a/IO/Xdmf2/vtkXdmfHeavyData.cxx +++ b/IO/Xdmf2/vtkXdmfHeavyData.cxx @@ -1278,7 +1278,7 @@ bool vtkXdmfHeavyData::ReadGhostSets(vtkDataSet* dataSet, XdmfGrid* xmfGrid, continue; } - vtkUnsignedCharArray* ghosts = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray* ghosts = vtkArrayDownCast( dsa->GetArray(vtkDataSetAttributes::GhostArrayName())); if (!ghosts) { diff --git a/IO/Xdmf2/vtkXdmfReader.h b/IO/Xdmf2/vtkXdmfReader.h index cb4a0d11a2f..f3baceea90c 100644 --- a/IO/Xdmf2/vtkXdmfReader.h +++ b/IO/Xdmf2/vtkXdmfReader.h @@ -138,7 +138,6 @@ class VTKIOXDMF2_EXPORT vtkXdmfReader : public vtkDataReader // eg. blocks/materials/hierarchies. virtual vtkGraph* GetSIL(); -//BTX class XdmfDataSetTopoGeoPath { public: @@ -214,7 +213,7 @@ class VTKIOXDMF2_EXPORT vtkXdmfReader : public vtkDataReader private: vtkXdmfReader(const vtkXdmfReader&); // Not implemented void operator=(const vtkXdmfReader&); // Not implemented -//ETX + }; #endif diff --git a/IO/Xdmf3/vtkXdmf3DataSet.cxx b/IO/Xdmf3/vtkXdmf3DataSet.cxx index 951c09b2967..a47d83deed3 100644 --- a/IO/Xdmf3/vtkXdmf3DataSet.cxx +++ b/IO/Xdmf3/vtkXdmf3DataSet.cxx @@ -1801,7 +1801,7 @@ void vtkXdmf3DataSet::VTKToXdmf( mColumnIndex->initialize(XdmfArrayType::Int32()); } - vtkDoubleArray *wA = vtkDoubleArray::SafeDownCast( + vtkDoubleArray *wA = vtkArrayDownCast( dataSet->GetEdgeData()->GetArray("Edge Weights")); while (vit->HasNext()) diff --git a/Imaging/Color/vtkImageQuantizeRGBToIndex.h b/Imaging/Color/vtkImageQuantizeRGBToIndex.h index 6732af8fde9..bbbe4369edd 100644 --- a/Imaging/Color/vtkImageQuantizeRGBToIndex.h +++ b/Imaging/Color/vtkImageQuantizeRGBToIndex.h @@ -55,7 +55,6 @@ class VTKIMAGINGCOLOR_EXPORT vtkImageQuantizeRGBToIndex : public vtkImageAlgorit vtkGetMacro( BuildTreeExecuteTime, double ); vtkGetMacro( LookupIndexExecuteTime, double ); -//BTX // Description: // For internal use only - get the type of the image vtkGetMacro( InputType, int ); @@ -65,7 +64,6 @@ class VTKIMAGINGCOLOR_EXPORT vtkImageQuantizeRGBToIndex : public vtkImageAlgorit vtkSetMacro( InitializeExecuteTime, double ); vtkSetMacro( BuildTreeExecuteTime, double ); vtkSetMacro( LookupIndexExecuteTime, double ); -//ETX protected: vtkImageQuantizeRGBToIndex(); diff --git a/Imaging/Core/Testing/Data/Baseline/voxelModel.png.md5 b/Imaging/Core/Testing/Data/Baseline/voxelModel.png.md5 index 87c06ff9cea..e98d936dbfa 100644 --- a/Imaging/Core/Testing/Data/Baseline/voxelModel.png.md5 +++ b/Imaging/Core/Testing/Data/Baseline/voxelModel.png.md5 @@ -1 +1 @@ -d7f2831ab5559018e708d192be429181 +438eeb5dfdcc3322d8b5a667e448de5e diff --git a/Imaging/Core/vtkAbstractImageInterpolator.cxx b/Imaging/Core/vtkAbstractImageInterpolator.cxx index 308c3cd43ec..926b10ed913 100644 --- a/Imaging/Core/vtkAbstractImageInterpolator.cxx +++ b/Imaging/Core/vtkAbstractImageInterpolator.cxx @@ -66,8 +66,6 @@ vtkAbstractImageInterpolator::vtkAbstractImageInterpolator() { this->Extent[2*j] = 0; this->Extent[2*j+1] = -1; - this->WholeExtent[2*j] = 0; - this->WholeExtent[2*j+1] = -1; this->Spacing[j] = 1.0; this->Origin[j] = 0.0; } @@ -110,7 +108,6 @@ void vtkAbstractImageInterpolator::DeepCopy(vtkAbstractImageInterpolator *obj) this->SetComponentCount(obj->ComponentCount); this->SetBorderMode(obj->BorderMode); obj->GetExtent(this->Extent); - obj->GetWholeExtent(this->WholeExtent); obj->GetOrigin(this->Origin); obj->GetSpacing(this->Spacing); if (this->Scalars) @@ -139,10 +136,6 @@ void vtkAbstractImageInterpolator::PrintSelf(ostream& os, vtkIndent indent) os << indent << "Extent: " << this->Extent[0] << " " << this->Extent[1] << " " << this->Extent[2] << " " << this->Extent[3] << " " << this->Extent[4] << " " << this->Extent[5] << "\n"; - os << indent << "WholeExtent: " - << this->WholeExtent[0] << " " << this->WholeExtent[1] << " " - << this->WholeExtent[2] << " " << this->WholeExtent[3] << " " - << this->WholeExtent[4] << " " << this->WholeExtent[5] << "\n"; os << indent << "Origin: " << this->Origin[0] << " " << this->Origin[1] << " " << this->Origin[2] << "\n"; os << indent << "Spacing: " << this->Spacing[0] << " " << this->Spacing[1] @@ -266,7 +259,6 @@ void vtkAbstractImageInterpolator::Initialize(vtkDataObject *o) // get the image information data->GetSpacing(this->Spacing); data->GetOrigin(this->Origin); - data->GetExtent(this->WholeExtent); data->GetExtent(this->Extent); // call update @@ -317,10 +309,9 @@ void vtkAbstractImageInterpolator::Update() extent[4] = this->Extent[4]; extent[5] = this->Extent[5]; - // use the WholeExtent and Tolerance to set the bounds + // use the Extent and Tolerance to set the bounds double *bounds = this->StructuredBoundsDouble; float *fbounds = this->StructuredBoundsFloat; - int *wholeExtent = this->WholeExtent; double tol = this->Tolerance; // always restrict the bounds to the limits of int int supportSize[3]; @@ -335,13 +326,13 @@ void vtkAbstractImageInterpolator::Update() for (int i = 0; i < 3; i++) { // use min tolerance of 0.5 if just one slice thick - double newtol = 0.5*(wholeExtent[2*i] == wholeExtent[2*i+1]); + double newtol = 0.5*(extent[2*i] == extent[2*i+1]); newtol = ((newtol > tol) ? newtol : tol); - double bound = wholeExtent[2*i] - newtol; + double bound = extent[2*i] - newtol; bound = ((bound > minbound) ? bound : minbound); fbounds[2*i] = bounds[2*i] = bound; - bound = wholeExtent[2*i+1] + newtol; + bound = extent[2*i+1] + newtol; bound = ((bound < maxbound) ? bound : maxbound); fbounds[2*i+1] = bounds[2*i+1] = bound; } @@ -509,3 +500,22 @@ void vtkAbstractImageInterpolator::FreePrecomputedWeights( weights = NULL; } + +//---------------------------------------------------------------------------- +#if !defined(VTK_LEGACY_REMOVE) +int *vtkAbstractImageInterpolator::GetWholeExtent() +{ + VTK_LEGACY_REPLACED_BODY( + vtkAbstractImageInterpolator::GetWholeExtent, "VTK 7.1", + vtkAbstractImageInterpolator::GetExtent); + return this->GetExtent(); +} + +void vtkAbstractImageInterpolator::GetWholeExtent(int extent[6]) +{ + VTK_LEGACY_REPLACED_BODY( + vtkAbstractImageInterpolator::GetWholeExtent, "VTK 7.1", + vtkAbstractImageInterpolator::GetExtent); + this->GetExtent(extent); +} +#endif diff --git a/Imaging/Core/vtkAbstractImageInterpolator.h b/Imaging/Core/vtkAbstractImageInterpolator.h index c286e9ff528..d3075103aab 100644 --- a/Imaging/Core/vtkAbstractImageInterpolator.h +++ b/Imaging/Core/vtkAbstractImageInterpolator.h @@ -213,7 +213,8 @@ class VTKIMAGINGCORE_EXPORT vtkAbstractImageInterpolator : public vtkObject // Description: // Get the whole extent of the data being interpolated, including // parts of the data that are not currently in memory. - vtkGetVector6Macro(WholeExtent, int); + VTK_LEGACY(int *GetWholeExtent()); + VTK_LEGACY(void GetWholeExtent(int extent[6])); protected: vtkAbstractImageInterpolator(); @@ -248,7 +249,6 @@ class VTKIMAGINGCORE_EXPORT vtkAbstractImageInterpolator : public vtkObject vtkDataArray *Scalars; double StructuredBoundsDouble[6]; float StructuredBoundsFloat[6]; - int WholeExtent[6]; int Extent[6]; double Spacing[3]; double Origin[3]; diff --git a/Imaging/Core/vtkImageBSplineCoefficients.cxx b/Imaging/Core/vtkImageBSplineCoefficients.cxx index 19f351642f0..a1453f84b7d 100644 --- a/Imaging/Core/vtkImageBSplineCoefficients.cxx +++ b/Imaging/Core/vtkImageBSplineCoefficients.cxx @@ -142,6 +142,16 @@ int vtkImageBSplineCoefficients::RequestData( { this->Iteration = i; + // ensure that iteration axis is not split during threaded execution + this->SplitPathLength = 0; + for (int axis = 2; axis >= 0; --axis) + { + if (axis != i) + { + this->SplitPath[this->SplitPathLength++] = axis; + } + } + if (ie[2*i+1] > ie[2*i]) { if (!this->vtkThreadedImageAlgorithm::RequestData( @@ -231,52 +241,6 @@ int vtkImageBSplineCoefficients::RequestUpdateExtent( return 1; } -//---------------------------------------------------------------------------- -// For streaming and threads. Splits output update extent into num pieces. -// This method needs to be called num times. Results must not overlap for -// consistent starting extent. This particular filter requires splitting -// along different directions depending on the iteration. -int vtkImageBSplineCoefficients::SplitExtent( - int splitExt[6], int fullExt[6], int num, int total) -{ - static int splitAxisPriority[3][2] = { - { 2, 1 }, { 2, 0 }, { 1, 0 } }; - - // start with same extent - for (int i = 0; i < 6; i++) - { - splitExt[i] = fullExt[i]; - } - - int axis = this->Iteration; - int splitAxis = splitAxisPriority[axis][0]; - int minIdx = fullExt[splitAxis*2]; - int maxIdx = fullExt[splitAxis*2 + 1]; - int size = maxIdx - minIdx + 1; - if (size == 1) - { - splitAxis = splitAxisPriority[axis][1]; - minIdx = fullExt[splitAxis*2]; - maxIdx = fullExt[splitAxis*2 + 1]; - size = maxIdx - minIdx + 1; - } - - // determine the actual number of pieces that will be generated - if (size < total) - { - total = size; - } - - // make sure that num isn't greater than the number of possible splits - if (num < total) - { - splitExt[splitAxis*2] = minIdx + size*num/total; - splitExt[splitAxis*2 + 1] = minIdx + size*(num + 1)/total - 1; - } - - return total; -} - //---------------------------------------------------------------------------- template void vtkImageBSplineCoefficientsExecute( diff --git a/Imaging/Core/vtkImageBSplineCoefficients.h b/Imaging/Core/vtkImageBSplineCoefficients.h index c715b185568..ea56bd0e4a8 100644 --- a/Imaging/Core/vtkImageBSplineCoefficients.h +++ b/Imaging/Core/vtkImageBSplineCoefficients.h @@ -120,11 +120,6 @@ class VTKIMAGINGCORE_EXPORT vtkImageBSplineCoefficients : double Evaluate(const double point[3]) { return this->Evaluate(point[0], point[1], point[2]); } - // Description: - // Internal method. Override SplitExtent so that the full extent is - // available in the direction currently being processed. - int SplitExtent(int splitExt[6], int startExt[6], int num, int total); - protected: vtkImageBSplineCoefficients(); ~vtkImageBSplineCoefficients(); diff --git a/Imaging/Core/vtkImageDifference.cxx b/Imaging/Core/vtkImageDifference.cxx index 78cee627978..d2287d16f77 100644 --- a/Imaging/Core/vtkImageDifference.cxx +++ b/Imaging/Core/vtkImageDifference.cxx @@ -19,25 +19,46 @@ #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkSMPTools.h" vtkStandardNewMacro(vtkImageDifference); +// Thread-local data needed for each thread. +class vtkImageDifferenceThreadData +{ +public: + vtkImageDifferenceThreadData() + : ErrorMessage(0), Error(0.0), ThresholdedError(0.0) {} + + const char *ErrorMessage; + double Error; + double ThresholdedError; +}; + +// Holds thread-local data for all threads. +class vtkImageDifferenceSMPThreadLocal + : public vtkSMPThreadLocal +{ +public: + typedef vtkSMPThreadLocal::iterator iterator; +}; + // Construct object to extract all of the input data. vtkImageDifference::vtkImageDifference() { - int i; - for ( i = 0; i < this->NumberOfThreads; i++ ) - { - this->ErrorPerThread[i] = 0; - this->ThresholdedErrorPerThread[i] = 0.0; - } this->Threshold = 16; this->AllowShift = 1; this->Averaging = 1; - this->SetNumberOfInputPorts(2); -} + this->ErrorMessage = 0; + this->Error = 0.0; + this->ThresholdedError = 0.0; + + this->ThreadData = NULL; + this->SMPThreadData = NULL; + this->SetNumberOfInputPorts(2); +} // not so simple macro for calculating error #define vtkImageDifferenceComputeError(c1,c2) \ @@ -92,8 +113,68 @@ if (this->Averaging && \ if ((r1+g1+b1) < (tr+tg+tb)) { tr = r1; tg = g1; tb = b1; } \ } +//---------------------------------------------------------------------------- +// This functor is used with vtkSMPTools to execute the algorithm in pieces +// split over the extent of the data. +class vtkImageDifferenceSMPFunctor +{ +public: + // Create the functor by providing all of the information that will be + // needed by the ThreadedRequestData method that the functor will call. + vtkImageDifferenceSMPFunctor( + vtkImageDifference *algo, vtkImageData ***inputs, vtkImageData **outputs, + int *extent, vtkIdType pieces) + : Algorithm(algo), Inputs(inputs), Outputs(outputs), + Extent(extent), NumberOfPieces(pieces) {} + + void Initialize() {} + void operator()(vtkIdType begin, vtkIdType end); + void Reduce(); + +private: + vtkImageDifferenceSMPFunctor(); + + vtkImageDifference *Algorithm; + vtkImageData ***Inputs; + vtkImageData **Outputs; + int *Extent; + vtkIdType NumberOfPieces; +}; +//---------------------------------------------------------------------------- +void vtkImageDifferenceSMPFunctor::operator()(vtkIdType begin, vtkIdType end) +{ + this->Algorithm->SMPRequestData( + 0, 0, 0, this->Inputs, this->Outputs, + begin, end, this->NumberOfPieces, this->Extent); +} + +//---------------------------------------------------------------------------- +// Used with vtkSMPTools to compute the error +void vtkImageDifferenceSMPFunctor::Reduce() +{ + const char *errorMessage = 0; + double error = 0.0; + double thresholdedError = 0.0; + + for (vtkImageDifferenceSMPThreadLocal::iterator + iter = this->Algorithm->SMPThreadData->begin(); + iter != this->Algorithm->SMPThreadData->end(); + ++iter) + { + errorMessage = iter->ErrorMessage; + if (errorMessage) + { + break; + } + error += iter->Error; + thresholdedError += iter->ThresholdedError; + } + this->Algorithm->ErrorMessage = errorMessage; + this->Algorithm->Error = error; + this->Algorithm->ThresholdedError = thresholdedError; +} //---------------------------------------------------------------------------- // This method computes the input extent necessary to generate the output. @@ -183,18 +264,28 @@ void vtkImageDifference::ThreadedRequestData( int matched; unsigned long count = 0; unsigned long target; + double error = 0.0; + double thresholdedError = 0.0; + vtkImageDifferenceThreadData *threadData = NULL; - this->ErrorPerThread[id] = 0; - this->ThresholdedErrorPerThread[id] = 0; + if (this->EnableSMP) + { + threadData = &this->SMPThreadData->Local(); + } + else + { + threadData = &this->ThreadData[id]; + } + + // If an error has occurred, then do not continue. + if (threadData->ErrorMessage) + { + return; + } if (inData[0] == NULL || inData[1] == NULL || outData == NULL) { - if (!id) - { - vtkErrorMacro(<< "Execute: Missing data"); - } - this->ErrorPerThread[id] = 1000; - this->ThresholdedErrorPerThread[id] = 1000; + threadData->ErrorMessage = "Missing data"; return; } @@ -202,12 +293,7 @@ void vtkImageDifference::ThreadedRequestData( inData[1][0]->GetNumberOfScalarComponents() != 3 || outData[0]->GetNumberOfScalarComponents() != 3) { - if (!id) - { - vtkErrorMacro(<< "Execute: Expecting 3 components (RGB)"); - } - this->ErrorPerThread[id] = 1000; - this->ThresholdedErrorPerThread[id] = 1000; + threadData->ErrorMessage = "Expecting 3 components (RGB)"; return; } @@ -215,15 +301,10 @@ void vtkImageDifference::ThreadedRequestData( if (inData[0][0]->GetScalarType() != VTK_UNSIGNED_CHAR || inData[1][0]->GetScalarType() != VTK_UNSIGNED_CHAR || outData[0]->GetScalarType() != VTK_UNSIGNED_CHAR) - { - if (!id) - { - vtkErrorMacro(<< "Execute: All ScalarTypes must be unsigned char"); - } - this->ErrorPerThread[id] = 1000; - this->ThresholdedErrorPerThread[id] = 1000; - return; - } + { + threadData->ErrorMessage = "All ScalarTypes must be unsigned char"; + return; + } in1Ptr2 = static_cast( inData[0][0]->GetScalarPointerForExtent(outExt)); @@ -328,7 +409,7 @@ void vtkImageDifference::ThreadedRequestData( } } - this->ErrorPerThread[id] = this->ErrorPerThread[id] + (tr + tg + tb)/(3.0*255); + error += (tr + tg + tb)/(3.0*255); tr -= this->Threshold; if (tr < 0) { @@ -347,7 +428,7 @@ void vtkImageDifference::ThreadedRequestData( *outPtr0++ = static_cast(tr); *outPtr0++ = static_cast(tg); *outPtr0++ = static_cast(tb); - this->ThresholdedErrorPerThread[id] += (tr + tg + tb)/(3.0*255.0); + thresholdedError += (tr + tg + tb)/(3.0*255.0); in1Ptr0 += in1Inc0; in2Ptr0 += in2Inc0; @@ -360,6 +441,85 @@ void vtkImageDifference::ThreadedRequestData( in1Ptr2 += in1Inc2; in2Ptr2 += in2Inc2; } + + // Add the results to the thread-local total. + threadData->Error += error; + threadData->ThresholdedError += thresholdedError; +} + +//---------------------------------------------------------------------------- +// Create thread-local objects before initiating the multithreading +int vtkImageDifference::RequestData( + vtkInformation *request, + vtkInformationVector **inputVector, + vtkInformationVector *outputVector) +{ + int r = 1; + + if (this->EnableSMP) // For vtkSMPTools implementation. + { + // Get the input and output data objects + vtkImageData *inDataPointer[2]; + vtkImageData **inData[2] = { &inDataPointer[0], &inDataPointer[1] }; + vtkImageData *outData[1]; + this->PrepareImageData(inputVector, outputVector, inData, outData); + + // Get the extent + int extent[6]; + outData[0]->GetExtent(extent); + + // Do a dummy execution of SplitExtent to compute the number of pieces + vtkIdType pieces = this->SplitExtent(0, extent, 0, this->NumberOfThreads); + + // Use vtkSMPTools to multithread the functor + vtkImageDifferenceSMPThreadLocal threadData; + vtkImageDifferenceSMPFunctor functor( + this, inData, outData, extent, pieces); + this->SMPThreadData = &threadData; + bool debug = this->Debug; + this->Debug = false; + vtkSMPTools::For(0, pieces, functor); + this->Debug = debug; + this->SMPThreadData = NULL; + } + else + { + // For vtkMultiThreader implementation. + int n = this->NumberOfThreads; + this->ThreadData = new vtkImageDifferenceThreadData[n]; + + // The superclass will call ThreadedRequestData + r = this->Superclass::RequestData(request, inputVector, outputVector); + + // Compute error sums here. + this->Error = 0.0; + this->ThresholdedError = 0.0; + for (int i = 0; i < n; i++) + { + this->Error += this->ThreadData[i].Error; + this->ThresholdedError += this->ThreadData[i].ThresholdedError; + this->ErrorMessage = this->ThreadData[i].ErrorMessage; + if (this->ErrorMessage) + { + break; + } + } + + delete [] this->ThreadData; + this->ThreadData = NULL; + } + + if (this->ErrorMessage) + { + // Report errors here, do not report errors while multithreading! + vtkErrorMacro("RequestData: " << this->ErrorMessage); + this->ErrorMessage = NULL; + this->Error = 1000.0; + this->ThresholdedError = 1000.0; + r = 0; + } + + return r; } //---------------------------------------------------------------------------- @@ -383,11 +543,9 @@ int vtkImageDifference::RequestInformation ( in1Ext[2] != in2Ext[2] || in1Ext[3] != in2Ext[3] || in1Ext[4] != in2Ext[4] || in1Ext[5] != in2Ext[5]) { - for (i = 0; i < this->NumberOfThreads; i++) - { - this->ErrorPerThread[i] = 1000; - this->ThresholdedErrorPerThread[i] = 1000; - } + this->Error = 1000.0; + this->ThresholdedError = 1000.0; + vtkErrorMacro("ExecuteInformation: Input are not the same size.\n" << " Input1 is: " << in1Ext[0] << "," << in1Ext[1] << "," << in1Ext[2] << "," << in1Ext[3] << "," @@ -418,32 +576,7 @@ int vtkImageDifference::RequestInformation ( return 1; } -double vtkImageDifference::GetError() -{ - double error = 0.0; - int i; - - for ( i= 0; i < this->NumberOfThreads; i++ ) - { - error += this->ErrorPerThread[i]; - } - - return error; -} - -double vtkImageDifference::GetThresholdedError() -{ - double error = 0.0; - int i; - - for ( i= 0; i < this->NumberOfThreads; i++ ) - { - error += this->ThresholdedErrorPerThread[i]; - } - - return error; -} - +//---------------------------------------------------------------------------- vtkImageData *vtkImageDifference::GetImage() { if (this->GetNumberOfInputConnections(1) < 1) @@ -454,22 +587,15 @@ vtkImageData *vtkImageDifference::GetImage() this->GetExecutive()->GetInputData(1, 0)); } - +//---------------------------------------------------------------------------- void vtkImageDifference::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); - int i; - - for ( i= 0; i < this->NumberOfThreads; i++ ) - { - os << indent << "Error for thread " << i << ": " << this->ErrorPerThread[i] << "\n"; - os << indent << "ThresholdedError for thread " << i << ": " - << this->ThresholdedErrorPerThread[i] << "\n"; - } + os << indent << "Error: " << this->Error << "\n"; + os << indent << "ThresholdedError: " << this->ThresholdedError << "\n"; os << indent << "Threshold: " << this->Threshold << "\n"; os << indent << "AllowShift: " << this->AllowShift << "\n"; os << indent << "Averaging: " << this->Averaging << "\n"; } - diff --git a/Imaging/Core/vtkImageDifference.h b/Imaging/Core/vtkImageDifference.h index 84aeda064a8..772171d6047 100644 --- a/Imaging/Core/vtkImageDifference.h +++ b/Imaging/Core/vtkImageDifference.h @@ -37,6 +37,9 @@ #include "vtkImagingCoreModule.h" // For export macro #include "vtkThreadedImageAlgorithm.h" +class vtkImageDifferenceThreadData; +class vtkImageDifferenceSMPThreadLocal; + class VTKIMAGINGCORE_EXPORT vtkImageDifference : public vtkThreadedImageAlgorithm { public: @@ -55,17 +58,16 @@ class VTKIMAGINGCORE_EXPORT vtkImageDifference : public vtkThreadedImageAlgorith // Description: // Return the total error in comparing the two images. - double GetError(void); + double GetError() { return this->Error; } void GetError(double *e) { *e = this->GetError(); }; // Description: // Return the total thresholded error in comparing the two images. // The thresholded error is the error for a given pixel minus the // threshold and clamped at a minimum of zero. - double GetThresholdedError(void); + double GetThresholdedError() { return this->ThresholdedError; } void GetThresholdedError(double *e) { *e = this->GetThresholdedError(); }; - // Description: // Specify a threshold tolerance for pixel differences. vtkSetMacro(Threshold,int); @@ -94,18 +96,25 @@ class VTKIMAGINGCORE_EXPORT vtkImageDifference : public vtkThreadedImageAlgorith vtkImageDifference(); ~vtkImageDifference() {} - double ErrorPerThread[VTK_MAX_THREADS]; - double ThresholdedErrorPerThread[VTK_MAX_THREADS]; + // Parameters int AllowShift; int Threshold; int Averaging; + // Outputs + const char *ErrorMessage; + double Error; + double ThresholdedError; + virtual int RequestInformation (vtkInformation *, vtkInformationVector **, vtkInformationVector *); virtual int RequestUpdateExtent(vtkInformation *, vtkInformationVector **, vtkInformationVector *); + virtual int RequestData(vtkInformation *, + vtkInformationVector **, + vtkInformationVector *); virtual void ThreadedRequestData(vtkInformation *request, vtkInformationVector **inputVector, @@ -114,9 +123,17 @@ class VTKIMAGINGCORE_EXPORT vtkImageDifference : public vtkThreadedImageAlgorith vtkImageData **outData, int extent[6], int threadId); + // Used for vtkMultiThreader operation. + vtkImageDifferenceThreadData *ThreadData; + + // Used for vtkSMPTools operation. + vtkImageDifferenceSMPThreadLocal *SMPThreadData; + private: vtkImageDifference(const vtkImageDifference&); // Not implemented. void operator=(const vtkImageDifference&); // Not implemented. + + friend class vtkImageDifferenceSMPFunctor; }; #endif diff --git a/Imaging/Core/vtkImageMapToColors.cxx b/Imaging/Core/vtkImageMapToColors.cxx index 8bd094b748c..ea1944d26c7 100644 --- a/Imaging/Core/vtkImageMapToColors.cxx +++ b/Imaging/Core/vtkImageMapToColors.cxx @@ -315,7 +315,7 @@ void vtkImageMapToColors::ThreadedRequestData( int outExt[6], int id) { vtkDataArray* outArray = outData[0]->GetPointData()->GetScalars(); - vtkCharArray *maskArray = vtkCharArray::SafeDownCast(inData[0][0]->GetPointData()->GetArray("vtkValidPointMask")); + vtkCharArray *maskArray = vtkArrayDownCast(inData[0][0]->GetPointData()->GetArray("vtkValidPointMask")); vtkDataArray* inArray = this->GetInputArrayToProcess(0, inputVector); // Working method diff --git a/Imaging/Core/vtkImageResize.cxx b/Imaging/Core/vtkImageResize.cxx index 7c1b4cecc60..35e6d958060 100644 --- a/Imaging/Core/vtkImageResize.cxx +++ b/Imaging/Core/vtkImageResize.cxx @@ -75,6 +75,10 @@ vtkImageResize::vtkImageResize() this->Interpolator = NULL; this->NNInterpolator = NULL; this->Interpolate = 1; + + // This filter works best when the number of pieces is equal to + // the number of threads, so never try for smaller pieces. + this->DesiredBytesPerPiece = 0; } //---------------------------------------------------------------------------- diff --git a/Imaging/Core/vtkImageReslice.cxx b/Imaging/Core/vtkImageReslice.cxx index 85d9dfc762b..ed73eacccae 100644 --- a/Imaging/Core/vtkImageReslice.cxx +++ b/Imaging/Core/vtkImageReslice.cxx @@ -2054,7 +2054,6 @@ void vtkImageResliceExecute(vtkImageReslice *self, int componentOffset = interpolator->GetComponentOffset(); int borderMode = interpolator->GetBorderMode(); int *inExt = interpolator->GetExtent(); - int *inWholeExt = interpolator->GetWholeExtent(); vtkIdType inInc[3]; inInc[0] = scalars->GetNumberOfComponents(); inInc[1] = inInc[0]*(inExt[1] - inExt[0] + 1); @@ -2084,10 +2083,7 @@ void vtkImageResliceExecute(vtkImageReslice *self, !(newtrans || perspective || convertScalars || rescaleScalars) && inputScalarType == outData->GetScalarType() && fullSize == scalars->GetNumberOfTuples() && - self->GetBorder() == 1 && nsamples <= 1 && - inExt[0] >= inWholeExt[0] && inExt[1] <= inWholeExt[1] && - inExt[2] >= inWholeExt[2] && inExt[3] <= inWholeExt[3] && - inExt[4] >= inWholeExt[4] && inExt[5] <= inWholeExt[5]) + self->GetBorder() == 1 && nsamples <= 1) { optimizeNearest = 1; } @@ -2842,7 +2838,6 @@ void vtkReslicePermuteExecute(vtkImageReslice *self, bool doConversion = true; int inputScalarType = scalars->GetDataType(); if (interpolationMode == VTK_NEAREST_INTERPOLATION && - interpolator->IsA("vtkImageInterpolator") && inputScalarType == scalarType && !convertScalars && !rescaleScalars && nsamples == 1) { diff --git a/Imaging/Core/vtkImageReslice.h b/Imaging/Core/vtkImageReslice.h index 1e8d0b3cedc..bcb2b9fe5f3 100644 --- a/Imaging/Core/vtkImageReslice.h +++ b/Imaging/Core/vtkImageReslice.h @@ -348,7 +348,7 @@ class VTKIMAGINGCORE_EXPORT vtkImageReslice : public vtkThreadedImageAlgorithm // Description: // Report object referenced by instances of this class. - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; // Description: // Convenient methods for switching between nearest-neighbor and linear diff --git a/Imaging/Core/vtkImageStencilData.h b/Imaging/Core/vtkImageStencilData.h index 9f7cd16e012..d2d1138a9ce 100644 --- a/Imaging/Core/vtkImageStencilData.h +++ b/Imaging/Core/vtkImageStencilData.h @@ -127,12 +127,10 @@ class VTKIMAGINGCORE_EXPORT vtkImageStencilData : public vtkDataObject virtual void CopyInformationFromPipeline(vtkInformation *info); virtual void CopyInformationToPipeline(vtkInformation *info); - //BTX // Description: // Retrieve an instance of this class from an information object. static vtkImageStencilData* GetData(vtkInformation* info); static vtkImageStencilData* GetData(vtkInformationVector* v, int i=0); - //ETX // Description: // Add merges the stencil supplied as argument into Self. @@ -199,7 +197,6 @@ class VTKIMAGINGCORE_EXPORT vtkImageStencilData : public vtkDataObject friend class vtkImageStencilIteratorFriendship; }; -//BTX // Description: // This is a helper class for stencil creation. It is a raster with // infinite resolution in the X direction (approximately, since it uses @@ -259,7 +256,6 @@ class VTKIMAGINGCORE_EXPORT vtkImageStencilRaster vtkImageStencilRaster(const vtkImageStencilRaster&); // Not implemented. void operator=(const vtkImageStencilRaster&); // Not implemented. }; -//ETX #endif diff --git a/Imaging/Core/vtkImageStencilSource.h b/Imaging/Core/vtkImageStencilSource.h index 52f69897e05..db5f652662a 100644 --- a/Imaging/Core/vtkImageStencilSource.h +++ b/Imaging/Core/vtkImageStencilSource.h @@ -77,7 +77,7 @@ class VTKIMAGINGCORE_EXPORT vtkImageStencilSource : // Description: // Report object referenced by instances of this class. - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; protected: vtkImageStencilSource(); diff --git a/Imaging/Core/vtkRTAnalyticSource.cxx b/Imaging/Core/vtkRTAnalyticSource.cxx index 9cf6d209126..99c7f149f08 100644 --- a/Imaging/Core/vtkRTAnalyticSource.cxx +++ b/Imaging/Core/vtkRTAnalyticSource.cxx @@ -102,6 +102,16 @@ int vtkRTAnalyticSource::RequestInformation( { // get the info objects vtkInformation *outInfo = outputVector->GetInformationObject(0); + if (this->WholeExtent[0] > this->WholeExtent[1] || + this->WholeExtent[2] > this->WholeExtent[3] || + this->WholeExtent[4] > this->WholeExtent[5]) + { + vtkErrorMacro("Invalid WholeExtent: " + << this->WholeExtent[0] << ", " << this->WholeExtent[1] << ", " + << this->WholeExtent[2] << ", " << this->WholeExtent[3] << ", " + << this->WholeExtent[4] << ", " << this->WholeExtent[5]); + return 0; + } int tmpExt[6], i; for (i = 0; i < 3; i++) diff --git a/Imaging/Fourier/vtkImageFFT.cxx b/Imaging/Fourier/vtkImageFFT.cxx index bf92a49d25d..49df0c2d2d6 100644 --- a/Imaging/Fourier/vtkImageFFT.cxx +++ b/Imaging/Fourier/vtkImageFFT.cxx @@ -219,90 +219,3 @@ void vtkImageFFT::ThreadedRequestData( return; } } - - - -//---------------------------------------------------------------------------- -// For streaming and threads. Splits output update extent into num pieces. -// This method needs to be called num times. Results must not overlap for -// consistent starting extent. Subclass can override this method. -// This method returns the number of peices resulting from a successful split. -// This can be from 1 to "total". -// If 1 is returned, the extent cannot be split. -int vtkImageFFT::SplitExtent(int splitExt[6], int startExt[6], - int num, int total) -{ - int splitAxis; - int min, max; - - vtkDebugMacro("SplitExtent: ( " << startExt[0] << ", " << startExt[1] << ", " - << startExt[2] << ", " << startExt[3] << ", " - << startExt[4] << ", " << startExt[5] << "), " - << num << " of " << total); - - // start with same extent - memcpy(splitExt, startExt, 6 * sizeof(int)); - - splitAxis = 2; - min = startExt[4]; - max = startExt[5]; - while ((splitAxis == this->Iteration) || (min == max)) - { - splitAxis--; - if (splitAxis < 0) - { // cannot split - vtkDebugMacro(" Cannot Split"); - return 1; - } - min = startExt[splitAxis*2]; - max = startExt[splitAxis*2+1]; - } - - // determine the actual number of pieces that will be generated - if ((max - min + 1) < total) - { - total = max - min + 1; - } - - if (num >= total) - { - vtkDebugMacro(" SplitRequest (" << num - << ") larger than total: " << total); - return total; - } - - // determine the extent of the piece - splitExt[splitAxis*2] = min + (max - min + 1)*num/total; - if (num == total - 1) - { - splitExt[splitAxis*2+1] = max; - } - else - { - splitExt[splitAxis*2+1] = (min-1) + (max - min + 1)*(num+1)/total; - } - - vtkDebugMacro(" Split Piece: ( " <ExecuteFftForwardBackward(in, out, N, -1); } +//---------------------------------------------------------------------------- +// Called each axis over which the filter is executed. +int vtkImageFourierFilter::RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) +{ + // ensure that iteration axis is not split during threaded execution + this->SplitPathLength = 0; + for (int axis = 2; axis >= 0; --axis) + { + if (axis != this->Iteration) + { + this->SplitPath[this->SplitPathLength++] = axis; + } + } + + return this->Superclass::RequestData(request, inputVector, outputVector); +} + diff --git a/Imaging/Fourier/vtkImageFourierFilter.h b/Imaging/Fourier/vtkImageFourierFilter.h index 0c6bcb6819d..3d7cb1396d0 100644 --- a/Imaging/Fourier/vtkImageFourierFilter.h +++ b/Imaging/Fourier/vtkImageFourierFilter.h @@ -25,8 +25,6 @@ #include "vtkImagingFourierModule.h" // For export macro #include "vtkImageDecomposeFilter.h" - -//BTX /******************************************************************* COMPLEX number stuff *******************************************************************/ @@ -82,7 +80,6 @@ typedef struct{ } /******************* End of COMPLEX number stuff ********************/ -//ETX class VTKIMAGINGFOURIER_EXPORT vtkImageFourierFilter : public vtkImageDecomposeFilter { @@ -91,7 +88,6 @@ class VTKIMAGINGFOURIER_EXPORT vtkImageFourierFilter : public vtkImageDecomposeF // public for templated functions of this object - //BTX // Description: // This function calculates the whole fft of an array. @@ -106,20 +102,23 @@ class VTKIMAGINGFOURIER_EXPORT vtkImageFourierFilter : public vtkImageDecomposeF // (It is engineered for no decimation) void ExecuteRfft(vtkImageComplex *in, vtkImageComplex *out, int N); - //ETX - protected: vtkImageFourierFilter() {} ~vtkImageFourierFilter() {} - //BTX void ExecuteFftStep2(vtkImageComplex *p_in, vtkImageComplex *p_out, int N, int bsize, int fb); void ExecuteFftStepN(vtkImageComplex *p_in, vtkImageComplex *p_out, int N, int bsize, int n, int fb); void ExecuteFftForwardBackward(vtkImageComplex *in, vtkImageComplex *out, int N, int fb); - //ETX + + // Description: + // Override to change extent splitting rules. + int RequestData(vtkInformation* request, + vtkInformationVector** inputVector, + vtkInformationVector* outputVector); + private: vtkImageFourierFilter(const vtkImageFourierFilter&); // Not implemented. void operator=(const vtkImageFourierFilter&); // Not implemented. diff --git a/Imaging/Fourier/vtkImageRFFT.cxx b/Imaging/Fourier/vtkImageRFFT.cxx index 85a2ccdcdaa..46d24bbcfe7 100644 --- a/Imaging/Fourier/vtkImageRFFT.cxx +++ b/Imaging/Fourier/vtkImageRFFT.cxx @@ -221,90 +221,3 @@ void vtkImageRFFT::ThreadedRequestData( return; } } - - - -//---------------------------------------------------------------------------- -// For streaming and threads. Splits output update extent into num pieces. -// This method needs to be called num times. Results must not overlap for -// consistent starting extent. Subclass can override this method. -// This method returns the number of peices resulting from a successful split. -// This can be from 1 to "total". -// If 1 is returned, the extent cannot be split. -int vtkImageRFFT::SplitExtent(int splitExt[6], int startExt[6], - int num, int total) -{ - int splitAxis; - int min, max; - - vtkDebugMacro("SplitExtent: ( " << startExt[0] << ", " << startExt[1] << ", " - << startExt[2] << ", " << startExt[3] << ", " - << startExt[4] << ", " << startExt[5] << "), " - << num << " of " << total); - - // start with same extent - memcpy(splitExt, startExt, 6 * sizeof(int)); - - splitAxis = 2; - min = startExt[4]; - max = startExt[5]; - while ((splitAxis == this->Iteration) || (min == max)) - { - splitAxis--; - if (splitAxis < 0) - { // cannot split - vtkDebugMacro(" Cannot Split"); - return 1; - } - min = startExt[splitAxis*2]; - max = startExt[splitAxis*2+1]; - } - - // determine the actual number of pieces that will be generated - if ((max - min + 1) < total) - { - total = max - min + 1; - } - - if (num >= total) - { - vtkDebugMacro(" SplitRequest (" << num - << ") larger than total: " << total); - return total; - } - - // determine the extent of the piece - splitExt[splitAxis*2] = min + (max - min + 1)*num/total; - if (num == total - 1) - { - splitExt[splitAxis*2+1] = max; - } - else - { - splitExt[splitAxis*2+1] = (min-1) + (max - min + 1)*(num+1)/total; - } - - vtkDebugMacro(" Split Piece: ( " <UpdateProgress((double)col/numColumns); - vtkDataArray *array = vtkDataArray::SafeDownCast(input->GetColumn(col)); + vtkDataArray *array = vtkArrayDownCast(input->GetColumn(col)); if (!array) continue; if (array->GetNumberOfComponents() != 1) continue; if (array->GetName()) diff --git a/Imaging/Fourier/vtkTableFFT.h b/Imaging/Fourier/vtkTableFFT.h index 7fdfd03ca2f..7f3bb222884 100644 --- a/Imaging/Fourier/vtkTableFFT.h +++ b/Imaging/Fourier/vtkTableFFT.h @@ -55,11 +55,9 @@ class VTKIMAGINGFOURIER_EXPORT vtkTableFFT : public vtkTableAlgorithm vtkInformationVector **inputVector, vtkInformationVector *outputVector); -//BTX // Description: // Perform the FFT on the given data array. virtual vtkSmartPointer DoFFT(vtkDataArray *input); -//ETX private: vtkTableFFT(const vtkTableFFT &); // Not implemented diff --git a/Imaging/General/vtkImageConvolve.h b/Imaging/General/vtkImageConvolve.h index c5c76ef9b1a..4f833dce0e4 100644 --- a/Imaging/General/vtkImageConvolve.h +++ b/Imaging/General/vtkImageConvolve.h @@ -41,9 +41,8 @@ class VTKIMAGINGGENERAL_EXPORT vtkImageConvolve : public vtkThreadedImageAlgorit // Set the kernel to be a given 3x3 or 5x5 or 7x7 kernel. void SetKernel3x3(const double kernel[9]); void SetKernel5x5(const double kernel[25]); -//BTX + void SetKernel7x7(const double kernel[49]); -//ETX // Description: // Return an array that contains the kernel. @@ -51,29 +50,26 @@ class VTKIMAGINGGENERAL_EXPORT vtkImageConvolve : public vtkThreadedImageAlgorit void GetKernel3x3(double kernel[9]); double* GetKernel5x5(); void GetKernel5x5(double kernel[25]); -//BTX + double* GetKernel7x7(); void GetKernel7x7(double kernel[49]); -//ETX // Description: // Set the kernel to be a 3x3x3 or 5x5x5 or 7x7x7 kernel. void SetKernel3x3x3(const double kernel[27]); -//BTX + void SetKernel5x5x5(const double kernel[125]); void SetKernel7x7x7(const double kernel[343]); -//ETX // Description: // Return an array that contains the kernel double* GetKernel3x3x3(); void GetKernel3x3x3(double kernel[27]); -//BTX + double* GetKernel5x5x5(); void GetKernel5x5x5(double kernel[125]); double* GetKernel7x7x7(); void GetKernel7x7x7(double kernel[343]); -//ETX protected: vtkImageConvolve(); diff --git a/Imaging/General/vtkImageEuclideanDistance.cxx b/Imaging/General/vtkImageEuclideanDistance.cxx index e29422ec642..5f6b682ffc3 100644 --- a/Imaging/General/vtkImageEuclideanDistance.cxx +++ b/Imaging/General/vtkImageEuclideanDistance.cxx @@ -597,6 +597,16 @@ int vtkImageEuclideanDistance::IterativeRequestData( return 1; } + // ensure that iteration axis is not split during threaded execution + int iteration = this->GetIteration(); + this->SplitPathLength = 0; + for (int axis = 2; axis >= 0; --axis) + { + if (axis != iteration) + { + this->SplitPath[this->SplitPathLength++] = axis; + } + } // this filter expects that the output be doubles. if (outData->GetScalarType() != VTK_DOUBLE) @@ -661,74 +671,7 @@ int vtkImageEuclideanDistance::IterativeRequestData( return 1; } - //---------------------------------------------------------------------------- -// For streaming and threads. Splits output update extent into num pieces. -// This method needs to be called num times. Results must not overlap for -// consistent starting extent. Subclass can override this method. -// This method returns the number of peices resulting from a successful split. -// This can be from 1 to "total". -// If 1 is returned, the extent cannot be split. -int vtkImageEuclideanDistance::SplitExtent(int splitExt[6], int startExt[6], - int num, int total) -{ - int splitAxis; - int min, max; - - vtkDebugMacro("SplitExtent: ( " << startExt[0] << ", " << startExt[1] << ", " - << startExt[2] << ", " << startExt[3] << ", " - << startExt[4] << ", " << startExt[5] << "), " - << num << " of " << total); - - // start with same extent - memcpy(splitExt, startExt, 6 * sizeof(int)); - - splitAxis = 2; - min = startExt[4]; - max = startExt[5]; - while ((splitAxis == this->Iteration) || (min == max)) - { - splitAxis--; - if (splitAxis < 0) - { // cannot split - vtkDebugMacro(" Cannot Split"); - return 1; - } - min = startExt[splitAxis*2]; - max = startExt[splitAxis*2+1]; - } - - // determine the actual number of pieces that will be generated - if ((max - min + 1) < total) - { - total = max - min + 1; - } - - if (num >= total) - { - vtkDebugMacro(" SplitRequest (" << num - << ") larger than total: " << total); - return total; - } - - // determine the extent of the piece - splitExt[splitAxis*2] = min + (max - min + 1)*num/total; - if (num == total - 1) - { - splitExt[splitAxis*2+1] = max; - } - else - { - splitExt[splitAxis*2+1] = (min-1) + (max - min + 1)*(num+1)/total; - } - - vtkDebugMacro(" Split Piece: ( " <Superclass::PrintSelf(os,indent); @@ -752,20 +695,3 @@ void vtkImageEuclideanDistance::PrintSelf(ostream& os, vtkIndent indent) os << "Saito Cached\n"; } } - - - - - - - - - - - - - - - - - diff --git a/Imaging/General/vtkImageEuclideanDistance.h b/Imaging/General/vtkImageEuclideanDistance.h index e742eda8908..156e8ac7588 100644 --- a/Imaging/General/vtkImageEuclideanDistance.h +++ b/Imaging/General/vtkImageEuclideanDistance.h @@ -56,17 +56,6 @@ class VTKIMAGINGGENERAL_EXPORT vtkImageEuclideanDistance : public vtkImageDecomp vtkTypeMacro(vtkImageEuclideanDistance,vtkImageDecomposeFilter); void PrintSelf(ostream& os, vtkIndent indent); - // Description: - // Used internally for streaming and threads. - // Splits output update extent into num pieces. - // This method needs to be called num times. Results must not overlap for - // consistent starting extent. Subclass can override this method. - // This method returns the number of peices resulting from a - // successful split. This can be from 1 to "total". - // If 1 is returned, the extent cannot be split. - int SplitExtent(int splitExt[6], int startExt[6], - int num, int total); - // Description: // Used to set all non-zero voxels to MaximumDistance before starting // the distance transformation. Setting Initialize off keeps the current diff --git a/Imaging/Hybrid/vtkBooleanTexture.cxx b/Imaging/Hybrid/vtkBooleanTexture.cxx index 520f04d86be..f9aeb8f90a5 100644 --- a/Imaging/Hybrid/vtkBooleanTexture.cxx +++ b/Imaging/Hybrid/vtkBooleanTexture.cxx @@ -72,7 +72,7 @@ void vtkBooleanTexture::ExecuteDataWithInformation(vtkDataObject *outp, vtkImageData *output = this->AllocateOutputData( outp, outInfo); vtkUnsignedCharArray *newScalars = - vtkUnsignedCharArray::SafeDownCast(output->GetPointData()->GetScalars()); + vtkArrayDownCast(output->GetPointData()->GetScalars()); if (!newScalars || this->XSize*this->YSize < 1 ) { diff --git a/Imaging/Hybrid/vtkFastSplatter.h b/Imaging/Hybrid/vtkFastSplatter.h index 7180659579f..ff807179fda 100644 --- a/Imaging/Hybrid/vtkFastSplatter.h +++ b/Imaging/Hybrid/vtkFastSplatter.h @@ -65,9 +65,7 @@ class VTKIMAGINGHYBRID_EXPORT vtkFastSplatter : public vtkImageAlgorithm vtkSetVector3Macro( OutputDimensions, int ); vtkGetVector3Macro( OutputDimensions, int ); -//BTX enum { NoneLimit, ClampLimit, ScaleLimit, FreezeScaleLimit }; -//ETX // Description: // Set/get the way voxel values will be limited. If this is set to None (the @@ -143,8 +141,6 @@ class VTKIMAGINGHYBRID_EXPORT vtkFastSplatter : public vtkImageAlgorithm void operator=(const vtkFastSplatter &); // Not implemented }; -//BTX - //----------------------------------------------------------------------------- template @@ -259,6 +255,4 @@ void vtkFastSplatterFrozenScale(T *array, } } -//ETX - #endif //vtkFastSplatter_h diff --git a/Imaging/Hybrid/vtkGaussianSplatter.cxx b/Imaging/Hybrid/vtkGaussianSplatter.cxx index 52900c4b1cd..55984209a52 100644 --- a/Imaging/Hybrid/vtkGaussianSplatter.cxx +++ b/Imaging/Hybrid/vtkGaussianSplatter.cxx @@ -184,7 +184,7 @@ int vtkGaussianSplatter::RequestData( vtkDataArray *inNormals=NULL; double loc[3]; vtkDoubleArray *newScalars = - vtkDoubleArray::SafeDownCast(output->GetPointData()->GetScalars()); + vtkArrayDownCast(output->GetPointData()->GetScalars()); newScalars->SetName("SplatterValues"); vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); diff --git a/Imaging/Hybrid/vtkGaussianSplatter.h b/Imaging/Hybrid/vtkGaussianSplatter.h index 1cc7dc96daa..82d66c210b0 100644 --- a/Imaging/Hybrid/vtkGaussianSplatter.h +++ b/Imaging/Hybrid/vtkGaussianSplatter.h @@ -194,7 +194,6 @@ class VTKIMAGINGHYBRID_EXPORT vtkGaussianSplatter : public vtkImageAlgorithm void ComputeModelBounds(vtkCompositeDataSet *input, vtkImageData *output, vtkInformation *outInfo); -//BTX // Description: // Provide access to templated helper class. Note that SamplePoint() method // is public here because some compilers don't handle friend functions @@ -234,7 +233,6 @@ class VTKIMAGINGHYBRID_EXPORT vtkGaussianSplatter : public vtkImageAlgorithm } }//not first visit } -//ETX protected: vtkGaussianSplatter(); @@ -268,7 +266,6 @@ class VTKIMAGINGHYBRID_EXPORT vtkGaussianSplatter : public vtkImageAlgorithm double PositionSampling(double) {return this->ScaleFactor;} -//BTX private: double Radius2; double (vtkGaussianSplatter::*Sample)(double x[3]); @@ -282,7 +279,6 @@ class VTKIMAGINGHYBRID_EXPORT vtkGaussianSplatter : public vtkImageAlgorithm double Spacing[3]; double SplatDistance[3]; double NullValue; -//ETX private: vtkGaussianSplatter(const vtkGaussianSplatter&); // Not implemented. diff --git a/Imaging/Hybrid/vtkPointLoad.cxx b/Imaging/Hybrid/vtkPointLoad.cxx index 7d8848d908e..c249854a146 100644 --- a/Imaging/Hybrid/vtkPointLoad.cxx +++ b/Imaging/Hybrid/vtkPointLoad.cxx @@ -132,7 +132,7 @@ void vtkPointLoad::ExecuteDataWithInformation(vtkDataObject *outp, vtkInformatio double sx, sy, sz, seff; vtkImageData *output = this->AllocateOutputData(outp, outInfo); vtkFloatArray *newScalars = - vtkFloatArray::SafeDownCast(output->GetPointData()->GetScalars()); + vtkArrayDownCast(output->GetPointData()->GetScalars()); double *spacing, *origin; vtkDebugMacro(<< "Computing point load stress tensors"); diff --git a/Imaging/Hybrid/vtkSampleFunction.cxx b/Imaging/Hybrid/vtkSampleFunction.cxx index 48b98c4fe58..bbff733d6ca 100644 --- a/Imaging/Hybrid/vtkSampleFunction.cxx +++ b/Imaging/Hybrid/vtkSampleFunction.cxx @@ -113,6 +113,7 @@ class vtkSampleFunctionAlgorithm { x[0] = this->Algo->Origin[0] + i*this->Algo->Spacing[0]; this->Algo->ImplicitFunction->FunctionGradient(x,n); + vtkMath::Normalize(n); nPtr = this->Algo->Normals + 3*((i-extent[0])+jOffset+kOffset); nPtr[0] = static_cast(-n[0]); nPtr[1] = static_cast(-n[1]); diff --git a/Imaging/Hybrid/vtkSampleFunction.h b/Imaging/Hybrid/vtkSampleFunction.h index c4402543d64..0c0d2cb18c1 100644 --- a/Imaging/Hybrid/vtkSampleFunction.h +++ b/Imaging/Hybrid/vtkSampleFunction.h @@ -138,7 +138,7 @@ class VTKIMAGINGHYBRID_EXPORT vtkSampleFunction : public vtkImageAlgorithm ~vtkSampleFunction(); - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; void ExecuteDataWithInformation(vtkDataObject *, vtkInformation *); virtual int RequestInformation (vtkInformation *, diff --git a/Imaging/Hybrid/vtkShepardMethod.cxx b/Imaging/Hybrid/vtkShepardMethod.cxx index 31fdf99572b..305eafe620e 100644 --- a/Imaging/Hybrid/vtkShepardMethod.cxx +++ b/Imaging/Hybrid/vtkShepardMethod.cxx @@ -337,7 +337,7 @@ int vtkShepardMethod::RequestData( vtkIdType numPts, numNewPts; vtkIdType min[3], max[3]; vtkFloatArray *newScalars = - vtkFloatArray::SafeDownCast(output->GetPointData()->GetScalars()); + vtkArrayDownCast(output->GetPointData()->GetScalars()); vtkDebugMacro(<< "Executing Shepard method"); diff --git a/Imaging/Hybrid/vtkSurfaceReconstructionFilter.cxx b/Imaging/Hybrid/vtkSurfaceReconstructionFilter.cxx index c588280e347..a3b4e5d27f6 100644 --- a/Imaging/Hybrid/vtkSurfaceReconstructionFilter.cxx +++ b/Imaging/Hybrid/vtkSurfaceReconstructionFilter.cxx @@ -437,7 +437,7 @@ int vtkSurfaceReconstructionFilter::RequestData( 0, dim[0]-1, 0, dim[1]-1, 0, dim[2]-1); vtkFloatArray *newScalars = - vtkFloatArray::SafeDownCast(output->GetPointData()->GetScalars()); + vtkArrayDownCast(output->GetPointData()->GetScalars()); outInfo->Set(vtkDataObject::SPACING(), this->SampleSpacing, this->SampleSpacing, this->SampleSpacing); outInfo->Set(vtkDataObject::ORIGIN(),topleft,3); diff --git a/Imaging/Hybrid/vtkTriangularTexture.cxx b/Imaging/Hybrid/vtkTriangularTexture.cxx index 801f94ca4a5..ae46e12e3de 100644 --- a/Imaging/Hybrid/vtkTriangularTexture.cxx +++ b/Imaging/Hybrid/vtkTriangularTexture.cxx @@ -164,7 +164,7 @@ void vtkTriangularTexture::ExecuteDataWithInformation(vtkDataObject *outp, { vtkImageData *output = this->AllocateOutputData(outp, outInfo); vtkUnsignedCharArray *newScalars = - vtkUnsignedCharArray::SafeDownCast(output->GetPointData()->GetScalars()); + vtkArrayDownCast(output->GetPointData()->GetScalars()); if (this->XSize*this->YSize < 1) { diff --git a/Imaging/Morphological/vtkImageConnector.h b/Imaging/Morphological/vtkImageConnector.h index 7dcef47f68f..f6429660c0f 100644 --- a/Imaging/Morphological/vtkImageConnector.h +++ b/Imaging/Morphological/vtkImageConnector.h @@ -35,8 +35,6 @@ class vtkImageData; // // Special classes for manipulating data // -//BTX - begin tcl exclude -// // For the breadth first search class vtkImageConnectorSeed { //;prevent man page generation public: @@ -45,8 +43,6 @@ class vtkImageConnectorSeed { //;prevent man page generation int Index[3]; vtkImageConnectorSeed *Next; }; -//ETX - end tcl exclude -// class VTKIMAGINGMORPHOLOGICAL_EXPORT vtkImageConnector : public vtkObject @@ -57,11 +53,10 @@ class VTKIMAGINGMORPHOLOGICAL_EXPORT vtkImageConnector : public vtkObject vtkTypeMacro(vtkImageConnector,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); - //BTX vtkImageConnectorSeed *NewSeed(int index[3], void *ptr); void AddSeed(vtkImageConnectorSeed *seed); void AddSeedToEnd(vtkImageConnectorSeed *seed); - //ETX + void RemoveAllSeeds(); // Description: diff --git a/Imaging/Morphological/vtkImageIslandRemoval2D.h b/Imaging/Morphological/vtkImageIslandRemoval2D.h index 323cca4c6cf..80776f1d0a9 100644 --- a/Imaging/Morphological/vtkImageIslandRemoval2D.h +++ b/Imaging/Morphological/vtkImageIslandRemoval2D.h @@ -27,14 +27,12 @@ #include "vtkImagingMorphologicalModule.h" // For export macro #include "vtkImageAlgorithm.h" -//BTX typedef struct{ void *inPtr; void *outPtr; int idx0; int idx1; } vtkImage2DIslandPixel; -//ETX class VTKIMAGINGMORPHOLOGICAL_EXPORT vtkImageIslandRemoval2D : public vtkImageAlgorithm { diff --git a/Imaging/Morphological/vtkImageOpenClose3D.h b/Imaging/Morphological/vtkImageOpenClose3D.h index a5fe94bb960..bb1284781b4 100644 --- a/Imaging/Morphological/vtkImageOpenClose3D.h +++ b/Imaging/Morphological/vtkImageOpenClose3D.h @@ -105,7 +105,7 @@ class VTKIMAGINGMORPHOLOGICAL_EXPORT vtkImageOpenClose3D : public vtkImageAlgori vtkImageDilateErode3D *Filter0; vtkImageDilateErode3D *Filter1; - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; private: vtkImageOpenClose3D(const vtkImageOpenClose3D&); // Not implemented. void operator=(const vtkImageOpenClose3D&); // Not implemented. diff --git a/Imaging/Morphological/vtkImageThresholdConnectivity.cxx b/Imaging/Morphological/vtkImageThresholdConnectivity.cxx index 25b6c9d0395..55a731433bc 100644 --- a/Imaging/Morphological/vtkImageThresholdConnectivity.cxx +++ b/Imaging/Morphological/vtkImageThresholdConnectivity.cxx @@ -199,7 +199,7 @@ class vtkFloodFillSeed vtkFloodFillSeed(const vtkFloodFillSeed &seed) { store[0]=seed.store[0]; store[1]=seed.store[1]; store[2]=seed.store[2]; }; const int &operator[](int i) const { return store[i]; }; - const vtkFloodFillSeed &operator=(const vtkFloodFillSeed &seed) { + vtkFloodFillSeed &operator=(const vtkFloodFillSeed &seed) { store[0]=seed.store[0]; store[1]=seed.store[1]; store[2]=seed.store[2]; return *this; }; diff --git a/Imaging/Statistics/vtkImageHistogram.cxx b/Imaging/Statistics/vtkImageHistogram.cxx index 00f31111c3a..38b8d23b47a 100644 --- a/Imaging/Statistics/vtkImageHistogram.cxx +++ b/Imaging/Statistics/vtkImageHistogram.cxx @@ -25,6 +25,7 @@ #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkMultiThreader.h" #include "vtkTemplateAliasMacro.h" +#include "vtkSMPTools.h" #include @@ -36,6 +37,25 @@ vtkStandardNewMacro(vtkImageHistogram); +//---------------------------------------------------------------------------- +// Data needed for each thread. +class vtkImageHistogramThreadData +{ +public: + vtkImageHistogramThreadData() : Data(0) {} + + vtkIdType *Data; + int Range[2]; +}; + +// Holds thread-local data for SMP implementation. +class vtkImageHistogramSMPThreadLocal + : public vtkSMPThreadLocal +{ +public: + typedef vtkSMPThreadLocal::iterator iterator; +}; + //---------------------------------------------------------------------------- // Constructor sets default values vtkImageHistogram::vtkImageHistogram() @@ -55,6 +75,9 @@ vtkImageHistogram::vtkImageHistogram() this->Histogram = vtkIdTypeArray::New(); this->Total = 0; + this->ThreadData = 0; + this->SMPThreadData = 0; + this->SetNumberOfInputPorts(2); this->SetNumberOfOutputPorts(1); } @@ -572,6 +595,89 @@ void vtkImageHistogramGenerateImage( } // end anonymous namespace +// Functor for vtkSMPTools execution +class vtkImageHistogramFunctor +{ +public: + // Create the functor, provide all info it needs to execute. + vtkImageHistogramFunctor( + vtkImageHistogramThreadStruct *pipelineInfo, + vtkImageHistogramSMPThreadLocal *threadLocal, + const int extent[6], + vtkIdType pieces, + vtkIdTypeArray *histogram, + vtkIdType *total) + : PipelineInfo(pipelineInfo), ThreadLocal(threadLocal), + NumberOfPieces(pieces), Histogram(histogram), Total(total) + { + for (int i = 0; i < 6; i++) + { + this->Extent[i] = extent[i]; + } + } + + void Initialize() {} + void operator()(vtkIdType begin, vtkIdType end); + void Reduce(); + +private: + vtkImageHistogramThreadStruct *PipelineInfo; + vtkImageHistogramSMPThreadLocal *ThreadLocal; + int Extent[6]; + vtkIdType NumberOfPieces; + vtkIdTypeArray *Histogram; + vtkIdType *Total; +}; + +// Called by vtkSMPTools to execute the algorithm over specific pieces. +void vtkImageHistogramFunctor::operator()(vtkIdType begin, vtkIdType end) +{ + vtkImageHistogramThreadStruct *ts = this->PipelineInfo; + + ts->Algorithm->SMPRequestData( + ts->Request, ts->InputsInfo, ts->OutputsInfo, NULL, NULL, + begin, end, this->NumberOfPieces, this->Extent); +} + +// Called by vtkSMPTools once the multi-threading has finished. +void vtkImageHistogramFunctor::Reduce() +{ + vtkIdType *histogram = this->Histogram->GetPointer(0); + vtkIdType total = 0; + + int numberOfBins = static_cast( + this->PipelineInfo->Algorithm)->GetNumberOfBins(); + + // clear histogram to zero + for (int i = 0; i < numberOfBins; i++) + { + histogram[i] = 0; + } + + // sum the histograms created by each thread + for (vtkImageHistogramSMPThreadLocal::iterator + iter = this->ThreadLocal->begin(); + iter != this->ThreadLocal->end(); + ++iter) + { + vtkIdType *data = iter->Data; + if (data) + { + int minbin = iter->Range[0]; + int maxbin = iter->Range[1]; + for (int j = minbin; j <= maxbin; j++) + { + vtkIdType f = data[j]; + histogram[j] += f; + total += f; + } + delete [] data; + } + } + + (*this->Total) = total; +} + //---------------------------------------------------------------------------- // override from vtkThreadedImageAlgorithm to customize the multithreading int vtkImageHistogram::RequestData( @@ -579,13 +685,6 @@ int vtkImageHistogram::RequestData( vtkInformationVector** inputVector, vtkInformationVector* outputVector) { - // clear the thread output pointers - int n = this->GetNumberOfThreads(); - for (int k = 0; k < n; k++) - { - this->ThreadOutput[k] = 0; - } - vtkInformation* info = inputVector[0]->GetInformationObject(0); vtkImageData *image = vtkImageData::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); @@ -657,8 +756,6 @@ int vtkImageHistogram::RequestData( } } - // start of code copied from vtkThreadedImageAlgorithm - // setup the threads structure vtkImageHistogramThreadStruct ts; ts.Algorithm = this; @@ -667,52 +764,7 @@ int vtkImageHistogram::RequestData( ts.OutputsInfo = outputVector; // allocate the output data - int numberOfOutputs = this->GetNumberOfOutputPorts(); - if (numberOfOutputs > 0) - { - for (int i = 0; i < numberOfOutputs; ++i) - { - vtkInformation* outInfo = outputVector->GetInformationObject(i); - vtkImageData *outData = vtkImageData::SafeDownCast( - outInfo->Get(vtkDataObject::DATA_OBJECT())); - if (outData) - { - int updateExtent[6]; - outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(), - updateExtent); - this->AllocateOutputData(outData, outInfo, updateExtent); - } - } - } - - // copy arrays from first input to output - int numberOfInputs = this->GetNumberOfInputPorts(); - if (numberOfInputs > 0) - { - vtkInformationVector* portInfo = inputVector[0]; - int numberOfConnections = portInfo->GetNumberOfInformationObjects(); - if (numberOfConnections && numberOfOutputs) - { - vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); - vtkImageData *inData = vtkImageData::SafeDownCast( - inInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkInformation* outInfo = outputVector->GetInformationObject(0); - vtkImageData *outData = vtkImageData::SafeDownCast( - outInfo->Get(vtkDataObject::DATA_OBJECT())); - this->CopyAttributeData(inData, outData, inputVector); - } - } - - this->Threader->SetNumberOfThreads(this->NumberOfThreads); - this->Threader->SetSingleMethod(vtkImageHistogramThreadedExecute, &ts); - - // always shut off debugging to avoid threading problems with GetMacros - bool debug = this->Debug; - this->Debug = false; - this->Threader->SingleMethodExecute(); - this->Debug = debug; - - // end of code copied from vtkThreadedImageAlgorithm + this->PrepareImageData(inputVector, outputVector); // create the histogram array this->Histogram->SetNumberOfComponents(1); @@ -727,31 +779,70 @@ int vtkImageHistogram::RequestData( histogram[ix] = 0; } - // piece together the histogram results from each thread - vtkIdType total = 0; - for (int j = 0; j < n; j++) + if (this->EnableSMP) { - vtkIdType *outPtr2 = this->ThreadOutput[j]; - if (outPtr2) + // code for vtkSMPTools + vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); + vtkImageData *inData = vtkImageData::SafeDownCast( + inInfo->Get(vtkDataObject::DATA_OBJECT())); + int extent[6]; + inData->GetExtent(extent); + + // do a dummy execution of SplitExtent to compute the number of pieces + vtkIdType pieces = this->SplitExtent(0, extent, 0, this->NumberOfThreads); + + // create the thread-local object and the functor + vtkImageHistogramSMPThreadLocal tlocal; + vtkImageHistogramFunctor functor(&ts, &tlocal, extent, pieces, + this->Histogram, &this->Total); + this->SMPThreadData = &tlocal; + bool debug = this->Debug; + this->Debug = false; + vtkSMPTools::For(0, pieces, functor); + this->Debug = debug; + this->SMPThreadData = 0; + } + else + { + // code for vtkMultiThreader + int n = this->NumberOfThreads; + this->ThreadData = new vtkImageHistogramThreadData[n]; + this->Threader->SetNumberOfThreads(n); + this->Threader->SetSingleMethod(vtkImageHistogramThreadedExecute, &ts); + + // always shut off debugging to avoid threading problems with GetMacros + bool debug = this->Debug; + this->Debug = false; + this->Threader->SingleMethodExecute(); + this->Debug = debug; + + // piece together the histogram results from each thread + vtkIdType total = 0; + for (int j = 0; j < n; j++) { - int xmin = this->ThreadBinRange[j][0]; - int xmax = this->ThreadBinRange[j][1]; - for (ix = xmin; ix <= xmax; ++ix) + vtkIdType *outPtr2 = this->ThreadData[j].Data; + if (outPtr2) { - vtkIdType c = *outPtr2++; - histogram[ix] += c; - total += c; + int xmin = this->ThreadData[j].Range[0]; + int xmax = this->ThreadData[j].Range[1]; + for (ix = xmin; ix <= xmax; ++ix) + { + vtkIdType c = *outPtr2++; + histogram[ix] += c; + total += c; + } } } - } - // set the total - this->Total = total; + // set the total + this->Total = total; - // delete the temporary memory - for (int j = 0; j < n; j++) - { - delete [] this->ThreadOutput[j]; + // delete the temporary memory + for (int j = 0; j < n; j++) + { + delete [] this->ThreadData[j].Data; + } + delete [] this->ThreadData; } // generate the output image @@ -801,7 +892,6 @@ void vtkImageHistogram::ThreadedRequestData( scalarType != VTK_FLOAT && scalarType != VTK_DOUBLE); double scalarRange[2]; - int *binRange = this->ThreadBinRange[threadId]; // compute the scalar range of the data unless it is byte data, // this allows us to allocate less memory for the histogram @@ -844,21 +934,74 @@ void vtkImageHistogram::ThreadedRequestData( maxBinRange = maxBin; useFastExecute = false; } - binRange[0] = vtkMath::Floor(minBinRange + 0.5); - binRange[1] = vtkMath::Floor(maxBinRange + 0.5); - // allocate the histogram - int n = binRange[1] - binRange[0] + 1; - vtkIdType *histogram = new vtkIdType[n]; - this->ThreadOutput[threadId] = histogram; - vtkIdType *tmpPtr = histogram; - do { *tmpPtr++ = 0; } while (--n); + vtkIdType *histogram; + int *binRange; + + if (this->EnableSMP) + { + // code for vtkSMPTools + vtkImageHistogramThreadData *threadLocal = &this->SMPThreadData->Local(); + binRange = threadLocal->Range; + + int a = vtkMath::Floor(minBinRange + 0.5); + int b = vtkMath::Floor(maxBinRange + 0.5); + if (threadLocal->Data == 0) + { + // allocate the histogram + histogram = new vtkIdType[this->NumberOfBins]; + for (int i = a; i <= b; i++) + { + histogram[i] = 0; + } + threadLocal->Data = histogram; + binRange[0] = a; + binRange[1] = b; + } + else + { + // expand the range, if necessary + histogram = threadLocal->Data; + if (a < binRange[0]) + { + for (int i = a; i < binRange[0]; i++) + { + histogram[i] = 0; + } + binRange[0] = a; + } + if (b > binRange[1]) + { + for (int i = binRange[1] + 1; i <= b; i++) + { + histogram[i] = 0; + } + binRange[1] = b; + } + } + } + else + { + // code for vtkMultiThreader + vtkImageHistogramThreadData *threadLocal = &this->ThreadData[threadId]; + binRange = threadLocal->Range; + binRange[0] = vtkMath::Floor(minBinRange + 0.5); + binRange[1] = vtkMath::Floor(maxBinRange + 0.5); + // allocate the histogram + int n = binRange[1] - binRange[0] + 1; + histogram = new vtkIdType[n]; + threadLocal->Data = histogram; + vtkIdType *tmpPtr = histogram; + do { *tmpPtr++ = 0; } while (--n); + // adjust the pointer to allow direct indexing + histogram -= binRange[0]; + } // generate the histogram if (useFastExecute) { // adjust the pointer to allow direct indexing - histogram -= binRange[0] + vtkMath::Floor(binOrigin + 0.5); + histogram -= vtkMath::Floor(binOrigin + 0.5); // fast path for integer data switch(scalarType) @@ -873,9 +1016,6 @@ void vtkImageHistogram::ThreadedRequestData( } else { - // adjust the pointer to allow direct indexing - histogram -= binRange[0]; - // bin via floating point shift/scale switch (scalarType) { diff --git a/Imaging/Statistics/vtkImageHistogram.h b/Imaging/Statistics/vtkImageHistogram.h index 6675e40068f..cfd453896f7 100644 --- a/Imaging/Statistics/vtkImageHistogram.h +++ b/Imaging/Statistics/vtkImageHistogram.h @@ -33,6 +33,8 @@ class vtkImageStencilData; class vtkIdTypeArray; +class vtkImageHistogramThreadData; +class vtkImageHistogramSMPThreadLocal; class VTKIMAGINGSTATISTICS_EXPORT vtkImageHistogram : public vtkThreadedImageAlgorithm { @@ -192,12 +194,17 @@ class VTKIMAGINGSTATISTICS_EXPORT vtkImageHistogram : public vtkThreadedImageAlg vtkIdTypeArray *Histogram; vtkIdType Total; - vtkIdType *ThreadOutput[VTK_MAX_THREADS]; - int ThreadBinRange[VTK_MAX_THREADS][2]; + // Used for vtkMultiThreader operation. + vtkImageHistogramThreadData *ThreadData; + + // Used for vtkSMPTools operation. + vtkImageHistogramSMPThreadLocal *SMPThreadData; private: vtkImageHistogram(const vtkImageHistogram&); // Not implemented. void operator=(const vtkImageHistogram&); // Not implemented. + + friend class vtkImageHistogramFunctor; }; #endif diff --git a/Imaging/Stencil/vtkLassoStencilSource.h b/Imaging/Stencil/vtkLassoStencilSource.h index 72f7c4cb3a1..c6c21ca3dfc 100644 --- a/Imaging/Stencil/vtkLassoStencilSource.h +++ b/Imaging/Stencil/vtkLassoStencilSource.h @@ -41,12 +41,10 @@ class VTKIMAGINGSTENCIL_EXPORT vtkLassoStencilSource : public vtkImageStencilSou vtkTypeMacro(vtkLassoStencilSource, vtkImageStencilSource); void PrintSelf(ostream& os, vtkIndent indent); -//BTX enum { POLYGON = 0, SPLINE = 1 }; -//ETX // Description: // The shape to use, default is "Polygon". The spline is a diff --git a/Imaging/Stencil/vtkROIStencilSource.h b/Imaging/Stencil/vtkROIStencilSource.h index 715fe5357a6..a7b71b21943 100644 --- a/Imaging/Stencil/vtkROIStencilSource.h +++ b/Imaging/Stencil/vtkROIStencilSource.h @@ -37,7 +37,6 @@ class VTKIMAGINGSTENCIL_EXPORT vtkROIStencilSource : public vtkImageStencilSourc vtkTypeMacro(vtkROIStencilSource, vtkImageStencilSource); void PrintSelf(ostream& os, vtkIndent indent); -//BTX enum { BOX = 0, ELLIPSOID = 1, @@ -45,7 +44,6 @@ class VTKIMAGINGSTENCIL_EXPORT vtkROIStencilSource : public vtkImageStencilSourc CYLINDERY = 3, CYLINDERZ = 4 }; -//ETX // Description: // The shape of the region of interest. Cylinders can be oriented diff --git a/Infovis/BoostGraphAlgorithms/Testing/Cxx/TestBoostBetweennessClustering.cxx b/Infovis/BoostGraphAlgorithms/Testing/Cxx/TestBoostBetweennessClustering.cxx index 1066b5b80be..e1c6d2436ce 100644 --- a/Infovis/BoostGraphAlgorithms/Testing/Cxx/TestBoostBetweennessClustering.cxx +++ b/Infovis/BoostGraphAlgorithms/Testing/Cxx/TestBoostBetweennessClustering.cxx @@ -113,7 +113,7 @@ int TestBoostBetweennessClustering(int vtkNotUsed(argc), return 1; } - vtkIntArray* compArray = vtkIntArray::SafeDownCast(og->GetVertexData()-> + vtkIntArray* compArray = vtkArrayDownCast(og->GetVertexData()-> GetArray("component")); if(!compArray) { diff --git a/Infovis/BoostGraphAlgorithms/Testing/Cxx/TestBoostDividedEdgeBundling.cxx b/Infovis/BoostGraphAlgorithms/Testing/Cxx/TestBoostDividedEdgeBundling.cxx index f6cb013484c..306ceff4c1b 100644 --- a/Infovis/BoostGraphAlgorithms/Testing/Cxx/TestBoostDividedEdgeBundling.cxx +++ b/Infovis/BoostGraphAlgorithms/Testing/Cxx/TestBoostDividedEdgeBundling.cxx @@ -83,13 +83,13 @@ void BuildGraphMLGraph(vtkMutableDirectedGraph* graph, std::string file) reader->ReadCharDataOn(); reader->Update(); vtkTree *tree = reader->GetOutput(); - vtkStringArray *keyArr = vtkStringArray::SafeDownCast( + vtkStringArray *keyArr = vtkArrayDownCast( tree->GetVertexData()->GetAbstractArray("key")); - vtkStringArray *sourceArr = vtkStringArray::SafeDownCast( + vtkStringArray *sourceArr = vtkArrayDownCast( tree->GetVertexData()->GetAbstractArray("source")); - vtkStringArray *targetArr = vtkStringArray::SafeDownCast( + vtkStringArray *targetArr = vtkArrayDownCast( tree->GetVertexData()->GetAbstractArray("target")); - vtkStringArray *contentArr = vtkStringArray::SafeDownCast( + vtkStringArray *contentArr = vtkArrayDownCast( tree->GetVertexData()->GetAbstractArray(".chardata")); double x = 0.0; double y = 0.0; diff --git a/Infovis/BoostGraphAlgorithms/vtkBoostBreadthFirstSearch.cxx b/Infovis/BoostGraphAlgorithms/vtkBoostBreadthFirstSearch.cxx index bd76b7c5a52..f1ea0ce0284 100644 --- a/Infovis/BoostGraphAlgorithms/vtkBoostBreadthFirstSearch.cxx +++ b/Infovis/BoostGraphAlgorithms/vtkBoostBreadthFirstSearch.cxx @@ -153,7 +153,7 @@ vtkIdType vtkBoostBreadthFirstSearch::GetVertexIndex( // Okay now what type of array is it if (abstract->IsNumeric()) { - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstract); + vtkDataArray *dataArray = vtkArrayDownCast(abstract); int intValue = value.ToInt(); for(int i=0; iGetNumberOfTuples(); ++i) { @@ -165,7 +165,7 @@ vtkIdType vtkBoostBreadthFirstSearch::GetVertexIndex( } else { - vtkStringArray *stringArray = vtkStringArray::SafeDownCast(abstract); + vtkStringArray *stringArray = vtkArrayDownCast(abstract); vtkStdString stringValue(value.ToString()); for(int i=0; iGetNumberOfTuples(); ++i) { diff --git a/Infovis/BoostGraphAlgorithms/vtkBoostBreadthFirstSearchTree.cxx b/Infovis/BoostGraphAlgorithms/vtkBoostBreadthFirstSearchTree.cxx index d94668be3a9..8b18ae16725 100644 --- a/Infovis/BoostGraphAlgorithms/vtkBoostBreadthFirstSearchTree.cxx +++ b/Infovis/BoostGraphAlgorithms/vtkBoostBreadthFirstSearchTree.cxx @@ -177,7 +177,7 @@ vtkIdType vtkBoostBreadthFirstSearchTree::GetVertexIndex( // Okay now what type of array is it if (abstract->IsNumeric()) { - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstract); + vtkDataArray *dataArray = vtkArrayDownCast(abstract); int intValue = value.ToInt(); for(int i=0; iGetNumberOfTuples(); ++i) { @@ -189,7 +189,7 @@ vtkIdType vtkBoostBreadthFirstSearchTree::GetVertexIndex( } else { - vtkStringArray *stringArray = vtkStringArray::SafeDownCast(abstract); + vtkStringArray *stringArray = vtkArrayDownCast(abstract); vtkStdString stringValue(value.ToString()); for(int i=0; iGetNumberOfTuples(); ++i) { diff --git a/Infovis/BoostGraphAlgorithms/vtkBoostDividedEdgeBundling.cxx b/Infovis/BoostGraphAlgorithms/vtkBoostDividedEdgeBundling.cxx index 1e1ddc23903..35ae8382ab1 100644 --- a/Infovis/BoostGraphAlgorithms/vtkBoostDividedEdgeBundling.cxx +++ b/Infovis/BoostGraphAlgorithms/vtkBoostDividedEdgeBundling.cxx @@ -48,7 +48,7 @@ class vtkBundlingMetadata : Outer(alg), Graph(g) { this->Nodes = reinterpret_cast( - vtkFloatArray::SafeDownCast(g->GetPoints()->GetData())->GetPointer(0)); + vtkArrayDownCast(g->GetPoints()->GetData())->GetPointer(0)); this->Edges.resize(g->GetNumberOfEdges()); for (vtkIdType e = 0; e < g->GetNumberOfEdges(); ++e) { diff --git a/Infovis/BoostGraphAlgorithms/vtkBoostExtractLargestComponent.cxx b/Infovis/BoostGraphAlgorithms/vtkBoostExtractLargestComponent.cxx index db05b741b13..a8e526e02d3 100644 --- a/Infovis/BoostGraphAlgorithms/vtkBoostExtractLargestComponent.cxx +++ b/Infovis/BoostGraphAlgorithms/vtkBoostExtractLargestComponent.cxx @@ -71,7 +71,7 @@ int vtkBoostExtractLargestComponent::RequestData(vtkInformation *vtkNotUsed(requ connectedComponents->SetInputData(inputCopy); connectedComponents->Update(); - vtkIntArray* components = vtkIntArray::SafeDownCast( + vtkIntArray* components = vtkArrayDownCast( connectedComponents->GetOutput()->GetVertexData()->GetArray("component")); // Create an array to store the count of the number of vertices diff --git a/Infovis/BoostGraphAlgorithms/vtkBoostLogWeighting.h b/Infovis/BoostGraphAlgorithms/vtkBoostLogWeighting.h index 6f6943b278a..b08ba23852d 100644 --- a/Infovis/BoostGraphAlgorithms/vtkBoostLogWeighting.h +++ b/Infovis/BoostGraphAlgorithms/vtkBoostLogWeighting.h @@ -41,13 +41,11 @@ class VTKINFOVISBOOSTGRAPHALGORITHMS_EXPORT vtkBoostLogWeighting : public vtkArr vtkTypeMacro(vtkBoostLogWeighting, vtkArrayDataAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); -//BTX enum { BASE_E = 0, BASE_2 = 1 }; -//ETX // Description: // Specify the logarithm base to apply @@ -60,7 +58,6 @@ class VTKINFOVISBOOSTGRAPHALGORITHMS_EXPORT vtkBoostLogWeighting : public vtkArr vtkGetMacro(EmitProgress, bool); vtkBooleanMacro(EmitProgress, bool); -//BTX protected: vtkBoostLogWeighting(); ~vtkBoostLogWeighting(); @@ -76,7 +73,7 @@ class VTKINFOVISBOOSTGRAPHALGORITHMS_EXPORT vtkBoostLogWeighting : public vtkArr int Base; bool EmitProgress; -//ETX + }; #endif diff --git a/Infovis/BoostGraphAlgorithms/vtkBoostPrimMinimumSpanningTree.cxx b/Infovis/BoostGraphAlgorithms/vtkBoostPrimMinimumSpanningTree.cxx index abeec354fb2..fb88ea9054a 100644 --- a/Infovis/BoostGraphAlgorithms/vtkBoostPrimMinimumSpanningTree.cxx +++ b/Infovis/BoostGraphAlgorithms/vtkBoostPrimMinimumSpanningTree.cxx @@ -113,7 +113,7 @@ vtkIdType vtkBoostPrimMinimumSpanningTree::GetVertexIndex( // Okay now what type of array is it if (abstract->IsNumeric()) { - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstract); + vtkDataArray *dataArray = vtkArrayDownCast(abstract); int intValue = value.ToInt(); for(int i=0; iGetNumberOfTuples(); ++i) { @@ -125,7 +125,7 @@ vtkIdType vtkBoostPrimMinimumSpanningTree::GetVertexIndex( } else { - vtkStringArray *stringArray = vtkStringArray::SafeDownCast(abstract); + vtkStringArray *stringArray = vtkArrayDownCast(abstract); vtkStdString stringValue(value.ToString()); for(int i=0; iGetNumberOfTuples(); ++i) { diff --git a/Infovis/BoostGraphAlgorithms/vtkBoostRandomSparseArraySource.h b/Infovis/BoostGraphAlgorithms/vtkBoostRandomSparseArraySource.h index 1ca7721710c..78a8a319d1d 100644 --- a/Infovis/BoostGraphAlgorithms/vtkBoostRandomSparseArraySource.h +++ b/Infovis/BoostGraphAlgorithms/vtkBoostRandomSparseArraySource.h @@ -38,7 +38,6 @@ class VTKINFOVISBOOSTGRAPHALGORITHMS_EXPORT vtkBoostRandomSparseArraySource : pu vtkTypeMacro(vtkBoostRandomSparseArraySource, vtkArrayDataAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); -//BTX // Description: // Sets the extents (dimensionality and size) of the output array void SetExtents(const vtkArrayExtents&); @@ -46,7 +45,6 @@ class VTKINFOVISBOOSTGRAPHALGORITHMS_EXPORT vtkBoostRandomSparseArraySource : pu // Description: // Returns the extents (dimensionality and size) of the output array vtkArrayExtents GetExtents(); -//ETX // Description: // Stores a random-number-seed for determining which elements within @@ -75,7 +73,6 @@ class VTKINFOVISBOOSTGRAPHALGORITHMS_EXPORT vtkBoostRandomSparseArraySource : pu vtkGetMacro(MaxValue, double); vtkSetMacro(MaxValue, double); -//BTX protected: vtkBoostRandomSparseArraySource(); ~vtkBoostRandomSparseArraySource(); @@ -97,7 +94,7 @@ class VTKINFOVISBOOSTGRAPHALGORITHMS_EXPORT vtkBoostRandomSparseArraySource : pu vtkTypeUInt32 ElementValueSeed; double MinValue; double MaxValue; -//ETX + }; #endif diff --git a/Infovis/BoostGraphAlgorithms/vtkBoostSplitTableField.h b/Infovis/BoostGraphAlgorithms/vtkBoostSplitTableField.h index 73da1b0fd9b..de41a5ed617 100644 --- a/Infovis/BoostGraphAlgorithms/vtkBoostSplitTableField.h +++ b/Infovis/BoostGraphAlgorithms/vtkBoostSplitTableField.h @@ -79,9 +79,9 @@ class VTKINFOVISBOOSTGRAPHALGORITHMS_EXPORT vtkBoostSplitTableField : public vtk vtkStringArray* Delimiters; private: -//BTX + class implementation; -//ETX + vtkBoostSplitTableField(const vtkBoostSplitTableField&); // Not implemented void operator=(const vtkBoostSplitTableField&); // Not implemented }; diff --git a/Infovis/Core/Testing/Cxx/TestDataObjectToTable.cxx b/Infovis/Core/Testing/Cxx/TestDataObjectToTable.cxx index ea8629ce028..9510b88ec76 100644 --- a/Infovis/Core/Testing/Cxx/TestDataObjectToTable.cxx +++ b/Infovis/Core/Testing/Cxx/TestDataObjectToTable.cxx @@ -89,13 +89,13 @@ int TestDataObjectToTable(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) cerr << "Checking table ..." << endl; // Check the table - vtkIntArray* out1 = vtkIntArray::SafeDownCast(table->GetColumnByName("column1")); + vtkIntArray* out1 = vtkArrayDownCast(table->GetColumnByName("column1")); if (!out1) { errors++; cerr << "ERROR: column1 not found when extracting field type " << type << endl; } - vtkIntArray* out2 = vtkIntArray::SafeDownCast(table->GetColumnByName("column2")); + vtkIntArray* out2 = vtkArrayDownCast(table->GetColumnByName("column2")); if (!out2) { errors++; diff --git a/Infovis/Core/Testing/Cxx/TestExtractSelectedTree.cxx b/Infovis/Core/Testing/Cxx/TestExtractSelectedTree.cxx index 976fb860f4c..eaf4ad89906 100644 --- a/Infovis/Core/Testing/Cxx/TestExtractSelectedTree.cxx +++ b/Infovis/Core/Testing/Cxx/TestExtractSelectedTree.cxx @@ -98,7 +98,7 @@ int TestExtractSelectedTree(int, char*[]) } else { - vtkStringArray * nodename = vtkStringArray::SafeDownCast(vertexData->GetAbstractArray("node name")); + vtkStringArray * nodename = vtkArrayDownCast(vertexData->GetAbstractArray("node name")); vtkStdString n = nodename->GetValue(4); if (n.compare("d") != 0) { diff --git a/Infovis/Core/Testing/Cxx/TestMergeGraphs.cxx b/Infovis/Core/Testing/Cxx/TestMergeGraphs.cxx index fd95e40f5c1..62954bcd1ec 100644 --- a/Infovis/Core/Testing/Cxx/TestMergeGraphs.cxx +++ b/Infovis/Core/Testing/Cxx/TestMergeGraphs.cxx @@ -51,8 +51,8 @@ bool CheckTable(vtkTable* expected, vtkTable* output) bool ok = true; for (vtkIdType col = 0; col < expected->GetNumberOfColumns(); ++col) { - vtkStringArray* exp_arr = vtkStringArray::SafeDownCast(expected->GetColumn(col)); - vtkStringArray* out_arr = vtkStringArray::SafeDownCast(output->GetColumnByName(exp_arr->GetName())); + vtkStringArray* exp_arr = vtkArrayDownCast(expected->GetColumn(col)); + vtkStringArray* out_arr = vtkArrayDownCast(output->GetColumnByName(exp_arr->GetName())); if (!out_arr) { cerr << "Output array " << exp_arr->GetName() << " does not exist" << endl; diff --git a/Infovis/Core/Testing/Cxx/TestStringToNumeric.cxx b/Infovis/Core/Testing/Cxx/TestStringToNumeric.cxx index d304fd3a7c2..c0f4c84775a 100644 --- a/Infovis/Core/Testing/Cxx/TestStringToNumeric.cxx +++ b/Infovis/Core/Testing/Cxx/TestStringToNumeric.cxx @@ -51,34 +51,34 @@ int ArrayTypesTest(int argc, char* argv[]) cerr << "Testing array types..." << endl; int errors = 0; - if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Author"))) + if (!vtkArrayDownCast(table->GetColumnByName("Author"))) { cerr << "ERROR: Author array missing" << endl; ++errors; } - if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Affiliation"))) + if (!vtkArrayDownCast(table->GetColumnByName("Affiliation"))) { cerr << "ERROR: Affiliation array missing" << endl; ++errors; } - if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Alma Mater"))) + if (!vtkArrayDownCast(table->GetColumnByName("Alma Mater"))) { cerr << "ERROR: Alma Mater array missing" << endl; ++errors; } - if (!vtkStringArray::SafeDownCast(table->GetColumnByName("Categories"))) + if (!vtkArrayDownCast(table->GetColumnByName("Categories"))) { cerr << "ERROR: Categories array missing" << endl; ++errors; } - if (!vtkIntArray::SafeDownCast(table->GetColumnByName("Age"))) + if (!vtkArrayDownCast(table->GetColumnByName("Age"))) { cerr << "ERROR: Age array missing or not converted to int" << endl; ++errors; } else { - vtkIntArray* age = vtkIntArray::SafeDownCast(table->GetColumnByName("Age")); + vtkIntArray* age = vtkArrayDownCast(table->GetColumnByName("Age")); int sum = 0; for (vtkIdType i = 0; i < age->GetNumberOfTuples(); i++) { @@ -90,14 +90,14 @@ int ArrayTypesTest(int argc, char* argv[]) ++errors; } } - if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("Coolness"))) + if (!vtkArrayDownCast(table->GetColumnByName("Coolness"))) { cerr << "ERROR: Coolness array missing or not converted to double" << endl; ++errors; } else { - vtkDoubleArray* cool = vtkDoubleArray::SafeDownCast(table->GetColumnByName("Coolness")); + vtkDoubleArray* cool = vtkArrayDownCast(table->GetColumnByName("Coolness")); double sum = 0; for (vtkIdType i = 0; i < cool->GetNumberOfTuples(); i++) { @@ -116,7 +116,7 @@ int ArrayTypesTest(int argc, char* argv[]) numeric->ForceDoubleOn(); numeric->Update(); table = vtkTable::SafeDownCast(numeric->GetOutput()); - if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("Age"))) + if (!vtkArrayDownCast(table->GetColumnByName("Age"))) { cerr << "ERROR: Arrays should have been forced to double" << endl; ++errors; @@ -157,7 +157,7 @@ int WhitespaceAndEmptyCellsTest() cerr << "Testing handling whitespace and empty cells..." << endl; int errors = 0; - if (!vtkIntArray::SafeDownCast(table->GetColumnByName("IntegerColumn"))) + if (!vtkArrayDownCast(table->GetColumnByName("IntegerColumn"))) { cerr << "ERROR: IntegerColumn array missing or not converted to int" << endl; ++errors; @@ -165,7 +165,7 @@ int WhitespaceAndEmptyCellsTest() else { vtkIntArray* column = - vtkIntArray::SafeDownCast(table->GetColumnByName("IntegerColumn")); + vtkArrayDownCast(table->GetColumnByName("IntegerColumn")); if (defaultIntValue != column->GetValue(0)) { cerr << "ERROR: Empty cell value is: " << column->GetValue(0) @@ -180,7 +180,7 @@ int WhitespaceAndEmptyCellsTest() } } - if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName("DoubleColumn"))) + if (!vtkArrayDownCast(table->GetColumnByName("DoubleColumn"))) { cerr << "ERROR: DoubleColumn array missing or not converted to double" << endl; @@ -189,7 +189,7 @@ int WhitespaceAndEmptyCellsTest() else { vtkDoubleArray* column = - vtkDoubleArray::SafeDownCast(table->GetColumnByName("DoubleColumn")); + vtkArrayDownCast(table->GetColumnByName("DoubleColumn")); if (!vtkMath::IsNan(column->GetValue(0))) { cerr << "ERROR: Empty cell value is: " << column->GetValue(0) diff --git a/Infovis/Core/Testing/Cxx/TestThresholdTable.cxx b/Infovis/Core/Testing/Cxx/TestThresholdTable.cxx index b0013848722..b45705c9d8a 100644 --- a/Infovis/Core/Testing/Cxx/TestThresholdTable.cxx +++ b/Infovis/Core/Testing/Cxx/TestThresholdTable.cxx @@ -69,7 +69,7 @@ int TestThresholdTable(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) threshold->SetMode(vtkThresholdTable::ACCEPT_BETWEEN); threshold->Update(); vtkTable* output = threshold->GetOutput(); - vtkIntArray* intArrOut = vtkIntArray::SafeDownCast(output->GetColumnByName("intArr")); + vtkIntArray* intArrOut = vtkArrayDownCast(output->GetColumnByName("intArr")); // Perform error checking if (!intArrOut) @@ -101,7 +101,7 @@ int TestThresholdTable(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) threshold->SetMode(vtkThresholdTable::ACCEPT_LESS_THAN); threshold->Update(); output = threshold->GetOutput(); - vtkDoubleArray* doubleArrOut = vtkDoubleArray::SafeDownCast(output->GetColumnByName("doubleArr")); + vtkDoubleArray* doubleArrOut = vtkArrayDownCast(output->GetColumnByName("doubleArr")); // Perform error checking if (!doubleArrOut) @@ -139,7 +139,7 @@ int TestThresholdTable(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) threshold->SetMode(vtkThresholdTable::ACCEPT_OUTSIDE); threshold->Update(); output = threshold->GetOutput(); - vtkStringArray* stringArrOut = vtkStringArray::SafeDownCast(output->GetColumnByName("stringArr")); + vtkStringArray* stringArrOut = vtkArrayDownCast(output->GetColumnByName("stringArr")); // Perform error checking if (!stringArrOut) diff --git a/Infovis/Core/Testing/Cxx/TestTreeDifferenceFilter.cxx b/Infovis/Core/Testing/Cxx/TestTreeDifferenceFilter.cxx index 0f24e810a84..d32c0034cea 100644 --- a/Infovis/Core/Testing/Cxx/TestTreeDifferenceFilter.cxx +++ b/Infovis/Core/Testing/Cxx/TestTreeDifferenceFilter.cxx @@ -98,7 +98,7 @@ int TestTreeDifferenceFilter(int, char*[]) vtkNew outputTree; outputTree->ShallowCopy(filter->GetOutput()); - vtkDoubleArray *diff = vtkDoubleArray::SafeDownCast( + vtkDoubleArray *diff = vtkArrayDownCast( outputTree->GetEdgeData()->GetAbstractArray("weight differences")); if (diff->GetValue(0) != -1.0) diff --git a/Infovis/Core/vtkAddMembershipArray.h b/Infovis/Core/vtkAddMembershipArray.h index b7b508a4202..1372490c834 100644 --- a/Infovis/Core/vtkAddMembershipArray.h +++ b/Infovis/Core/vtkAddMembershipArray.h @@ -40,7 +40,6 @@ class VTKINFOVISCORE_EXPORT vtkAddMembershipArray : public vtkPassInputTypeAlgor vtkTypeMacro(vtkAddMembershipArray,vtkPassInputTypeAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); - //BTX enum { FIELD_DATA = 0, @@ -50,7 +49,6 @@ class VTKINFOVISCORE_EXPORT vtkAddMembershipArray : public vtkPassInputTypeAlgor EDGE_DATA = 4, ROW_DATA = 5 }; - //ETX // Description: // The field type to add the membership array to. @@ -83,9 +81,8 @@ class VTKINFOVISCORE_EXPORT vtkAddMembershipArray : public vtkPassInputTypeAlgor int FieldType; char* OutputArrayName; char* InputArrayName; -//BTX + vtkAbstractArray* InputValues; -//ETX private: vtkAddMembershipArray(const vtkAddMembershipArray&); // Not implemented diff --git a/Infovis/Core/vtkArrayNorm.h b/Infovis/Core/vtkArrayNorm.h index 1e834782a13..b33b5dc0a58 100644 --- a/Infovis/Core/vtkArrayNorm.h +++ b/Infovis/Core/vtkArrayNorm.h @@ -61,7 +61,6 @@ class VTKINFOVISCORE_EXPORT vtkArrayNorm : public vtkArrayDataAlgorithm vtkSetMacro(Invert, int); vtkGetMacro(Invert, int); -//BTX // Description: // Defines an optional "window" used to compute the norm on a subset of the elements // in a vector. @@ -85,7 +84,7 @@ class VTKINFOVISCORE_EXPORT vtkArrayNorm : public vtkArrayDataAlgorithm int L; int Invert; vtkArrayRange Window; -//ETX + }; #endif diff --git a/Infovis/Core/vtkCollapseVerticesByArray.cxx b/Infovis/Core/vtkCollapseVerticesByArray.cxx index 715b6e89e24..479b300c1af 100644 --- a/Infovis/Core/vtkCollapseVerticesByArray.cxx +++ b/Infovis/Core/vtkCollapseVerticesByArray.cxx @@ -289,7 +289,7 @@ vtkGraph* vtkCollapseVerticesByArray::Create(vtkGraph* inGraph) this->Internal->AggregateEdgeArrays[j].c_str()) == 0) { vtkDataArray* inDataArray = - vtkDataArray::SafeDownCast(absArray); + vtkArrayDownCast(absArray); if(inDataArray) { inEdgeDataArraysOI.push_back(inDataArray); @@ -328,7 +328,7 @@ vtkGraph* vtkCollapseVerticesByArray::Create(vtkGraph* inGraph) return 0; } - vtkDataArray* outDataArray = vtkDataArray::SafeDownCast( + vtkDataArray* outDataArray = vtkArrayDownCast( outGraph->GetEdgeData()->GetAbstractArray( inEdgeDataArraysOI[i]->GetName())); diff --git a/Infovis/Core/vtkDataObjectToTable.h b/Infovis/Core/vtkDataObjectToTable.h index 66c1841be53..12cdfb12f6b 100644 --- a/Infovis/Core/vtkDataObjectToTable.h +++ b/Infovis/Core/vtkDataObjectToTable.h @@ -36,7 +36,6 @@ class VTKINFOVISCORE_EXPORT vtkDataObjectToTable : public vtkTableAlgorithm vtkTypeMacro(vtkDataObjectToTable,vtkTableAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); - //BTX enum { FIELD_DATA = 0, @@ -45,7 +44,6 @@ class VTKINFOVISCORE_EXPORT vtkDataObjectToTable : public vtkTableAlgorithm VERTEX_DATA = 3, EDGE_DATA = 4 }; - //ETX // Description: // The field type to copy into the output table. diff --git a/Infovis/Core/vtkExtractSelectedGraph.cxx b/Infovis/Core/vtkExtractSelectedGraph.cxx index 1aa08bcac1c..c27a8b86534 100644 --- a/Infovis/Core/vtkExtractSelectedGraph.cxx +++ b/Infovis/Core/vtkExtractSelectedGraph.cxx @@ -224,7 +224,7 @@ int vtkExtractSelectedGraph::RequestData( if (list) { // Append the selection list to the selection - vtkIdTypeArray* curList = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkIdTypeArray* curList = vtkArrayDownCast(node->GetSelectionList()); if (curList) { int inverse = node->GetProperties()->Get(vtkSelectionNode::INVERSE()); diff --git a/Infovis/Core/vtkExtractSelectedTree.cxx b/Infovis/Core/vtkExtractSelectedTree.cxx index 2f2de1b1778..c104ff9231e 100644 --- a/Infovis/Core/vtkExtractSelectedTree.cxx +++ b/Infovis/Core/vtkExtractSelectedTree.cxx @@ -156,7 +156,7 @@ int vtkExtractSelectedTree::RequestData( vtkSelectionNode * node = converted->GetNode(i); // Append the selectedVerticesList - vtkIdTypeArray * curList = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkIdTypeArray * curList = vtkArrayDownCast(node->GetSelectionList()); if (curList) { int inverse = node->GetProperties()->Get(vtkSelectionNode::INVERSE()); diff --git a/Infovis/Core/vtkGenerateIndexArray.h b/Infovis/Core/vtkGenerateIndexArray.h index 0697f42612b..2fe4ecef961 100644 --- a/Infovis/Core/vtkGenerateIndexArray.h +++ b/Infovis/Core/vtkGenerateIndexArray.h @@ -75,7 +75,6 @@ class VTKINFOVISCORE_EXPORT vtkGenerateIndexArray : public vtkDataObjectAlgorith vtkSetMacro(PedigreeID, int); vtkGetMacro(PedigreeID, int); -//BTX enum { ROW_DATA = 0, @@ -84,7 +83,6 @@ class VTKINFOVISCORE_EXPORT vtkGenerateIndexArray : public vtkDataObjectAlgorith VERTEX_DATA = 3, EDGE_DATA = 4 }; -//ETX protected: vtkGenerateIndexArray(); diff --git a/Infovis/Core/vtkGroupLeafVertices.cxx b/Infovis/Core/vtkGroupLeafVertices.cxx index 62ec7af6063..71af09a8c2a 100644 --- a/Infovis/Core/vtkGroupLeafVertices.cxx +++ b/Infovis/Core/vtkGroupLeafVertices.cxx @@ -179,7 +179,7 @@ int vtkGroupLeafVertices::RequestData( // Get the domain array. If none exists, create one, and initialize bool addInputDomain = false; - vtkStringArray* domainArr = vtkStringArray::SafeDownCast(builderVertexData->GetAbstractArray("domain")); + vtkStringArray* domainArr = vtkArrayDownCast(builderVertexData->GetAbstractArray("domain")); int group_index = 0; if(!domainArr) { @@ -211,7 +211,8 @@ int vtkGroupLeafVertices::RequestData( } } } - else if(vtkStringArray::SafeDownCast(pedigreeIdArr)||vtkVariantArray::SafeDownCast(pedigreeIdArr)) + else if(vtkArrayDownCast(pedigreeIdArr) || + vtkArrayDownCast(pedigreeIdArr)) { for(vtkIdType i=0; iGetNumberOfIds(); ++i) { @@ -299,9 +300,9 @@ int vtkGroupLeafVertices::RequestData( continue; } int comps = arr->GetNumberOfComponents(); - if (vtkDataArray::SafeDownCast(arr2)) + if (vtkArrayDownCast(arr2)) { - vtkDataArray* data = vtkDataArray::SafeDownCast(arr2); + vtkDataArray* data = vtkArrayDownCast(arr2); double* tuple = new double[comps]; for (int j = 0; j < comps; j++) { @@ -310,25 +311,25 @@ int vtkGroupLeafVertices::RequestData( data->InsertTuple(group_vertex, tuple); delete[] tuple; } - else if (vtkStringArray::SafeDownCast(arr2)) + else if (vtkArrayDownCast(arr2)) { - vtkStringArray* data = vtkStringArray::SafeDownCast(arr2); + vtkStringArray* data = vtkArrayDownCast(arr2); for (int j = 0; j < comps; j++) { data->InsertValue(group_vertex + j - 1, vtkStdString("")); } } - else if (vtkVariantArray::SafeDownCast(arr2)) + else if (vtkArrayDownCast(arr2)) { - vtkVariantArray* data = vtkVariantArray::SafeDownCast(arr2); + vtkVariantArray* data = vtkArrayDownCast(arr2); for (int j = 0; j < comps; j++) { data->InsertValue(group_vertex + j - 1, vtkVariant()); } } - else if (vtkUnicodeStringArray::SafeDownCast(arr2)) + else if (vtkArrayDownCast(arr2)) { - vtkUnicodeStringArray* data = vtkUnicodeStringArray::SafeDownCast(arr2); + vtkUnicodeStringArray* data = vtkArrayDownCast(arr2); for (int j = 0; j < comps; j++) { data->InsertValue(group_vertex + j - 1, vtkUnicodeString::from_utf8("")); diff --git a/Infovis/Core/vtkMergeColumns.cxx b/Infovis/Core/vtkMergeColumns.cxx index 7b1c206e50e..bab8112e9b1 100644 --- a/Infovis/Core/vtkMergeColumns.cxx +++ b/Infovis/Core/vtkMergeColumns.cxx @@ -94,9 +94,9 @@ int vtkMergeColumns::RequestData( { case VTK_STRING: { - vtkStringArray* col1Str = vtkStringArray::SafeDownCast(col1); - vtkStringArray* col2Str = vtkStringArray::SafeDownCast(col2); - vtkStringArray* mergedStr = vtkStringArray::SafeDownCast(merged); + vtkStringArray* col1Str = vtkArrayDownCast(col1); + vtkStringArray* col2Str = vtkArrayDownCast(col2); + vtkStringArray* mergedStr = vtkArrayDownCast(merged); for (vtkIdType i = 0; i < merged->GetNumberOfTuples(); i++) { vtkStdString combined = col1Str->GetValue(i); @@ -112,9 +112,9 @@ int vtkMergeColumns::RequestData( } case VTK_UNICODE_STRING: { - vtkUnicodeStringArray* col1Str = vtkUnicodeStringArray::SafeDownCast(col1); - vtkUnicodeStringArray* col2Str = vtkUnicodeStringArray::SafeDownCast(col2); - vtkUnicodeStringArray* mergedStr = vtkUnicodeStringArray::SafeDownCast(merged); + vtkUnicodeStringArray* col1Str = vtkArrayDownCast(col1); + vtkUnicodeStringArray* col2Str = vtkArrayDownCast(col2); + vtkUnicodeStringArray* mergedStr = vtkArrayDownCast(merged); for (vtkIdType i = 0; i < merged->GetNumberOfTuples(); i++) { vtkUnicodeString combined = col1Str->GetValue(i); diff --git a/Infovis/Core/vtkMergeGraphs.cxx b/Infovis/Core/vtkMergeGraphs.cxx index 807d0c4f0ed..eba184962f9 100644 --- a/Infovis/Core/vtkMergeGraphs.cxx +++ b/Infovis/Core/vtkMergeGraphs.cxx @@ -231,7 +231,7 @@ int vtkMergeGraphs::ExtendGraph(vtkMutableGraphHelper* builder, vtkGraph* graph2 vtkErrorMacro("EdgeWindowArrayName must not be null if using edge window."); return 0; } - vtkDataArray* windowArr = vtkDataArray::SafeDownCast( + vtkDataArray* windowArr = vtkArrayDownCast( builder->GetGraph()->GetEdgeData()->GetAbstractArray(this->EdgeWindowArrayName)); if (!windowArr) { diff --git a/Infovis/Core/vtkMutableGraphHelper.h b/Infovis/Core/vtkMutableGraphHelper.h index 7aa71b906df..307e1e93a79 100644 --- a/Infovis/Core/vtkMutableGraphHelper.h +++ b/Infovis/Core/vtkMutableGraphHelper.h @@ -55,11 +55,10 @@ class VTKINFOVISCORE_EXPORT vtkMutableGraphHelper : public vtkObject void SetGraph(vtkGraph* g); vtkGraph* GetGraph(); -//BTX // Description: // Add an edge to the underlying mutable graph. vtkEdgeType AddEdge(vtkIdType u, vtkIdType v); -//ETX + vtkGraphEdge* AddGraphEdge(vtkIdType u, vtkIdType v); // Description: diff --git a/Infovis/Core/vtkNetworkHierarchy.cxx b/Infovis/Core/vtkNetworkHierarchy.cxx index f0e1427d7a1..1eb3120c26c 100644 --- a/Infovis/Core/vtkNetworkHierarchy.cxx +++ b/Infovis/Core/vtkNetworkHierarchy.cxx @@ -125,7 +125,7 @@ int vtkNetworkHierarchy::RequestData( // Get the field to filter on vtkAbstractArray* arr = inputGraph->GetVertexData()->GetAbstractArray(this->IPArrayName); - vtkStringArray* ipArray = vtkStringArray::SafeDownCast(arr); + vtkStringArray* ipArray = vtkArrayDownCast(arr); if (ipArray == NULL) { vtkErrorMacro(<< "An string based ip array must be specified"); @@ -161,7 +161,7 @@ int vtkNetworkHierarchy::RequestData( vtkAbstractArray* pedIDArr = builderVertexData->GetPedigreeIds(); // Get domain. If there isn't one, make one. - vtkStringArray* domainArr = vtkStringArray::SafeDownCast( + vtkStringArray* domainArr = vtkArrayDownCast( builderVertexData->GetAbstractArray("domain")); if (pedIDArr && !domainArr) { diff --git a/Infovis/Core/vtkPipelineGraphSource.h b/Infovis/Core/vtkPipelineGraphSource.h index ae67fa33cfa..e81f104340a 100644 --- a/Infovis/Core/vtkPipelineGraphSource.h +++ b/Infovis/Core/vtkPipelineGraphSource.h @@ -35,7 +35,6 @@ class VTKINFOVISCORE_EXPORT vtkPipelineGraphSource : public vtkDirectedGraphAlgo void AddSink(vtkObject* object); void RemoveSink(vtkObject* object); -//BTX // Description: // Generates a GraphViz DOT file that describes the VTK pipeline // terminating at the given sink. @@ -59,7 +58,7 @@ class VTKINFOVISCORE_EXPORT vtkPipelineGraphSource : public vtkDirectedGraphAlgo private: vtkPipelineGraphSource(const vtkPipelineGraphSource&); // Not implemented void operator=(const vtkPipelineGraphSource&); // Not implemented -//ETX + }; #endif diff --git a/Infovis/Core/vtkReduceTable.h b/Infovis/Core/vtkReduceTable.h index f1156cee61f..23ba7e11e0e 100644 --- a/Infovis/Core/vtkReduceTable.h +++ b/Infovis/Core/vtkReduceTable.h @@ -79,7 +79,6 @@ class VTKINFOVISCORE_EXPORT vtkReduceTable : public vtkTableAlgorithm // the specified column. void SetReductionMethodForColumn(vtkIdType col, int method); - //BTX // Description: // Enum for methods of reduction enum @@ -88,7 +87,6 @@ class VTKINFOVISCORE_EXPORT vtkReduceTable : public vtkTableAlgorithm MEDIAN, MODE }; - //ETX protected: vtkReduceTable(); diff --git a/Infovis/Core/vtkRemoveHiddenData.h b/Infovis/Core/vtkRemoveHiddenData.h index 1d3f73054f1..ad90373503b 100644 --- a/Infovis/Core/vtkRemoveHiddenData.h +++ b/Infovis/Core/vtkRemoveHiddenData.h @@ -63,10 +63,9 @@ class VTKINFOVISCORE_EXPORT vtkRemoveHiddenData : public vtkPassInputTypeAlgorit vtkRemoveHiddenData(const vtkRemoveHiddenData&); // Not implemented. void operator=(const vtkRemoveHiddenData&); // Not implemented. -//BTX vtkSmartPointer ExtractGraph; vtkSmartPointer ExtractTable; -//ETX + }; #endif diff --git a/Infovis/Core/vtkStringToCategory.cxx b/Infovis/Core/vtkStringToCategory.cxx index 9c90f16ce2b..b1e2e0eafdd 100644 --- a/Infovis/Core/vtkStringToCategory.cxx +++ b/Infovis/Core/vtkStringToCategory.cxx @@ -73,7 +73,7 @@ int vtkStringToCategory::RequestData( vtkTable* stringTable = vtkTable::SafeDownCast(outKeyInfo->Get(vtkDataObject::DATA_OBJECT())); vtkStringArray* strings = - vtkStringArray::SafeDownCast(stringTable->GetColumnByName("Strings")); + vtkArrayDownCast(stringTable->GetColumnByName("Strings")); if (strings) { strings->SetNumberOfTuples(0); @@ -87,7 +87,7 @@ int vtkStringToCategory::RequestData( } vtkAbstractArray* arr = this->GetInputAbstractArrayToProcess(0, 0, inputVector); - vtkStringArray* stringArr = vtkStringArray::SafeDownCast(arr); + vtkStringArray* stringArr = vtkArrayDownCast(arr); if (!stringArr) { vtkErrorMacro("String array input could not be found"); diff --git a/Infovis/Core/vtkStringToNumeric.cxx b/Infovis/Core/vtkStringToNumeric.cxx index 80db4f7b19a..2ce21cb3f71 100644 --- a/Infovis/Core/vtkStringToNumeric.cxx +++ b/Infovis/Core/vtkStringToNumeric.cxx @@ -59,9 +59,9 @@ int vtkStringToNumeric::CountItemsToConvert(vtkFieldData *fieldData) for (int arr = 0; arr < fieldData->GetNumberOfArrays(); arr++) { vtkAbstractArray *array = fieldData->GetAbstractArray(arr); - vtkStringArray* stringArray = vtkStringArray::SafeDownCast(array); + vtkStringArray* stringArray = vtkArrayDownCast(array); vtkUnicodeStringArray* unicodeArray = - vtkUnicodeStringArray::SafeDownCast(array); + vtkArrayDownCast(array); if (!stringArray && !unicodeArray) { continue; @@ -155,9 +155,9 @@ void vtkStringToNumeric::ConvertArrays(vtkFieldData* fieldData) { for (int arr = 0; arr < fieldData->GetNumberOfArrays(); arr++) { - vtkStringArray* stringArray = vtkStringArray::SafeDownCast( + vtkStringArray* stringArray = vtkArrayDownCast( fieldData->GetAbstractArray(arr)); - vtkUnicodeStringArray* unicodeArray = vtkUnicodeStringArray::SafeDownCast( + vtkUnicodeStringArray* unicodeArray = vtkArrayDownCast( fieldData->GetAbstractArray(arr)); if (!stringArray && !unicodeArray) { diff --git a/Infovis/Core/vtkTableToArray.h b/Infovis/Core/vtkTableToArray.h index fa52b2ed625..922e75a99bf 100644 --- a/Infovis/Core/vtkTableToArray.h +++ b/Infovis/Core/vtkTableToArray.h @@ -64,7 +64,6 @@ class VTKINFOVISCORE_EXPORT vtkTableToArray : public vtkArrayDataAlgorithm // Add every input table column to the output matrix. void AddAllColumns(); -//BTX protected: vtkTableToArray(); ~vtkTableToArray(); @@ -82,7 +81,7 @@ class VTKINFOVISCORE_EXPORT vtkTableToArray : public vtkArrayDataAlgorithm class implementation; implementation* const Implementation; -//ETX + }; #endif diff --git a/Infovis/Core/vtkTableToGraph.cxx b/Infovis/Core/vtkTableToGraph.cxx index c7468a356fe..0ee65a18716 100644 --- a/Infovis/Core/vtkTableToGraph.cxx +++ b/Infovis/Core/vtkTableToGraph.cxx @@ -76,7 +76,7 @@ int vtkTableToGraph::ValidateLinkGraph() { this->LinkGraph = vtkMutableDirectedGraph::New(); } - if (!vtkStringArray::SafeDownCast( + if (!vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("column"))) { if (this->LinkGraph->GetNumberOfVertices() == 0) @@ -93,7 +93,7 @@ int vtkTableToGraph::ValidateLinkGraph() return 0; } } - if (!vtkStringArray::SafeDownCast( + if (!vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("domain"))) { vtkStringArray* domain = vtkStringArray::New(); @@ -107,7 +107,7 @@ int vtkTableToGraph::ValidateLinkGraph() domain->Delete(); this->Modified(); } - if (!vtkBitArray::SafeDownCast( + if (!vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("hidden"))) { vtkBitArray* hidden = vtkBitArray::New(); @@ -117,7 +117,7 @@ int vtkTableToGraph::ValidateLinkGraph() hidden->Delete(); this->Modified(); } - if (!vtkIntArray::SafeDownCast( + if (!vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("active"))) { vtkIntArray* active = vtkIntArray::New(); @@ -154,13 +154,13 @@ void vtkTableToGraph::AddLinkVertex(const char* column, const char* domain, int return; } - vtkStringArray* columnArr = vtkStringArray::SafeDownCast( + vtkStringArray* columnArr = vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("column")); - vtkStringArray* domainArr = vtkStringArray::SafeDownCast( + vtkStringArray* domainArr = vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("domain")); - vtkBitArray* hiddenArr = vtkBitArray::SafeDownCast( + vtkBitArray* hiddenArr = vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("hidden")); - vtkIntArray* activeArr = vtkIntArray::SafeDownCast( + vtkIntArray* activeArr = vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("active")); vtkIdType index = -1; @@ -193,7 +193,7 @@ void vtkTableToGraph::AddLinkVertex(const char* column, const char* domain, int void vtkTableToGraph::ClearLinkVertices() { this->ValidateLinkGraph(); - vtkIntArray* activeArr = vtkIntArray::SafeDownCast( + vtkIntArray* activeArr = vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("active")); for (vtkIdType i = 0; i < this->LinkGraph->GetNumberOfVertices(); ++i) { @@ -210,7 +210,7 @@ void vtkTableToGraph::AddLinkEdge(const char* column1, const char* column2) vtkErrorMacro("Column names may not be null."); } this->ValidateLinkGraph(); - vtkStringArray* columnArr = vtkStringArray::SafeDownCast( + vtkStringArray* columnArr = vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("column")); vtkIdType source = -1; vtkIdType target = -1; @@ -403,7 +403,7 @@ int vtkTableToGraph::RequestData( vertexTableInfo->Get(vtkDataObject::DATA_OBJECT())); } - if (vtkIntArray::SafeDownCast( + if (vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("active"))) { // Extract only the active link graph. @@ -428,7 +428,7 @@ int vtkTableToGraph::RequestData( extract->Delete(); } - vtkStringArray* linkColumn = vtkStringArray::SafeDownCast( + vtkStringArray* linkColumn = vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("column")); if (!linkColumn) @@ -437,9 +437,9 @@ int vtkTableToGraph::RequestData( return 0; } - vtkStringArray* linkDomain = vtkStringArray::SafeDownCast( + vtkStringArray* linkDomain = vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("domain")); - vtkBitArray* linkHidden = vtkBitArray::SafeDownCast( + vtkBitArray* linkHidden = vtkArrayDownCast( this->LinkGraph->GetVertexData()->GetAbstractArray("hidden")); // Find all the hidden types @@ -534,7 +534,7 @@ int vtkTableToGraph::RequestData( domainValuesArr->Delete(); for (vtkIdType r = 0; r < vertexTable->GetNumberOfRows(); ++r) { - if (vtkStringArray::SafeDownCast(domainValuesArr)) + if (vtkArrayDownCast(domainValuesArr)) { vertexTable->SetValueByName(r, domain, ""); } diff --git a/Infovis/Core/vtkTableToSparseArray.h b/Infovis/Core/vtkTableToSparseArray.h index dff0040b71f..059110a1b7f 100644 --- a/Infovis/Core/vtkTableToSparseArray.h +++ b/Infovis/Core/vtkTableToSparseArray.h @@ -72,7 +72,6 @@ class VTKINFOVISCORE_EXPORT vtkTableToSparseArray : public vtkArrayDataAlgorithm void ClearOutputExtents(); void SetOutputExtents(const vtkArrayExtents& extents); -//BTX protected: vtkTableToSparseArray(); ~vtkTableToSparseArray(); @@ -90,7 +89,7 @@ class VTKINFOVISCORE_EXPORT vtkTableToSparseArray : public vtkArrayDataAlgorithm class implementation; implementation* const Implementation; -//ETX + }; #endif diff --git a/Infovis/Core/vtkThresholdGraph.h b/Infovis/Core/vtkThresholdGraph.h index 63bb2f99c6b..496e73eabbd 100644 --- a/Infovis/Core/vtkThresholdGraph.h +++ b/Infovis/Core/vtkThresholdGraph.h @@ -45,7 +45,6 @@ class VTKINFOVISCORE_EXPORT vtkThresholdGraph : public vtkGraphAlgorithm vtkGetMacro(UpperThreshold, double); vtkSetMacro(UpperThreshold, double); -//BTX protected: vtkThresholdGraph(); @@ -64,7 +63,7 @@ class VTKINFOVISCORE_EXPORT vtkThresholdGraph : public vtkGraphAlgorithm vtkThresholdGraph(const vtkThresholdGraph&); // Not implemented. void operator =(const vtkThresholdGraph&); // Not implemented. -//ETX + }; #endif // vtkThresholdGraph_h diff --git a/Infovis/Core/vtkThresholdTable.h b/Infovis/Core/vtkThresholdTable.h index 215f73611c2..28c6ba40408 100644 --- a/Infovis/Core/vtkThresholdTable.h +++ b/Infovis/Core/vtkThresholdTable.h @@ -38,14 +38,12 @@ class VTKINFOVISCORE_EXPORT vtkThresholdTable : public vtkTableAlgorithm vtkTypeMacro(vtkThresholdTable, vtkTableAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); - //BTX enum { ACCEPT_LESS_THAN = 0, ACCEPT_GREATER_THAN = 1, ACCEPT_BETWEEN = 2, ACCEPT_OUTSIDE = 3 }; - //ETX // Description: // The mode of the threshold filter. Options are: diff --git a/Infovis/Core/vtkTreeDifferenceFilter.cxx b/Infovis/Core/vtkTreeDifferenceFilter.cxx index 218b41b0112..68604cfbcd5 100644 --- a/Infovis/Core/vtkTreeDifferenceFilter.cxx +++ b/Infovis/Core/vtkTreeDifferenceFilter.cxx @@ -140,7 +140,7 @@ bool vtkTreeDifferenceFilter::GenerateMapping(vtkTree *tree1, vtkTree *tree2) this->EdgeMap.clear(); this->EdgeMap.assign(tree1->GetNumberOfEdges(), -1); - vtkStringArray *nodeNames1 = vtkStringArray::SafeDownCast( + vtkStringArray *nodeNames1 = vtkArrayDownCast( tree1->GetVertexData()->GetAbstractArray(this->IdArrayName)); if (nodeNames1 == NULL) { @@ -149,7 +149,7 @@ bool vtkTreeDifferenceFilter::GenerateMapping(vtkTree *tree1, vtkTree *tree2) return false; } - vtkStringArray *nodeNames2 = vtkStringArray::SafeDownCast( + vtkStringArray *nodeNames2 = vtkArrayDownCast( tree2->GetVertexData()->GetAbstractArray(this->IdArrayName)); if (nodeNames2 == NULL) { diff --git a/Infovis/Core/vtkTreeFieldAggregator.cxx b/Infovis/Core/vtkTreeFieldAggregator.cxx index 93b17458137..6bb40131c6a 100644 --- a/Infovis/Core/vtkTreeFieldAggregator.cxx +++ b/Infovis/Core/vtkTreeFieldAggregator.cxx @@ -87,7 +87,7 @@ int vtkTreeFieldAggregator::RequestData( arr->SetName(this->Field); for (vtkIdType i = 0; i < arr->GetNumberOfTuples(); i++) { - vtkIntArray::SafeDownCast(arr)->SetTuple1(i, 1); + vtkArrayDownCast(arr)->SetTuple1(i, 1); } output->GetVertexData()->AddArray(arr); arr->Delete(); @@ -180,7 +180,7 @@ double vtkTreeFieldAggregator::GetDoubleValue(vtkAbstractArray* arr, vtkIdType i { if (arr->IsA("vtkDataArray")) { - double d = vtkDataArray::SafeDownCast(arr)->GetTuple1(id); + double d = vtkArrayDownCast(arr)->GetTuple1(id); if (d < this->MinValue) { return MinValue; @@ -189,7 +189,7 @@ double vtkTreeFieldAggregator::GetDoubleValue(vtkAbstractArray* arr, vtkIdType i } else if (arr->IsA("vtkVariantArray")) { - vtkVariant v = vtkVariantArray::SafeDownCast(arr)->GetValue(id); + vtkVariant v = vtkArrayDownCast(arr)->GetValue(id); if (!v.IsValid()) { return this->MinValue; @@ -208,7 +208,7 @@ double vtkTreeFieldAggregator::GetDoubleValue(vtkAbstractArray* arr, vtkIdType i } else if (arr->IsA("vtkStringArray")) { - vtkVariant v(vtkStringArray::SafeDownCast(arr)->GetValue(id)); + vtkVariant v(vtkArrayDownCast(arr)->GetValue(id)); bool ok; double d = v.ToDouble(&ok); if (!ok) @@ -228,14 +228,14 @@ void vtkTreeFieldAggregator::SetDoubleValue(vtkAbstractArray* arr, vtkIdType id, { if (arr->IsA("vtkDataArray")) { - vtkDataArray::SafeDownCast(arr)->SetTuple1(id, value); + vtkArrayDownCast(arr)->SetTuple1(id, value); } else if (arr->IsA("vtkVariantArray")) { - vtkVariantArray::SafeDownCast(arr)->SetValue(id, vtkVariant(value)); + vtkArrayDownCast(arr)->SetValue(id, vtkVariant(value)); } else if (arr->IsA("vtkStringArray")) { - vtkStringArray::SafeDownCast(arr)->SetValue(id, vtkVariant(value).ToString()); + vtkArrayDownCast(arr)->SetValue(id, vtkVariant(value).ToString()); } } diff --git a/Infovis/Layout/vtkAreaLayout.cxx b/Infovis/Layout/vtkAreaLayout.cxx index 868f759c6bc..3f24c8fb638 100644 --- a/Infovis/Layout/vtkAreaLayout.cxx +++ b/Infovis/Layout/vtkAreaLayout.cxx @@ -184,8 +184,8 @@ void vtkAreaLayout::GetBoundingArea(vtkIdType id, float *sinfo) return; } - vtkFloatArray *sectorInfo = vtkFloatArray::SafeDownCast(array); - sectorInfo->GetTupleValue(id, sinfo); + vtkFloatArray *sectorInfo = vtkArrayDownCast(array); + sectorInfo->GetTypedTuple(id, sinfo); } unsigned long vtkAreaLayout::GetMTime() diff --git a/Infovis/Layout/vtkAssignCoordinatesLayoutStrategy.h b/Infovis/Layout/vtkAssignCoordinatesLayoutStrategy.h index 6c0d5f2a566..93671ec4428 100644 --- a/Infovis/Layout/vtkAssignCoordinatesLayoutStrategy.h +++ b/Infovis/Layout/vtkAssignCoordinatesLayoutStrategy.h @@ -61,9 +61,7 @@ class VTKINFOVISLAYOUT_EXPORT vtkAssignCoordinatesLayoutStrategy : public vtkGra vtkAssignCoordinatesLayoutStrategy(); ~vtkAssignCoordinatesLayoutStrategy(); - //BTX vtkSmartPointer AssignCoordinates; - //ETX private: vtkAssignCoordinatesLayoutStrategy(const vtkAssignCoordinatesLayoutStrategy&); // Not implemented. diff --git a/Infovis/Layout/vtkAttributeClustering2DLayoutStrategy.cxx b/Infovis/Layout/vtkAttributeClustering2DLayoutStrategy.cxx index 66ee6f8f819..5ec8d8fe6f4 100644 --- a/Infovis/Layout/vtkAttributeClustering2DLayoutStrategy.cxx +++ b/Infovis/Layout/vtkAttributeClustering2DLayoutStrategy.cxx @@ -224,7 +224,7 @@ void vtkAttributeClustering2DLayoutStrategy::Initialize() } // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Avoid divide by zero @@ -333,7 +333,7 @@ void vtkAttributeClustering2DLayoutStrategy::Layout() vtkIdType numVertices = this->Graph->GetNumberOfVertices(); // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // This is the mega, uber, triple inner loop @@ -551,7 +551,7 @@ void vtkAttributeClustering2DLayoutStrategy::ResolveCoincidentVertices() // Get a quick pointer to the point data vtkPoints* pts = this->Graph->GetPoints(); - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Place the vertices into a giant grid (100xNumVertices) diff --git a/Infovis/Layout/vtkAttributeClustering2DLayoutStrategy.h b/Infovis/Layout/vtkAttributeClustering2DLayoutStrategy.h index b60554ddb46..1ba614a188c 100644 --- a/Infovis/Layout/vtkAttributeClustering2DLayoutStrategy.h +++ b/Infovis/Layout/vtkAttributeClustering2DLayoutStrategy.h @@ -132,14 +132,12 @@ class VTKINFOVISLAYOUT_EXPORT vtkAttributeClustering2DLayoutStrategy : public vt private: - //BTX // This class 'has a' vtkFastSplatter for the density grid vtkSmartPointer DensityGrid; vtkSmartPointer SplatImage; vtkSmartPointer RepulsionArray; vtkSmartPointer AttractionArray; vtkSmartPointer EdgeCountArray; - //ETX int RandomSeed; int IterationsPerLayout; @@ -155,10 +153,8 @@ class VTKINFOVISLAYOUT_EXPORT vtkAttributeClustering2DLayoutStrategy : public vt void GenerateGaussianSplat(vtkImageData *splat, int x, int y); void ResolveCoincidentVertices(); -//BTX class Internals; Internals* Implementation; -//ETX vtkAttributeClustering2DLayoutStrategy(const vtkAttributeClustering2DLayoutStrategy&); // Not implemented. void operator=(const vtkAttributeClustering2DLayoutStrategy&); // Not implemented. diff --git a/Infovis/Layout/vtkCirclePackFrontChainLayoutStrategy.cxx b/Infovis/Layout/vtkCirclePackFrontChainLayoutStrategy.cxx index 4961221fbb5..73ceea960a2 100644 --- a/Infovis/Layout/vtkCirclePackFrontChainLayoutStrategy.cxx +++ b/Infovis/Layout/vtkCirclePackFrontChainLayoutStrategy.cxx @@ -134,7 +134,7 @@ void vtkCirclePackFrontChainLayoutStrategyImplementation::incrListIteratorWrapAr { if(i != frontChain.end()) ++i; - else if(i == frontChain.end()) + else i = frontChain.begin(); } diff --git a/Infovis/Layout/vtkCirclePackLayout.cxx b/Infovis/Layout/vtkCirclePackLayout.cxx index 6c59603c0cd..10202b011cd 100644 --- a/Infovis/Layout/vtkCirclePackLayout.cxx +++ b/Infovis/Layout/vtkCirclePackLayout.cxx @@ -192,9 +192,9 @@ vtkIdType vtkCirclePackLayout::FindVertex(double pnt[2], double *cinfo) double climits[3]; vtkIdType vertex = otree->GetRoot(); - vtkDoubleArray *circleInfo = vtkDoubleArray::SafeDownCast(array); + vtkDoubleArray *circleInfo = vtkArrayDownCast(array); // Now try to find the vertex that contains the point - circleInfo->GetTupleValue(vertex, climits); // Get the extents of the root + circleInfo->GetTypedTuple(vertex, climits); // Get the extents of the root if (pow((pnt[0]- climits[0]),2) + pow((pnt[1] - climits[1]),2) > pow(climits[2],2)) { // Point is not in the tree at all @@ -216,7 +216,7 @@ vtkIdType vtkCirclePackLayout::FindVertex(double pnt[2], double *cinfo) while (it->HasNext()) { child = it->Next(); - circleInfo->GetTupleValue(child, climits); // Get the extents of the child + circleInfo->GetTypedTuple(child, climits); // Get the extents of the child if (pow((pnt[0]- climits[0]),2) + pow((pnt[1] - climits[1]),2) > pow(climits[2],2)) { continue; @@ -262,8 +262,8 @@ void vtkCirclePackLayout::GetBoundingCircle(vtkIdType id, double *cinfo) return; } - vtkDoubleArray *boxInfo = vtkDoubleArray::SafeDownCast(array); - boxInfo->GetTupleValue(id, cinfo); + vtkDoubleArray *boxInfo = vtkArrayDownCast(array); + boxInfo->GetTypedTuple(id, cinfo); } unsigned long vtkCirclePackLayout::GetMTime() diff --git a/Infovis/Layout/vtkClustering2DLayoutStrategy.cxx b/Infovis/Layout/vtkClustering2DLayoutStrategy.cxx index 8aae411f157..d49c1ff0e1b 100644 --- a/Infovis/Layout/vtkClustering2DLayoutStrategy.cxx +++ b/Infovis/Layout/vtkClustering2DLayoutStrategy.cxx @@ -166,7 +166,7 @@ void vtkClustering2DLayoutStrategy::Initialize() } // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Avoid divide by zero @@ -223,7 +223,7 @@ void vtkClustering2DLayoutStrategy::Initialize() double weight, maxWeight = 1; if (this->WeightEdges && this->EdgeWeightField != NULL) { - weightArray = vtkDataArray::SafeDownCast(this->Graph->GetEdgeData()->GetAbstractArray(this->EdgeWeightField)); + weightArray = vtkArrayDownCast(this->Graph->GetEdgeData()->GetAbstractArray(this->EdgeWeightField)); if (weightArray != NULL) { for (vtkIdType w = 0; w < weightArray->GetNumberOfTuples(); w++) @@ -300,7 +300,7 @@ void vtkClustering2DLayoutStrategy::Layout() vtkIdType numEdges = this->Graph->GetNumberOfEdges(); // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // This is the mega, uber, triple inner loop @@ -518,7 +518,7 @@ void vtkClustering2DLayoutStrategy::ResolveCoincidentVertices() // Get a quick pointer to the point data vtkPoints* pts = this->Graph->GetPoints(); - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Place the vertices into a giant grid (100xNumVertices) diff --git a/Infovis/Layout/vtkClustering2DLayoutStrategy.h b/Infovis/Layout/vtkClustering2DLayoutStrategy.h index 025d5b2bcff..81f6bdc2057 100644 --- a/Infovis/Layout/vtkClustering2DLayoutStrategy.h +++ b/Infovis/Layout/vtkClustering2DLayoutStrategy.h @@ -126,8 +126,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkClustering2DLayoutStrategy : public vtkGraphLay private: - //BTX - // An edge consists of two vertices joined together. // This struct acts as a "pointer" to those two vertices. typedef struct @@ -146,7 +144,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkClustering2DLayoutStrategy : public vtkGraphLay vtkSmartPointer RepulsionArray; vtkSmartPointer AttractionArray; vtkSmartPointer EdgeCountArray; - //ETX vtkLayoutEdge *EdgeArray; diff --git a/Infovis/Layout/vtkCommunity2DLayoutStrategy.cxx b/Infovis/Layout/vtkCommunity2DLayoutStrategy.cxx index 3925667e9bc..7bd4427b89e 100644 --- a/Infovis/Layout/vtkCommunity2DLayoutStrategy.cxx +++ b/Infovis/Layout/vtkCommunity2DLayoutStrategy.cxx @@ -169,7 +169,7 @@ void vtkCommunity2DLayoutStrategy::Initialize() } // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Avoid divide by zero @@ -217,7 +217,7 @@ void vtkCommunity2DLayoutStrategy::Initialize() double weight, maxWeight = 1; if (this->WeightEdges && this->EdgeWeightField != NULL) { - weightArray = vtkDataArray::SafeDownCast(this->Graph->GetEdgeData()->GetAbstractArray(this->EdgeWeightField)); + weightArray = vtkArrayDownCast(this->Graph->GetEdgeData()->GetAbstractArray(this->EdgeWeightField)); if (weightArray != NULL) { for (vtkIdType w = 0; w < weightArray->GetNumberOfTuples(); w++) @@ -295,7 +295,7 @@ void vtkCommunity2DLayoutStrategy::Layout() } // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // This is the mega, uber, triple inner loop @@ -509,7 +509,7 @@ void vtkCommunity2DLayoutStrategy::ResolveCoincidentVertices() // Get a quick pointer to the point data vtkPoints* pts = this->Graph->GetPoints(); - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Place the vertices into a giant grid (100xNumVertices) diff --git a/Infovis/Layout/vtkCommunity2DLayoutStrategy.h b/Infovis/Layout/vtkCommunity2DLayoutStrategy.h index 243705b7456..4b445e518e2 100644 --- a/Infovis/Layout/vtkCommunity2DLayoutStrategy.h +++ b/Infovis/Layout/vtkCommunity2DLayoutStrategy.h @@ -141,8 +141,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkCommunity2DLayoutStrategy : public vtkGraphLayo private: - //BTX - // An edge consists of two vertices joined together. // This struct acts as a "pointer" to those two vertices. typedef struct @@ -157,7 +155,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkCommunity2DLayoutStrategy : public vtkGraphLayo vtkSmartPointer SplatImage; vtkSmartPointer RepulsionArray; vtkSmartPointer AttractionArray; - //ETX vtkLayoutEdge *EdgeArray; diff --git a/Infovis/Layout/vtkConstrained2DLayoutStrategy.cxx b/Infovis/Layout/vtkConstrained2DLayoutStrategy.cxx index 50f32eab7c9..14ff1407285 100644 --- a/Infovis/Layout/vtkConstrained2DLayoutStrategy.cxx +++ b/Infovis/Layout/vtkConstrained2DLayoutStrategy.cxx @@ -168,7 +168,7 @@ void vtkConstrained2DLayoutStrategy::Initialize() } // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Avoid divide by zero @@ -216,7 +216,7 @@ void vtkConstrained2DLayoutStrategy::Initialize() double weight, maxWeight = 1; if (this->WeightEdges && this->EdgeWeightField != NULL) { - weightArray = vtkDataArray::SafeDownCast(this->Graph->GetEdgeData()->GetAbstractArray(this->EdgeWeightField)); + weightArray = vtkArrayDownCast(this->Graph->GetEdgeData()->GetAbstractArray(this->EdgeWeightField)); if (weightArray != NULL) { for (vtkIdType w = 0; w < weightArray->GetNumberOfTuples(); w++) @@ -285,7 +285,7 @@ void vtkConstrained2DLayoutStrategy::Layout() vtkIdType numEdges = this->Graph->GetNumberOfEdges(); // Get a quick pointer to the constraint array - vtkDoubleArray *constraint = vtkDoubleArray::SafeDownCast( + vtkDoubleArray *constraint = vtkArrayDownCast( this->Graph->GetVertexData()->GetArray(this->GetInputArrayName())); if (constraint == NULL) { @@ -294,7 +294,7 @@ void vtkConstrained2DLayoutStrategy::Layout() } // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // This is the mega, uber, triple inner loop @@ -481,7 +481,7 @@ void vtkConstrained2DLayoutStrategy::ResolveCoincidentVertices() // Get a quick pointer to the point data vtkPoints* pts = this->Graph->GetPoints(); - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Place the vertices into a giant grid (100xNumVertices) diff --git a/Infovis/Layout/vtkConstrained2DLayoutStrategy.h b/Infovis/Layout/vtkConstrained2DLayoutStrategy.h index 8bf16f9c813..dd605e5492c 100644 --- a/Infovis/Layout/vtkConstrained2DLayoutStrategy.h +++ b/Infovis/Layout/vtkConstrained2DLayoutStrategy.h @@ -138,8 +138,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkConstrained2DLayoutStrategy : public vtkGraphLa private: - //BTX - // An edge consists of two vertices joined together. // This struct acts as a "pointer" to those two vertices. typedef struct @@ -154,7 +152,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkConstrained2DLayoutStrategy : public vtkGraphLa vtkSmartPointer SplatImage; vtkSmartPointer RepulsionArray; vtkSmartPointer AttractionArray; - //ETX vtkLayoutEdge *EdgeArray; diff --git a/Infovis/Layout/vtkCosmicTreeLayoutStrategy.cxx b/Infovis/Layout/vtkCosmicTreeLayoutStrategy.cxx index ca9bcf387a8..e8f579d7659 100644 --- a/Infovis/Layout/vtkCosmicTreeLayoutStrategy.cxx +++ b/Infovis/Layout/vtkCosmicTreeLayoutStrategy.cxx @@ -330,7 +330,7 @@ void vtkCosmicTreeLayoutStrategy::Layout() scale = this->CreateScaleFactors( numVertices ); this->Graph->GetVertexData()->AddArray( scale ); scale->Delete(); - radii = vtkDoubleArray::SafeDownCast( inputRadii ); + radii = vtkArrayDownCast( inputRadii ); // Did we find a node size spec? if ( radii ) { @@ -396,7 +396,7 @@ void vtkCosmicTreeLayoutStrategy::Layout() { reordered->SetPoint( i, 0, 0, 0 ); } - vtkIdTypeArray* graphVertexIdArr = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* graphVertexIdArr = vtkArrayDownCast( tree->GetVertexData()->GetAbstractArray( "GraphVertexId" ) ); for ( vtkIdType i = 0; i < graphVertexIdArr->GetNumberOfTuples(); ++ i ) { diff --git a/Infovis/Layout/vtkCosmicTreeLayoutStrategy.h b/Infovis/Layout/vtkCosmicTreeLayoutStrategy.h index 76ba3e269d4..501b293a682 100644 --- a/Infovis/Layout/vtkCosmicTreeLayoutStrategy.h +++ b/Infovis/Layout/vtkCosmicTreeLayoutStrategy.h @@ -88,7 +88,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkCosmicTreeLayoutStrategy : public vtkGraphLayou protected: - //BTX /// How are node sizes specified? enum RadiusMode { @@ -96,12 +95,10 @@ class VTKINFOVISLAYOUT_EXPORT vtkCosmicTreeLayoutStrategy : public vtkGraphLayou LEAVES, //!< Only leaf node sizes specified... parents are calculated during layout. ALL //!< All node sizes specified (overconstrained, so a scale factor for each parent is calculated during layout). }; - //ETX vtkCosmicTreeLayoutStrategy(); virtual ~vtkCosmicTreeLayoutStrategy(); - //BTX // Description: // Recursive routine used to lay out tree nodes. Called from Layout(). void LayoutChildren( @@ -116,7 +113,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkCosmicTreeLayoutStrategy : public vtkGraphLayou void OffsetChildren( vtkTree* tree, vtkPoints* pts, vtkDoubleArray* radii, vtkDoubleArray* scale, double parent[4], vtkIdType root, int depth, RadiusMode mode ); - //ETX // Description: // Create an array to hold radii, named appropriately (depends on \a NodeSizeArrayName) diff --git a/Infovis/Layout/vtkFast2DLayoutStrategy.cxx b/Infovis/Layout/vtkFast2DLayoutStrategy.cxx index 4d642ca667d..e15323c4a09 100644 --- a/Infovis/Layout/vtkFast2DLayoutStrategy.cxx +++ b/Infovis/Layout/vtkFast2DLayoutStrategy.cxx @@ -166,7 +166,7 @@ void vtkFast2DLayoutStrategy::Initialize() } // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Avoid divide by zero @@ -214,7 +214,7 @@ void vtkFast2DLayoutStrategy::Initialize() double weight, maxWeight = 1; if (this->WeightEdges && this->EdgeWeightField != NULL) { - weightArray = vtkDataArray::SafeDownCast(this->Graph->GetEdgeData()->GetAbstractArray(this->EdgeWeightField)); + weightArray = vtkArrayDownCast(this->Graph->GetEdgeData()->GetAbstractArray(this->EdgeWeightField)); if (weightArray != NULL) { for (vtkIdType w = 0; w < weightArray->GetNumberOfTuples(); w++) @@ -292,7 +292,7 @@ void vtkFast2DLayoutStrategy::Layout() vtkIdType numEdges = this->Graph->GetNumberOfEdges(); // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // This is the mega, uber, triple inner loop @@ -471,7 +471,7 @@ void vtkFast2DLayoutStrategy::ResolveCoincidentVertices() // Get a quick pointer to the point data vtkPoints* pts = this->Graph->GetPoints(); - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Place the vertices into a giant grid (100xNumVertices) diff --git a/Infovis/Layout/vtkFast2DLayoutStrategy.h b/Infovis/Layout/vtkFast2DLayoutStrategy.h index 26ef5ddec7c..71a070ab069 100644 --- a/Infovis/Layout/vtkFast2DLayoutStrategy.h +++ b/Infovis/Layout/vtkFast2DLayoutStrategy.h @@ -126,8 +126,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkFast2DLayoutStrategy : public vtkGraphLayoutStr private: - //BTX - // An edge consists of two vertices joined together. // This struct acts as a "pointer" to those two vertices. typedef struct @@ -143,7 +141,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkFast2DLayoutStrategy : public vtkGraphLayoutStr vtkSmartPointer SplatImage; vtkSmartPointer RepulsionArray; vtkSmartPointer AttractionArray; - //ETX vtkLayoutEdge *EdgeArray; diff --git a/Infovis/Layout/vtkForceDirectedLayoutStrategy.h b/Infovis/Layout/vtkForceDirectedLayoutStrategy.h index ad86f4d4c0d..3b967872b51 100644 --- a/Infovis/Layout/vtkForceDirectedLayoutStrategy.h +++ b/Infovis/Layout/vtkForceDirectedLayoutStrategy.h @@ -139,7 +139,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkForceDirectedLayoutStrategy : public vtkGraphLa int RandomInitialPoints; //Boolean for having random points private: - //BTX // A vertex contains a position and a displacement. typedef struct { @@ -154,7 +153,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkForceDirectedLayoutStrategy : public vtkGraphLa int t; int u; } vtkLayoutEdge; - //ETX int RandomSeed; int IterationsPerLayout; diff --git a/Infovis/Layout/vtkIncrementalForceLayout.cxx b/Infovis/Layout/vtkIncrementalForceLayout.cxx index f681f6ab54b..8d5030b0b7d 100644 --- a/Infovis/Layout/vtkIncrementalForceLayout.cxx +++ b/Infovis/Layout/vtkIncrementalForceLayout.cxx @@ -253,7 +253,7 @@ void vtkIncrementalForceLayout::UpdatePositions() vtkIdType numVerts = this->Graph->GetNumberOfVertices(); vtkIdType numEdges = this->Graph->GetNumberOfEdges(); - this->Impl->Position = vtkFloatArray::SafeDownCast(this->Graph->GetPoints()->GetData())->GetPointer(0); + this->Impl->Position = vtkArrayDownCast(this->Graph->GetPoints()->GetData())->GetPointer(0); while (numVerts >= static_cast(this->Impl->LastPosition.size())) { this->Impl->LastPosition.push_back(vtkVector2f(0.0f, 0.0f)); diff --git a/Infovis/Layout/vtkIncrementalForceLayout.h b/Infovis/Layout/vtkIncrementalForceLayout.h index cd5167d4e16..8a674a9221c 100644 --- a/Infovis/Layout/vtkIncrementalForceLayout.h +++ b/Infovis/Layout/vtkIncrementalForceLayout.h @@ -92,7 +92,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkIncrementalForceLayout : public vtkObject vtkSetMacro(Friction, float); vtkGetMacro(Friction, float); -//BTX // Description: // Set the gravity point where all vertices will migrate. Generally this // should be set to the location in the center of the scene. @@ -101,7 +100,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkIncrementalForceLayout : public vtkObject { this->GravityPoint = point; } virtual vtkVector2f GetGravityPoint() { return this->GravityPoint; } -//ETX // Description: // Perform one iteration of the force-directed layout. diff --git a/Infovis/Layout/vtkKCoreLayout.cxx b/Infovis/Layout/vtkKCoreLayout.cxx index 6fd3f8a36c5..508a77c4e96 100644 --- a/Infovis/Layout/vtkKCoreLayout.cxx +++ b/Infovis/Layout/vtkKCoreLayout.cxx @@ -186,7 +186,7 @@ int vtkKCoreLayout::RequestData(vtkInformation* vtkNotUsed(request), // Get the kcore attribute array vtkIntArray * kcore_array = NULL; - kcore_array = vtkIntArray::SafeDownCast(output->GetVertexData()->GetArray(this->KCoreLabelArrayName)); + kcore_array = vtkArrayDownCast(output->GetVertexData()->GetArray(this->KCoreLabelArrayName)); if(!kcore_array) { diff --git a/Infovis/Layout/vtkSimple2DLayoutStrategy.cxx b/Infovis/Layout/vtkSimple2DLayoutStrategy.cxx index b8899487aab..42e224f37e9 100644 --- a/Infovis/Layout/vtkSimple2DLayoutStrategy.cxx +++ b/Infovis/Layout/vtkSimple2DLayoutStrategy.cxx @@ -99,7 +99,7 @@ void vtkSimple2DLayoutStrategy::Initialize() } // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // Avoid divide by zero @@ -152,7 +152,7 @@ void vtkSimple2DLayoutStrategy::Initialize() double weight, maxWeight = 1; if (this->WeightEdges && this->EdgeWeightField != NULL) { - weightArray = vtkDataArray::SafeDownCast(this->Graph->GetEdgeData()->GetAbstractArray(this->EdgeWeightField)); + weightArray = vtkArrayDownCast(this->Graph->GetEdgeData()->GetAbstractArray(this->EdgeWeightField)); if (weightArray != NULL) { for (vtkIdType w = 0; w < weightArray->GetNumberOfTuples(); w++) @@ -212,7 +212,7 @@ void vtkSimple2DLayoutStrategy::Layout() vtkIdType numEdges = this->Graph->GetNumberOfEdges(); // Get a quick pointer to the point data - vtkFloatArray *array = vtkFloatArray::SafeDownCast(pts->GetData()); + vtkFloatArray *array = vtkArrayDownCast(pts->GetData()); float *rawPointData = array->GetPointer(0); // This is the mega, uber, triple inner loop diff --git a/Infovis/Layout/vtkSimple2DLayoutStrategy.h b/Infovis/Layout/vtkSimple2DLayoutStrategy.h index b8b9428c7f0..f0aeffb4793 100644 --- a/Infovis/Layout/vtkSimple2DLayoutStrategy.h +++ b/Infovis/Layout/vtkSimple2DLayoutStrategy.h @@ -132,7 +132,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkSimple2DLayoutStrategy : public vtkGraphLayoutS private: - //BTX // An edge consists of two vertices joined together. // This struct acts as a "pointer" to those two vertices. typedef struct @@ -146,7 +145,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkSimple2DLayoutStrategy : public vtkGraphLayoutS vtkFloatArray *RepulsionArray; vtkFloatArray *AttractionArray; vtkLayoutEdge *EdgeArray; - //ETX int RandomSeed; int IterationsPerLayout; diff --git a/Infovis/Layout/vtkSimple3DCirclesStrategy.h b/Infovis/Layout/vtkSimple3DCirclesStrategy.h index d63df067f16..ef6bab5a70a 100644 --- a/Infovis/Layout/vtkSimple3DCirclesStrategy.h +++ b/Infovis/Layout/vtkSimple3DCirclesStrategy.h @@ -53,12 +53,11 @@ class VTKINFOVISLAYOUT_EXPORT vtkSimple3DCirclesStrategy : public vtkGraphLayout vtkTypeMacro(vtkSimple3DCirclesStrategy,vtkGraphLayoutStrategy); void PrintSelf( ostream& os, vtkIndent indent ); -//BTX enum { FixedRadiusMethod = 0, FixedDistanceMethod = 1 }; -//ETX + // Description: // Set or get cicrle generating method (FixedRadiusMethod/FixedDistanceMethod). Default is FixedRadiusMethod. vtkSetMacro(Method,int); @@ -131,7 +130,7 @@ class VTKINFOVISLAYOUT_EXPORT vtkSimple3DCirclesStrategy : public vtkGraphLayout // Set graph (warning: HierarchicalOrder and HierarchicalLayers will set to zero. These reference counts will be decreased!) virtual void SetGraph( vtkGraph * graph ); protected: -//BTX + vtkSimple3DCirclesStrategy( void ); virtual ~vtkSimple3DCirclesStrategy( void ); @@ -150,9 +149,9 @@ class VTKINFOVISLAYOUT_EXPORT vtkSimple3DCirclesStrategy : public vtkGraphLayout vtkIntArray * HierarchicalLayers; vtkIdTypeArray * HierarchicalOrder; -//ETX + private: -//BTX + // Description: // Search and fill in target all zero input degree vertices where the output degree is more than zero. The finded vertices hierarchical // layer ID will be zero. @@ -165,7 +164,6 @@ class VTKINFOVISLAYOUT_EXPORT vtkSimple3DCirclesStrategy : public vtkGraphLayout virtual void BuildPointOrder( vtkDirectedGraph * input, vtkSimple3DCirclesStrategyInternal *source, vtkSimple3DCirclesStrategyInternal *StandAlones, vtkIntArray * layers, vtkIdTypeArray * order ); double T[3][3]; -//ETX vtkSimple3DCirclesStrategy(const vtkSimple3DCirclesStrategy&); // Not implemented. void operator=(const vtkSimple3DCirclesStrategy&); // Not implemented. diff --git a/Infovis/Layout/vtkSplineGraphEdges.h b/Infovis/Layout/vtkSplineGraphEdges.h index ea466811cbe..33b0e99cbd2 100644 --- a/Infovis/Layout/vtkSplineGraphEdges.h +++ b/Infovis/Layout/vtkSplineGraphEdges.h @@ -45,13 +45,11 @@ class VTKINFOVISLAYOUT_EXPORT vtkSplineGraphEdges : public vtkGraphAlgorithm virtual void SetSpline(vtkSpline* s); vtkGetObjectMacro(Spline, vtkSpline); - //BTX enum { BSPLINE = 0, CUSTOM }; - //ETX // Description: // Spline type used by the filter. @@ -83,11 +81,9 @@ class VTKINFOVISLAYOUT_EXPORT vtkSplineGraphEdges : public vtkGraphAlgorithm int SplineType; - //BTX vtkSmartPointer XSpline; vtkSmartPointer YSpline; vtkSmartPointer ZSpline; - //ETX vtkIdType NumberOfSubdivisions; diff --git a/Infovis/Layout/vtkStackedTreeLayoutStrategy.cxx b/Infovis/Layout/vtkStackedTreeLayoutStrategy.cxx index 1d3172553a6..fa024d1ec37 100644 --- a/Infovis/Layout/vtkStackedTreeLayoutStrategy.cxx +++ b/Infovis/Layout/vtkStackedTreeLayoutStrategy.cxx @@ -107,7 +107,7 @@ void vtkStackedTreeLayoutStrategy::Layout(vtkTree* inputTree, levelFilter->Update(); vtkTree* levelTree = levelFilter->GetOutput(); - vtkIntArray *levelArray = vtkIntArray::SafeDownCast( + vtkIntArray *levelArray = vtkArrayDownCast( levelTree->GetVertexData()->GetAbstractArray("level")); int max_level = 0; for( int i = 0; i < levelTree->GetNumberOfVertices(); i++ ) @@ -231,7 +231,7 @@ void vtkStackedTreeLayoutStrategy::LayoutEdgePoints( vtkTree* levelTree = levelFilter->GetOutput(); outputTree->ShallowCopy( levelTree ); - vtkIntArray* levelArray = vtkIntArray::SafeDownCast( + vtkIntArray* levelArray = vtkArrayDownCast( levelTree->GetVertexData()->GetAbstractArray("level")); double exteriorRadius = VTK_DOUBLE_MAX; @@ -482,10 +482,10 @@ vtkIdType vtkStackedTreeLayoutStrategy::FindVertex( { return vertex; } - vtkFloatArray *boundsInfo = vtkFloatArray::SafeDownCast(array); + vtkFloatArray *boundsInfo = vtkArrayDownCast(array); // Now try to find the vertex that contains the point - boundsInfo->GetTupleValue(vertex, blimits); // Get the extents of the root + boundsInfo->GetTypedTuple(vertex, blimits); // Get the extents of the root if( ((pnt[1] > blimits[2]) && (pnt[1] < blimits[3])) && ((pnt[0] > blimits[0]) && (pnt[0] < blimits[1])) ) { @@ -503,7 +503,7 @@ vtkIdType vtkStackedTreeLayoutStrategy::FindVertex( while (it->HasNext()) { child = it->Next(); - boundsInfo->GetTupleValue(child, blimits); // Get the extents of the child + boundsInfo->GetTypedTuple(child, blimits); // Get the extents of the child bool beyond_radial_bounds = false; bool beyond_angle_bounds = false; if( (pnt[1] < blimits[2]) || (pnt[1] > blimits[3])) @@ -534,10 +534,10 @@ vtkIdType vtkStackedTreeLayoutStrategy::FindVertex( { return vertex; } - vtkFloatArray *boundsInfo = vtkFloatArray::SafeDownCast(array); + vtkFloatArray *boundsInfo = vtkArrayDownCast(array); // Now try to find the vertex that contains the point - boundsInfo->GetTupleValue(vertex, blimits); // Get the extents of the root + boundsInfo->GetTypedTuple(vertex, blimits); // Get the extents of the root if( ((polar_location[0] > blimits[2]) && (polar_location[0] < blimits[3])) && ((polar_location[1] > blimits[0]) && (polar_location[1] < blimits[1])) ) { @@ -564,7 +564,7 @@ vtkIdType vtkStackedTreeLayoutStrategy::FindVertex( { continue; } - boundsInfo->GetTupleValue(child, blimits); // Get the extents of the child + boundsInfo->GetTypedTuple(child, blimits); // Get the extents of the child // the range checking below doesn't work if either or both of blimits > 360 if ((blimits[0] > 360.0) && (blimits[1] > 360.0)) diff --git a/Infovis/Layout/vtkTreeLayoutStrategy.cxx b/Infovis/Layout/vtkTreeLayoutStrategy.cxx index 675c097b165..db518896e6d 100644 --- a/Infovis/Layout/vtkTreeLayoutStrategy.cxx +++ b/Infovis/Layout/vtkTreeLayoutStrategy.cxx @@ -113,7 +113,7 @@ void vtkTreeLayoutStrategy::Layout() vtkErrorMacro("Distance array not found."); return; } - distanceArr = vtkDataArray::SafeDownCast(aa); + distanceArr = vtkArrayDownCast(aa); if (!distanceArr) { vtkErrorMacro("Distance array must be a data array."); @@ -370,7 +370,7 @@ void vtkTreeLayoutStrategy::Layout() { reordered->SetPoint(i, 0, 0, 0); } - vtkIdTypeArray* graphVertexIdArr = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* graphVertexIdArr = vtkArrayDownCast( tree->GetVertexData()->GetAbstractArray("GraphVertexId")); for (vtkIdType i = 0; i < graphVertexIdArr->GetNumberOfTuples(); i++) { diff --git a/Infovis/Layout/vtkTreeMapLayout.cxx b/Infovis/Layout/vtkTreeMapLayout.cxx index bba5246f228..58245af2bc6 100644 --- a/Infovis/Layout/vtkTreeMapLayout.cxx +++ b/Infovis/Layout/vtkTreeMapLayout.cxx @@ -139,9 +139,9 @@ vtkIdType vtkTreeMapLayout::FindVertex(float pnt[2], float *binfo) float blimits[4]; vtkIdType vertex = otree->GetRoot(); - vtkFloatArray *boxInfo = vtkFloatArray::SafeDownCast(array); + vtkFloatArray *boxInfo = vtkArrayDownCast(array); // Now try to find the vertex that contains the point - boxInfo->GetTupleValue(vertex, blimits); // Get the extents of the root + boxInfo->GetTypedTuple(vertex, blimits); // Get the extents of the root if ((pnt[0] < blimits[0]) || (pnt[0] > blimits[1]) || (pnt[1] < blimits[2]) || (pnt[1] > blimits[3])) { @@ -165,7 +165,7 @@ vtkIdType vtkTreeMapLayout::FindVertex(float pnt[2], float *binfo) while (it->HasNext()) { child = it->Next(); - boxInfo->GetTupleValue(child, blimits); // Get the extents of the child + boxInfo->GetTypedTuple(child, blimits); // Get the extents of the child if ((pnt[0] < blimits[0]) || (pnt[0] > blimits[1]) || (pnt[1] < blimits[2]) || (pnt[1] > blimits[3])) { @@ -200,8 +200,8 @@ void vtkTreeMapLayout::GetBoundingBox(vtkIdType id, float *binfo) return; } - vtkFloatArray *boxInfo = vtkFloatArray::SafeDownCast(array); - boxInfo->GetTupleValue(id, binfo); + vtkFloatArray *boxInfo = vtkArrayDownCast(array); + boxInfo->GetTypedTuple(id, binfo); } unsigned long vtkTreeMapLayout::GetMTime() diff --git a/Infovis/Layout/vtkTreeMapLayoutStrategy.cxx b/Infovis/Layout/vtkTreeMapLayoutStrategy.cxx index 6fe772f9c24..8128ff3fb4e 100644 --- a/Infovis/Layout/vtkTreeMapLayoutStrategy.cxx +++ b/Infovis/Layout/vtkTreeMapLayoutStrategy.cxx @@ -56,9 +56,9 @@ vtkIdType vtkTreeMapLayoutStrategy::FindVertex( float blimits[4]; vtkIdType vertex = otree->GetRoot(); - vtkFloatArray *boxInfo = vtkFloatArray::SafeDownCast(array); + vtkFloatArray *boxInfo = vtkArrayDownCast(array); // Now try to find the vertex that contains the point - boxInfo->GetTupleValue(vertex, blimits); // Get the extents of the root + boxInfo->GetTypedTuple(vertex, blimits); // Get the extents of the root if ((pnt[0] < blimits[0]) || (pnt[0] > blimits[1]) || (pnt[1] < blimits[2]) || (pnt[1] > blimits[3])) { @@ -84,7 +84,7 @@ vtkIdType vtkTreeMapLayoutStrategy::FindVertex( while (it->HasNext()) { child = it->Next(); - boxInfo->GetTupleValue(child, blimits); // Get the extents of the child + boxInfo->GetTypedTuple(child, blimits); // Get the extents of the child if ((pnt[0] < blimits[0]) || (pnt[0] > blimits[1]) || (pnt[1] < blimits[2]) || (pnt[1] > blimits[3])) { diff --git a/Infovis/Layout/vtkTreeOrbitLayoutStrategy.cxx b/Infovis/Layout/vtkTreeOrbitLayoutStrategy.cxx index 7bf1c99de53..dae1f9d6b56 100644 --- a/Infovis/Layout/vtkTreeOrbitLayoutStrategy.cxx +++ b/Infovis/Layout/vtkTreeOrbitLayoutStrategy.cxx @@ -63,7 +63,7 @@ void vtkTreeOrbitLayoutStrategy::OrbitChildren(vtkTree *t, yCenter = pt[1]; // Check for leaf_count array - vtkIntArray* leaf_count = vtkIntArray::SafeDownCast( + vtkIntArray* leaf_count = vtkArrayDownCast( t->GetVertexData()->GetArray("leaf_count")); if (!leaf_count) { @@ -171,7 +171,7 @@ void vtkTreeOrbitLayoutStrategy::Layout() { reordered->SetPoint(i, 0, 0, 0); } - vtkIdTypeArray* graphVertexIdArr = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* graphVertexIdArr = vtkArrayDownCast( tree->GetVertexData()->GetAbstractArray("GraphVertexId")); for (vtkIdType i = 0; i < graphVertexIdArr->GetNumberOfTuples(); i++) { diff --git a/Infovis/Parallel/Testing/Cxx/TestPBGLAlgorithms.cxx b/Infovis/Parallel/Testing/Cxx/TestPBGLAlgorithms.cxx index 6f18d3ea506..ded44e6ca45 100644 --- a/Infovis/Parallel/Testing/Cxx/TestPBGLAlgorithms.cxx +++ b/Infovis/Parallel/Testing/Cxx/TestPBGLAlgorithms.cxx @@ -152,7 +152,7 @@ void TestDirectedGraph() graph = vtkMutableDirectedGraph::SafeDownCast(bfs->GetOutput()); int index; vtkIntArray *distArray - = vtkIntArray::SafeDownCast(graph->GetVertexData()->GetArray("BFS", index)); + = vtkArrayDownCast(graph->GetVertexData()->GetArray("BFS", index)); assert(distArray); for (vtkIdType i = 0; i < verticesPerNode; ++i) { @@ -279,7 +279,7 @@ void TestUndirectedGraph() graph = vtkMutableUndirectedGraph::SafeDownCast(bfs->GetOutput()); int index; vtkIntArray *distArray - = vtkIntArray::SafeDownCast(graph->GetVertexData()->GetArray("BFS", index)); + = vtkArrayDownCast(graph->GetVertexData()->GetArray("BFS", index)); assert(distArray); for (vtkIdType i = 0; i < verticesPerNode; ++i) { diff --git a/Infovis/Parallel/Testing/Cxx/TestPBGLCollapseGraph.cxx b/Infovis/Parallel/Testing/Cxx/TestPBGLCollapseGraph.cxx index b44755d1da5..5366c94e2b9 100644 --- a/Infovis/Parallel/Testing/Cxx/TestPBGLCollapseGraph.cxx +++ b/Infovis/Parallel/Testing/Cxx/TestPBGLCollapseGraph.cxx @@ -119,7 +119,7 @@ void TestPSQLGraphReader() // Display the output vtkGraph* output = collapse->GetOutput(); - vtkAbstractArray* colorArr = vtkAbstractArray::SafeDownCast(output->GetVertexData()->GetAbstractArray("color")); + vtkAbstractArray* colorArr = vtkArrayDownCast(output->GetVertexData()->GetAbstractArray("color")); vtkSmartPointer vit = vtkSmartPointer::New(); output->GetVertices(vit); diff --git a/Infovis/Parallel/Testing/Cxx/TestPBGLEdgesPedigrees.cxx b/Infovis/Parallel/Testing/Cxx/TestPBGLEdgesPedigrees.cxx index 5630dad418c..650379f536f 100644 --- a/Infovis/Parallel/Testing/Cxx/TestPBGLEdgesPedigrees.cxx +++ b/Infovis/Parallel/Testing/Cxx/TestPBGLEdgesPedigrees.cxx @@ -102,7 +102,7 @@ void UseCase3() vtkIdType vtx = vit->Next(); int idx = mdg->GetDistributedGraphHelper()->GetVertexIndex(vtx); - vtkVariant ped = vtkVariantArray::SafeDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); + vtkVariant ped = vtkArrayDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); cout <<" Rank #" << myRank << ": vertex " << ped.ToString() << " (" << hex << vtx << ")" << " owner="<GetDistributedGraphHelper()->GetVertexOwner(vtx)<< ", " @@ -111,7 +111,7 @@ void UseCase3() cout << myRank<<") "<<" GetNumberOfArrays= " << mdg->GetVertexData()->GetNumberOfArrays() << endl; for (int iprop=0; ipropGetVertexData()->GetAbstractArray(iprop)); + vtkAbstractArray* aa = vtkArrayDownCast(mdg->GetVertexData()->GetAbstractArray(iprop)); // int idx = helper->GetVertexIndex(vtx); cout << " idx="<GetVariantValue(idx).ToString() <GetProcessGroup()); reader->Update(rank, total, 0); vtkGraph* output = reader->GetOutput(); - vtkAbstractArray* idArr = vtkAbstractArray::SafeDownCast(output->GetVertexData()->GetAbstractArray("id")); - vtkStringArray* nameArr = vtkStringArray::SafeDownCast(output->GetVertexData()->GetAbstractArray("name")); + vtkAbstractArray* idArr = vtkArrayDownCast(output->GetVertexData()->GetAbstractArray("id")); + vtkStringArray* nameArr = vtkArrayDownCast(output->GetVertexData()->GetAbstractArray("name")); vtkSmartPointer vit = vtkSmartPointer::New(); output->GetVertices(vit); @@ -123,7 +123,7 @@ void TestPSQLGraphReader() << "," << name << "," << id << endl; } - nameArr = vtkStringArray::SafeDownCast(output->GetEdgeData()->GetAbstractArray("name")); + nameArr = vtkArrayDownCast(output->GetEdgeData()->GetAbstractArray("name")); vtkSmartPointer it = vtkSmartPointer::New(); output->GetEdges(it); diff --git a/Infovis/Parallel/Testing/Cxx/TestPBGLPedigrees.cxx b/Infovis/Parallel/Testing/Cxx/TestPBGLPedigrees.cxx index 29ecf9d0242..6f9b9813812 100644 --- a/Infovis/Parallel/Testing/Cxx/TestPBGLPedigrees.cxx +++ b/Infovis/Parallel/Testing/Cxx/TestPBGLPedigrees.cxx @@ -149,7 +149,7 @@ void UseCase0() while (vit->HasNext()) { vtkIdType vtx = vit->Next(); - vtkVariant ped = vtkVariantArray::SafeDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); + vtkVariant ped = vtkArrayDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); cout << " ======Rank " << myRank << ": vertex " << ped.ToString() << " (" << hex << vtx << ")" << " owner="<GetDistributedGraphHelper()->GetVertexOwner(vtx)<< ", " << " index="<GetDistributedGraphHelper()->GetVertexIndex(vtx) << endl; @@ -252,7 +252,7 @@ void UseCase1() while (vit->HasNext()) { vtkIdType vtx = vit->Next(); - vtkVariant ped = vtkVariantArray::SafeDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); + vtkVariant ped = vtkArrayDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); cout << " ======Rank " << myRank << ": vertex " << ped.ToString() << " (" << hex << vtx << ")" << " owner="<GetDistributedGraphHelper()->GetVertexOwner(vtx)<< ", " << " index="<GetDistributedGraphHelper()->GetVertexIndex(vtx) << endl; @@ -410,7 +410,7 @@ void UseCase2() vtkIdType vtx = vit->Next(); int idx = mdg->GetDistributedGraphHelper()->GetVertexIndex(vtx); - vtkVariant ped = vtkVariantArray::SafeDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); + vtkVariant ped = vtkArrayDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); cout << " Rank #" << myRank << ": vertex " << ped.ToString() << " (" << hex << vtx << ")" << " owner="<GetDistributedGraphHelper()->GetVertexOwner(vtx)<< ", " @@ -419,7 +419,7 @@ void UseCase2() cout << myRank<<") GetNumberOfArrays= " << mdg->GetVertexData()->GetNumberOfArrays() << endl; for (int iprop=0; ipropGetVertexData()->GetAbstractArray(iprop)); + vtkAbstractArray* aa = vtkArrayDownCast(mdg->GetVertexData()->GetAbstractArray(iprop)); // int idx = helper->GetVertexIndex(vtx); cout << " idx="<GetVariantValue(idx).ToString() <Next(); int idx = mdg->GetDistributedGraphHelper()->GetVertexIndex(vtx); - vtkVariant ped = vtkVariantArray::SafeDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); + vtkVariant ped = vtkArrayDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); cout << " Rank #" << myRank << ": vertex " << ped.ToString() << " (" << hex << vtx << ")" << " owner="<GetDistributedGraphHelper()->GetVertexOwner(vtx)<< ", " @@ -478,7 +478,7 @@ void UseCase2() cout << myRank<<") GetNumberOfArrays= " << mdg->GetVertexData()->GetNumberOfArrays() << endl; for (int iprop=0; ipropGetVertexData()->GetAbstractArray(iprop)); + vtkAbstractArray* aa = vtkArrayDownCast(mdg->GetVertexData()->GetAbstractArray(iprop)); // int idx = helper->GetVertexIndex(vtx); cout << " idx="<GetVariantValue(idx).ToString() <Next(); int idx = mdg->GetDistributedGraphHelper()->GetVertexIndex(vtx); - vtkVariant ped = vtkVariantArray::SafeDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); + vtkVariant ped = vtkArrayDownCast(peds)->GetValue(helper->GetVertexIndex(vtx)); cout <<" Rank #" << myRank << ": vertex " << ped.ToString() << " (" << hex << vtx << ")" << " owner="<GetDistributedGraphHelper()->GetVertexOwner(vtx)<< ", " @@ -557,7 +557,7 @@ void UseCase3() cout << myRank<<") "<<" GetNumberOfArrays= " << mdg->GetVertexData()->GetNumberOfArrays() << endl; for (int iprop=0; ipropGetVertexData()->GetAbstractArray(iprop)); + vtkAbstractArray* aa = vtkArrayDownCast(mdg->GetVertexData()->GetAbstractArray(iprop)); // int idx = helper->GetVertexIndex(vtx); cout << " idx="<GetVariantValue(idx).ToString() <GetVertexData()->GetArray("myPeds", &pedIdx); cout << " pedIdx= "<GetVertexData()->GetAbstractArray("labels")); + vtkStringArray *charArr = vtkArrayDownCast(mdg->GetVertexData()->GetAbstractArray("labels")); cout << " yes, we got --labels--\n"; // cout << " --labels-- array= " << *charArr <GetVertexData()->GetAbstractArray("myPeds")); + vtkVariantArray *pedArr = vtkArrayDownCast(mdg->GetVertexData()->GetAbstractArray("myPeds")); cout << " yes, we got --myPeds--\n"; // cout << " --myPeds-- array= " << *pedArr <::type pathLengthMap = MakeDistributedVertexPropertyMap(output, pathLengthArray); diff --git a/Infovis/Parallel/Testing/Cxx/TestPRandomGraphSource.cxx b/Infovis/Parallel/Testing/Cxx/TestPRandomGraphSource.cxx index e5416ac07f3..c7d67c5b2f8 100644 --- a/Infovis/Parallel/Testing/Cxx/TestPRandomGraphSource.cxx +++ b/Infovis/Parallel/Testing/Cxx/TestPRandomGraphSource.cxx @@ -263,7 +263,7 @@ int TestPRandomGraphSource(int argc, char* argv[]) // Turn the color array into a property map vtkIdTypeArray* colorArray - = vtkIdTypeArray::SafeDownCast + = vtkArrayDownCast (output->GetVertexData()->GetAbstractArray("Color")); vtkDistributedVertexPropertyMapType::type colorMap = MakeDistributedVertexPropertyMap(output, colorArray); @@ -332,7 +332,7 @@ int TestPRandomGraphSource(int argc, char* argv[]) // Turn the component array into a property map vtkIdTypeArray* componentArray - = vtkIdTypeArray::SafeDownCast + = vtkArrayDownCast (output->GetVertexData()->GetAbstractArray("Component")); vtkDistributedVertexPropertyMapType::type componentMap = MakeDistributedVertexPropertyMap(output, componentArray); diff --git a/Infovis/Parallel/vtkPBGLBreadthFirstSearch.cxx b/Infovis/Parallel/vtkPBGLBreadthFirstSearch.cxx index 5733fc22bb5..9d4031dfcfb 100644 --- a/Infovis/Parallel/vtkPBGLBreadthFirstSearch.cxx +++ b/Infovis/Parallel/vtkPBGLBreadthFirstSearch.cxx @@ -197,7 +197,7 @@ vtkIdType vtkPBGLBreadthFirstSearch::GetVertexIndex( // Okay now what type of array is it if (abstract->IsNumeric()) { - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstract); + vtkDataArray *dataArray = vtkArrayDownCast(abstract); int intValue = value.ToInt(); for(int i=0; iGetNumberOfTuples(); ++i) { @@ -209,7 +209,7 @@ vtkIdType vtkPBGLBreadthFirstSearch::GetVertexIndex( } else { - vtkStringArray *stringArray = vtkStringArray::SafeDownCast(abstract); + vtkStringArray *stringArray = vtkArrayDownCast(abstract); vtkStdString stringValue(value.ToString()); for(int i=0; iGetNumberOfTuples(); ++i) { diff --git a/Infovis/Parallel/vtkPBGLCollapseGraph.cxx b/Infovis/Parallel/vtkPBGLCollapseGraph.cxx index c301a4ac504..d5ef2bc7429 100644 --- a/Infovis/Parallel/vtkPBGLCollapseGraph.cxx +++ b/Infovis/Parallel/vtkPBGLCollapseGraph.cxx @@ -87,7 +87,7 @@ int vtkPBGLCollapseGraphRequestData( typedef vtkDistributedVertexPropertyMapType::type DistributedLabelMap; DistributedLabelMap distrib_input_arr - = MakeDistributedVertexPropertyMap(input, vtkAbstractArray::SafeDownCast(input_arr)); + = MakeDistributedVertexPropertyMap(input, vtkArrayDownCast(input_arr)); // Create directed or undirected graph MutableGraph* builder = MutableGraph::New(); diff --git a/Infovis/Parallel/vtkPBGLCollectGraph.cxx b/Infovis/Parallel/vtkPBGLCollectGraph.cxx index 5f6103dbe65..6308d35ef92 100644 --- a/Infovis/Parallel/vtkPBGLCollectGraph.cxx +++ b/Infovis/Parallel/vtkPBGLCollectGraph.cxx @@ -204,7 +204,7 @@ int vtkPBGLCollectGraph::RequestData( // okay for now since the GetVertexOwner() and GetVertexIndex() // methods take a vtkIdType vale. (i.e., TemplateMacro ) vtkIdTypeArray * distributedIdArray = NULL; - distributedIdArray = vtkIdTypeArray::SafeDownCast( arrays[arrayIndex]); + distributedIdArray = vtkArrayDownCast( arrays[arrayIndex]); if(distributedIdArray) { for(vtkIdType vertIndex=0; vertIndex < myNumVertices; ++vertIndex) diff --git a/Infovis/Parallel/vtkPBGLDistributedGraphHelper.cxx b/Infovis/Parallel/vtkPBGLDistributedGraphHelper.cxx index 74bbe7a9b44..b35447843a8 100644 --- a/Infovis/Parallel/vtkPBGLDistributedGraphHelper.cxx +++ b/Infovis/Parallel/vtkPBGLDistributedGraphHelper.cxx @@ -461,13 +461,13 @@ vtkPBGLDistributedGraphHelper::AddEdgeInternal(vtkIdType uDistributedId, for (int iprop=0; ipropGetAbstractArray(iprop); - if (vtkDataArray::SafeDownCast(arr)) + if (vtkArrayDownCast(arr)) { - vtkDataArray::SafeDownCast(arr)->InsertNextTuple1(propertyArr->GetPointer(iprop)->ToDouble()); + vtkArrayDownCast(arr)->InsertNextTuple1(propertyArr->GetPointer(iprop)->ToDouble()); } - else if (vtkStringArray::SafeDownCast(arr)) + else if (vtkArrayDownCast(arr)) { - vtkStringArray::SafeDownCast(arr)->InsertNextValue(propertyArr->GetPointer(iprop)->ToString()); + vtkArrayDownCast(arr)->InsertNextValue(propertyArr->GetPointer(iprop)->ToString()); } else { diff --git a/Infovis/Parallel/vtkPBGLDistributedGraphHelper.h b/Infovis/Parallel/vtkPBGLDistributedGraphHelper.h index ad67a809e55..48f337b4ab0 100644 --- a/Infovis/Parallel/vtkPBGLDistributedGraphHelper.h +++ b/Infovis/Parallel/vtkPBGLDistributedGraphHelper.h @@ -41,11 +41,9 @@ class vtkPBGLDistributedGraphHelperInternals; -//BTX namespace boost { namespace graph { namespace distributed { class mpi_process_group; } } } /// end namespace boost::graph::distributed -//ETX #if !defined(VTK_LEGACY_REMOVE) class VTKINFOVISPARALLEL_EXPORT vtkPBGLDistributedGraphHelper : public vtkDistributedGraphHelper @@ -70,11 +68,9 @@ class VTKINFOVISPARALLEL_EXPORT vtkPBGLDistributedGraphHelper : public vtkDistri // Clones this distributed graph helper. vtkDistributedGraphHelper *Clone(); - //BTX // Description: // Return the process group associated with this distributed graph. boost::graph::distributed::mpi_process_group GetProcessGroup(); - //ETX // Description: // The Parallel BGL-specific internal information for this distributed @@ -87,7 +83,6 @@ class VTKINFOVISPARALLEL_EXPORT vtkPBGLDistributedGraphHelper : public vtkDistri vtkPBGLDistributedGraphHelper(); ~vtkPBGLDistributedGraphHelper(); - //BTX enum Tags { // Find a vertex by pedigree ID. This always has a reply. @@ -208,15 +203,13 @@ class VTKINFOVISPARALLEL_EXPORT vtkPBGLDistributedGraphHelper : public vtkDistri // Attach this distributed graph helper to the given graph. This will // be called as part of vtkGraph::SetDistributedGraphHelper. void AttachToGraph(vtkGraph *graph); - //ETX private: vtkPBGLDistributedGraphHelper(const vtkPBGLDistributedGraphHelper&); // Not implemented void operator=(const vtkPBGLDistributedGraphHelper&); // Not implemented - //BTX friend class vtkPBGLDistributedGraphHelperInternals; - //ETX + }; #endif //VTK_LEGACY_REMOVE diff --git a/Infovis/Parallel/vtkPBGLGraphAdapter.h b/Infovis/Parallel/vtkPBGLGraphAdapter.h index 478b67f39fa..93efe33c9d0 100644 --- a/Infovis/Parallel/vtkPBGLGraphAdapter.h +++ b/Infovis/Parallel/vtkPBGLGraphAdapter.h @@ -28,7 +28,6 @@ #include "vtkBoostGraphAdapter.h" // for the sequential BGL adapters -//BTX #include // required for Boost 1.54.0 #include #include @@ -38,7 +37,6 @@ #include #include #include -//ETX #include "vtkPBGLDistributedGraphHelper.h" #include "vtkVariantBoostSerialization.h" diff --git a/Infovis/Parallel/vtkPBGLMinimumSpanningTree.cxx b/Infovis/Parallel/vtkPBGLMinimumSpanningTree.cxx index 71544aefa6b..3ac3a6f78ac 100644 --- a/Infovis/Parallel/vtkPBGLMinimumSpanningTree.cxx +++ b/Infovis/Parallel/vtkPBGLMinimumSpanningTree.cxx @@ -142,7 +142,7 @@ int vtkPBGLMinimumSpanningTree::RequestData( bool edgeWeightArrayIsTemporary = false; vtkDoubleArray *edgeWeightArray - = vtkDoubleArray::SafeDownCast(abstractEdgeWeightArray); + = vtkArrayDownCast(abstractEdgeWeightArray); if (edgeWeightArray == 0) { // Edge-weight array does not contain "double" values. We will diff --git a/Infovis/Parallel/vtkPBGLShortestPaths.cxx b/Infovis/Parallel/vtkPBGLShortestPaths.cxx index cad82a7feb5..cfcc6a59bc8 100644 --- a/Infovis/Parallel/vtkPBGLShortestPaths.cxx +++ b/Infovis/Parallel/vtkPBGLShortestPaths.cxx @@ -168,7 +168,7 @@ vtkIdType vtkPBGLShortestPaths::GetVertexIndex( // Okay now what type of array is it if (abstract->IsNumeric()) { - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstract); + vtkDataArray *dataArray = vtkArrayDownCast(abstract); int intValue = value.ToInt(); for(int i=0; iGetNumberOfTuples(); ++i) { @@ -180,7 +180,7 @@ vtkIdType vtkPBGLShortestPaths::GetVertexIndex( } else { - vtkStringArray *stringArray = vtkStringArray::SafeDownCast(abstract); + vtkStringArray *stringArray = vtkArrayDownCast(abstract); vtkStdString stringValue(value.ToString()); for(int i=0; iGetNumberOfTuples(); ++i) { @@ -290,7 +290,7 @@ int vtkPBGLShortestPaths::RequestData( return 1; } - edgeWeightArray = vtkDoubleArray::SafeDownCast(abstractEdgeWeightArray); + edgeWeightArray = vtkArrayDownCast(abstractEdgeWeightArray); if (edgeWeightArray == 0) { // Edge-weight array does not contain "double" values. We will diff --git a/Interaction/Image/vtkImageViewer2.h b/Interaction/Image/vtkImageViewer2.h index e1ce506b638..9f2b750f870 100644 --- a/Interaction/Image/vtkImageViewer2.h +++ b/Interaction/Image/vtkImageViewer2.h @@ -92,14 +92,14 @@ class VTKINTERACTIONIMAGE_EXPORT vtkImageViewer2 : public vtkObject // Description: // Set/get the slice orientation - //BTX + enum { SLICE_ORIENTATION_YZ = 0, SLICE_ORIENTATION_XZ = 1, SLICE_ORIENTATION_XY = 2 }; - //ETX + vtkGetMacro(SliceOrientation, int); virtual void SetSliceOrientation(int orientation); virtual void SetSliceOrientationToXY() diff --git a/Interaction/Image/vtkResliceImageViewer.h b/Interaction/Image/vtkResliceImageViewer.h index 586040b74d9..2ef813d102a 100644 --- a/Interaction/Image/vtkResliceImageViewer.h +++ b/Interaction/Image/vtkResliceImageViewer.h @@ -69,13 +69,12 @@ class VTKINTERACTIONIMAGE_EXPORT vtkResliceImageViewer : public vtkImageViewer2 // Description: // Set/get the slice orientation - //BTX + enum { RESLICE_AXIS_ALIGNED = 0, RESLICE_OBLIQUE = 1 }; - //ETX vtkGetMacro(ResliceMode, int); virtual void SetResliceMode(int resliceMode); diff --git a/Interaction/Style/vtkInteractorStyleFlight.h b/Interaction/Style/vtkInteractorStyleFlight.h index 01b686c6ed7..4a2a6466582 100644 --- a/Interaction/Style/vtkInteractorStyleFlight.h +++ b/Interaction/Style/vtkInteractorStyleFlight.h @@ -37,9 +37,8 @@ #include "vtkInteractorStyle.h" class vtkCamera; class vtkPerspectiveTransform; -//BTX + class CPIDControl; -//ETX class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleFlight : public vtkInteractorStyle { @@ -151,10 +150,10 @@ class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleFlight : public vtkInteractor double lYaw; double DeltaPitch; double lPitch; -//BTX + CPIDControl *PID_Yaw; CPIDControl *PID_Pitch; -//ETX + private: vtkInteractorStyleFlight(const vtkInteractorStyleFlight&); // Not implemented. void operator=(const vtkInteractorStyleFlight&); // Not implemented. diff --git a/Interaction/Style/vtkInteractorStyleImage.cxx b/Interaction/Style/vtkInteractorStyleImage.cxx index 66c127af9b7..6bdf777180a 100644 --- a/Interaction/Style/vtkInteractorStyleImage.cxx +++ b/Interaction/Style/vtkInteractorStyleImage.cxx @@ -44,6 +44,7 @@ vtkInteractorStyleImage::vtkInteractorStyleImage() this->WindowLevelInitial[1] = 0.5; // Level this->CurrentImageProperty = 0; + this->CurrentImageNumber = -1; this->InteractionMode = VTKIS_IMAGE2D; @@ -91,7 +92,7 @@ void vtkInteractorStyleImage::StartWindowLevel() this->StartState(VTKIS_WINDOW_LEVEL); // Get the last (the topmost) image - this->SetCurrentImageToNthImage(-1); + this->SetCurrentImageNumber(this->CurrentImageNumber); if (this->HandleObservers && this->HasObserver(vtkCommand::StartWindowLevelEvent)) @@ -626,8 +627,10 @@ void vtkInteractorStyleImage::SetImageOrientation( // interactor ivars from the Nth image that it finds. You can // also use negative numbers, i.e. -1 will return the last image, // -2 will return the second-to-last image, etc. -void vtkInteractorStyleImage::SetCurrentImageToNthImage(int i) +void vtkInteractorStyleImage::SetCurrentImageNumber(int i) { + this->CurrentImageNumber = i; + if (!this->CurrentRenderer) { return; @@ -648,9 +651,10 @@ void vtkInteractorStyleImage::SetCurrentImageToNthImage(int i) for (prop->InitPathTraversal(); (path = prop->GetNextPath()); ) { vtkProp *tryProp = path->GetLastNode()->GetViewProp(); - if ( (imageProp = vtkImageSlice::SafeDownCast(tryProp)) != 0 ) + imageProp = vtkImageSlice::SafeDownCast(tryProp); + if (imageProp) { - if (j == i) + if (j == i && imageProp->GetPickable()) { foundImageProp = true; break; diff --git a/Interaction/Style/vtkInteractorStyleImage.h b/Interaction/Style/vtkInteractorStyleImage.h index 9429cbec0df..bb22b1fd8a3 100644 --- a/Interaction/Style/vtkInteractorStyleImage.h +++ b/Interaction/Style/vtkInteractorStyleImage.h @@ -157,6 +157,18 @@ class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleImage : public vtkInteractorS void SetImageOrientation(const double leftToRight[3], const double bottomToTop[3]); + // Description: + // Set the image to use for WindowLevel interaction. + // Any images for which the Pickable flag is off are ignored. + // Images are counted back-to-front, so 0 is the rearmost image. + // Negative values can be used to count front-to-back, so -1 is + // the frontmost image, -2 is the image behind that one, etc. + // The default is to use the frontmost image for interaction. + // If the specified image does not exist, then no WindowLevel + // interaction will take place. + virtual void SetCurrentImageNumber(int i); + int GetCurrentImageNumber() { return this->CurrentImageNumber; } + // Description: // Get the current image property, which is set when StartWindowLevel // is called immediately before StartWindowLevelEvent is generated. @@ -169,12 +181,11 @@ class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleImage : public vtkInteractorS vtkInteractorStyleImage(); ~vtkInteractorStyleImage(); - void SetCurrentImageToNthImage(int i); - int WindowLevelStartPosition[2]; int WindowLevelCurrentPosition[2]; double WindowLevelInitial[2]; vtkImageProperty *CurrentImageProperty; + int CurrentImageNumber; int InteractionMode; double XViewRightVector[3]; diff --git a/Interaction/Style/vtkInteractorStyleMultiTouchCamera.cxx b/Interaction/Style/vtkInteractorStyleMultiTouchCamera.cxx index 2a63fd976cf..db93c1ba142 100644 --- a/Interaction/Style/vtkInteractorStyleMultiTouchCamera.cxx +++ b/Interaction/Style/vtkInteractorStyleMultiTouchCamera.cxx @@ -27,12 +27,6 @@ vtkStandardNewMacro(vtkInteractorStyleMultiTouchCamera); //---------------------------------------------------------------------------- vtkInteractorStyleMultiTouchCamera::vtkInteractorStyleMultiTouchCamera() { - this->MotionFactor = 10.0; - this->PointersDownCount = 0; - for (int i = 0; i < VTKI_MAX_POINTERS; ++i) - { - this->PointersDown[i] = 0; - } } //---------------------------------------------------------------------------- @@ -41,215 +35,79 @@ vtkInteractorStyleMultiTouchCamera::~vtkInteractorStyleMultiTouchCamera() } //---------------------------------------------------------------------------- -void vtkInteractorStyleMultiTouchCamera::OnMouseMove() +void vtkInteractorStyleMultiTouchCamera::OnRotate() { int pointer = this->Interactor->GetPointerIndex(); this->FindPokedRenderer(this->Interactor->GetEventPositions(pointer)[0], this->Interactor->GetEventPositions(pointer)[1]); - if (this->State == VTKIS_TWO_POINTER) - { - this->AdjustCamera(); - this->InvokeEvent(vtkCommand::InteractionEvent, NULL); - } - else - { - this->Superclass::OnMouseMove(); - } -} - -//---------------------------------------------------------------------------- -void vtkInteractorStyleMultiTouchCamera::OnLeftButtonDown() -{ - int pointer = this->Interactor->GetPointerIndex(); - - vtkDebugMacro("pointer index down for " << pointer); - - // if it is already down ignore this event - if (this->PointersDown[pointer]) - { - return; - } - - this->FindPokedRenderer(this->Interactor->GetEventPositions(pointer)[0], - this->Interactor->GetEventPositions(pointer)[1]); - if (this->CurrentRenderer == NULL) - { - return; - } - this->PointersDown[pointer] = 1; - this->PointersDownCount++; - - // do the standard single pointer event handling - if (this->PointersDownCount == 1) + if ( this->CurrentRenderer == NULL ) { - this->Superclass::OnLeftButtonDown(); return; } - // if going from 1 to 2 pointers stop the one pointer action - if (this->PointersDownCount == 2) - { - this->LastState = this->State; - switch (this->State) - { - case VTKIS_DOLLY: - this->EndDolly(); - break; - - case VTKIS_PAN: - this->EndPan(); - break; - - case VTKIS_SPIN: - this->EndSpin(); - break; - - case VTKIS_ROTATE: - this->EndRotate(); - break; - } - // start the multipointer action - this->StartTwoPointer(); - return; - } + vtkCamera *camera = this->CurrentRenderer->GetActiveCamera(); + camera->Roll( this->Interactor->GetRotation() - this->Interactor->GetLastRotation() ); - // if going from 2 to 3 pointers stop the two pointer action - if (this->PointersDownCount == 3 && this->State == VTKIS_TWO_POINTER) - { - this->EndTwoPointer(); - } + camera->OrthogonalizeViewUp(); + this->Interactor->Render(); } + //---------------------------------------------------------------------------- -void vtkInteractorStyleMultiTouchCamera::OnLeftButtonUp() +void vtkInteractorStyleMultiTouchCamera::OnPinch() { int pointer = this->Interactor->GetPointerIndex(); - vtkDebugMacro("pointer index up for " << pointer); + this->FindPokedRenderer(this->Interactor->GetEventPositions(pointer)[0], + this->Interactor->GetEventPositions(pointer)[1]); - // if it is already up, ignore this event - if (!this->PointersDown[pointer]) + if ( this->CurrentRenderer == NULL ) { return; } - this->PointersDownCount--; - this->PointersDown[pointer] = 0; + vtkCamera *camera = this->CurrentRenderer->GetActiveCamera(); - // if we were just one pointer then do the usual handling - if (this->PointersDownCount == 0) + double dyf = this->Interactor->GetScale()/this->Interactor->GetLastScale(); + if (camera->GetParallelProjection()) { - this->Superclass::OnLeftButtonUp(); - return; + camera->SetParallelScale(camera->GetParallelScale() / dyf); } - - switch (this->State) + else { - case VTKIS_TWO_POINTER: - this->EndTwoPointer(); - for (int i = 0; i < VTKI_MAX_POINTERS; ++i) - { - if (this->PointersDown[i] != 0) - this->Interactor->SetPointerIndex(i); - switch (this->LastState) - { - case VTKIS_DOLLY: - this->StartDolly(); - break; - - case VTKIS_PAN: - this->StartPan(); - break; - - case VTKIS_SPIN: - this->StartSpin(); - break; - - case VTKIS_ROTATE: - this->StartRotate(); - break; - } - } - break; + camera->Dolly(dyf); + if (this->AutoAdjustCameraClippingRange) + { + this->CurrentRenderer->ResetCameraClippingRange(); + } } - if ( this->Interactor ) + if (this->Interactor->GetLightFollowCamera()) { - this->ReleaseFocus(); + this->CurrentRenderer->UpdateLightsGeometryToFollowCamera(); } + this->Interactor->Render(); } -double distance2D(int *a, int *b) -{ - return sqrt((double)(a[0] - b[0])*(a[0] - b[0]) + (double)(a[1]-b[1])*(a[1]-b[1])); -} //---------------------------------------------------------------------------- -void vtkInteractorStyleMultiTouchCamera::AdjustCamera() +void vtkInteractorStyleMultiTouchCamera::OnPan() { - if ( this->CurrentRenderer == NULL ) - { - return; - } - - vtkRenderWindowInteractor *rwi = this->Interactor; - - // OK we have two pointers, that means 4 constraints - // P1.x P1.y P2.x P2.y - // - // We use those 4 contraints to control: - // Zoom (variant is the distance between points - 1 DOF) - // Roll (variant is the angle formed by the line connecting the points - 1 DOF) - // Position (variant is the X,Y position of the midpoint of the line - 2 DOF) - // - + int pointer = this->Interactor->GetPointerIndex(); - // find the moving and non moving points - int eventPI = rwi->GetPointerIndex(); - int otherPI = 0; + this->FindPokedRenderer(this->Interactor->GetEventPositions(pointer)[0], + this->Interactor->GetEventPositions(pointer)[1]); - for (int i = 0; i < VTKI_MAX_POINTERS; ++i) + if ( this->CurrentRenderer == NULL ) { - if (this->PointersDown[i] > 0 && i != eventPI) - { - otherPI = i; - break; - } + return; } - // compute roll - 1 DOF - double oldAngle = - vtkMath::DegreesFromRadians( atan2( (double)rwi->GetLastEventPositions(eventPI)[1] - rwi->GetLastEventPositions(otherPI)[1], - (double)rwi->GetLastEventPositions(eventPI)[0] - rwi->GetLastEventPositions(otherPI)[0] ) ); - - double newAngle = - vtkMath::DegreesFromRadians( atan2( (double)rwi->GetEventPositions(eventPI)[1] - rwi->GetEventPositions(otherPI)[1], - (double)rwi->GetEventPositions(eventPI)[0] - rwi->GetEventPositions(otherPI)[0] ) ); - - vtkCamera *camera = this->CurrentRenderer->GetActiveCamera(); - camera->Roll( newAngle - oldAngle ); - - // compute dolly/scale - 1 DOF - double oldDist = distance2D(rwi->GetLastEventPositions(otherPI), rwi->GetLastEventPositions(eventPI)); - double newDist = distance2D(rwi->GetEventPositions(otherPI), rwi->GetEventPositions(eventPI)); - - double dyf = newDist/oldDist; - if (camera->GetParallelProjection()) - { - camera->SetParallelScale(camera->GetParallelScale() / dyf); - } - else - { - camera->Dolly(dyf); - if (this->AutoAdjustCameraClippingRange) - { - this->CurrentRenderer->ResetCameraClippingRange(); - } - } + vtkRenderWindowInteractor *rwi = this->Interactor; // handle panning - 2 DOF double viewFocus[4], focalDepth, viewPoint[3]; @@ -261,15 +119,17 @@ void vtkInteractorStyleMultiTouchCamera::AdjustCamera() viewFocus); focalDepth = viewFocus[2]; - this->ComputeDisplayToWorld((rwi->GetEventPositions(eventPI)[0] + rwi->GetEventPositions(otherPI)[0])/2.0, - (rwi->GetEventPositions(eventPI)[1] + rwi->GetEventPositions(otherPI)[1])/2.0, + double *trans = this->Interactor->GetTranslation(); + double *lastTrans = this->Interactor->GetLastTranslation(); + this->ComputeDisplayToWorld(viewFocus[0] + trans[0] - lastTrans[0], + viewFocus[1] + trans[1] - lastTrans[1], focalDepth, newPickPoint); // Has to recalc old mouse point since the viewport has moved, // so can't move it outside the loop - this->ComputeDisplayToWorld((rwi->GetLastEventPositions(eventPI)[0] + rwi->GetLastEventPositions(otherPI)[0])/2.0, - (rwi->GetLastEventPositions(eventPI)[1] + rwi->GetLastEventPositions(otherPI)[1])/2.0, + this->ComputeDisplayToWorld(viewFocus[0], + viewFocus[1], focalDepth, oldPickPoint); @@ -302,5 +162,4 @@ void vtkInteractorStyleMultiTouchCamera::AdjustCamera() void vtkInteractorStyleMultiTouchCamera::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); - os << indent << "MotionFactor: " << this->MotionFactor << "\n"; } diff --git a/Interaction/Style/vtkInteractorStyleMultiTouchCamera.h b/Interaction/Style/vtkInteractorStyleMultiTouchCamera.h index fec3be7cbfa..bde90c04081 100644 --- a/Interaction/Style/vtkInteractorStyleMultiTouchCamera.h +++ b/Interaction/Style/vtkInteractorStyleMultiTouchCamera.h @@ -12,14 +12,11 @@ PURPOSE. See the above copyright notice for more information. =========================================================================*/ -// .NAME vtkInteractorStyleMultiTouchCamera - interactive manipulation of the camera +// .NAME vtkInteractorStyleMultiTouchCamera - multitouch manipulation of the camera // .SECTION Description // vtkInteractorStyleMultiTouchCamera allows the user to interactively -// manipulate (rotate, pan, etc.) the camera, the viewpoint of the scene. In -// trackball interaction, the magnitude of the mouse motion is proportional -// to the camera motion associated with a particular mouse binding. For -// example, small left-button motions cause small changes in the rotation of -// the camera around its focal point. +// manipulate (rotate, pan, etc.) the camera, the viewpoint of the scene +// using multitouch gestures in addition to regular gestures // .SECTION See Also // vtkInteractorStyleTrackballActor vtkInteractorStyleJoystickCamera @@ -40,33 +37,15 @@ class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleMultiTouchCamera : public vtk void PrintSelf(ostream& os, vtkIndent indent); // Description: - // Event bindings controlling the effects of pressing mouse buttons - // or moving the mouse. - virtual void OnMouseMove(); - virtual void OnLeftButtonDown(); - virtual void OnLeftButtonUp(); - - // These methods for the different interactions in different modes - // are overridden in subclasses to perform the correct motion. Since - // they are called by OnTimer, they do not have mouse coord parameters - // (use interactor's GetEventPosition and GetLastEventPosition) - virtual void AdjustCamera(); - - // Description: - // Set the apparent sensitivity of the interactor style to mouse motion. - vtkSetMacro(MotionFactor,double); - vtkGetMacro(MotionFactor,double); + // Event bindings for gestures + virtual void OnRotate(); + virtual void OnPinch(); + virtual void OnPan(); protected: vtkInteractorStyleMultiTouchCamera(); ~vtkInteractorStyleMultiTouchCamera(); - int PointersDownCount; - int PointersDown[VTKI_MAX_POINTERS]; - - double MotionFactor; - int LastState; - private: vtkInteractorStyleMultiTouchCamera(const vtkInteractorStyleMultiTouchCamera&); // Not implemented. void operator=(const vtkInteractorStyleMultiTouchCamera&); // Not implemented. diff --git a/Interaction/Style/vtkInteractorStyleRubberBand2D.h b/Interaction/Style/vtkInteractorStyleRubberBand2D.h index 6a098a5cb85..d05943d5256 100644 --- a/Interaction/Style/vtkInteractorStyleRubberBand2D.h +++ b/Interaction/Style/vtkInteractorStyleRubberBand2D.h @@ -65,7 +65,6 @@ class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleRubberBand2D : public vtkInte vtkGetMacro(RenderOnMouseMove, bool); vtkBooleanMacro(RenderOnMouseMove, bool); - //BTX // Description: // Selection types enum @@ -73,13 +72,11 @@ class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleRubberBand2D : public vtkInte SELECT_NORMAL = 0, SELECT_UNION = 1 }; - //ETX // Description: // Current interaction state vtkGetMacro(Interaction, int); - //BTX enum { NONE, @@ -87,7 +84,6 @@ class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleRubberBand2D : public vtkInte ZOOMING, SELECTING }; - //ETX // Description: // Access to the start and end positions (display coordinates) of the rubber diff --git a/Interaction/Style/vtkInteractorStyleRubberBand3D.h b/Interaction/Style/vtkInteractorStyleRubberBand3D.h index 99b723088d6..6c4ba6538e7 100644 --- a/Interaction/Style/vtkInteractorStyleRubberBand3D.h +++ b/Interaction/Style/vtkInteractorStyleRubberBand3D.h @@ -63,7 +63,6 @@ class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleRubberBand3D : public vtkInte vtkGetMacro(RenderOnMouseMove, bool); vtkBooleanMacro(RenderOnMouseMove, bool); - //BTX // Description: // Selection types enum @@ -71,13 +70,11 @@ class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleRubberBand3D : public vtkInte SELECT_NORMAL = 0, SELECT_UNION = 1 }; - //ETX // Description: // Current interaction state vtkGetMacro(Interaction, int); - //BTX enum { NONE, @@ -86,7 +83,6 @@ class VTKINTERACTIONSTYLE_EXPORT vtkInteractorStyleRubberBand3D : public vtkInte ROTATING, SELECTING }; - //ETX // Description: // Access to the start and end positions (display coordinates) of the rubber diff --git a/Interaction/Style/vtkInteractorStyleUnicam.cxx b/Interaction/Style/vtkInteractorStyleUnicam.cxx index 458a0afd2c0..b3617155a68 100644 --- a/Interaction/Style/vtkInteractorStyleUnicam.cxx +++ b/Interaction/Style/vtkInteractorStyleUnicam.cxx @@ -39,7 +39,7 @@ vtkStandardNewMacro(vtkInteractorStyleUnicam); // define 'TheTime()' function-- returns time in elapsed seconds -#if defined(_WIN32) || defined(WIN32) +#if defined(_WIN32) # include "vtkWindows.h" static double TheTime() diff --git a/Interaction/Style/vtkParallelCoordinatesInteractorStyle.h b/Interaction/Style/vtkParallelCoordinatesInteractorStyle.h index 6602589d4ff..af329baf671 100644 --- a/Interaction/Style/vtkParallelCoordinatesInteractorStyle.h +++ b/Interaction/Style/vtkParallelCoordinatesInteractorStyle.h @@ -20,12 +20,11 @@ // .NAME vtkParallelCoordinatesInteractorStyle - interactive manipulation of the camera specialized for parallel coordinates // .SECTION Description // vtkParallelCoordinatesInteractorStyle allows the user to interactively manipulate -// (rotate, pan, zoomm etc.) the camera. +// (rotate, pan, zoom etc.) the camera. // Several events are overloaded from its superclass -// vtkParallelCoordinatesInteractorStyle, hence the mouse bindings are -// different. (The bindings -// keep the camera's view plane normal perpendicular to the x-y plane.) In -// summary the mouse events are as follows: +// vtkInteractorStyleTrackballCamera, hence the mouse bindings are different. +// (The bindings keep the camera's view plane normal perpendicular to the x-y plane.) +// In summary, the mouse events are as follows: // + Left Mouse button triggers window level events // + CTRL Left Mouse spins the camera around its view plane normal // + SHIFT Left Mouse pans the camera @@ -55,14 +54,12 @@ class VTKINTERACTIONSTYLE_EXPORT vtkParallelCoordinatesInteractorStyle : public vtkTypeMacro(vtkParallelCoordinatesInteractorStyle, vtkInteractorStyleTrackballCamera); void PrintSelf(ostream& os, vtkIndent indent); - //BTX enum { INTERACT_HOVER=0, INTERACT_INSPECT, INTERACT_ZOOM, INTERACT_PAN }; - //ETX // Description: // Get the cursor positions in pixel coords diff --git a/Interaction/Widgets/CMakeLists.txt b/Interaction/Widgets/CMakeLists.txt index 38d9b2a2bf5..ddbd5c42503 100644 --- a/Interaction/Widgets/CMakeLists.txt +++ b/Interaction/Widgets/CMakeLists.txt @@ -95,6 +95,8 @@ set(Module_SRCS vtkPolygonalHandleRepresentation3D.cxx vtkPolygonalSurfaceContourLineInterpolator.cxx vtkPolygonalSurfacePointPlacer.cxx + vtkProgressBarRepresentation.cxx + vtkProgressBarWidget.cxx vtkProp3DButtonRepresentation.cxx vtkRectilinearWipeRepresentation.cxx vtkRectilinearWipeWidget.cxx diff --git a/Interaction/Widgets/Testing/Cxx/CMakeLists.txt b/Interaction/Widgets/Testing/Cxx/CMakeLists.txt index 31c3ec0440a..1b8366bab99 100644 --- a/Interaction/Widgets/Testing/Cxx/CMakeLists.txt +++ b/Interaction/Widgets/Testing/Cxx/CMakeLists.txt @@ -30,8 +30,10 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestImageActorContourWidget.cxx TestImageTracerWidget.cxx TestImplicitCylinderWidget.cxx + TestImplicitCylinderWidget2.cxx TestImplicitPlaneWidget2b.cxx TestImplicitPlaneWidget2.cxx + TestImplicitPlaneWidget3.cxx TestImplicitPlaneWidget2LockNormalToCamera.cxx TestImplicitPlaneWidget.cxx TestLogoWidgetAlphaBlending.cxx @@ -46,6 +48,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestPlaybackWidget.cxx TestPointHandleRepresentation3D.cxx TestProgrammaticPlacement.cxx + TestProgressBarWidget.cxx TestProp3DButtonRepresentation.cxx,NO_VALID TestRectilinearWipeWidget.cxx TestResliceCursorWidget2.cxx @@ -58,6 +61,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestSliderWidget.cxx TestSplineWidget.cxx TestSphereWidgetZoomInOut.cxx + TestSphereWidget2CenterCursor.cxx TestTextWidget.cxx ) vtk_add_test_cxx(${vtk-module}CxxTests no_valid_tests diff --git a/Interaction/Widgets/Testing/Cxx/ScaledBoxWidget2.cxx b/Interaction/Widgets/Testing/Cxx/ScaledBoxWidget2.cxx index c77203672ae..d1f688544ba 100644 --- a/Interaction/Widgets/Testing/Cxx/ScaledBoxWidget2.cxx +++ b/Interaction/Widgets/Testing/Cxx/ScaledBoxWidget2.cxx @@ -141,26 +141,7 @@ int ScaledBoxWidget2( int , char *[] ) scaleTransform->SetInput(dataTransform); vtkCamera *camera = renderer->GetActiveCamera(); - - int cameraScale = 1; - if ( cameraScale == 0 ) - { - maceActor->SetUserTransform(scaleTransform); - boxRep->SetTransform(scaleTransform); - } - else if ( cameraScale == 1) - { - camera->SetModelTransformMatrix(scaleTransform->GetMatrix()); - } - else if ( cameraScale == 2) - { - camera->SetUserTransform(scaleTransform); - } - else if ( cameraScale == 3 ) - { - camera->SetUserViewTransform(scaleTransform); - } - + camera->SetModelTransformMatrix(scaleTransform->GetMatrix()); // record events vtkSmartPointer recorder = diff --git a/Interaction/Widgets/Testing/Cxx/TestHandleWidget.cxx b/Interaction/Widgets/Testing/Cxx/TestHandleWidget.cxx index 0aa3e036f4a..3f027d4d71c 100644 --- a/Interaction/Widgets/Testing/Cxx/TestHandleWidget.cxx +++ b/Interaction/Widgets/Testing/Cxx/TestHandleWidget.cxx @@ -624,12 +624,13 @@ int TestHandleWidget( int argc, char *argv[] ) vtkSmartPointer::New(); outlineActor->SetMapper( outlineMapper); + double repBounds[6] = { -0.7, 0.7, -0.7, 0.7, -0.7, 0.7 }; vtkSmartPointer rep = vtkSmartPointer::New(); - rep->SetPlaceFactor(0.7); + rep->SetPlaceFactor(1.0); rep->GetPlaneProperty()->SetAmbientColor(0.0, 0.5, 0.5); rep->GetPlaneProperty()->SetOpacity(0.3); - rep->PlaceWidget(outline->GetOutput()->GetBounds()); + rep->PlaceWidget(repBounds); vtkSmartPointer planeWidget = vtkSmartPointer::New(); planeWidget->SetRepresentation(rep); diff --git a/Interaction/Widgets/Testing/Cxx/TestImplicitCylinderWidget2.cxx b/Interaction/Widgets/Testing/Cxx/TestImplicitCylinderWidget2.cxx new file mode 100644 index 00000000000..41785fdc1c0 --- /dev/null +++ b/Interaction/Widgets/Testing/Cxx/TestImplicitCylinderWidget2.cxx @@ -0,0 +1,472 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestImplicitCylinderWidget.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkSmartPointer.h" + +#include "vtkActor.h" +#include "vtkAppendPolyData.h" +#include "vtkClipPolyData.h" +#include "vtkCommand.h" +#include "vtkConeSource.h" +#include "vtkGlyph3D.h" +#include "vtkImplicitCylinderWidget.h" +#include "vtkImplicitCylinderRepresentation.h" +#include "vtkInteractorEventRecorder.h" +#include "vtkLODActor.h" +#include "vtkCylinder.h" +#include "vtkPolyData.h" +#include "vtkPolyDataMapper.h" +#include "vtkProperty.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkRenderer.h" +#include "vtkSphereSource.h" + +namespace { + +const char eventLog[] = + "# StreamVersion 1\n" + "CharEvent 108 202 0 0 105 1 i\n" + "MouseWheelBackwardEvent 161 106 0 0 0 0 i\n" + "MouseWheelBackwardEvent 161 106 0 0 0 1 i\n" + "MouseWheelBackwardEvent 161 106 0 0 0 0 i\n" + "MouseWheelBackwardEvent 161 106 0 0 0 1 i\n" + "MouseWheelBackwardEvent 161 106 0 0 0 0 i\n" + "MouseWheelBackwardEvent 161 106 0 0 0 1 i\n" + "MouseWheelBackwardEvent 161 106 0 0 0 0 i\n" + "MouseWheelBackwardEvent 161 106 0 0 0 1 i\n" + "LeftButtonPressEvent 174 264 0 0 0 0 i\n" + "MouseMoveEvent 177 265 0 0 0 0 i\n" + "MouseMoveEvent 194 266 0 0 0 0 i\n" + "MouseMoveEvent 261 266 0 0 0 0 i\n" + "MouseMoveEvent 313 268 0 0 0 0 i\n" + "MouseMoveEvent 359 268 0 0 0 0 i\n" + "MouseMoveEvent 395 266 0 0 0 0 i\n" + "MouseMoveEvent 437 266 0 0 0 0 i\n" + "MouseMoveEvent 475 262 0 0 0 0 i\n" + "MouseMoveEvent 515 262 0 0 0 0 i\n" + "MouseMoveEvent 549 259 0 0 0 0 i\n" + "MouseMoveEvent 579 259 0 0 0 0 i\n" + "MouseMoveEvent 599 259 0 0 0 0 i\n" + "MouseMoveEvent 605 259 0 0 0 0 i\n" + "MouseMoveEvent 611 259 0 0 0 0 i\n" + "MouseMoveEvent 618 259 0 0 0 0 i\n" + "MouseMoveEvent 622 255 0 0 0 0 i\n" + "MouseMoveEvent 626 245 0 0 0 0 i\n" + "MouseMoveEvent 632 227 0 0 0 0 i\n" + "MouseMoveEvent 639 207 0 0 0 0 i\n" + "MouseMoveEvent 646 190 0 0 0 0 i\n" + "MouseMoveEvent 649 177 0 0 0 0 i\n" + "MouseMoveEvent 652 168 0 0 0 0 i\n" + "MouseMoveEvent 656 155 0 0 0 0 i\n" + "MouseMoveEvent 658 144 0 0 0 0 i\n" + "MouseMoveEvent 662 133 0 0 0 0 i\n" + "MouseMoveEvent 664 118 0 0 0 0 i\n" + "MouseMoveEvent 666 107 0 0 0 0 i\n" + "MouseMoveEvent 668 97 0 0 0 0 i\n" + "MouseMoveEvent 670 84 0 0 0 0 i\n" + "MouseMoveEvent 671 73 0 0 0 0 i\n" + "MouseMoveEvent 675 62 0 0 0 0 i\n" + "MouseMoveEvent 677 53 0 0 0 0 i\n" + "MouseMoveEvent 681 40 0 0 0 0 i\n" + "MouseMoveEvent 686 12 0 0 0 0 i\n" + "MouseMoveEvent 688 6 0 0 0 0 i\n" + "MouseMoveEvent 689 -4 0 0 0 0 i\n" + "MouseMoveEvent 690 -20 0 0 0 0 i\n" + "MouseMoveEvent 692 -29 0 0 0 0 i\n" + "MouseMoveEvent 688 -35 0 0 0 0 i\n" + "MouseMoveEvent 661 -42 0 0 0 0 i\n" + "MouseMoveEvent 617 -47 0 0 0 0 i\n" + "MouseMoveEvent 577 -50 0 0 0 0 i\n" + "MouseMoveEvent 554 -55 0 0 0 0 i\n" + "MouseMoveEvent 523 -58 0 0 0 0 i\n" + "MouseMoveEvent 497 -62 0 0 0 0 i\n" + "MouseMoveEvent 468 -64 0 0 0 0 i\n" + "MouseMoveEvent 438 -66 0 0 0 0 i\n" + "MouseMoveEvent 412 -70 0 0 0 0 i\n" + "MouseMoveEvent 388 -73 0 0 0 0 i\n" + "MouseMoveEvent 350 -78 0 0 0 0 i\n" + "MouseMoveEvent 317 -80 0 0 0 0 i\n" + "MouseMoveEvent 270 -86 0 0 0 0 i\n" + "MouseMoveEvent 223 -90 0 0 0 0 i\n" + "MouseMoveEvent 182 -95 0 0 0 0 i\n" + "MouseMoveEvent 149 -99 0 0 0 0 i\n" + "MouseMoveEvent 109 -101 0 0 0 0 i\n" + "MouseMoveEvent 75 -103 0 0 0 0 i\n" + "MouseMoveEvent 39 -103 0 0 0 0 i\n" + "MouseMoveEvent 1 -103 0 0 0 0 i\n" + "MouseMoveEvent -8 -103 0 0 0 0 i\n" + "MouseMoveEvent -13 -102 0 0 0 0 i\n" + "MouseMoveEvent -20 -92 0 0 0 0 i\n" + "MouseMoveEvent -34 -75 0 0 0 0 i\n" + "MouseMoveEvent -43 -58 0 0 0 0 i\n" + "MouseMoveEvent -59 -36 0 0 0 0 i\n" + "MouseMoveEvent -69 -6 0 0 0 0 i\n" + "MouseMoveEvent -81 20 0 0 0 0 i\n" + "MouseMoveEvent -96 59 0 0 0 0 i\n" + "MouseMoveEvent -104 89 0 0 0 0 i\n" + "MouseMoveEvent -115 121 0 0 0 0 i\n" + "MouseMoveEvent -129 154 0 0 0 0 i\n" + "MouseMoveEvent -137 181 0 0 0 0 i\n" + "MouseMoveEvent -145 209 0 0 0 0 i\n" + "MouseMoveEvent -152 234 0 0 0 0 i\n" + "MouseMoveEvent -155 253 0 0 0 0 i\n" + "MouseMoveEvent -160 275 0 0 0 0 i\n" + "MouseMoveEvent -162 298 0 0 0 0 i\n" + "MouseMoveEvent -167 330 0 0 0 0 i\n" + "MouseMoveEvent -169 346 0 0 0 0 i\n" + "MouseMoveEvent -170 366 0 0 0 0 i\n" + "MouseMoveEvent -174 387 0 0 0 0 i\n" + "MouseMoveEvent -176 413 0 0 0 0 i\n" + "MouseMoveEvent -177 439 0 0 0 0 i\n" + "MouseMoveEvent -177 467 0 0 0 0 i\n" + "MouseMoveEvent -177 492 0 0 0 0 i\n" + "MouseMoveEvent -177 513 0 0 0 0 i\n" + "MouseMoveEvent -177 520 0 0 0 0 i\n" + "MouseMoveEvent -176 525 0 0 0 0 i\n" + "MouseMoveEvent -161 529 0 0 0 0 i\n" + "MouseMoveEvent -129 535 0 0 0 0 i\n" + "MouseMoveEvent -90 535 0 0 0 0 i\n" + "MouseMoveEvent -49 541 0 0 0 0 i\n" + "MouseMoveEvent -2 541 0 0 0 0 i\n" + "MouseMoveEvent 42 541 0 0 0 0 i\n" + "MouseMoveEvent 85 544 0 0 0 0 i\n" + "MouseMoveEvent 115 547 0 0 0 0 i\n" + "MouseMoveEvent 145 547 0 0 0 0 i\n" + "MouseMoveEvent 186 547 0 0 0 0 i\n" + "MouseMoveEvent 234 547 0 0 0 0 i\n" + "MouseMoveEvent 272 547 0 0 0 0 i\n" + "MouseMoveEvent 299 547 0 0 0 0 i\n" + "MouseMoveEvent 320 549 0 0 0 0 i\n" + "MouseMoveEvent 345 549 0 0 0 0 i\n" + "MouseMoveEvent 365 549 0 0 0 0 i\n" + "MouseMoveEvent 382 549 0 0 0 0 i\n" + "MouseMoveEvent 410 549 0 0 0 0 i\n" + "MouseMoveEvent 439 549 0 0 0 0 i\n" + "MouseMoveEvent 465 547 0 0 0 0 i\n" + "MouseMoveEvent 482 545 0 0 0 0 i\n" + "MouseMoveEvent 484 538 0 0 0 0 i\n" + "MouseMoveEvent 484 529 0 0 0 0 i\n" + "MouseMoveEvent 491 507 0 0 0 0 i\n" + "MouseMoveEvent 492 498 0 0 0 0 i\n" + "MouseMoveEvent 494 488 0 0 0 0 i\n" + "MouseMoveEvent 496 480 0 0 0 0 i\n" + "MouseMoveEvent 496 476 0 0 0 0 i\n" + "MouseMoveEvent 497 468 0 0 0 0 i\n" + "MouseMoveEvent 499 459 0 0 0 0 i\n" + "MouseMoveEvent 500 450 0 0 0 0 i\n" + "MouseMoveEvent 501 441 0 0 0 0 i\n" + "MouseMoveEvent 502 433 0 0 0 0 i\n" + "MouseMoveEvent 504 428 0 0 0 0 i\n" + "MouseMoveEvent 505 420 0 0 0 0 i\n" + "MouseMoveEvent 505 415 0 0 0 0 i\n" + "MouseMoveEvent 506 409 0 0 0 0 i\n" + "MouseMoveEvent 506 403 0 0 0 0 i\n" + "MouseMoveEvent 506 395 0 0 0 0 i\n" + "MouseMoveEvent 507 389 0 0 0 0 i\n" + "MouseMoveEvent 507 383 0 0 0 0 i\n" + "MouseMoveEvent 507 376 0 0 0 0 i\n" + "MouseMoveEvent 507 368 0 0 0 0 i\n" + "MouseMoveEvent 508 358 0 0 0 0 i\n" + "MouseMoveEvent 509 350 0 0 0 0 i\n" + "MouseMoveEvent 509 346 0 0 0 0 i\n" + "MouseMoveEvent 509 341 0 0 0 0 i\n" + "MouseMoveEvent 510 335 0 0 0 0 i\n" + "MouseMoveEvent 510 333 0 0 0 0 i\n" + "MouseMoveEvent 510 330 0 0 0 0 i\n" + "MouseMoveEvent 510 325 0 0 0 0 i\n" + "MouseMoveEvent 510 321 0 0 0 0 i\n" + "MouseMoveEvent 510 318 0 0 0 0 i\n" + "MouseMoveEvent 511 310 0 0 0 0 i\n" + "MouseMoveEvent 512 304 0 0 0 0 i\n" + "MouseMoveEvent 512 298 0 0 0 0 i\n" + "MouseMoveEvent 514 290 0 0 0 0 i\n" + "MouseMoveEvent 515 284 0 0 0 0 i\n" + "MouseMoveEvent 515 278 0 0 0 0 i\n" + "MouseMoveEvent 515 270 0 0 0 0 i\n" + "MouseMoveEvent 516 260 0 0 0 0 i\n" + "MouseMoveEvent 516 253 0 0 0 0 i\n" + "MouseMoveEvent 517 242 0 0 0 0 i\n" + "MouseMoveEvent 517 238 0 0 0 0 i\n" + "MouseMoveEvent 519 234 0 0 0 0 i\n" + "MouseMoveEvent 519 231 0 0 0 0 i\n" + "MouseMoveEvent 519 229 0 0 0 0 i\n" + "MouseMoveEvent 519 225 0 0 0 0 i\n" + "MouseMoveEvent 519 221 0 0 0 0 i\n" + "MouseMoveEvent 519 218 0 0 0 0 i\n" + "MouseMoveEvent 520 211 0 0 0 0 i\n" + "MouseMoveEvent 520 207 0 0 0 0 i\n" + "MouseMoveEvent 521 203 0 0 0 0 i\n" + "MouseMoveEvent 521 199 0 0 0 0 i\n" + "MouseMoveEvent 520 197 0 0 0 0 i\n" + "MouseMoveEvent 518 197 0 0 0 0 i\n" + "MouseMoveEvent 515 197 0 0 0 0 i\n" + "MouseMoveEvent 513 197 0 0 0 0 i\n" + "MouseMoveEvent 504 197 0 0 0 0 i\n" + "MouseMoveEvent 494 197 0 0 0 0 i\n" + "MouseMoveEvent 485 197 0 0 0 0 i\n" + "MouseMoveEvent 480 197 0 0 0 0 i\n" + "MouseMoveEvent 472 197 0 0 0 0 i\n" + "MouseMoveEvent 462 197 0 0 0 0 i\n" + "MouseMoveEvent 455 197 0 0 0 0 i\n" + "MouseMoveEvent 450 197 0 0 0 0 i\n" + "MouseMoveEvent 444 197 0 0 0 0 i\n" + "MouseMoveEvent 439 197 0 0 0 0 i\n" + "MouseMoveEvent 433 197 0 0 0 0 i\n" + "MouseMoveEvent 427 197 0 0 0 0 i\n" + "MouseMoveEvent 419 197 0 0 0 0 i\n" + "MouseMoveEvent 412 197 0 0 0 0 i\n" + "MouseMoveEvent 405 197 0 0 0 0 i\n" + "MouseMoveEvent 399 197 0 0 0 0 i\n" + "MouseMoveEvent 393 197 0 0 0 0 i\n" + "MouseMoveEvent 385 197 0 0 0 0 i\n" + "MouseMoveEvent 377 197 0 0 0 0 i\n" + "MouseMoveEvent 368 197 0 0 0 0 i\n" + "MouseMoveEvent 362 197 0 0 0 0 i\n" + "MouseMoveEvent 355 197 0 0 0 0 i\n" + "MouseMoveEvent 347 197 0 0 0 0 i\n" + "MouseMoveEvent 338 197 0 0 0 0 i\n" + "MouseMoveEvent 329 197 0 0 0 0 i\n" + "MouseMoveEvent 324 197 0 0 0 0 i\n" + "MouseMoveEvent 319 197 0 0 0 0 i\n" + "MouseMoveEvent 313 197 0 0 0 0 i\n" + "MouseMoveEvent 308 197 0 0 0 0 i\n" + "MouseMoveEvent 304 197 0 0 0 0 i\n" + "MouseMoveEvent 300 197 0 0 0 0 i\n" + "MouseMoveEvent 297 198 0 0 0 0 i\n" + "MouseMoveEvent 297 202 0 0 0 0 i\n" + "MouseMoveEvent 297 206 0 0 0 0 i\n" + "MouseMoveEvent 297 211 0 0 0 0 i\n" + "MouseMoveEvent 299 215 0 0 0 0 i\n" + "MouseMoveEvent 299 220 0 0 0 0 i\n" + "MouseMoveEvent 300 222 0 0 0 0 i\n" + "MouseMoveEvent 300 225 0 0 0 0 i\n" + "MouseMoveEvent 300 227 0 0 0 0 i\n" + "MouseMoveEvent 300 234 0 0 0 0 i\n" + "MouseMoveEvent 300 236 0 0 0 0 i\n" + "MouseMoveEvent 300 239 0 0 0 0 i\n" + "MouseMoveEvent 300 241 0 0 0 0 i\n" + "MouseMoveEvent 300 244 0 0 0 0 i\n" + "MouseMoveEvent 300 246 0 0 0 0 i\n" + "MouseMoveEvent 299 249 0 0 0 0 i\n" + "MouseMoveEvent 299 251 0 0 0 0 i\n" + "MouseMoveEvent 299 254 0 0 0 0 i\n" + "MouseMoveEvent 299 257 0 0 0 0 i\n" + "MouseMoveEvent 299 260 0 0 0 0 i\n" + "MouseMoveEvent 299 265 0 0 0 0 i\n" + "MouseMoveEvent 299 267 0 0 0 0 i\n" + "MouseMoveEvent 299 270 0 0 0 0 i\n" + "MouseMoveEvent 299 272 0 0 0 0 i\n" + "MouseMoveEvent 299 275 0 0 0 0 i\n" + "MouseMoveEvent 298 275 0 0 0 0 i\n" + "LeftButtonReleaseEvent 298 275 0 0 0 0 i\n" + ; + +// This does the actual work: updates the vtkCylinder implicit function. +// This in turn causes the pipeline to update and clip the object. +// Callback for the interaction +class vtkTICWCallback : public vtkCommand +{ +public: + static vtkTICWCallback *New() + { + return new vtkTICWCallback; + } + + virtual void Execute(vtkObject *caller, unsigned long, void*) + { + vtkImplicitCylinderWidget *planeWidget = + reinterpret_cast(caller); + vtkImplicitCylinderRepresentation *rep = + reinterpret_cast(planeWidget->GetRepresentation()); + rep->GetCylinder(this->Cylinder); + this->Actor->VisibilityOn(); + } + + vtkTICWCallback() : Cylinder(0), Actor(0) {} + + vtkCylinder *Cylinder; + vtkActor *Actor; +}; + +} // anonymous namespace + +int TestImplicitCylinderWidget2(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) +{ + // Create a mace out of filters. + vtkSmartPointer sphere = + vtkSmartPointer::New(); + vtkSmartPointer cone = + vtkSmartPointer::New(); + vtkSmartPointer glyph = + vtkSmartPointer::New(); + glyph->SetInputConnection(sphere->GetOutputPort()); + glyph->SetSourceConnection(cone->GetOutputPort()); + glyph->SetVectorModeToUseNormal(); + glyph->SetScaleModeToScaleByVector(); + glyph->SetScaleFactor(0.25); + glyph->Update(); + + // The sphere and spikes are appended into a single polydata. + // This just makes things simpler to manage. + vtkSmartPointer apd = + vtkSmartPointer::New(); + apd->AddInputConnection(glyph->GetOutputPort()); + apd->AddInputConnection(sphere->GetOutputPort()); + + vtkSmartPointer maceMapper = + vtkSmartPointer::New(); + maceMapper->SetInputConnection(apd->GetOutputPort()); + + vtkSmartPointer maceActor = + vtkSmartPointer::New(); + maceActor->SetMapper(maceMapper); + maceActor->VisibilityOn(); + + // This portion of the code clips the mace with the vtkCylinders + // implicit function. The clipped region is colored green. + vtkSmartPointer cylinder = + vtkSmartPointer::New(); + vtkSmartPointer clipper = + vtkSmartPointer::New(); + clipper->SetInputConnection(apd->GetOutputPort()); + clipper->SetClipFunction(cylinder); + clipper->InsideOutOn(); + + vtkSmartPointer selectMapper = + vtkSmartPointer::New(); + selectMapper->SetInputConnection(clipper->GetOutputPort()); + + vtkSmartPointer selectActor = + vtkSmartPointer::New(); + selectActor->SetMapper(selectMapper); + selectActor->GetProperty()->SetColor(0,1,0); + selectActor->VisibilityOff(); + selectActor->SetScale(1.01, 1.01, 1.01); + + // Create the RenderWindow, Renderer and both Actors + vtkSmartPointer ren1 = + vtkSmartPointer::New(); + vtkSmartPointer renWin = + vtkSmartPointer::New(); + renWin->AddRenderer(ren1); + + vtkSmartPointer iren = + vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + + // The SetInteractor method is how 3D widgets are associated with the render + // window interactor. Internally, SetInteractor sets up a bunch of callbacks + // using the Command/Observer mechanism (AddObserver()). + vtkSmartPointer myCallback = + vtkSmartPointer::New(); + myCallback->Cylinder = cylinder; + myCallback->Actor = selectActor; + + vtkSmartPointer rep = + vtkSmartPointer::New(); + rep->SetPlaceFactor(1.25); + rep->PlaceWidget(glyph->GetOutput()->GetBounds()); + + vtkSmartPointer planeWidget = + vtkSmartPointer::New(); + planeWidget->SetInteractor(iren); + planeWidget->SetRepresentation(rep); + planeWidget->AddObserver(vtkCommand::InteractionEvent,myCallback); + + ren1->AddActor(maceActor); + ren1->AddActor(selectActor); + + // Add the actors to the renderer, set the background and size + ren1->SetBackground(0.1, 0.2, 0.4); + renWin->SetSize(300, 300); + renWin->SetMultiSamples(0); + + // Tests + double wbounds[6]; + double center[3], center1[3], center2[3]; + planeWidget->SetEnabled(1); + rep->GetCenter(center); + + // #1: With ConstrainCenter on, center SHOULD NOT be settable outside widget bounds + rep->ConstrainToWidgetBoundsOn(); + rep->GetWidgetBounds(wbounds); + rep->SetCenter(wbounds[1] + 1.0, wbounds[3] + 1.0, wbounds[5] + 1.0); + rep->GetCenter(center1); + if (center1[0] > wbounds[1] || center1[1] > wbounds[3] || center1[2] > wbounds[5]) + { + std::cerr << "center (" + << center1[0] << "," << center1[1] << "," << center1[2] + << ") outside widget bounds (" + << wbounds[0] << "-" << wbounds[1] << "," + << wbounds[2] << "-" << wbounds[3] << "," + << wbounds[4] << "-" << wbounds[5] << std::endl; + return EXIT_FAILURE; + } + + // #2: With ConstrainCenter off, center SHOULD be settable outside current widget bounds. + rep->ConstrainToWidgetBoundsOff(); + center1[0] = wbounds[1] + 1.0; + center1[1] = wbounds[3] + 1.0; + center1[2] = wbounds[5] + 1.0; + rep->SetCenter(center1); + rep->GetCenter(center2); + if (center1[0] != center2[0] || center1[1] != center2[1] || center1[2] != center2[2]) + { + std::cerr << "center not set correctly. expected (" + << center1[0] << "," << center1[1] << "," << center1[2] + << "), got: (" + << center2[0] << "," << center2[1] << "," << center2[2] + << ")" << std::endl; + return EXIT_FAILURE; + } + + rep->SetCenter(center); + planeWidget->SetEnabled(0); + + // #3: With ConstrainCenter on and OutsideBounds off, the translation of the + // widget should be limited + rep->OutsideBoundsOff(); + rep->ConstrainToWidgetBoundsOn(); + + vtkSmartPointer recorder = + vtkSmartPointer::New(); + recorder->SetInteractor(iren); +#if 0 // uncomment if recording + recorder->SetFileName("record.log"); + recorder->Record(); + + iren->Initialize(); + renWin->Render(); + iren->Start(); + + recorder->Off(); +#else + recorder->ReadFromInputStringOn(); + recorder->SetInputString(eventLog); + + // render the image + iren->Initialize(); + renWin->Render(); + recorder->Play(); + + // Remove the observers so we can go interactive. Without this the "-I" + // testing option fails. + recorder->Off(); + + iren->Start(); +#endif + + return EXIT_SUCCESS; +} diff --git a/Interaction/Widgets/Testing/Cxx/TestImplicitPlaneWidget3.cxx b/Interaction/Widgets/Testing/Cxx/TestImplicitPlaneWidget3.cxx new file mode 100644 index 00000000000..a56e91d8a4f --- /dev/null +++ b/Interaction/Widgets/Testing/Cxx/TestImplicitPlaneWidget3.cxx @@ -0,0 +1,337 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestImplicitPlaneWidget2.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkSmartPointer.h" + +#include "vtkActor.h" +#include "vtkAppendPolyData.h" +#include "vtkClipPolyData.h" +#include "vtkCommand.h" +#include "vtkConeSource.h" +#include "vtkGlyph3D.h" +#include "vtkImplicitPlaneWidget2.h" +#include "vtkImplicitPlaneRepresentation.h" +#include "vtkInteractorEventRecorder.h" +#include "vtkLODActor.h" +#include "vtkPlane.h" +#include "vtkPolyData.h" +#include "vtkPolyDataMapper.h" +#include "vtkProperty.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkRenderer.h" +#include "vtkSphereSource.h" + +const char eventLog3[] = + "# StreamVersion 1\n" + "CharEvent 108 202 0 0 105 1 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 0 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 0 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 0 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 1 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 0 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 0 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 1 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 0 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 1 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 0 i\n" + "MouseWheelBackwardEvent 147 151 0 0 0 0 i\n" + "LeftButtonPressEvent 196 93 0 0 0 0 i\n" + "MouseMoveEvent 196 92 0 0 0 0 i\n" + "MouseMoveEvent 246 84 0 0 0 0 i\n" + "MouseMoveEvent 297 76 0 0 0 0 i\n" + "MouseMoveEvent 308 76 0 0 0 0 i\n" + "MouseMoveEvent 314 76 0 0 0 0 i\n" + "MouseMoveEvent 325 73 0 0 0 0 i\n" + "MouseMoveEvent 331 71 0 0 0 0 i\n" + "MouseMoveEvent 336 69 0 0 0 0 i\n" + "MouseMoveEvent 344 67 0 0 0 0 i\n" + "MouseMoveEvent 348 67 0 0 0 0 i\n" + "MouseMoveEvent 351 67 0 0 0 0 i\n" + "MouseMoveEvent 356 66 0 0 0 0 i\n" + "MouseMoveEvent 356 60 0 0 0 0 i\n" + "MouseMoveEvent 359 49 0 0 0 0 i\n" + "MouseMoveEvent 361 34 0 0 0 0 i\n" + "MouseMoveEvent 364 22 0 0 0 0 i\n" + "MouseMoveEvent 367 -1 0 0 0 0 i\n" + "MouseMoveEvent 373 -23 0 0 0 0 i\n" + "MouseMoveEvent 375 -41 0 0 0 0 i\n" + "MouseMoveEvent 376 -53 0 0 0 0 i\n" + "MouseMoveEvent 378 -65 0 0 0 0 i\n" + "MouseMoveEvent 380 -77 0 0 0 0 i\n" + "MouseMoveEvent 381 -87 0 0 0 0 i\n" + "MouseMoveEvent 383 -94 0 0 0 0 i\n" + "MouseMoveEvent 382 -98 0 0 0 0 i\n" + "MouseMoveEvent 374 -102 0 0 0 0 i\n" + "MouseMoveEvent 357 -105 0 0 0 0 i\n" + "MouseMoveEvent 337 -109 0 0 0 0 i\n" + "MouseMoveEvent 322 -112 0 0 0 0 i\n" + "MouseMoveEvent 298 -114 0 0 0 0 i\n" + "MouseMoveEvent 277 -117 0 0 0 0 i\n" + "MouseMoveEvent 250 -121 0 0 0 0 i\n" + "MouseMoveEvent 220 -124 0 0 0 0 i\n" + "MouseMoveEvent 191 -129 0 0 0 0 i\n" + "MouseMoveEvent 154 -132 0 0 0 0 i\n" + "MouseMoveEvent 134 -137 0 0 0 0 i\n" + "MouseMoveEvent 116 -139 0 0 0 0 i\n" + "MouseMoveEvent 96 -140 0 0 0 0 i\n" + "MouseMoveEvent 83 -143 0 0 0 0 i\n" + "MouseMoveEvent 69 -145 0 0 0 0 i\n" + "MouseMoveEvent 48 -147 0 0 0 0 i\n" + "MouseMoveEvent 28 -149 0 0 0 0 i\n" + "MouseMoveEvent 18 -150 0 0 0 0 i\n" + "MouseMoveEvent 15 -148 0 0 0 0 i\n" + "MouseMoveEvent 10 -136 0 0 0 0 i\n" + "MouseMoveEvent 1 -109 0 0 0 0 i\n" + "MouseMoveEvent -6 -82 0 0 0 0 i\n" + "MouseMoveEvent -14 -59 0 0 0 0 i\n" + "MouseMoveEvent -19 -32 0 0 0 0 i\n" + "MouseMoveEvent -26 -3 0 0 0 0 i\n" + "MouseMoveEvent -37 35 0 0 0 0 i\n" + "MouseMoveEvent -40 66 0 0 0 0 i\n" + "MouseMoveEvent -44 95 0 0 0 0 i\n" + "MouseMoveEvent -50 125 0 0 0 0 i\n" + "MouseMoveEvent -56 149 0 0 0 0 i\n" + "MouseMoveEvent -61 172 0 0 0 0 i\n" + "MouseMoveEvent -65 201 0 0 0 0 i\n" + "MouseMoveEvent -69 216 0 0 0 0 i\n" + "MouseMoveEvent -72 227 0 0 0 0 i\n" + "MouseMoveEvent -74 235 0 0 0 0 i\n" + "MouseMoveEvent -56 236 0 0 0 0 i\n" + "MouseMoveEvent -41 237 0 0 0 0 i\n" + "MouseMoveEvent -19 237 0 0 0 0 i\n" + "MouseMoveEvent -1 237 0 0 0 0 i\n" + "MouseMoveEvent 20 237 0 0 0 0 i\n" + "MouseMoveEvent 48 237 0 0 0 0 i\n" + "MouseMoveEvent 133 237 0 0 0 0 i\n" + "MouseMoveEvent 215 237 0 0 0 0 i\n" + "MouseMoveEvent 277 237 0 0 0 0 i\n" + "MouseMoveEvent 307 237 0 0 0 0 i\n" + "MouseMoveEvent 338 237 0 0 0 0 i\n" + "MouseMoveEvent 369 237 0 0 0 0 i\n" + "MouseMoveEvent 399 237 0 0 0 0 i\n" + "MouseMoveEvent 417 237 0 0 0 0 i\n" + "MouseMoveEvent 430 237 0 0 0 0 i\n" + "MouseMoveEvent 432 237 0 0 0 0 i\n" + "MouseMoveEvent 435 234 0 0 0 0 i\n" + "MouseMoveEvent 438 227 0 0 0 0 i\n" + "MouseMoveEvent 440 222 0 0 0 0 i\n" + "MouseMoveEvent 442 216 0 0 0 0 i\n" + "MouseMoveEvent 445 209 0 0 0 0 i\n" + "MouseMoveEvent 447 198 0 0 0 0 i\n" + "MouseMoveEvent 452 186 0 0 0 0 i\n" + "MouseMoveEvent 453 176 0 0 0 0 i\n" + "MouseMoveEvent 457 164 0 0 0 0 i\n" + "MouseMoveEvent 461 150 0 0 0 0 i\n" + "MouseMoveEvent 463 138 0 0 0 0 i\n" + "MouseMoveEvent 465 128 0 0 0 0 i\n" + "MouseMoveEvent 465 122 0 0 0 0 i\n" + "MouseMoveEvent 466 112 0 0 0 0 i\n" + "MouseMoveEvent 467 102 0 0 0 0 i\n" + "MouseMoveEvent 467 92 0 0 0 0 i\n" + "MouseMoveEvent 467 83 0 0 0 0 i\n" + "LeftButtonReleaseEvent 467 83 0 0 0 0 i\n" + ; + +// This does the actual work: updates the vtkPlane implicit function. +// This in turn causes the pipeline to update and clip the object. +// Callback for the interaction +class vtkTIPW2Callback : public vtkCommand +{ +public: + static vtkTIPW2Callback *New() + { return new vtkTIPW2Callback; } + virtual void Execute(vtkObject *caller, unsigned long, void*) + { + vtkImplicitPlaneWidget2 *planeWidget = + reinterpret_cast(caller); + vtkImplicitPlaneRepresentation *rep = + reinterpret_cast(planeWidget->GetRepresentation()); + rep->GetPlane(this->Plane); + this->Actor->VisibilityOn(); + } + vtkTIPW2Callback():Plane(0),Actor(0) {} + vtkPlane *Plane; + vtkActor *Actor; + +}; + +int TestImplicitPlaneWidget3(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) +{ + // Create a mace out of filters. + vtkSmartPointer sphere = + vtkSmartPointer::New(); + vtkSmartPointer cone = + vtkSmartPointer::New(); + vtkSmartPointer glyph = + vtkSmartPointer::New(); + glyph->SetInputConnection(sphere->GetOutputPort()); + glyph->SetSourceConnection(cone->GetOutputPort()); + glyph->SetVectorModeToUseNormal(); + glyph->SetScaleModeToScaleByVector(); + glyph->SetScaleFactor(0.25); + glyph->Update(); + + // The sphere and spikes are appended into a single polydata. + // This just makes things simpler to manage. + vtkSmartPointer apd = + vtkSmartPointer::New(); + apd->AddInputConnection(glyph->GetOutputPort()); + apd->AddInputConnection(sphere->GetOutputPort()); + + vtkSmartPointer maceMapper = + vtkSmartPointer::New(); + maceMapper->SetInputConnection(apd->GetOutputPort()); + + vtkSmartPointer maceActor = + vtkSmartPointer::New(); + maceActor->SetMapper(maceMapper); + maceActor->VisibilityOn(); + + // This portion of the code clips the mace with the vtkPlanes + // implicit function. The clipped region is colored green. + vtkSmartPointer plane = + vtkSmartPointer::New(); + vtkSmartPointer clipper = + vtkSmartPointer::New(); + clipper->SetInputConnection(apd->GetOutputPort()); + clipper->SetClipFunction(plane); + clipper->InsideOutOn(); + + vtkSmartPointer selectMapper = + vtkSmartPointer::New(); + selectMapper->SetInputConnection(clipper->GetOutputPort()); + + vtkSmartPointer selectActor = + vtkSmartPointer::New(); + selectActor->SetMapper(selectMapper); + selectActor->GetProperty()->SetColor(0,1,0); + selectActor->VisibilityOff(); + selectActor->SetScale(1.01, 1.01, 1.01); + + // Create the RenderWindow, Renderer and both Actors + vtkSmartPointer ren1 = + vtkSmartPointer::New(); + vtkSmartPointer renWin = + vtkSmartPointer::New(); + renWin->AddRenderer(ren1); + + vtkSmartPointer iren = + vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + + // The SetInteractor method is how 3D widgets are associated with the render + // window interactor. Internally, SetInteractor sets up a bunch of callbacks + // using the Command/Observer mechanism (AddObserver()). + vtkSmartPointer myCallback = + vtkSmartPointer::New(); + myCallback->Plane = plane; + myCallback->Actor = selectActor; + + vtkSmartPointer rep = + vtkSmartPointer::New(); + rep->SetPlaceFactor(1.25); + rep->PlaceWidget(glyph->GetOutput()->GetBounds()); + + vtkSmartPointer planeWidget = + vtkSmartPointer::New(); + planeWidget->SetInteractor(iren); + planeWidget->SetRepresentation(rep); + planeWidget->AddObserver(vtkCommand::InteractionEvent,myCallback); + + ren1->AddActor(maceActor); + ren1->AddActor(selectActor); + + // Add the actors to the renderer, set the background and size + ren1->SetBackground(0.1, 0.2, 0.4); + renWin->SetSize(300, 300); + renWin->SetMultiSamples(0); + + // Tests + double wbounds[6]; + double origin[3], origin1[3], origin2[3]; + planeWidget->SetEnabled(1); + rep->GetOrigin(origin); + + // #1: With ConstrainOrigin on, origin SHOULD NOT be settable outside widget bounds + rep->ConstrainToWidgetBoundsOn(); + rep->GetWidgetBounds(wbounds); + rep->SetOrigin(wbounds[1] + 1.0, wbounds[3] + 1.0, wbounds[5] + 1.0); + rep->GetOrigin(origin1); + if (origin1[0] > wbounds[1] || origin1[1] > wbounds[3] || origin1[2] > wbounds[5]) + { + std::cerr << "origin (" + << origin1[0] << "," << origin1[1] << "," << origin1[2] + << ") outside widget bounds (" + << wbounds[0] << "-" << wbounds[1] << "," + << wbounds[2] << "-" << wbounds[3] << "," + << wbounds[4] << "-" << wbounds[5] << std::endl; + return EXIT_FAILURE; + } + + // #2: With ConstrainOrigin off, origin SHOULD be settable outside current widget bounds. + rep->ConstrainToWidgetBoundsOff(); + origin1[0] = wbounds[1] + 1.0; + origin1[1] = wbounds[3] + 1.0; + origin1[2] = wbounds[5] + 1.0; + rep->SetOrigin(origin1); + rep->GetOrigin(origin2); + if (origin1[0] != origin2[0] || origin1[1] != origin2[1] || origin1[2] != origin2[2]) + { + std::cerr << "origin not set correctly. expected (" + << origin1[0] << "," << origin1[1] << "," << origin1[2] + << "), got: (" + << origin2[0] << "," << origin2[1] << "," << origin2[2] + << ")" << std::endl; + return EXIT_FAILURE; + } + + rep->SetOrigin(origin); + planeWidget->SetEnabled(0); + + // #3: With ConstrainOrigin on and OutsideBounds off, the translation of the + // widget should be limited + rep->OutsideBoundsOff(); + rep->ConstrainToWidgetBoundsOn(); + + vtkSmartPointer recorder = + vtkSmartPointer::New(); + recorder->SetInteractor(iren); +#if 0 // uncomment if recording + recorder->SetFileName("record.log"); + recorder->Record(); + + iren->Initialize(); + renWin->Render(); + iren->Start(); + + recorder->Off(); +#else + recorder->ReadFromInputStringOn(); + recorder->SetInputString(eventLog3); + + // render the image + iren->Initialize(); + renWin->Render(); + recorder->Play(); + + // Remove the observers so we can go interactive. Without this the "-I" + // testing option fails. + recorder->Off(); + + iren->Start(); +#endif + + return EXIT_SUCCESS; +} diff --git a/Interaction/Widgets/Testing/Cxx/TestProgressBarWidget.cxx b/Interaction/Widgets/Testing/Cxx/TestProgressBarWidget.cxx new file mode 100644 index 00000000000..e9dbf1f1248 --- /dev/null +++ b/Interaction/Widgets/Testing/Cxx/TestProgressBarWidget.cxx @@ -0,0 +1,113 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestProgressBarWidget.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// +// This example tests the vtkProgressBarWidget. + +// First include the required header files for the VTK classes we are using. +#include "vtkActor.h" +#include "vtkCommand.h" +#include "vtkConeSource.h" +#include "vtkCylinderSource.h" +#include "vtkInteractorStyleTrackballCamera.h" +#include "vtkNew.h" +#include "vtkPolyDataMapper.h" +#include "vtkProgressBarRepresentation.h" +#include "vtkProgressBarWidget.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkRenderer.h" +#include "vtkSphereSource.h" +#include "vtkTestUtilities.h" + +int TestProgressBarWidget(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) +{ + // Create the RenderWindow, Renderer and both Actors + // + vtkNew ren1; + vtkNew renWin; + renWin->AddRenderer(ren1.Get()); + + vtkNew style; + vtkNew iren; + iren->SetRenderWindow(renWin.Get()); + iren->SetInteractorStyle(style.Get()); + + // Create a test pipeline + // + vtkNew ss; + vtkNew mapper; + mapper->SetInputConnection(ss->GetOutputPort()); + vtkNew sph; + sph->SetMapper(mapper.Get()); + + vtkNew cs; + vtkNew csMapper; + csMapper->SetInputConnection(cs->GetOutputPort()); + vtkNew cyl; + cyl->SetMapper(csMapper.Get()); + cyl->AddPosition(5, 0, 0); + + vtkNew coneSource; + vtkNew coneMapper; + coneMapper->SetInputConnection(coneSource->GetOutputPort()); + vtkNew cone; + cone->SetMapper(coneMapper.Get()); + cone->AddPosition(0, 5, 0); + + // Create the widget + vtkNew rep; + + vtkNew widget; + widget->SetInteractor(iren.Get()); + widget->SetRepresentation(rep.Get()); + + // Create the widget + vtkNew widget2; + widget2->SetInteractor(iren.Get()); + widget2->CreateDefaultRepresentation(); + vtkProgressBarRepresentation* rep2 = vtkProgressBarRepresentation::SafeDownCast(widget2->GetRepresentation()); + + // Add the actors to the renderer, set the background and size + // + ren1->AddActor(sph.Get()); + ren1->AddActor(cyl.Get()); + ren1->AddActor(cone.Get()); + ren1->SetBackground(0.1, 0.2, 0.4); + renWin->SetSize(300, 300); + + // render the image + // + iren->Initialize(); + rep->SetProgressRate(0.4); + rep->SetPosition(0.4, 0.4); + rep->SetProgressBarColor(0.2, 0.4, 0); + rep->SetBackgroundColor(1, 1, 0.5); + rep->DrawBackgroundOff(); + + rep2->SetProgressRate(0.8); + rep2->SetProgressBarColor(0.1, 0.8, 0); + rep2->SetBackgroundColor(1, 1, 0.5); + rep2->DrawBackgroundOn(); + + renWin->Render(); + widget->On(); + widget2->On(); + renWin->Render(); + + iren->Start(); + + return EXIT_SUCCESS; + +} diff --git a/Interaction/Widgets/Testing/Cxx/TestSphereWidget2CenterCursor.cxx b/Interaction/Widgets/Testing/Cxx/TestSphereWidget2CenterCursor.cxx new file mode 100644 index 00000000000..fd8d29d0c2a --- /dev/null +++ b/Interaction/Widgets/Testing/Cxx/TestSphereWidget2CenterCursor.cxx @@ -0,0 +1,80 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestSphereWidgetCenterCursor.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int TestSphereWidget2CenterCursor( int argc, char* argv[] ) +{ + // Create a renderer and a render window + vtkNew renderer; + vtkNew renderWindow; + renderWindow->AddRenderer(renderer.Get()); + + // Create an interactor + vtkNew renderWindowInteractor; + renderWindowInteractor->SetRenderWindow(renderWindow.Get()); + + // Create a sphere widget + vtkNew sphereWidget; + sphereWidget->SetInteractor(renderWindowInteractor.Get()); + sphereWidget->CreateDefaultRepresentation(); + + vtkSphereRepresentation* sphereRepresentation = + vtkSphereRepresentation::SafeDownCast( sphereWidget->GetRepresentation() ); + sphereRepresentation->HandleVisibilityOff(); + double center[3] = {4, 0, 0}; + sphereRepresentation->SetCenter(center); + sphereRepresentation->SetRadius(3); + + // Create a second sphere widget + vtkNew sphereWidget2; + sphereWidget2->SetInteractor(renderWindowInteractor.Get()); + sphereWidget2->CreateDefaultRepresentation(); + + vtkSphereRepresentation* sphereRepresentation2 = + vtkSphereRepresentation::SafeDownCast( sphereWidget2->GetRepresentation() ); + sphereRepresentation2->HandleVisibilityOff(); + double center2[3] = {-4, 0, 0}; + sphereRepresentation2->SetCenter(center2); + sphereRepresentation2->SetRadius(3); + sphereRepresentation2->SetCenterCursor(true); + + vtkCamera* camera = renderer->GetActiveCamera(); + renderWindow->SetSize(300, 300); + camera->SetPosition(0.0, 0.0, 20.0); + camera->SetFocalPoint(0.0, 0.0, -1); + + renderWindow->Render(); + renderWindowInteractor->Initialize(); + sphereWidget->On(); + sphereWidget2->On(); + renderWindow->Render(); + + int retVal = vtkRegressionTestImage( renderWindow.Get() ); + if ( retVal == vtkRegressionTester::DO_INTERACTOR) + { + renderWindowInteractor->Start(); + } + return !retVal; +} diff --git a/Interaction/Widgets/Testing/Cxx/WidgetTestingMacros.h b/Interaction/Widgets/Testing/Cxx/WidgetTestingMacros.h index 4e33ae61745..ea19ba76f8e 100644 --- a/Interaction/Widgets/Testing/Cxx/WidgetTestingMacros.h +++ b/Interaction/Widgets/Testing/Cxx/WidgetTestingMacros.h @@ -1,5 +1,5 @@ -#ifndef __WidgetTestingMacros_h -#define __WidgetTestingMacros_h +#ifndef vtkWidgetTestingMacros_h +#define vtkWidgetTestingMacros_h #include #include diff --git a/Interaction/Widgets/Testing/Cxx/vtkPolyLineRepresentationTest1.cxx b/Interaction/Widgets/Testing/Cxx/vtkPolyLineRepresentationTest1.cxx index 6bbbdf640ed..18a1fd1abd8 100644 --- a/Interaction/Widgets/Testing/Cxx/vtkPolyLineRepresentationTest1.cxx +++ b/Interaction/Widgets/Testing/Cxx/vtkPolyLineRepresentationTest1.cxx @@ -177,7 +177,7 @@ int vtkPolyLineRepresentationTest1(int , char * [] ) for (vtkIdType i = 0; i < da->GetNumberOfTuples(); i++) { double val[3]; - da->GetTupleValue(i, val); + da->GetTypedTuple(i, val); std::cout << i << " = " << val[0] << ", " << val[1] << ", " << val[2] << std::endl; } } @@ -204,7 +204,7 @@ int vtkPolyLineRepresentationTest1(int , char * [] ) for (vtkIdType i = 0; i < da->GetNumberOfTuples(); i++) { double val[3]; - da->GetTupleValue(i, val); + da->GetTypedTuple(i, val); std::cout << i << " = " << val[0] << ", " << val[1] << ", " << val[2] << std::endl; } } diff --git a/Interaction/Widgets/Testing/Cxx/vtkSplineRepresentationTest1.cxx b/Interaction/Widgets/Testing/Cxx/vtkSplineRepresentationTest1.cxx index 06d06d7f914..42badc66cf8 100644 --- a/Interaction/Widgets/Testing/Cxx/vtkSplineRepresentationTest1.cxx +++ b/Interaction/Widgets/Testing/Cxx/vtkSplineRepresentationTest1.cxx @@ -180,7 +180,7 @@ int vtkSplineRepresentationTest1(int , char * [] ) for (vtkIdType i = 0; i < da->GetNumberOfTuples(); i++) { double val[3]; - da->GetTupleValue(i, val); + da->GetTypedTuple(i, val); std::cout << i << " = " << val[0] << ", " << val[1] << ", " << val[2] << std::endl; } } @@ -207,7 +207,7 @@ int vtkSplineRepresentationTest1(int , char * [] ) for (vtkIdType i = 0; i < da->GetNumberOfTuples(); i++) { double val[3]; - da->GetTupleValue(i, val); + da->GetTypedTuple(i, val); std::cout << i << " = " << val[0] << ", " << val[1] << ", " << val[2] << std::endl; } } diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestFinitePlaneWidget_1.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestFinitePlaneWidget_1.png.md5 new file mode 100644 index 00000000000..3782e691ba3 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestFinitePlaneWidget_1.png.md5 @@ -0,0 +1 @@ +5ff44f770ac818770b44fff9b384369c diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestImplicitCylinderWidget2.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestImplicitCylinderWidget2.png.md5 new file mode 100644 index 00000000000..79675cae214 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestImplicitCylinderWidget2.png.md5 @@ -0,0 +1 @@ +469040cb54d461e07e2ca4098589c2a2 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestImplicitCylinderWidget2_1.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestImplicitCylinderWidget2_1.png.md5 new file mode 100644 index 00000000000..04e9f0f780b --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestImplicitCylinderWidget2_1.png.md5 @@ -0,0 +1 @@ +66e5a2ca2500f60ab2d9129f9c8475f0 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestImplicitPlaneWidget3.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestImplicitPlaneWidget3.png.md5 new file mode 100644 index 00000000000..9ad60dabad2 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestImplicitPlaneWidget3.png.md5 @@ -0,0 +1 @@ +17ce51906545d09eab8b9b2bddb514a5 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestImplicitPlaneWidget3_1.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestImplicitPlaneWidget3_1.png.md5 new file mode 100644 index 00000000000..751d7800031 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestImplicitPlaneWidget3_1.png.md5 @@ -0,0 +1 @@ +e4b9df246d37c98d7903b0b11aa1f974 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget.png.md5 new file mode 100644 index 00000000000..3622c6903aa --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget.png.md5 @@ -0,0 +1 @@ +4a7c032b4acfbc5ba075dc727c4303af diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget_1.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget_1.png.md5 new file mode 100644 index 00000000000..d25eaf47959 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget_1.png.md5 @@ -0,0 +1 @@ +048ae717ac9f6d4f9ea32d541e1d2c07 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget_2.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget_2.png.md5 new file mode 100644 index 00000000000..3f7c47b29d4 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget_2.png.md5 @@ -0,0 +1 @@ +3382d2bc99b46da3c1ff598dba98c14b diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget_3.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget_3.png.md5 new file mode 100644 index 00000000000..786f0e2a945 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestProgressBarWidget_3.png.md5 @@ -0,0 +1 @@ +729e027aaeba5fdf1cd9fbde802d14e2 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor.png.md5 new file mode 100644 index 00000000000..c5d8956c93a --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor.png.md5 @@ -0,0 +1 @@ +89d22601180d4d862d79cf5b1ff2824f diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_1.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_1.png.md5 new file mode 100644 index 00000000000..5c6b14b4c25 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_1.png.md5 @@ -0,0 +1 @@ +7efdd8f7dd4ce3157bfc03ceb660aed3 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_2.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_2.png.md5 new file mode 100644 index 00000000000..57f8953e6a9 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_2.png.md5 @@ -0,0 +1 @@ +75d7e05721ba3bfa5244b618684f4692 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_3.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_3.png.md5 new file mode 100644 index 00000000000..79236a032bc --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_3.png.md5 @@ -0,0 +1 @@ +37f886b659c65924c0e3bd7426c73a30 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_4.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_4.png.md5 new file mode 100644 index 00000000000..456155a3066 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_4.png.md5 @@ -0,0 +1 @@ +e234e8e2b6a2ce1792821c3ef20b0190 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_5.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_5.png.md5 new file mode 100644 index 00000000000..7e614d18f83 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_5.png.md5 @@ -0,0 +1 @@ +97d0f5a2607f5013f2df0f19d1e7a748 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_6.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_6.png.md5 new file mode 100644 index 00000000000..79236a032bc --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_6.png.md5 @@ -0,0 +1 @@ +37f886b659c65924c0e3bd7426c73a30 diff --git a/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_7.png.md5 b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_7.png.md5 new file mode 100644 index 00000000000..6edcee6fe24 --- /dev/null +++ b/Interaction/Widgets/Testing/Data/Baseline/TestSphereWidget2CenterCursor_7.png.md5 @@ -0,0 +1 @@ +c47deb713b623a6bb2edbde1a0914a0a diff --git a/Interaction/Widgets/vtkAffineRepresentation.h b/Interaction/Widgets/vtkAffineRepresentation.h index e8de8c9da06..d364897dd50 100644 --- a/Interaction/Widgets/vtkAffineRepresentation.h +++ b/Interaction/Widgets/vtkAffineRepresentation.h @@ -64,7 +64,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkAffineRepresentation : public vtkWidgetRep vtkSetClampMacro(Tolerance,int,1,100); vtkGetMacro(Tolerance,int); -//BTX // Enums define the state of the representation relative to the mouse pointer // position. Used by ComputeInteractionState() to communicate with the // widget. @@ -75,7 +74,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkAffineRepresentation : public vtkWidgetRep ShearEEdge, ShearWEdge, ShearNEdge, ShearSEdge, MoveOriginX, MoveOriginY, MoveOrigin }; -//ETX // Description: // Methods to make this class properly act like a vtkWidgetRepresentation. diff --git a/Interaction/Widgets/vtkAngleWidget.h b/Interaction/Widgets/vtkAngleWidget.h index edc349d1fd9..da52388215b 100644 --- a/Interaction/Widgets/vtkAngleWidget.h +++ b/Interaction/Widgets/vtkAngleWidget.h @@ -123,9 +123,8 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkAngleWidget : public vtkAbstractWidget // Enum defining the state of the widget. By default the widget is in Start mode, // and expects to be interactively placed. While placing the points the widget // transitions to Define state. Once placed, the widget enters the Manipulate state. - //BTX + enum {Start=0,Define,Manipulate}; - //ETX // Description: // Set the state of the widget. If the state is set to "Manipulate" then it @@ -172,9 +171,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkAngleWidget : public vtkAbstractWidget void AngleInteraction(int handleNum); void EndAngleInteraction(int handleNum); -//BTX friend class vtkAngleWidgetCallback; -//ETX private: vtkAngleWidget(const vtkAngleWidget&); //Not implemented diff --git a/Interaction/Widgets/vtkBalloonRepresentation.h b/Interaction/Widgets/vtkBalloonRepresentation.h index 8b2e4aa9acb..4ba22cd15c8 100644 --- a/Interaction/Widgets/vtkBalloonRepresentation.h +++ b/Interaction/Widgets/vtkBalloonRepresentation.h @@ -117,9 +117,8 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBalloonRepresentation : public vtkWidgetRe virtual void SetImageProperty(vtkProperty2D *p); vtkGetObjectMacro(ImageProperty,vtkProperty2D); -//BTX enum {ImageLeft=0,ImageRight,ImageBottom,ImageTop}; -//ETX + // Description: // Specify the layout of the image and text within the balloon. Note that // there are reduncies in these methods, for example diff --git a/Interaction/Widgets/vtkBalloonWidget.cxx b/Interaction/Widgets/vtkBalloonWidget.cxx index 3ce96a9c403..03c78f9f4e1 100644 --- a/Interaction/Widgets/vtkBalloonWidget.cxx +++ b/Interaction/Widgets/vtkBalloonWidget.cxx @@ -74,7 +74,7 @@ struct vtkBalloon this->Image->UnRegister(NULL); } } - void operator=(const vtkBalloon &balloon) + vtkBalloon& operator=(const vtkBalloon &balloon) { this->Text = balloon.Text; @@ -90,19 +90,21 @@ struct vtkBalloon { this->Image->Register(NULL); } + + return *this; } - int operator==(const vtkBalloon &balloon) const + bool operator==(const vtkBalloon &balloon) const { if ( this->Image == balloon.Image ) { if ( this->Text == balloon.Text ) { - return 1; + return true; } } - return 0; + return false; } - int operator!=(const vtkBalloon &balloon) const + bool operator!=(const vtkBalloon &balloon) const { return !(*this == balloon); } diff --git a/Interaction/Widgets/vtkBezierContourLineInterpolator.cxx b/Interaction/Widgets/vtkBezierContourLineInterpolator.cxx index 1fe2c47f861..600dee4cd4a 100644 --- a/Interaction/Widgets/vtkBezierContourLineInterpolator.cxx +++ b/Interaction/Widgets/vtkBezierContourLineInterpolator.cxx @@ -213,7 +213,7 @@ void vtkBezierContourLineInterpolator::GetSpan( int nodeIndex, if ( index[0] >= 0 && index[0] < rep->GetNumberOfNodes() && index[1] >= 0 && index[1] < rep->GetNumberOfNodes() ) { - nodeIndices->InsertNextTupleValue( index ); + nodeIndices->InsertNextTypedTuple( index ); } } } diff --git a/Interaction/Widgets/vtkBezierContourLineInterpolator.h b/Interaction/Widgets/vtkBezierContourLineInterpolator.h index 3745189fee1..782f3563dae 100644 --- a/Interaction/Widgets/vtkBezierContourLineInterpolator.h +++ b/Interaction/Widgets/vtkBezierContourLineInterpolator.h @@ -15,7 +15,7 @@ // .NAME vtkBezierContourLineInterpolator - Interpolates supplied nodes with bezier line segments // .SECTION Description // The line interpolator interpolates supplied nodes (see InterpolateLine) -// with bezier line segments. The finess of the curve may be controlled using +// with Bezier line segments. The fitness of the curve may be controlled using // SetMaximumCurveError and SetMaximumNumberOfLineSegments. // // .SECTION See Also @@ -38,7 +38,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBezierContourLineInterpolator // Description: // Standard methods for instances of this class. - vtkTypeMacro(vtkBezierContourLineInterpolator,vtkContourLineInterpolator); + vtkTypeMacro(vtkBezierContourLineInterpolator, vtkContourLineInterpolator); void PrintSelf(ostream& os, vtkIndent indent); virtual int InterpolateLine( vtkRenderer *ren, @@ -60,25 +60,25 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBezierContourLineInterpolator vtkGetMacro(MaximumCurveLineSegments, int); // Description: - // Span of the interpolator. ie. the number of control points its supposed + // Span of the interpolator, i.e. the number of control points it's supposed // to interpolate given a node. // // The first argument is the current nodeIndex. - // ie, you'd be trying to interpolate between nodes "nodeIndex" and - // "nodeIndex-1", unless you're closing the contour in which case, you're + // i.e., you'd be trying to interpolate between nodes "nodeIndex" and + // "nodeIndex-1", unless you're closing the contour, in which case you're // trying to interpolate "nodeIndex" and "Node=0". The node span is // returned in a vtkIntArray. // // The node span is returned in a vtkIntArray. The node span returned by // this interpolator will be a 2-tuple with a span of 4. - virtual void GetSpan( int nodeIndex, vtkIntArray *nodeIndices, - vtkContourRepresentation *rep ); + virtual void GetSpan(int nodeIndex, vtkIntArray *nodeIndices, + vtkContourRepresentation *rep); protected: vtkBezierContourLineInterpolator(); ~vtkBezierContourLineInterpolator(); - void ComputeMidpoint( double p1[3], double p2[3], double mid[3] ) + void ComputeMidpoint(double p1[3], double p2[3], double mid[3]) { mid[0] = (p1[0] + p2[0])/2; mid[1] = (p1[1] + p2[1])/2; diff --git a/Interaction/Widgets/vtkBiDimensionalWidget.h b/Interaction/Widgets/vtkBiDimensionalWidget.h index 7bc66db00e3..c0b5e2f9764 100644 --- a/Interaction/Widgets/vtkBiDimensionalWidget.h +++ b/Interaction/Widgets/vtkBiDimensionalWidget.h @@ -137,14 +137,12 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBiDimensionalWidget : public vtkAbstractWi // becomes valid after two of the four points are placed. int IsMeasureValid(); - //BTX // Description: // Events. enum { EndWidgetSelectEvent = 10050 }; - //ETX // Description: // Methods to change the whether the widget responds to interaction. @@ -155,9 +153,8 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBiDimensionalWidget : public vtkAbstractWi // Enum defining the state of the widget. By default the widget is in Start mode, // and expects to be interactively placed. While placing the points the widget // transitions to Define state. Once placed, the widget enters the Manipulate state. - //BTX + enum {Start=0,Define,Manipulate}; - //ETX // Description: // Set the state of the widget. If the state is set to "Manipulate" then it @@ -212,9 +209,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBiDimensionalWidget : public vtkAbstractWi void StartBiDimensionalInteraction(); virtual void EndBiDimensionalInteraction(); -//BTX friend class vtkBiDimensionalWidgetCallback; -//ETX private: vtkBiDimensionalWidget(const vtkBiDimensionalWidget&); //Not implemented diff --git a/Interaction/Widgets/vtkBorderRepresentation.h b/Interaction/Widgets/vtkBorderRepresentation.h index 226e1bd466a..40b47ffdbcf 100644 --- a/Interaction/Widgets/vtkBorderRepresentation.h +++ b/Interaction/Widgets/vtkBorderRepresentation.h @@ -73,9 +73,8 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBorderRepresentation : public vtkWidgetRep vtkViewportCoordinateMacro(Position); vtkViewportCoordinateMacro(Position2); -//BTX enum {BORDER_OFF=0,BORDER_ON,BORDER_ACTIVE}; -//ETX + // Description: // Specify when and if the border should appear. If ShowBorder is "on", // then the border will always appear. If ShowBorder is "off" then the @@ -149,7 +148,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBorderRepresentation : public vtkWidgetRep vtkGetMacro(Moving,int); vtkBooleanMacro(Moving,int); -//BTX // Description: // Define the various states that the representation can be in. enum _InteractionState @@ -165,7 +163,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBorderRepresentation : public vtkWidgetRep AdjustingE2, AdjustingE3 }; -//ETX // Description: // Subclasses should implement these methods. See the superclasses' diff --git a/Interaction/Widgets/vtkBorderWidget.h b/Interaction/Widgets/vtkBorderWidget.h index c0f94cfdd99..2ab7dda55b0 100644 --- a/Interaction/Widgets/vtkBorderWidget.h +++ b/Interaction/Widgets/vtkBorderWidget.h @@ -152,11 +152,9 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBorderWidget : public vtkAbstractWidget // helper methods for cursoe management virtual void SetCursor(int State); -//BTX //widget state int WidgetState; enum _WidgetState{Start=0,Define,Manipulate,Selected}; -//ETX private: vtkBorderWidget(const vtkBorderWidget&); //Not implemented diff --git a/Interaction/Widgets/vtkBoundedPlanePointPlacer.h b/Interaction/Widgets/vtkBoundedPlanePointPlacer.h index 9b4b65325e8..85a29d63bb7 100644 --- a/Interaction/Widgets/vtkBoundedPlanePointPlacer.h +++ b/Interaction/Widgets/vtkBoundedPlanePointPlacer.h @@ -90,7 +90,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBoundedPlanePointPlacer : public vtkPointP vtkGetObjectMacro(BoundingPlanes,vtkPlaneCollection); void SetBoundingPlanes(vtkPlanes *planes); -//BTX enum { XAxis=0, @@ -98,7 +97,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkBoundedPlanePointPlacer : public vtkPointP ZAxis, Oblique }; -//ETX // Description: // Given a renderer and a display position, compute the diff --git a/Interaction/Widgets/vtkButtonRepresentation.h b/Interaction/Widgets/vtkButtonRepresentation.h index 7a0f698582c..95298ab20c7 100644 --- a/Interaction/Widgets/vtkButtonRepresentation.h +++ b/Interaction/Widgets/vtkButtonRepresentation.h @@ -70,7 +70,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkButtonRepresentation : public vtkWidgetRep Outside=0, Inside }; -//ETX // Description: // These methods control the appearance of the button as it is being diff --git a/Interaction/Widgets/vtkCaptionWidget.h b/Interaction/Widgets/vtkCaptionWidget.h index d9c99fb6e2e..d3544bf9854 100644 --- a/Interaction/Widgets/vtkCaptionWidget.h +++ b/Interaction/Widgets/vtkCaptionWidget.h @@ -96,9 +96,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkCaptionWidget : public vtkBorderWidget void AnchorInteraction(); void EndAnchorInteraction(); -//BTX friend class vtkCaptionAnchorCallback; -//ETX private: vtkCaptionWidget(const vtkCaptionWidget&); //Not implemented diff --git a/Interaction/Widgets/vtkCenteredSliderRepresentation.cxx b/Interaction/Widgets/vtkCenteredSliderRepresentation.cxx index 64231f87fb9..bb3ed4ad307 100644 --- a/Interaction/Widgets/vtkCenteredSliderRepresentation.cxx +++ b/Interaction/Widgets/vtkCenteredSliderRepresentation.cxx @@ -189,19 +189,19 @@ void vtkCenteredSliderRepresentation::BuildTube() this->Points->SetPoint(1, 0.0, this->ArcEnd, 0.0); this->Points->SetPoint(this->ArcCount+2, 0.0, this->ArcStart, 0.0); this->Points->SetPoint(this->ArcCount+3, 0.0, 1.0 - this->TubeSize, 0.0); - colors->SetTupleValue(0,col); - colors->SetTupleValue(1,col); - colors->SetTupleValue(this->ArcCount+2,col); - colors->SetTupleValue(this->ArcCount+3,col); + colors->SetTypedTuple(0,col); + colors->SetTypedTuple(1,col); + colors->SetTypedTuple(this->ArcCount+2,col); + colors->SetTypedTuple(this->ArcCount+3,col); this->Points->SetPoint(this->ArcCount+4, 1.0,1.0, 0.0); this->Points->SetPoint(this->ArcCount+5, 1.0, this->ArcEnd, 0.0); this->Points->SetPoint(2*this->ArcCount+6, 1.0, this->ArcStart, 0.0); this->Points->SetPoint(2*this->ArcCount+7, 1.0, 1.0 - this->TubeSize, 0.0); - colors->SetTupleValue(this->ArcCount+4,col); - colors->SetTupleValue(this->ArcCount+5,col); - colors->SetTupleValue(2*this->ArcCount+6,col); - colors->SetTupleValue(2*this->ArcCount+7,col); + colors->SetTypedTuple(this->ArcCount+4,col); + colors->SetTypedTuple(this->ArcCount+5,col); + colors->SetTypedTuple(2*this->ArcCount+6,col); + colors->SetTypedTuple(2*this->ArcCount+7,col); // and the arc double midPoint = this->ArcCount/2.0; @@ -222,8 +222,8 @@ void vtkCenteredSliderRepresentation::BuildTube() (i + this->ArcCount + 6, 0.7, (1.0 - this->TubeSize/2.0) - halfArcLength*factor*sign, 0.0); col[3] = static_cast(255*factor); - colors->SetTupleValue(i+2,col); - colors->SetTupleValue(i+this->ArcCount+6,col); + colors->SetTypedTuple(i+2,col); + colors->SetTypedTuple(i+this->ArcCount+6,col); } // last four points are the slider @@ -236,10 +236,10 @@ void vtkCenteredSliderRepresentation::BuildTube() this->Points->SetPoint(this->ArcCount*2+11, 1.0, (this->ArcStart + this->ArcEnd)/2.0 + 0.025, 0.0); col[0] = 255; col[1] = 255; col[2] = 255; col[3] = 255; - colors->SetTupleValue(this->ArcCount*2+8,col); - colors->SetTupleValue(this->ArcCount*2+9,col); - colors->SetTupleValue(this->ArcCount*2+10,col); - colors->SetTupleValue(this->ArcCount*2+11,col); + colors->SetTypedTuple(this->ArcCount*2+8,col); + colors->SetTypedTuple(this->ArcCount*2+9,col); + colors->SetTypedTuple(this->ArcCount*2+10,col); + colors->SetTypedTuple(this->ArcCount*2+11,col); } //---------------------------------------------------------------------- diff --git a/Interaction/Widgets/vtkCheckerboardRepresentation.h b/Interaction/Widgets/vtkCheckerboardRepresentation.h index 33ca4ce2030..4b2c3c8f89e 100644 --- a/Interaction/Widgets/vtkCheckerboardRepresentation.h +++ b/Interaction/Widgets/vtkCheckerboardRepresentation.h @@ -67,14 +67,12 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkCheckerboardRepresentation : public vtkWid vtkSetClampMacro(CornerOffset,double,0.0,0.4); vtkGetMacro(CornerOffset,double); -//BTX enum { TopSlider=0, RightSlider, BottomSlider, LeftSlider }; -//ETX // Description: // This method is invoked by the vtkCheckerboardWidget() when a value of some diff --git a/Interaction/Widgets/vtkCheckerboardWidget.h b/Interaction/Widgets/vtkCheckerboardWidget.h index 9aa0c3e47b0..396d0a84494 100644 --- a/Interaction/Widgets/vtkCheckerboardWidget.h +++ b/Interaction/Widgets/vtkCheckerboardWidget.h @@ -100,9 +100,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkCheckerboardWidget : public vtkAbstractWid void CheckerboardInteraction(int sliderNum); void EndCheckerboardInteraction(); -//BTX friend class vtkCWCallback; -//ETX private: vtkCheckerboardWidget(const vtkCheckerboardWidget&); //Not implemented diff --git a/Interaction/Widgets/vtkConstrainedPointHandleRepresentation.h b/Interaction/Widgets/vtkConstrainedPointHandleRepresentation.h index 70c59f36311..3d2dd709c40 100644 --- a/Interaction/Widgets/vtkConstrainedPointHandleRepresentation.h +++ b/Interaction/Widgets/vtkConstrainedPointHandleRepresentation.h @@ -178,9 +178,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkConstrainedPointHandleRepresentation : pub virtual int HasTranslucentPolygonalGeometry(); virtual void ShallowCopy(vtkProp* prop); -//BTX enum {XAxis=0,YAxis,ZAxis,Oblique}; -//ETX void Highlight(int highlight); diff --git a/Interaction/Widgets/vtkContinuousValueWidgetRepresentation.h b/Interaction/Widgets/vtkContinuousValueWidgetRepresentation.h index b448a981d9e..4b05d28d9fb 100644 --- a/Interaction/Widgets/vtkContinuousValueWidgetRepresentation.h +++ b/Interaction/Widgets/vtkContinuousValueWidgetRepresentation.h @@ -51,7 +51,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkContinuousValueWidgetRepresentation : virtual void WidgetInteraction(double eventPos[2]) = 0; // virtual void Highlight(int); -//BTX // Enums are used to describe what is selected enum _InteractionState { @@ -59,7 +58,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkContinuousValueWidgetRepresentation : Inside, Adjusting }; -//ETX // Set/Get the value virtual void SetValue(double value); diff --git a/Interaction/Widgets/vtkContourLineInterpolator.cxx b/Interaction/Widgets/vtkContourLineInterpolator.cxx index 7f5182e891d..e5a335d06f7 100644 --- a/Interaction/Widgets/vtkContourLineInterpolator.cxx +++ b/Interaction/Widgets/vtkContourLineInterpolator.cxx @@ -78,7 +78,7 @@ void vtkContourLineInterpolator::GetSpan( int nodeIndex, if ( index[0] >= 0 && index[0] < rep->GetNumberOfNodes() && index[1] >= 0 && index[1] < rep->GetNumberOfNodes() ) { - nodeIndices->InsertNextTupleValue( index ); + nodeIndices->InsertNextTypedTuple( index ); } } } diff --git a/Interaction/Widgets/vtkContourLineInterpolator.h b/Interaction/Widgets/vtkContourLineInterpolator.h index e1b5e6bcd4c..f29322d281f 100644 --- a/Interaction/Widgets/vtkContourLineInterpolator.h +++ b/Interaction/Widgets/vtkContourLineInterpolator.h @@ -15,18 +15,16 @@ // .NAME vtkContourLineInterpolator - Defines API for interpolating/modifying nodes from a vtkContourRepresentation // .SECTION Description // vtkContourLineInterpolator is an abstract base class for interpolators -// that work are used by the contour representation class to interpolate +// that are used by the vtkContourRepresentation class to interpolate // and/or modify nodes in a contour. Subclasses must override the virtual -// method: \c InterpolateLine. This is used by the contour representation +// method \c InterpolateLine. This is used by the contour representation // to give the interpolator a chance to define an interpolation scheme // between nodes. See vtkBezierContourLineInterpolator for a concrete -// implementation. Subclasses may also override, \c UpdateNode. This provides +// implementation. Subclasses may also override \c UpdateNode. This provides // a way for the representation to give the interpolator a chance to modify -// the nodes, as the user constructs the contours. For instance a sticky +// the nodes, as the user constructs the contours. For instance, a sticky // contour widget may be implemented that moves nodes to nearby regions of -// high gradient, to be used in contour guided segmentation. -// -// .SECTION See Also +// high gradient, to be used in contour-guided segmentation. #ifndef vtkContourLineInterpolator_h #define vtkContourLineInterpolator_h diff --git a/Interaction/Widgets/vtkContourRepresentation.cxx b/Interaction/Widgets/vtkContourRepresentation.cxx index ab479cc9b55..dbc9d37dfcd 100644 --- a/Interaction/Widgets/vtkContourRepresentation.cxx +++ b/Interaction/Widgets/vtkContourRepresentation.cxx @@ -997,7 +997,7 @@ void vtkContourRepresentation::UpdateLines( int index ) int nNodes = arr->GetNumberOfTuples(); for (int i = 0; i < nNodes; i++) { - arr->GetTupleValue( i, indices ); + arr->GetTypedTuple( i, indices ); this->UpdateLine( indices[0], indices[1] ); } arr->Delete(); diff --git a/Interaction/Widgets/vtkContourRepresentation.h b/Interaction/Widgets/vtkContourRepresentation.h index 8f172f007ef..428a54fa5d6 100644 --- a/Interaction/Widgets/vtkContourRepresentation.h +++ b/Interaction/Widgets/vtkContourRepresentation.h @@ -15,36 +15,37 @@ // .NAME vtkContourRepresentation - represent the vtkContourWidget // .SECTION Description // The vtkContourRepresentation is a superclass for various types of -// representations for the vtkContourWidget. +// representations for vtkContourWidget. // // .SECTION Managing contour points // The classes vtkContourRepresentationNode, vtkContourRepresentationInternals, -// vtkContourRepresentationPoint manage the data structure used to represent +// and vtkContourRepresentationPoint manage the data structure used to represent // nodes and points on a contour. A contour may contain several nodes and -// several more points. Nodes are usually the result of user clicked points on -// the contour. Additional points are created between nodes to generate a -// smooth curve using some Interpolator. See the method \c SetLineInterpolator. +// several additional points. Nodes are usually the result of user-clicked points +// on the contour. Additional points are created between nodes to generate a +// smooth curve using some Interpolator -- see the method \c SetLineInterpolator. +// // \par // The data structure stores both the world and display positions for every // point. (This may seem like a duplication.) The default behaviour of this // class is to use the WorldPosition to do all the math. Typically a point is // added at a given display position. Its corresponding world position is -// computed using the point placer and stored. Any query of the display +// computed using the point placer, and stored. Any query of the display // position of a stored point is done via the Renderer, which computes the // display position given a world position. // // \par -// So why maintain the display position ? Consider drawing a contour on a +// So why maintain the display position? Consider drawing a contour on a // volume widget. You might want the contour to be located at a certain world // position in the volume or you might want to be overlayed over the window // like an Actor2D. The default behaviour of this class is to provide the // former behaviour. // // \par -// To achieve the latter behaviour override the methods that return the display +// To achieve the latter behaviour, override the methods that return the display // position (to return the set display position instead of computing it from // the world positions) and the method \c BuildLines() to interpolate lines -// using their display positions intead of world positions. +// using their display positions instead of world positions. // // .SECTION See Also // vtkContourWidget @@ -434,11 +435,9 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkContourRepresentation : public vtkWidgetRe virtual void BuildLines()=0; - // This method is called when something changes in the point - // placer. It will cause all points to - // be updates, and all lines to be regenerated. - // Should be extended to detect changes in the line interpolator - // too. + // This method is called when something changes in the point placer. + // It will cause all points to be updated, and all lines to be regenerated. + // It should be extended to detect changes in the line interpolator too. virtual int UpdateContour(); vtkTimeStamp ContourBuildTime; @@ -452,7 +451,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkContourRepresentation : public vtkWidgetRe // Description: // Build a contour representation from externally supplied PolyData. This // is very useful when you use an external program to compute a set of - // contour nodes, let's say based on image features. Subsequently, you want + // contour nodes (let's say based on image features) and subsequently want // to build and display a contour that runs through those points. // This method is protected and accessible only from // vtkContourWidget::Initialize. The idlist here may be used to initialize diff --git a/Interaction/Widgets/vtkContourWidget.h b/Interaction/Widgets/vtkContourWidget.h index 76ce2e9ac2c..f8e31716b8f 100644 --- a/Interaction/Widgets/vtkContourWidget.h +++ b/Interaction/Widgets/vtkContourWidget.h @@ -209,9 +209,8 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkContourWidget : public vtkAbstractWidget {this->Initialize(NULL);} // The state of the widget - //BTX + enum {Start,Define,Manipulate}; - //ETX protected: vtkContourWidget(); diff --git a/Interaction/Widgets/vtkCurveRepresentation.h b/Interaction/Widgets/vtkCurveRepresentation.h index b836d98e4b0..519f97ebc3a 100644 --- a/Interaction/Widgets/vtkCurveRepresentation.h +++ b/Interaction/Widgets/vtkCurveRepresentation.h @@ -48,7 +48,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkCurveRepresentation : public vtkWidgetRepr public: vtkTypeMacro(vtkCurveRepresentation, vtkWidgetRepresentation); void PrintSelf(ostream& os, vtkIndent indent); -//BTX + // Used to manage the InteractionState of the widget enum _InteractionState { Outside=0, @@ -60,7 +60,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkCurveRepresentation : public vtkWidgetRepr Inserting, Erasing }; -//ETX // Description: // Set the interaction state @@ -188,7 +187,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkCurveRepresentation : public vtkWidgetRepr // Ideally one should use GetLineProperty()->SetColor(). void SetLineColor(double r, double g, double b); -//BTX protected: vtkCurveRepresentation(); ~vtkCurveRepresentation(); @@ -257,7 +255,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkCurveRepresentation : public vtkWidgetRepr private: vtkCurveRepresentation(const vtkCurveRepresentation&); // Not implemented. void operator=(const vtkCurveRepresentation&); // Not implemented. -//ETX + }; diff --git a/Interaction/Widgets/vtkDistanceWidget.h b/Interaction/Widgets/vtkDistanceWidget.h index c7e325988b5..ba0339aae25 100644 --- a/Interaction/Widgets/vtkDistanceWidget.h +++ b/Interaction/Widgets/vtkDistanceWidget.h @@ -118,9 +118,8 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkDistanceWidget : public vtkAbstractWidget // Enum defining the state of the widget. By default the widget is in Start mode, // and expects to be interactively placed. While placing the points the widget // transitions to Define state. Once placed, the widget enters the Manipulate state. - //BTX + enum {Start=0,Define,Manipulate}; - //ETX // Description: // Set the state of the widget. If the state is set to "Manipulate" then it @@ -165,9 +164,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkDistanceWidget : public vtkAbstractWidget void DistanceInteraction(int handleNum); void EndDistanceInteraction(int handleNum); -//BTX friend class vtkDistanceWidgetCallback; -//ETX private: vtkDistanceWidget(const vtkDistanceWidget&); //Not implemented diff --git a/Interaction/Widgets/vtkEvent.cxx b/Interaction/Widgets/vtkEvent.cxx index d049fe037de..f73a306a342 100644 --- a/Interaction/Widgets/vtkEvent.cxx +++ b/Interaction/Widgets/vtkEvent.cxx @@ -35,48 +35,48 @@ vtkEvent::~vtkEvent() } // Comparison against event with no modifiers -int vtkEvent::operator==(unsigned long VTKEvent) +bool vtkEvent::operator==(unsigned long VTKEvent) { if ( this->EventId == VTKEvent ) { - return 1; + return true; } else { - return 0; + return false; } } // Comparison against event with modifiers -int vtkEvent::operator==(vtkEvent *e) +bool vtkEvent::operator==(vtkEvent *e) { if ( this->EventId != e->EventId ) { - return 0; + return false; } if ( this->Modifier != vtkEvent::AnyModifier && e->Modifier != vtkEvent::AnyModifier && this->Modifier != e->Modifier ) { - return 0; + return false; } if ( this->KeyCode != '\0' && e->KeyCode != '\0' && this->KeyCode != e->KeyCode ) { - return 0; + return false; } if ( this->RepeatCount != 0 && e->RepeatCount != 0 && this->RepeatCount != e->RepeatCount ) { - return 0; + return false; } if ( this->KeySym != NULL && e->KeySym != NULL && strcmp(this->KeySym,e->KeySym) != 0 ) { - return 0; + return false; } - return 1; + return true; } //---------------------------------------------------------------------------- diff --git a/Interaction/Widgets/vtkEvent.h b/Interaction/Widgets/vtkEvent.h index 67b3d7130e0..33204af7376 100644 --- a/Interaction/Widgets/vtkEvent.h +++ b/Interaction/Widgets/vtkEvent.h @@ -38,7 +38,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkEvent : public vtkObject vtkTypeMacro(vtkEvent,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); -//BTX // Description: // Ways to specify modifiers to VTK events. These can be logical OR'd to // produce combinations of modifiers. @@ -49,7 +48,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkEvent : public vtkObject ControlModifier = 2, AltModifier = 4 }; -//ETX // Description: // Set the modifier for the event. @@ -80,13 +78,11 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkEvent : public vtkObject // Convenience method computes the event modifier from an interactor. static int GetModifier(vtkRenderWindowInteractor*); -//BTX // Description: // Used to compare whether two events are equal. Takes into account // the EventId as well as the various modifiers. - int operator==(vtkEvent*); - int operator==(unsigned long VTKEvent); //event with no modifiers -//ETX + bool operator==(vtkEvent*); + bool operator==(unsigned long VTKEvent); //event with no modifiers protected: vtkEvent(); diff --git a/Interaction/Widgets/vtkHandleRepresentation.h b/Interaction/Widgets/vtkHandleRepresentation.h index 4ac702afd34..398a707fac6 100644 --- a/Interaction/Widgets/vtkHandleRepresentation.h +++ b/Interaction/Widgets/vtkHandleRepresentation.h @@ -87,13 +87,11 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkHandleRepresentation : public vtkWidgetRep vtkGetMacro(ActiveRepresentation,int); vtkBooleanMacro(ActiveRepresentation,int); -//BTX // Enums define the state of the representation relative to the mouse pointer // position. Used by ComputeInteractionState() to communicate with the // widget. Note that ComputeInteractionState() and several other methods // must be implemented by subclasses. enum _InteractionState { Outside=0, Nearby, Selecting, Translating, Scaling }; -//ETX // Description: // The interaction state may be set from a widget (e.g., HandleWidget) or diff --git a/Interaction/Widgets/vtkHoverWidget.h b/Interaction/Widgets/vtkHoverWidget.h index c667f76c4a5..6dfcebbde90 100644 --- a/Interaction/Widgets/vtkHoverWidget.h +++ b/Interaction/Widgets/vtkHoverWidget.h @@ -106,9 +106,9 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkHoverWidget : public vtkAbstractWidget ~vtkHoverWidget(); // The state of the widget -//BTX + enum {Start=0,Timing,TimedOut}; -//ETX + int WidgetState; // Callback interface to execute events diff --git a/Interaction/Widgets/vtkImageCroppingRegionsWidget.h b/Interaction/Widgets/vtkImageCroppingRegionsWidget.h index 8052ad69beb..c5f8e7b3d78 100644 --- a/Interaction/Widgets/vtkImageCroppingRegionsWidget.h +++ b/Interaction/Widgets/vtkImageCroppingRegionsWidget.h @@ -73,14 +73,14 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImageCroppingRegionsWidget : public vtk3DW // Description: // Set/get the slice orientation - //BTX + enum { SLICE_ORIENTATION_YZ = 0, SLICE_ORIENTATION_XZ = 1, SLICE_ORIENTATION_XY = 2 }; - //ETX + vtkGetMacro(SliceOrientation, int); virtual void SetSliceOrientation(int orientation); virtual void SetSliceOrientationToXY() @@ -144,14 +144,12 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImageCroppingRegionsWidget : public vtk3DW void OnButtonRelease(); void OnMouseMove(); - //BTX // Description: // Events invoked by this widget enum WidgetEventIds { CroppingPlanesPositionChangedEvent = 10050 }; - //ETX protected: @@ -186,7 +184,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImageCroppingRegionsWidget : public vtk3DW void SetMouseCursor(int state); - //BTX enum WidgetStates { NoLine = 0, @@ -199,7 +196,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImageCroppingRegionsWidget : public vtk3DW MovingH1, MovingH2 }; - //ETX int ComputeWorldCoordinate(int x, int y, double* coord); diff --git a/Interaction/Widgets/vtkImagePlaneWidget.cxx b/Interaction/Widgets/vtkImagePlaneWidget.cxx index 2fe3ae0ba80..5f69b318f48 100644 --- a/Interaction/Widgets/vtkImagePlaneWidget.cxx +++ b/Interaction/Widgets/vtkImagePlaneWidget.cxx @@ -246,7 +246,7 @@ void vtkImagePlaneWidget::SetTextureVisibility(int vis) if ( this->Enabled ) { - if (this->TextureVisibility) + if (this->TextureVisibility && this->ImageData) { this->CurrentRenderer->AddViewProp(this->TexturePlaneActor); } @@ -304,7 +304,7 @@ void vtkImagePlaneWidget::SetEnabled(int enabling) this->PlaneOutlineActor->SetProperty(this->PlaneProperty); //add the TexturePlaneActor - if (this->TextureVisibility) + if (this->TextureVisibility && this->ImageData) { this->CurrentRenderer->AddViewProp(this->TexturePlaneActor); } diff --git a/Interaction/Widgets/vtkImplicitCylinderRepresentation.cxx b/Interaction/Widgets/vtkImplicitCylinderRepresentation.cxx index 909ed53446d..b40fcaacfc0 100644 --- a/Interaction/Widgets/vtkImplicitCylinderRepresentation.cxx +++ b/Interaction/Widgets/vtkImplicitCylinderRepresentation.cxx @@ -92,6 +92,7 @@ vtkImplicitCylinderRepresentation::vtkImplicitCylinderRepresentation() this->OutlineTranslation = 1; this->ScaleEnabled = 1; this->OutsideBounds = 1; + this->ConstrainToWidgetBounds = 1; this->Cyl = vtkPolyData::New(); vtkPoints *pts = vtkPoints::New(); @@ -656,11 +657,20 @@ void vtkImplicitCylinderRepresentation::PrintSelf(ostream& os, vtkIndent indent) os << indent << "ALong Z Axis: " << (this->AlongZAxis ? "On" : "Off") << "\n"; + os << indent << "Widget Bounds: " << this->WidgetBounds[0] << ", " + << this->WidgetBounds[1] << ", " + << this->WidgetBounds[2] << ", " + << this->WidgetBounds[3] << ", " + << this->WidgetBounds[4] << ", " + << this->WidgetBounds[5] << "\n"; + os << indent << "Tubing: " << (this->Tubing ? "On" : "Off") << "\n"; os << indent << "Outline Translation: " << (this->OutlineTranslation ? "On" : "Off") << "\n"; os << indent << "Outside Bounds: " << (this->OutsideBounds ? "On" : "Off") << "\n"; + os << indent << "Constrain to Widget Bounds: " + << (this->ConstrainToWidgetBounds ? "On" : "Off") << "\n"; os << indent << "Scale Enabled: " << (this->ScaleEnabled ? "On" : "Off") << "\n"; os << indent << "Draw Cylinder: " << (this->DrawCylinder ? "On" : "Off") << "\n"; @@ -805,6 +815,7 @@ void vtkImplicitCylinderRepresentation::TranslateOutline(double *p1, double *p2) oNew[1] = origin[1] + v[1]; oNew[2] = origin[2] + v[2]; this->Box->SetOrigin(oNew); + this->Box->GetBounds(this->WidgetBounds); //Translate the cylinder origin = this->Cylinder->GetCenter(); @@ -923,6 +934,7 @@ void vtkImplicitCylinderRepresentation::Scale(double *p1, double *p2, this->Box->SetSpacing( (pNew[0]-oNew[0]), (pNew[1]-oNew[1]), (pNew[2]-oNew[2]) ); + this->Box->GetBounds(this->WidgetBounds); this->BuildRepresentation(); } @@ -1052,6 +1064,7 @@ void vtkImplicitCylinderRepresentation::PlaceWidget(double bds[6]) for (i=0; i<6; i++) { this->InitialBounds[i] = bounds[i]; + this->WidgetBounds[i] = bounds[i]; } this->InitialLength = sqrt((bounds[1]-bounds[0])*(bounds[1]-bounds[0]) + @@ -1078,18 +1091,6 @@ void vtkImplicitCylinderRepresentation::SetCenter(double x, double y, double z) // the bounding box or the cylinder tends to disappear as it hits the boundary. void vtkImplicitCylinderRepresentation::SetCenter(double x[3]) { - double *bounds = this->Outline->GetOutput()->GetBounds(); - for (int i=0; i<3; i++) - { - if ( x[i] <= bounds[2*i] ) - { - x[i] = bounds[2*i] + FLT_EPSILON; - } - else if ( x[i] >= bounds[2*i+1] ) - { - x[i] = bounds[2*i+1] - FLT_EPSILON; - } - } this->Cylinder->SetCenter(x); this->BuildRepresentation(); } @@ -1149,12 +1150,13 @@ void vtkImplicitCylinderRepresentation::GetAxis(double xyz[3]) // Set the radius the cylinder. The radius must be a positive number. void vtkImplicitCylinderRepresentation::SetRadius(double radius) { - double minRadius = this->Outline->GetOutput()->GetLength() * this->MinRadius; - double maxRadius = this->Outline->GetOutput()->GetLength() * this->MaxRadius; - - radius = ( radius < minRadius ? minRadius : - (radius > maxRadius ? maxRadius : radius) ); + if (this->ConstrainToWidgetBounds) + { + double minRadius = this->Outline->GetOutput()->GetLength() * this->MinRadius; + double maxRadius = this->Outline->GetOutput()->GetLength() * this->MaxRadius; + radius = std::min(maxRadius, std::max(minRadius, radius)); + } this->Cylinder->SetRadius(radius); this->BuildRepresentation(); } @@ -1305,23 +1307,79 @@ void vtkImplicitCylinderRepresentation::BuildRepresentation() double *center = this->Cylinder->GetCenter(); double *axis = this->Cylinder->GetAxis(); + + double bounds[6]; + std::copy(this->WidgetBounds, this->WidgetBounds + 6, bounds); + double p2[3]; - if( !this->OutsideBounds ) + if ( !this->OutsideBounds ) { - double *bounds = this->InitialBounds; + // restrict the center inside InitialBounds + double *ibounds = this->InitialBounds; for (int i=0; i<3; i++) { - if ( center[i] < bounds[2*i] ) + if ( center[i] < ibounds[2*i] ) { - center[i] = bounds[2*i]; + center[i] = ibounds[2*i]; } - else if ( center[i] > bounds[2*i+1] ) + else if ( center[i] > ibounds[2*i+1] ) { - center[i] = bounds[2*i+1]; + center[i] = ibounds[2*i+1]; } } } + if ( this->ConstrainToWidgetBounds ) + { + if ( !this->OutsideBounds ) + { + // center cannot move outside InitialBounds. Therefore, restrict + // movement of the Box. + double v[3] = { 0.0, 0.0, 0.0 }; + for (int i = 0; i < 3; ++i) + { + if (center[i] <= bounds[2*i]) + { + v[i] = center[i] - bounds[2*i] - FLT_EPSILON; + } + else if (center[i] >= bounds[2*i + 1]) + { + v[i] = center[i] - bounds[2*i + 1] + FLT_EPSILON; + } + bounds[2*i] += v[i]; + bounds[2*i + 1] += v[i]; + } + } + + // restrict center inside bounds + for (int i = 0; i < 3; ++i) + { + if (center[i] <= bounds[2*i]) + { + center[i] = bounds[2*i] + FLT_EPSILON; + } + if (center[i] >= bounds[2*i + 1]) + { + center[i] = bounds[2*i + 1] - FLT_EPSILON; + } + } + } + else // cylinder can move freely, adjust the bounds to change with it + { + double offset = this->Cylinder->GetRadius() * 1.2; + for (int i = 0; i < 3; ++i) + { + bounds[2*i] = vtkMath::Min(center[i] - offset, this->WidgetBounds[2*i]); + bounds[2*i + 1] = vtkMath::Max(center[i] + offset, this->WidgetBounds[2*i + 1]); + } + } + + this->Box->SetOrigin(bounds[0],bounds[2],bounds[4]); + this->Box->SetSpacing((bounds[1]-bounds[0]),(bounds[3]-bounds[2]), + (bounds[5]-bounds[4])); + this->Outline->Update(); + + // Setup the cylinder axis double d = this->Outline->GetOutput()->GetLength(); @@ -1391,8 +1449,7 @@ void vtkImplicitCylinderRepresentation::SizeHandles() void vtkImplicitCylinderRepresentation::BuildCylinder() { // Initialize the polydata - vtkPolyData *cyl = this->Cyl; - cyl->Reset(); + this->Cyl->Reset(); vtkPoints *pts = this->Cyl->GetPoints(); vtkDataArray *normals = this->Cyl->GetPointData()->GetNormals(); vtkCellArray *polys = this->Cyl->GetPolys(); @@ -1487,6 +1544,7 @@ void vtkImplicitCylinderRepresentation::BuildCylinder() polys->InsertNextCell(4,ptIds); } } + polys->Modified(); } //---------------------------------------------------------------------- diff --git a/Interaction/Widgets/vtkImplicitCylinderRepresentation.h b/Interaction/Widgets/vtkImplicitCylinderRepresentation.h index 272271b3a1c..8b44418fdff 100644 --- a/Interaction/Widgets/vtkImplicitCylinderRepresentation.h +++ b/Interaction/Widgets/vtkImplicitCylinderRepresentation.h @@ -109,7 +109,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImplicitCylinderRepresentation : public vt // Force the cylinder widget to be aligned with one of the x-y-z axes. // If one axis is set on, the other two will be set off. // Remember that when the state changes, a ModifiedEvent is invoked. - // This can be used to snap the plane to the axes if it is originally + // This can be used to snap the cylinder to the axes if it is originally // not aligned. void SetAlongXAxis(int); vtkGetMacro(AlongXAxis,int); @@ -126,7 +126,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImplicitCylinderRepresentation : public vt // interferes with the object that it is operating on (e.g., the // cylinder interferes with the cut surface it produces resulting in // z-buffer artifacts.) By default it is off. - void SetDrawCylinder(int plane); + void SetDrawCylinder(int drawCyl); vtkGetMacro(DrawCylinder,int); vtkBooleanMacro(DrawCylinder,int); @@ -155,11 +155,30 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImplicitCylinderRepresentation : public vt // Description: // Turn on/off the ability to move the widget outside of the bounds - // specified in the initial PlaceWidget() invocation. + // specified in the PlaceWidget() invocation. vtkSetMacro(OutsideBounds,int); vtkGetMacro(OutsideBounds,int); vtkBooleanMacro(OutsideBounds,int); + // Description: + // Set/Get the bounds of the widget representation. PlaceWidget can also be + // used to set the bounds of the widget but it may also have other effects + // on the internal state of the represenation. Use this function when only + // the widget bounds are needs to be modified. + vtkSetVector6Macro(WidgetBounds, double); + vtkGetVector6Macro(WidgetBounds, double); + + // Description: + // Turn on/off whether the cylinder should be constrained to the widget bounds. + // If on, the center will not be allowed to move outside the set widget bounds + // and the radius will be limited by MinRadius and MaxRadius. This is the + // default behaviour. + // If off, the center can be freely moved and the radius can be set to + // arbitrary values. The widget outline will change accordingly. + vtkSetMacro(ConstrainToWidgetBounds, int); + vtkGetMacro(ConstrainToWidgetBounds, int); + vtkBooleanMacro(ConstrainToWidgetBounds, int); + // Description: // Turn on/off the ability to scale the widget with the mouse. vtkSetMacro(ScaleEnabled,int); @@ -299,7 +318,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImplicitCylinderRepresentation : public vt int AlongYAxis; int AlongZAxis; - // The actual plane which is being manipulated + // The actual cylinder which is being manipulated vtkCylinder *Cylinder; // The facet resolution for rendering purposes. @@ -314,8 +333,10 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImplicitCylinderRepresentation : public vt int OutlineTranslation; //whether the outline can be moved int ScaleEnabled; //whether the widget can be scaled int OutsideBounds; //whether the widget can be moved outside input's bounds + double WidgetBounds[6]; + int ConstrainToWidgetBounds; - // The cut plane is produced with a vtkCutter + // The cut cylinder is produced with a vtkCutter vtkPolyData *Cyl; vtkPolyDataMapper *CylMapper; vtkActor *CylActor; @@ -350,7 +371,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImplicitCylinderRepresentation : public vt vtkPolyDataMapper *LineMapper2; vtkActor *LineActor2; - // The origin positioning handle + // The center positioning handle vtkSphereSource *Sphere; vtkPolyDataMapper *SphereMapper; vtkActor *SphereActor; @@ -365,8 +386,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImplicitCylinderRepresentation : public vt // Transform the normal (used for rotation) vtkTransform *Transform; - // Methods to manipulate the plane - void ConstrainCenter(double x[3]); + // Methods to manipulate the cylinder void Rotate(double X, double Y, double *p1, double *p2, double *vpn); void TranslateCylinder(double *p1, double *p2); void TranslateOutline(double *p1, double *p2); diff --git a/Interaction/Widgets/vtkImplicitPlaneRepresentation.cxx b/Interaction/Widgets/vtkImplicitPlaneRepresentation.cxx index f52a6bd0bb9..5c12edf102d 100644 --- a/Interaction/Widgets/vtkImplicitPlaneRepresentation.cxx +++ b/Interaction/Widgets/vtkImplicitPlaneRepresentation.cxx @@ -83,6 +83,7 @@ vtkImplicitPlaneRepresentation::vtkImplicitPlaneRepresentation() this->OutlineTranslation = 1; this->ScaleEnabled = 1; this->OutsideBounds = 1; + this->ConstrainToWidgetBounds = 1; this->Cutter = vtkCutter::New(); this->Cutter->SetInputData(this->Box); @@ -667,11 +668,20 @@ void vtkImplicitPlaneRepresentation::PrintSelf(ostream& os, vtkIndent indent) os << indent << "Lock Normal To Camera: " << (this->LockNormalToCamera ? "On" : "Off") << "\n"; + os << indent << "Widget Bounds: " << this->WidgetBounds[0] << ", " + << this->WidgetBounds[1] << ", " + << this->WidgetBounds[2] << ", " + << this->WidgetBounds[3] << ", " + << this->WidgetBounds[4] << ", " + << this->WidgetBounds[5] << "\n"; + os << indent << "Tubing: " << (this->Tubing ? "On" : "Off") << "\n"; os << indent << "Outline Translation: " << (this->OutlineTranslation ? "On" : "Off") << "\n"; os << indent << "Outside Bounds: " << (this->OutsideBounds ? "On" : "Off") << "\n"; + os << indent << "Constrain to Widget Bounds: " + << (this->ConstrainToWidgetBounds ? "On" : "Off") << "\n"; os << indent << "Scale Enabled: " << (this->ScaleEnabled ? "On" : "Off") << "\n"; os << indent << "Draw Plane: " << (this->DrawPlane ? "On" : "Off") << "\n"; @@ -812,6 +822,7 @@ void vtkImplicitPlaneRepresentation::TranslateOutline(double *p1, double *p2) oNew[1] = origin[1] + v[1]; oNew[2] = origin[2] + v[2]; this->Box->SetOrigin(oNew); + this->Box->GetBounds(this->WidgetBounds); //Translate the plane origin = this->Plane->GetOrigin(); @@ -889,6 +900,7 @@ void vtkImplicitPlaneRepresentation::Scale(double *p1, double *p2, this->Box->SetSpacing( (pNew[0]-oNew[0]), (pNew[1]-oNew[1]), (pNew[2]-oNew[2]) ); + this->Box->GetBounds(this->WidgetBounds); this->BuildRepresentation(); } @@ -1006,6 +1018,7 @@ void vtkImplicitPlaneRepresentation::PlaceWidget(double bds[6]) for (i=0; i<6; i++) { this->InitialBounds[i] = bounds[i]; + this->WidgetBounds[i] = bounds[i]; } this->InitialLength = sqrt((bounds[1]-bounds[0])*(bounds[1]-bounds[0]) + @@ -1035,18 +1048,6 @@ void vtkImplicitPlaneRepresentation::SetOrigin(double x, double y, double z) // when the plane is parallel to one of the faces of the bounding box). void vtkImplicitPlaneRepresentation::SetOrigin(double x[3]) { - double *bounds = this->Outline->GetOutput()->GetBounds(); - for (int i=0; i<3; i++) - { - if ( x[i] <= bounds[2*i] ) - { - x[i] = bounds[2*i] + FLT_EPSILON; - } - else if ( x[i] >= bounds[2*i+1] ) - { - x[i] = bounds[2*i+1] - FLT_EPSILON; - } - } this->Plane->SetOrigin(x); this->BuildRepresentation(); } @@ -1250,22 +1251,77 @@ void vtkImplicitPlaneRepresentation::BuildRepresentation() double *origin = this->Plane->GetOrigin(); double *normal = this->Plane->GetNormal(); + double bounds[6]; + std::copy(this->WidgetBounds, this->WidgetBounds + 6, bounds); + double p2[3]; - if( !this->OutsideBounds ) + if ( !this->OutsideBounds ) { - double *bounds = this->InitialBounds; + // restrict the origin inside InitialBounds + double *ibounds = this->InitialBounds; for (int i=0; i<3; i++) { - if ( origin[i] < bounds[2*i] ) + if ( origin[i] < ibounds[2*i] ) + { + origin[i] = ibounds[2*i]; + } + else if ( origin[i] > ibounds[2*i+1] ) + { + origin[i] = ibounds[2*i+1]; + } + } + } + + if ( this->ConstrainToWidgetBounds ) + { + if ( !this->OutsideBounds ) + { + // origin cannot move outside InitialBounds. Therefore, restrict + // movement of the Box. + double v[3] = { 0.0, 0.0, 0.0 }; + for (int i = 0; i < 3; ++i) + { + if (origin[i] <= bounds[2*i]) + { + v[i] = origin[i] - bounds[2*i] - FLT_EPSILON; + } + else if (origin[i] >= bounds[2*i + 1]) + { + v[i] = origin[i] - bounds[2*i + 1] + FLT_EPSILON; + } + bounds[2*i] += v[i]; + bounds[2*i + 1] += v[i]; + } + } + + // restrict origin inside bounds + for (int i = 0; i < 3; ++i) + { + if (origin[i] <= bounds[2*i]) { - origin[i] = bounds[2*i]; + origin[i] = bounds[2*i] + FLT_EPSILON; } - else if ( origin[i] > bounds[2*i+1] ) + if (origin[i] >= bounds[2*i + 1]) { - origin[i] = bounds[2*i+1]; + origin[i] = bounds[2*i + 1] - FLT_EPSILON; } } } + else // plane can move freely, adjust the bounds to change with it + { + double offset = this->Box->GetLength() * 0.02; + for (int i = 0; i < 3; ++i) + { + bounds[2*i] = vtkMath::Min(origin[i] - offset, this->WidgetBounds[2*i]); + bounds[2*i + 1] = vtkMath::Max(origin[i] + offset, this->WidgetBounds[2*i + 1]); + } + } + + this->Box->SetOrigin(bounds[0],bounds[2],bounds[4]); + this->Box->SetSpacing((bounds[1]-bounds[0]),(bounds[3]-bounds[2]), + (bounds[5]-bounds[4])); + this->Outline->Update(); + // Setup the plane normal double d = this->Outline->GetOutput()->GetLength(); diff --git a/Interaction/Widgets/vtkImplicitPlaneRepresentation.h b/Interaction/Widgets/vtkImplicitPlaneRepresentation.h index 3363ffc9292..52643776aaf 100644 --- a/Interaction/Widgets/vtkImplicitPlaneRepresentation.h +++ b/Interaction/Widgets/vtkImplicitPlaneRepresentation.h @@ -139,6 +139,24 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImplicitPlaneRepresentation : public vtkWi vtkGetMacro(OutsideBounds,int); vtkBooleanMacro(OutsideBounds,int); + // Description: + // Set/Get the bounds of the widget representation. PlaceWidget can also be + // used to set the bounds of the widget but it may also have other effects + // on the internal state of the represenation. Use this function when only + // the widget bounds are needs to be modified. + vtkSetVector6Macro(WidgetBounds, double); + vtkGetVector6Macro(WidgetBounds, double); + + // Description: + // Turn on/off whether the plane should be constrained to the widget bounds. + // If on, the origin will not be allowed to move outside the set widget bounds. + // This is the default behaviour. + // If off, the origin can be freely moved and the widget outline will change + // accordingly. + vtkSetMacro(ConstrainToWidgetBounds,int); + vtkGetMacro(ConstrainToWidgetBounds,int); + vtkBooleanMacro(ConstrainToWidgetBounds,int); + // Description: // Turn on/off the ability to scale the widget with the mouse. vtkSetMacro(ScaleEnabled,int); @@ -300,6 +318,8 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImplicitPlaneRepresentation : public vtkWi int OutlineTranslation; //whether the outline can be moved int ScaleEnabled; //whether the widget can be scaled int OutsideBounds; //whether the widget can be moved outside input's bounds + double WidgetBounds[6]; + int ConstrainToWidgetBounds; // The cut plane is produced with a vtkCutter vtkCutter *Cutter; @@ -351,7 +371,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkImplicitPlaneRepresentation : public vtkWi vtkTransform *Transform; // Methods to manipulate the plane - void ConstrainOrigin(double x[3]); void Rotate(double X, double Y, double *p1, double *p2, double *vpn); void TranslatePlane(double *p1, double *p2); void TranslateOutline(double *p1, double *p2); diff --git a/Interaction/Widgets/vtkOrientedGlyphContourRepresentation.cxx b/Interaction/Widgets/vtkOrientedGlyphContourRepresentation.cxx index f98a47198bd..de1d344b68f 100644 --- a/Interaction/Widgets/vtkOrientedGlyphContourRepresentation.cxx +++ b/Interaction/Widgets/vtkOrientedGlyphContourRepresentation.cxx @@ -61,26 +61,26 @@ vtkOrientedGlyphContourRepresentation::vtkOrientedGlyphContourRepresentation() this->FocalPoint = vtkPoints::New(); this->FocalPoint->SetNumberOfPoints(100); this->FocalPoint->SetNumberOfPoints(1); - this->FocalPoint->SetPoint(0, 0.0,0.0,0.0); + this->FocalPoint->SetPoint(0, 0.0, 0.0, 0.0); vtkDoubleArray *normals = vtkDoubleArray::New(); normals->SetNumberOfComponents(3); normals->SetNumberOfTuples(100); normals->SetNumberOfTuples(1); - double n[3] = {0,0,0}; - normals->SetTuple(0,n); + double n[3] = {0, 0, 0}; + normals->SetTuple(0, n); // Represent the position of the cursor this->ActiveFocalPoint = vtkPoints::New(); this->ActiveFocalPoint->SetNumberOfPoints(100); this->ActiveFocalPoint->SetNumberOfPoints(1); - this->ActiveFocalPoint->SetPoint(0, 0.0,0.0,0.0); + this->ActiveFocalPoint->SetPoint(0, 0.0, 0.0, 0.0); vtkDoubleArray *activeNormals = vtkDoubleArray::New(); activeNormals->SetNumberOfComponents(3); activeNormals->SetNumberOfTuples(100); activeNormals->SetNumberOfTuples(1); - activeNormals->SetTuple(0,n); + activeNormals->SetTuple(0, n); this->FocalData = vtkPolyData::New(); this->FocalData->SetPoints(this->FocalPoint); @@ -114,7 +114,7 @@ vtkOrientedGlyphContourRepresentation::vtkOrientedGlyphContourRepresentation() cursor2D->AllOff(); cursor2D->PointOn(); cursor2D->Update(); - this->SetCursorShape( cursor2D->GetOutput() ); + this->SetCursorShape(cursor2D->GetOutput()); cursor2D->Delete(); vtkCylinderSource *cylinder = vtkCylinderSource::New(); @@ -122,9 +122,9 @@ vtkOrientedGlyphContourRepresentation::vtkOrientedGlyphContourRepresentation() cylinder->SetRadius(0.5); cylinder->SetHeight(0.0); cylinder->CappingOff(); - cylinder->SetCenter(0,0,0); + cylinder->SetCenter(0, 0, 0); - vtkCleanPolyData* clean = vtkCleanPolyData::New(); + vtkCleanPolyData *clean = vtkCleanPolyData::New(); clean->PointMergingOn(); clean->CreateDefaultLocator(); clean->SetInputConnection(cylinder->GetOutputPort()); @@ -134,7 +134,7 @@ vtkOrientedGlyphContourRepresentation::vtkOrientedGlyphContourRepresentation() vtkTransformPolyDataFilter *tpd = vtkTransformPolyDataFilter::New(); tpd->SetInputConnection(clean->GetOutputPort()); - tpd->SetTransform( t ); + tpd->SetTransform(t); clean->Delete(); cylinder->Delete(); @@ -149,23 +149,22 @@ vtkOrientedGlyphContourRepresentation::vtkOrientedGlyphContourRepresentation() this->Mapper = vtkPolyDataMapper::New(); this->Mapper->SetInputConnection(this->Glypher->GetOutputPort()); - // this turns on resolve coincident topology for everything + // This turns on resolve coincident topology for everything // as it is a class static on the mapper this->Mapper->SetResolveCoincidentTopologyToPolygonOffset(); this->Mapper->ScalarVisibilityOff(); this->Mapper->ImmediateModeRenderingOn(); - // put this on top of other objects - this->Mapper->SetRelativeCoincidentTopologyLineOffsetParameters(-1,-1); - this->Mapper->SetRelativeCoincidentTopologyPolygonOffsetParameters(-1,-1); + // Put this on top of other objects + this->Mapper->SetRelativeCoincidentTopologyLineOffsetParameters(-1, -1); + this->Mapper->SetRelativeCoincidentTopologyPolygonOffsetParameters(-1, -1); this->Mapper->SetRelativeCoincidentTopologyPointOffsetParameter(-1); this->ActiveMapper = vtkPolyDataMapper::New(); - this->ActiveMapper->SetInputConnection( - this->ActiveGlypher->GetOutputPort()); + this->ActiveMapper->SetInputConnection(this->ActiveGlypher->GetOutputPort()); this->ActiveMapper->ScalarVisibilityOff(); this->ActiveMapper->ImmediateModeRenderingOn(); - this->ActiveMapper->SetRelativeCoincidentTopologyLineOffsetParameters(-1,-1); - this->ActiveMapper->SetRelativeCoincidentTopologyPolygonOffsetParameters(-1,-1); + this->ActiveMapper->SetRelativeCoincidentTopologyLineOffsetParameters(-1, -1); + this->ActiveMapper->SetRelativeCoincidentTopologyPolygonOffsetParameters(-1, -1); this->ActiveMapper->SetRelativeCoincidentTopologyPointOffsetParameter(-1); // Set up the initial properties @@ -188,8 +187,8 @@ vtkOrientedGlyphContourRepresentation::vtkOrientedGlyphContourRepresentation() this->LinesMapper->SetRelativeCoincidentTopologyPointOffsetParameter(-1); this->LinesActor = vtkActor::New(); - this->LinesActor->SetMapper( this->LinesMapper ); - this->LinesActor->SetProperty( this->LinesProperty ); + this->LinesActor->SetMapper(this->LinesMapper); + this->LinesActor->SetProperty(this->LinesProperty); this->InteractionOffset[0] = 0.0; this->InteractionOffset[1] = 0.0; @@ -213,8 +212,8 @@ vtkOrientedGlyphContourRepresentation::~vtkOrientedGlyphContourRepresentation() this->ActiveFocalPoint->Delete(); this->ActiveFocalData->Delete(); - this->SetCursorShape( NULL ); - this->SetActiveCursorShape( NULL ); + this->SetCursorShape(NULL); + this->SetActiveCursorShape(NULL); this->Glypher->Delete(); this->Mapper->Delete(); @@ -233,27 +232,27 @@ vtkOrientedGlyphContourRepresentation::~vtkOrientedGlyphContourRepresentation() this->LinesProperty->Delete(); // Clear the selected nodes representation - if(this->SelectedNodesPoints) + if (this->SelectedNodesPoints) { this->SelectedNodesPoints->Delete(); } - if(this->SelectedNodesData) + if (this->SelectedNodesData) { this->SelectedNodesData->Delete(); } - if(this->SelectedNodesCursorShape) + if (this->SelectedNodesCursorShape) { this->SelectedNodesCursorShape->Delete(); } - if(this->SelectedNodesGlypher) + if (this->SelectedNodesGlypher) { this->SelectedNodesGlypher->Delete(); } - if(this->SelectedNodesMapper) + if (this->SelectedNodesMapper) { this->SelectedNodesMapper->Delete(); } - if(this->SelectedNodesActor) + if (this->SelectedNodesActor) { this->SelectedNodesActor->Delete(); } @@ -262,18 +261,18 @@ vtkOrientedGlyphContourRepresentation::~vtkOrientedGlyphContourRepresentation() //---------------------------------------------------------------------- void vtkOrientedGlyphContourRepresentation::SetCursorShape(vtkPolyData *shape) { - if ( shape != this->CursorShape ) + if (shape != this->CursorShape) { - if ( this->CursorShape ) + if (this->CursorShape) { this->CursorShape->Delete(); } this->CursorShape = shape; - if ( this->CursorShape ) + if (this->CursorShape) { this->CursorShape->Register(this); } - if ( this->CursorShape ) + if (this->CursorShape) { this->Glypher->SetSourceData(this->CursorShape); } @@ -288,20 +287,21 @@ vtkPolyData *vtkOrientedGlyphContourRepresentation::GetCursorShape() } //---------------------------------------------------------------------- -void vtkOrientedGlyphContourRepresentation::SetActiveCursorShape(vtkPolyData *shape) +void vtkOrientedGlyphContourRepresentation::SetActiveCursorShape( + vtkPolyData *shape) { - if ( shape != this->ActiveCursorShape ) + if (shape != this->ActiveCursorShape) { - if ( this->ActiveCursorShape ) + if (this->ActiveCursorShape) { this->ActiveCursorShape->Delete(); } this->ActiveCursorShape = shape; - if ( this->ActiveCursorShape ) + if (this->ActiveCursorShape) { this->ActiveCursorShape->Register(this); } - if ( this->ActiveCursorShape ) + if (this->ActiveCursorShape) { this->ActiveGlypher->SetSourceData(this->ActiveCursorShape); } @@ -323,11 +323,12 @@ void vtkOrientedGlyphContourRepresentation::SetRenderer(vtkRenderer *ren) } //------------------------------------------------------------------------- -int vtkOrientedGlyphContourRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUsed(modified)) +int vtkOrientedGlyphContourRepresentation::ComputeInteractionState( + int X, int Y, int vtkNotUsed(modified)) { double pos[4], xyz[3]; - this->FocalPoint->GetPoint(0,pos); + this->FocalPoint->GetPoint(0, pos); pos[3] = 1.0; this->Renderer->SetWorldPoint(pos); this->Renderer->WorldToDisplay(); @@ -339,10 +340,10 @@ int vtkOrientedGlyphContourRepresentation::ComputeInteractionState(int X, int Y, this->VisibilityOn(); double tol2 = this->PixelTolerance * this->PixelTolerance; - if ( vtkMath::Distance2BetweenPoints(xyz,pos) <= tol2 ) + if (vtkMath::Distance2BetweenPoints(xyz, pos) <= tol2) { this->InteractionState = vtkContourRepresentation::Nearby; - if ( !this->ActiveCursorShape ) + if (!this->ActiveCursorShape) { this->VisibilityOff(); } @@ -350,7 +351,7 @@ int vtkOrientedGlyphContourRepresentation::ComputeInteractionState(int X, int Y, else { this->InteractionState = vtkContourRepresentation::Outside; - if ( !this->CursorShape ) + if (!this->CursorShape) { this->VisibilityOff(); } @@ -361,7 +362,8 @@ int vtkOrientedGlyphContourRepresentation::ComputeInteractionState(int X, int Y, //---------------------------------------------------------------------- // Record the current event position, and the rectilinear wipe position. -void vtkOrientedGlyphContourRepresentation::StartWidgetInteraction(double startEventPos[2]) +void vtkOrientedGlyphContourRepresentation::StartWidgetInteraction( + double startEventPos[2]) { this->StartEventPosition[0] = startEventPos[0]; this->StartEventPosition[1] = startEventPos[1]; @@ -393,15 +395,15 @@ void vtkOrientedGlyphContourRepresentation::StartWidgetInteraction(double startE void vtkOrientedGlyphContourRepresentation::WidgetInteraction(double eventPos[2]) { // Process the motion - if ( this->CurrentOperation == vtkContourRepresentation::Translate ) + if (this->CurrentOperation == vtkContourRepresentation::Translate) { this->Translate(eventPos); } - if ( this->CurrentOperation == vtkContourRepresentation::Shift ) + if (this->CurrentOperation == vtkContourRepresentation::Shift) { this->ShiftContour(eventPos); } - if ( this->CurrentOperation == vtkContourRepresentation::Scale ) + if (this->CurrentOperation == vtkContourRepresentation::Scale) { this->ScaleContour(eventPos); } @@ -417,7 +419,7 @@ void vtkOrientedGlyphContourRepresentation::Translate(double eventPos[2]) { double ref[3]; - if ( !this->GetActiveNodeWorldPosition( ref ) ) + if (!this->GetActiveNodeWorldPosition(ref)) { return; } @@ -427,12 +429,12 @@ void vtkOrientedGlyphContourRepresentation::Translate(double eventPos[2]) displayPos[1] = eventPos[1] + this->InteractionOffset[1]; double worldPos[3]; - double worldOrient[9] = {1.0,0.0,0.0, - 0.0,1.0,0.0, - 0.0,0.0,1.0}; - if ( this->PointPlacer->ComputeWorldPosition(this->Renderer, + double worldOrient[9] = {1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0}; + if (this->PointPlacer->ComputeWorldPosition(this->Renderer, displayPos, ref, worldPos, - worldOrient ) ) + worldOrient)) { this->SetActiveNodeToWorldPosition(worldPos, worldOrient); } @@ -448,7 +450,7 @@ void vtkOrientedGlyphContourRepresentation::ShiftContour(double eventPos[2]) { double ref[3]; - if ( !this->GetActiveNodeWorldPosition( ref ) ) + if (!this->GetActiveNodeWorldPosition(ref)) { return; } @@ -458,12 +460,12 @@ void vtkOrientedGlyphContourRepresentation::ShiftContour(double eventPos[2]) displayPos[1] = eventPos[1] + this->InteractionOffset[1]; double worldPos[3]; - double worldOrient[9] = {1.0,0.0,0.0, - 0.0,1.0,0.0, - 0.0,0.0,1.0}; - if ( this->PointPlacer->ComputeWorldPosition(this->Renderer, + double worldOrient[9] = {1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0}; + if (this->PointPlacer->ComputeWorldPosition(this->Renderer, displayPos, ref, worldPos, - worldOrient ) ) + worldOrient)) { this->SetActiveNodeToWorldPosition(worldPos, worldOrient); @@ -473,61 +475,62 @@ void vtkOrientedGlyphContourRepresentation::ShiftContour(double eventPos[2]) vector[1] = worldPos[1] - ref[1]; vector[2] = worldPos[2] - ref[2]; - for ( int i = 0; i < this->GetNumberOfNodes(); i++ ) + for (int i = 0; i < this->GetNumberOfNodes(); i++) { - if( i != this->ActiveNode ) + if (i != this->ActiveNode) { - this->GetNthNodeWorldPosition( i, ref ); + this->GetNthNodeWorldPosition(i, ref); worldPos[0] = ref[0] + vector[0]; worldPos[1] = ref[1] + vector[1]; worldPos[2] = ref[2] + vector[2]; - this->SetNthNodeWorldPosition( i, worldPos, worldOrient ); + this->SetNthNodeWorldPosition(i, worldPos, worldOrient); } } } } + //---------------------------------------------------------------------- void vtkOrientedGlyphContourRepresentation::ScaleContour(double eventPos[2]) { double ref[3]; - if ( !this->GetActiveNodeWorldPosition( ref ) ) + if (!this->GetActiveNodeWorldPosition(ref)) { return; } double centroid[3]; - ComputeCentroid( centroid ); + ComputeCentroid(centroid); - double r2 = vtkMath::Distance2BetweenPoints( ref, centroid ); + double r2 = vtkMath::Distance2BetweenPoints(ref, centroid); double displayPos[2]; displayPos[0] = eventPos[0] + this->InteractionOffset[0]; displayPos[1] = eventPos[1] + this->InteractionOffset[1]; double worldPos[3]; - double worldOrient[9] = {1.0,0.0,0.0, - 0.0,1.0,0.0, - 0.0,0.0,1.0}; - if ( this->PointPlacer->ComputeWorldPosition(this->Renderer, + double worldOrient[9] = {1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0}; + if (this->PointPlacer->ComputeWorldPosition(this->Renderer, displayPos, ref, worldPos, - worldOrient ) ) + worldOrient)) { - double d2 = vtkMath::Distance2BetweenPoints( worldPos, centroid ); - if( d2 != 0. ) + double d2 = vtkMath::Distance2BetweenPoints(worldPos, centroid); + if (d2 != 0.0) { - double ratio = sqrt( d2 / r2 ); -// this->SetActiveNodeToWorldPosition(worldPos, worldOrient); + double ratio = sqrt(d2 / r2); + //this->SetActiveNodeToWorldPosition(worldPos, worldOrient); - for ( int i = 0; i < this->GetNumberOfNodes(); i++ ) + for (int i = 0; i < this->GetNumberOfNodes(); i++) { -// if( i != this->ActiveNode ) + //if (i != this->ActiveNode) { - this->GetNthNodeWorldPosition( i, ref ); - worldPos[0] = centroid[0] + ratio * ( ref[0] - centroid[0] ); - worldPos[1] = centroid[0] + ratio * ( ref[1] - centroid[1] ); - worldPos[2] = centroid[0] + ratio * ( ref[2] - centroid[2] ); - this->SetNthNodeWorldPosition( i, worldPos, worldOrient ); + this->GetNthNodeWorldPosition(i, ref); + worldPos[0] = centroid[0] + ratio * (ref[0] - centroid[0]); + worldPos[1] = centroid[0] + ratio * (ref[1] - centroid[1]); + worldPos[2] = centroid[0] + ratio * (ref[2] - centroid[2]); + this->SetNthNodeWorldPosition(i, worldPos, worldOrient); } } } @@ -535,22 +538,21 @@ void vtkOrientedGlyphContourRepresentation::ScaleContour(double eventPos[2]) } //---------------------------------------------------------------------- -void vtkOrientedGlyphContourRepresentation::ComputeCentroid( - double* ioCentroid ) +void vtkOrientedGlyphContourRepresentation::ComputeCentroid(double *ioCentroid) { double p[3]; ioCentroid[0] = 0.; ioCentroid[1] = 0.; ioCentroid[2] = 0.; - for ( int i = 0; i < this->GetNumberOfNodes(); i++ ) + for (int i = 0; i < this->GetNumberOfNodes(); i++) { - this->GetNthNodeWorldPosition( i, p ); + this->GetNthNodeWorldPosition(i, p); ioCentroid[0] += p[0]; ioCentroid[1] += p[1]; ioCentroid[2] += p[2]; } - double inv_N = 1. / static_cast< double >( this->GetNumberOfNodes() ); + double inv_N = 1. / static_cast< double >(this->GetNumberOfNodes()); ioCentroid[0] *= inv_N; ioCentroid[1] *= inv_N; ioCentroid[2] *= inv_N; @@ -569,7 +571,7 @@ void vtkOrientedGlyphContourRepresentation::Scale(double eventPos[2]) // Scale the handle this->Glypher->SetScaleFactor(sf); - if(this->ShowSelectedNodes && this->SelectedNodesGlypher) + if (this->ShowSelectedNodes && this->SelectedNodesGlypher) { this->SelectedNodesGlypher->SetScaleFactor(sf); } @@ -579,12 +581,12 @@ void vtkOrientedGlyphContourRepresentation::Scale(double eventPos[2]) void vtkOrientedGlyphContourRepresentation::CreateDefaultProperties() { this->Property = vtkProperty::New(); - this->Property->SetColor(1.0,1.0,1.0); + this->Property->SetColor(1.0, 1.0, 1.0); this->Property->SetLineWidth(0.5); this->Property->SetPointSize(3); this->ActiveProperty = vtkProperty::New(); - this->ActiveProperty->SetColor(0.0,1.0,0.0); + this->ActiveProperty->SetColor(0.0, 1.0, 0.0); this->ActiveProperty->SetRepresentationToWireframe(); this->ActiveProperty->SetAmbient(1.0); this->ActiveProperty->SetDiffuse(0.0); @@ -595,7 +597,7 @@ void vtkOrientedGlyphContourRepresentation::CreateDefaultProperties() this->LinesProperty->SetAmbient(1.0); this->LinesProperty->SetDiffuse(0.0); this->LinesProperty->SetSpecular(0.0); - this->LinesProperty->SetColor(1,1,1); + this->LinesProperty->SetColor(1, 1, 1); this->LinesProperty->SetLineWidth(1); } @@ -609,7 +611,7 @@ void vtkOrientedGlyphContourRepresentation::BuildLines() vtkIdType index = 0; int count = this->GetNumberOfNodes(); - for ( i = 0; i < this->GetNumberOfNodes(); i++ ) + for (i = 0; i < this->GetNumberOfNodes(); i++) { count += this->GetNumberOfIntermediatePoints(i); } @@ -617,7 +619,7 @@ void vtkOrientedGlyphContourRepresentation::BuildLines() points->SetNumberOfPoints(count); vtkIdType numLines; - if ( this->ClosedLoop && count > 0 ) + if (this->ClosedLoop && count > 0) { numLines = count+1; } @@ -626,41 +628,41 @@ void vtkOrientedGlyphContourRepresentation::BuildLines() numLines = count; } - if ( numLines > 0 ) + if (numLines > 0) { vtkIdType *lineIndices = new vtkIdType[numLines]; double pos[3]; - for ( i = 0; i < this->GetNumberOfNodes(); i++ ) + for (i = 0; i < this->GetNumberOfNodes(); i++) { // Add the node - this->GetNthNodeWorldPosition( i, pos ); - points->InsertPoint( index, pos ); + this->GetNthNodeWorldPosition(i, pos); + points->InsertPoint(index, pos); lineIndices[index] = index; index++; int numIntermediatePoints = this->GetNumberOfIntermediatePoints(i); - for ( j = 0; j < numIntermediatePoints; j++ ) + for (j = 0; j < numIntermediatePoints; j++) { - this->GetIntermediatePointWorldPosition( i, j, pos ); - points->InsertPoint( index, pos ); + this->GetIntermediatePointWorldPosition(i, j, pos); + points->InsertPoint(index, pos); lineIndices[index] = index; index++; } } - if ( this->ClosedLoop ) + if (this->ClosedLoop) { lineIndices[index] = 0; } - lines->InsertNextCell( numLines, lineIndices ); + lines->InsertNextCell(numLines, lineIndices); delete [] lineIndices; } - this->Lines->SetPoints( points ); - this->Lines->SetLines( lines ); + this->Lines->SetPoints(points); + this->Lines->SetLines(lines); points->Delete(); lines->Delete(); @@ -734,7 +736,7 @@ void vtkOrientedGlyphContourRepresentation::BuildRepresentation() this->Renderer->GetWorldPoint(p2); double distance = - sqrt( vtkMath::Distance2BetweenPoints(p1,p2) ); + sqrt(vtkMath::Distance2BetweenPoints(p1, p2)); int *size = this->Renderer->GetRenderWindow()->GetSize(); double viewport[4]; @@ -745,40 +747,40 @@ void vtkOrientedGlyphContourRepresentation::BuildRepresentation() x = size[0] * (viewport[2]-viewport[0]); y = size[1] * (viewport[3]-viewport[1]); - scale = sqrt( x*x + y*y ); + scale = sqrt(x*x + y*y); - distance = 1000* distance / scale; + distance = 1000 * distance / scale; - this->Glypher->SetScaleFactor( distance * this->HandleSize ); - this->ActiveGlypher->SetScaleFactor( distance * this->HandleSize ); + this->Glypher->SetScaleFactor(distance * this->HandleSize); + this->ActiveGlypher->SetScaleFactor(distance * this->HandleSize); int numPoints = this->GetNumberOfNodes(); int i; - if(this->ShowSelectedNodes && this->SelectedNodesGlypher) + if (this->ShowSelectedNodes && this->SelectedNodesGlypher) { - this->SelectedNodesGlypher->SetScaleFactor( distance * this->HandleSize ); + this->SelectedNodesGlypher->SetScaleFactor(distance * this->HandleSize); this->FocalPoint->Reset(); this->FocalPoint->SetNumberOfPoints(0); this->FocalData->GetPointData()->GetNormals()->SetNumberOfTuples(0); this->SelectedNodesPoints->Reset(); this->SelectedNodesPoints->SetNumberOfPoints(0); this->SelectedNodesData->GetPointData()->GetNormals()->SetNumberOfTuples(0); - for ( i = 0; i < numPoints; i++ ) + for (i = 0; i < numPoints; i++) { - if ( i != this->ActiveNode ) + if (i != this->ActiveNode) { double worldPos[3]; double worldOrient[9]; - this->GetNthNodeWorldPosition( i, worldPos ); - this->GetNthNodeWorldOrientation( i, worldOrient ); - if(this->GetNthNodeSelected(i)) + this->GetNthNodeWorldPosition(i, worldPos); + this->GetNthNodeWorldOrientation(i, worldOrient); + if (this->GetNthNodeSelected(i)) { - this->SelectedNodesPoints->InsertNextPoint(worldPos ); + this->SelectedNodesPoints->InsertNextPoint(worldPos); this->SelectedNodesData->GetPointData()->GetNormals()->InsertNextTuple(worldOrient+6); } else { - this->FocalPoint->InsertNextPoint(worldPos ); + this->FocalPoint->InsertNextPoint(worldPos); this->FocalData->GetPointData()->GetNormals()->InsertNextTuple(worldOrient+6); } } @@ -789,8 +791,8 @@ void vtkOrientedGlyphContourRepresentation::BuildRepresentation() } else { - if ( this->ActiveNode >= 0 && - this->ActiveNode < this->GetNumberOfNodes() ) + if (this->ActiveNode >= 0 && + this->ActiveNode < this->GetNumberOfNodes()) { this->FocalPoint->SetNumberOfPoints(numPoints-1); this->FocalData->GetPointData()->GetNormals()->SetNumberOfTuples(numPoints-1); @@ -801,16 +803,16 @@ void vtkOrientedGlyphContourRepresentation::BuildRepresentation() this->FocalData->GetPointData()->GetNormals()->SetNumberOfTuples(numPoints); } int idx = 0; - for ( i = 0; i < numPoints; i++ ) + for (i = 0; i < numPoints; i++) { - if ( i != this->ActiveNode ) + if (i != this->ActiveNode) { double worldPos[3]; double worldOrient[9]; - this->GetNthNodeWorldPosition( i, worldPos ); - this->GetNthNodeWorldOrientation( i, worldOrient ); - this->FocalPoint->SetPoint(idx, worldPos ); - this->FocalData->GetPointData()->GetNormals()->SetTuple(idx,worldOrient+6); + this->GetNthNodeWorldPosition(i, worldPos); + this->GetNthNodeWorldOrientation(i, worldOrient); + this->FocalPoint->SetPoint(idx, worldPos); + this->FocalData->GetPointData()->GetNormals()->SetTuple(idx, worldOrient+6); idx++; } } @@ -820,15 +822,15 @@ void vtkOrientedGlyphContourRepresentation::BuildRepresentation() this->FocalData->GetPointData()->GetNormals()->Modified(); this->FocalData->Modified(); - if ( this->ActiveNode >= 0 && - this->ActiveNode < this->GetNumberOfNodes() ) + if (this->ActiveNode >= 0 && + this->ActiveNode < this->GetNumberOfNodes()) { double worldPos[3]; double worldOrient[9]; - this->GetNthNodeWorldPosition( this->ActiveNode, worldPos ); - this->GetNthNodeWorldOrientation( this->ActiveNode, worldOrient ); - this->ActiveFocalPoint->SetPoint(0, worldPos ); - this->ActiveFocalData->GetPointData()->GetNormals()->SetTuple(0,worldOrient+6); + this->GetNthNodeWorldPosition(this->ActiveNode, worldPos); + this->GetNthNodeWorldOrientation(this->ActiveNode, worldOrient); + this->ActiveFocalPoint->SetPoint(0, worldPos); + this->ActiveFocalData->GetPointData()->GetNormals()->SetTuple(0, worldOrient+6); this->ActiveFocalPoint->Modified(); this->ActiveFocalData->GetPointData()->GetNormals()->Modified(); @@ -848,14 +850,15 @@ void vtkOrientedGlyphContourRepresentation::GetActors(vtkPropCollection *pc) this->Actor->GetActors(pc); this->ActiveActor->GetActors(pc); this->LinesActor->GetActors(pc); - if(this->ShowSelectedNodes && this->SelectedNodesActor) + if (this->ShowSelectedNodes && this->SelectedNodesActor) { this->SelectedNodesActor->GetActors(pc); } } //---------------------------------------------------------------------- -void vtkOrientedGlyphContourRepresentation::ReleaseGraphicsResources(vtkWindow *win) +void vtkOrientedGlyphContourRepresentation::ReleaseGraphicsResources( + vtkWindow *win) { this->Actor->ReleaseGraphicsResources(win); this->ActiveActor->ReleaseGraphicsResources(win); @@ -867,11 +870,11 @@ int vtkOrientedGlyphContourRepresentation::RenderOverlay(vtkViewport *viewport) { int count=0; count += this->LinesActor->RenderOverlay(viewport); - if ( this->Actor->GetVisibility() ) + if (this->Actor->GetVisibility()) { count += this->Actor->RenderOverlay(viewport); } - if ( this->ActiveActor->GetVisibility() ) + if (this->ActiveActor->GetVisibility()) { count += this->ActiveActor->RenderOverlay(viewport); } @@ -888,15 +891,15 @@ int vtkOrientedGlyphContourRepresentation::RenderOpaqueGeometry( int count=0; count += this->LinesActor->RenderOpaqueGeometry(viewport); - if ( this->Actor->GetVisibility() ) + if (this->Actor->GetVisibility()) { count += this->Actor->RenderOpaqueGeometry(viewport); } - if ( this->ActiveActor->GetVisibility() ) + if (this->ActiveActor->GetVisibility()) { count += this->ActiveActor->RenderOpaqueGeometry(viewport); } - if(this->ShowSelectedNodes && this->SelectedNodesActor && + if (this->ShowSelectedNodes && this->SelectedNodesActor && this->SelectedNodesActor->GetVisibility()) { count += this->SelectedNodesActor->RenderOpaqueGeometry(viewport); @@ -911,11 +914,11 @@ int vtkOrientedGlyphContourRepresentation::RenderTranslucentPolygonalGeometry( { int count=0; count += this->LinesActor->RenderTranslucentPolygonalGeometry(viewport); - if ( this->Actor->GetVisibility() ) + if (this->Actor->GetVisibility()) { count += this->Actor->RenderTranslucentPolygonalGeometry(viewport); } - if ( this->ActiveActor->GetVisibility() ) + if (this->ActiveActor->GetVisibility()) { count += this->ActiveActor->RenderTranslucentPolygonalGeometry(viewport); } @@ -927,11 +930,11 @@ int vtkOrientedGlyphContourRepresentation::HasTranslucentPolygonalGeometry() { int result=0; result |= this->LinesActor->HasTranslucentPolygonalGeometry(); - if ( this->Actor->GetVisibility() ) + if (this->Actor->GetVisibility()) { result |= this->Actor->HasTranslucentPolygonalGeometry(); } - if ( this->ActiveActor->GetVisibility() ) + if (this->ActiveActor->GetVisibility()) { result |= this->ActiveActor->HasTranslucentPolygonalGeometry(); } @@ -942,15 +945,14 @@ int vtkOrientedGlyphContourRepresentation::HasTranslucentPolygonalGeometry() void vtkOrientedGlyphContourRepresentation::SetLineColor( double r, double g, double b) { - if(this->GetLinesProperty()) + if (this->GetLinesProperty()) { this->GetLinesProperty()->SetColor(r, g, b); } } //---------------------------------------------------------------------- -void vtkOrientedGlyphContourRepresentation::SetShowSelectedNodes( - int flag ) +void vtkOrientedGlyphContourRepresentation::SetShowSelectedNodes(int flag) { vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting ShowSelectedNodes to " << flag); @@ -959,9 +961,9 @@ void vtkOrientedGlyphContourRepresentation::SetShowSelectedNodes( this->ShowSelectedNodes = flag; this->Modified(); - if(this->ShowSelectedNodes) + if (this->ShowSelectedNodes) { - if(!this->SelectedNodesActor) + if (!this->SelectedNodesActor) { this->CreateSelectedNodesRepresentation(); } @@ -972,7 +974,7 @@ void vtkOrientedGlyphContourRepresentation::SetShowSelectedNodes( } else { - if(this->SelectedNodesActor) + if (this->SelectedNodesActor) { this->SelectedNodesActor->SetVisibility(0); } @@ -981,7 +983,7 @@ void vtkOrientedGlyphContourRepresentation::SetShowSelectedNodes( } //---------------------------------------------------------------------- -double* vtkOrientedGlyphContourRepresentation::GetBounds() +double *vtkOrientedGlyphContourRepresentation::GetBounds() { return this->Lines->GetPoints() ? this->Lines->GetPoints()->GetBounds() : NULL; @@ -1001,14 +1003,14 @@ void vtkOrientedGlyphContourRepresentation::CreateSelectedNodesRepresentation() this->SelectedNodesPoints = vtkPoints::New(); this->SelectedNodesPoints->SetNumberOfPoints(100); //this->SelectedNodesPoints->SetNumberOfPoints(1); - //this->SelectedNodesPoints->SetPoint(0, 0.0,0.0,0.0); + //this->SelectedNodesPoints->SetPoint(0, 0.0, 0.0, 0.0); vtkDoubleArray *normals = vtkDoubleArray::New(); normals->SetNumberOfComponents(3); normals->SetNumberOfTuples(100); normals->SetNumberOfTuples(1); - double n[3] = {0,0,0}; - normals->SetTuple(0,n); + double n[3] = {0, 0, 0}; + normals->SetTuple(0, n); this->SelectedNodesData = vtkPolyData::New(); this->SelectedNodesData->SetPoints(this->SelectedNodesPoints); @@ -1031,8 +1033,8 @@ void vtkOrientedGlyphContourRepresentation::CreateSelectedNodesRepresentation() this->SelectedNodesMapper->ScalarVisibilityOff(); this->SelectedNodesMapper->ImmediateModeRenderingOn(); - vtkProperty* selProperty = vtkProperty::New(); - selProperty->SetColor(0.0,1.0,0.0); + vtkProperty *selProperty = vtkProperty::New(); + selProperty->SetColor(0.0, 1.0, 0.0); selProperty->SetLineWidth(0.5); selProperty->SetPointSize(3); @@ -1047,13 +1049,13 @@ void vtkOrientedGlyphContourRepresentation::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os, indent); os << indent << "Always On Top: " << (this->AlwaysOnTop ? "On\n" : "Off\n"); os << indent << "ShowSelectedNodes: " << this->ShowSelectedNodes << endl; - if ( this->Property ) + if (this->Property) { os << indent << "Property: " << this->Property << "\n"; } @@ -1062,7 +1064,7 @@ void vtkOrientedGlyphContourRepresentation::PrintSelf(ostream& os, os << indent << "Property: (none)\n"; } - if ( this->ActiveProperty ) + if (this->ActiveProperty) { os << indent << "Active Property: " << this->ActiveProperty << "\n"; } @@ -1071,7 +1073,7 @@ void vtkOrientedGlyphContourRepresentation::PrintSelf(ostream& os, os << indent << "Active Property: (none)\n"; } - if ( this->LinesProperty ) + if (this->LinesProperty) { os << indent << "Lines Property: " << this->LinesProperty << "\n"; } diff --git a/Interaction/Widgets/vtkOrientedGlyphContourRepresentation.h b/Interaction/Widgets/vtkOrientedGlyphContourRepresentation.h index 133c7820539..b07881b0c01 100644 --- a/Interaction/Widgets/vtkOrientedGlyphContourRepresentation.h +++ b/Interaction/Widgets/vtkOrientedGlyphContourRepresentation.h @@ -49,7 +49,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkOrientedGlyphContourRepresentation : publi // Description: // Specify the cursor shape. Keep in mind that the shape will be - // aligned with the constraining plane by orienting it such that + // aligned with the constraining plane by orienting it such that // the x axis of the geometry lies along the normal of the plane. void SetCursorShape(vtkPolyData *cursorShape); vtkPolyData *GetCursorShape(); diff --git a/Interaction/Widgets/vtkParallelopipedWidget.h b/Interaction/Widgets/vtkParallelopipedWidget.h index b3cf100216b..c3d505a83cc 100644 --- a/Interaction/Widgets/vtkParallelopipedWidget.h +++ b/Interaction/Widgets/vtkParallelopipedWidget.h @@ -49,9 +49,9 @@ class vtkWidgetSet; class VTKINTERACTIONWIDGETS_EXPORT vtkParallelopipedWidget : public vtkAbstractWidget { - //BTX + friend class vtkWidgetSet; - //ETX + public: // Description: // Instantiate the object. @@ -124,7 +124,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkParallelopipedWidget : public vtkAbstractW // The positioning handle widgets vtkHandleWidget **HandleWidgets; - //BTX // Description: // Events invoked by this widget enum WidgetEventIds @@ -133,7 +132,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkParallelopipedWidget : public vtkAbstractW RequestResizeAlongAnAxisEvent, RequestChairModeEvent }; - //ETX vtkWidgetSet* WidgetSet; diff --git a/Interaction/Widgets/vtkPlaneWidget.cxx b/Interaction/Widgets/vtkPlaneWidget.cxx index c63bb74e168..c6394c88634 100644 --- a/Interaction/Widgets/vtkPlaneWidget.cxx +++ b/Interaction/Widgets/vtkPlaneWidget.cxx @@ -285,6 +285,12 @@ void vtkPlaneWidget::SetEnabled(int enabling) this->EventCallbackCommand, this->Priority); i->AddObserver(vtkCommand::RightButtonReleaseEvent, this->EventCallbackCommand, this->Priority); + i->AddObserver(vtkCommand::StartPinchEvent, + this->EventCallbackCommand, this->Priority); + i->AddObserver(vtkCommand::PinchEvent, + this->EventCallbackCommand, this->Priority); + i->AddObserver(vtkCommand::EndPinchEvent, + this->EventCallbackCommand, this->Priority); // Add the plane this->CurrentRenderer->AddActor(this->PlaneActor); @@ -386,6 +392,15 @@ void vtkPlaneWidget::ProcessEvents(vtkObject* vtkNotUsed(object), case vtkCommand::MouseMoveEvent: self->OnMouseMove(); break; + case vtkCommand::StartPinchEvent: + self->OnStartPinch(); + break; + case vtkCommand::PinchEvent: + self->OnPinch(); + break; + case vtkCommand::EndPinchEvent: + self->OnEndPinch(); + break; } } @@ -582,6 +597,87 @@ void vtkPlaneWidget::HighlightPlane(int highlight) } } +void vtkPlaneWidget::OnStartPinch() +{ + int X = this->Interactor->GetEventPosition()[0]; + int Y = this->Interactor->GetEventPosition()[1]; + + // Okay, make sure that the pick is in the current renderer + if (!this->CurrentRenderer || !this->CurrentRenderer->IsInViewport(X, Y)) + { + this->State = vtkPlaneWidget::Outside; + return; + } + + // Okay, we can process this. try to pick the plane. + vtkAssemblyPath* path = this->GetAssemblyPath(X, Y, 0., this->PlanePicker); + + if ( path != NULL ) + { + this->State = vtkPlaneWidget::Pinching; + this->HighlightPlane(1); + this->StartInteraction(); + this->InvokeEvent(vtkCommand::StartInteractionEvent,NULL); + } +} + +void vtkPlaneWidget::OnPinch() +{ + if ( this->State != vtkPlaneWidget::Pinching) + { + return; + } + + double sf = this->Interactor->GetScale()/this->Interactor->GetLastScale(); + double *o = this->PlaneSource->GetOrigin(); + double *pt1 = this->PlaneSource->GetPoint1(); + double *pt2 = this->PlaneSource->GetPoint2(); + + double center[3]; + center[0] = 0.5 * ( pt1[0] + pt2[0] ); + center[1] = 0.5 * ( pt1[1] + pt2[1] ); + center[2] = 0.5 * ( pt1[2] + pt2[2] ); + + // Move the corner points + double origin[3], point1[3], point2[3]; + for (int i=0; i<3; i++) + { + origin[i] = sf * (o[i] - center[i]) + center[i]; + point1[i] = sf * (pt1[i] - center[i]) + center[i]; + point2[i] = sf * (pt2[i] - center[i]) + center[i]; + } + + this->PlaneSource->SetOrigin(origin); + this->PlaneSource->SetPoint1(point1); + this->PlaneSource->SetPoint2(point2); + this->PlaneSource->Update(); + + this->PositionHandles(); + + this->EventCallbackCommand->SetAbortFlag(1); + this->InvokeEvent(vtkCommand::InteractionEvent,NULL); + this->Interactor->Render(); +} + +void vtkPlaneWidget::OnEndPinch() +{ + if ( this->State != vtkPlaneWidget::Pinching) + { + return; + } + + this->State = vtkPlaneWidget::Start; + this->HighlightHandle(NULL); + this->HighlightPlane(0); + this->HighlightNormal(0); + this->SizeHandles(); + + this->EventCallbackCommand->SetAbortFlag(1); + this->EndInteraction(); + this->InvokeEvent(vtkCommand::EndInteractionEvent,NULL); + this->Interactor->Render(); +} + void vtkPlaneWidget::OnLeftButtonDown() { int X = this->Interactor->GetEventPosition()[0]; @@ -962,6 +1058,12 @@ void vtkPlaneWidget::MovePoint1(double *p1, double *p2) double n02 = vtkMath::Norm(p02); double n32 = vtkMath::Norm(p32); + // if there is no motion then return + if (vN == 0.0) + { + return; + } + // Project v onto these vector to determine the amount of motion // Scale it by the relative size of the motion to the vector length double d1 = (vN/n02) * vtkMath::Dot(v,p02) / (vN*n02); @@ -1013,6 +1115,12 @@ void vtkPlaneWidget::MovePoint2(double *p1, double *p2) double n31 = vtkMath::Norm(p31); double n01 = vtkMath::Norm(p01); + // if there is no motion then return + if (vN == 0.0) + { + return; + } + // Project v onto these vector to determine the amount of motion // Scale it by the relative size of the motion to the vector length double d1 = (vN/n31) * vtkMath::Dot(v,p31) / (vN*n31); @@ -1058,6 +1166,12 @@ void vtkPlaneWidget::MovePoint3(double *p1, double *p2) double n10 = vtkMath::Norm(p10); double n20 = vtkMath::Norm(p20); + // if there is no motion then return + if (vN == 0.0) + { + return; + } + // Project v onto these vector to determine the amount of motion // Scale it by the relative size of the motion to the vector length double d1 = (vN/n10) * vtkMath::Dot(v,p10) / (vN*n10); diff --git a/Interaction/Widgets/vtkPlaneWidget.h b/Interaction/Widgets/vtkPlaneWidget.h index c543b5964a8..694913d1417 100644 --- a/Interaction/Widgets/vtkPlaneWidget.h +++ b/Interaction/Widgets/vtkPlaneWidget.h @@ -244,7 +244,8 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkPlaneWidget : public vtkPolyDataSourceWidg Pushing, Rotating, Spinning, - Outside + Outside, + Pinching }; //handles the events @@ -261,6 +262,9 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkPlaneWidget : public vtkPolyDataSourceWidg void OnRightButtonDown(); void OnRightButtonUp(); void OnMouseMove(); + void OnStartPinch(); + void OnPinch(); + void OnEndPinch(); // controlling ivars int NormalToXAxis; diff --git a/Interaction/Widgets/vtkPointHandleRepresentation3D.cxx b/Interaction/Widgets/vtkPointHandleRepresentation3D.cxx index 9038de6d371..d9ec1074364 100644 --- a/Interaction/Widgets/vtkPointHandleRepresentation3D.cxx +++ b/Interaction/Widgets/vtkPointHandleRepresentation3D.cxx @@ -277,7 +277,6 @@ void vtkPointHandleRepresentation3D::StartWidgetInteraction(double startEventPos vtkAssemblyPath* path = this->GetAssemblyPath( startEventPos[0], startEventPos[1], 0., this->CursorPicker); - path = this->CursorPicker->GetPath(); if ( path != NULL ) { this->InteractionState = vtkHandleRepresentation::Nearby; diff --git a/Interaction/Widgets/vtkPolyLineRepresentation.cxx b/Interaction/Widgets/vtkPolyLineRepresentation.cxx index db61574ec09..a2976a77ee8 100644 --- a/Interaction/Widgets/vtkPolyLineRepresentation.cxx +++ b/Interaction/Widgets/vtkPolyLineRepresentation.cxx @@ -78,7 +78,7 @@ vtkPolyLineRepresentation::~vtkPolyLineRepresentation() //---------------------------------------------------------------------------- vtkDoubleArray* vtkPolyLineRepresentation::GetHandlePositions() { - return vtkDoubleArray::SafeDownCast( + return vtkArrayDownCast( this->PolyLineSource->GetPoints()->GetData()); } diff --git a/Interaction/Widgets/vtkPolyLineRepresentation.h b/Interaction/Widgets/vtkPolyLineRepresentation.h index 52b96cacf15..86477d77c23 100644 --- a/Interaction/Widgets/vtkPolyLineRepresentation.h +++ b/Interaction/Widgets/vtkPolyLineRepresentation.h @@ -73,7 +73,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkPolyLineRepresentation : public vtkCurveRe // Build the representation for the poly line. virtual void BuildRepresentation(); -//BTX protected: vtkPolyLineRepresentation(); ~vtkPolyLineRepresentation(); @@ -87,7 +86,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkPolyLineRepresentation : public vtkCurveRe private: vtkPolyLineRepresentation(const vtkPolyLineRepresentation&); // Not implemented. void operator=(const vtkPolyLineRepresentation&); // Not implemented. -//ETX + }; #endif diff --git a/Interaction/Widgets/vtkPolyLineWidget.h b/Interaction/Widgets/vtkPolyLineWidget.h index 803f47087ee..71206a771da 100644 --- a/Interaction/Widgets/vtkPolyLineWidget.h +++ b/Interaction/Widgets/vtkPolyLineWidget.h @@ -49,7 +49,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkPolyLineWidget : public vtkAbstractWidget // Create the default widget representation if one is not set. By default, // this is an instance of the vtkPolyLineRepresentation class. void CreateDefaultRepresentation(); -//BTX + protected: vtkPolyLineWidget(); ~vtkPolyLineWidget(); @@ -67,7 +67,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkPolyLineWidget : public vtkAbstractWidget private: vtkPolyLineWidget(const vtkPolyLineWidget&); // Not implemented. void operator=(const vtkPolyLineWidget&); // Not implemented. -//ETX + }; #endif diff --git a/Interaction/Widgets/vtkPolygonalSurfacePointPlacer.h b/Interaction/Widgets/vtkPolygonalSurfacePointPlacer.h index d9434df58b6..a86340231fc 100644 --- a/Interaction/Widgets/vtkPolygonalSurfacePointPlacer.h +++ b/Interaction/Widgets/vtkPolygonalSurfacePointPlacer.h @@ -39,7 +39,6 @@ class vtkCellPicker; class vtkPolygonalSurfacePointPlacerInternals; class vtkPolyData; -//BTX // The Node stores information about the point. This information is used by // the interpolator. Reusing this information avoids the need for a second // pick operation to regenerate it. (Cellpickers are slow). @@ -52,7 +51,6 @@ struct vtkPolygonalSurfacePointPlacerNode double ParametricCoords[3]; // parametric coords within cell vtkPolyData *PolyData; }; -//ETX class VTKINTERACTIONWIDGETS_EXPORT vtkPolygonalSurfacePointPlacer : public vtkPolyDataPointPlacer @@ -141,12 +139,10 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkPolygonalSurfacePointPlacer vtkGetMacro( SnapToClosestPoint, int ); vtkBooleanMacro( SnapToClosestPoint, int ); -//BTX // Description: // Internally used by the interpolator. typedef vtkPolygonalSurfacePointPlacerNode Node; Node *GetNodeAtWorldPosition( double worldPos[3] ); -//ETX protected: vtkPolygonalSurfacePointPlacer(); diff --git a/Interaction/Widgets/vtkProgressBarRepresentation.cxx b/Interaction/Widgets/vtkProgressBarRepresentation.cxx new file mode 100644 index 00000000000..5f7b5a26c40 --- /dev/null +++ b/Interaction/Widgets/vtkProgressBarRepresentation.cxx @@ -0,0 +1,267 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkProgressBarRepresentation.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkProgressBarRepresentation.h" + +#include "vtkActor2D.h" +#include "vtkCellArray.h" +#include "vtkNew.h" +#include "vtkObjectFactory.h" +#include "vtkPointData.h" +#include "vtkPoints.h" +#include "vtkPolyData.h" +#include "vtkPolyDataMapper2D.h" +#include "vtkPropCollection.h" +#include "vtkProperty2D.h" +#include "vtkTransform.h" +#include "vtkTransformPolyDataFilter.h" +#include "vtkUnsignedCharArray.h" + +const double PROGRESS_BAR_WIDTH = 12; +const double PROGRESS_BAR_HEIGHT = 2; + +vtkStandardNewMacro(vtkProgressBarRepresentation); + +vtkProgressBarRepresentation::vtkProgressBarRepresentation() +{ + this->ProgressRate = 0; + this->ProgressBarColor[0] = 0; + this->ProgressBarColor[1] = 1; + this->ProgressBarColor[2] = 0; + this->BackgroundColor[0] = 1; + this->BackgroundColor[1] = 1; + this->BackgroundColor[2] = 1; + this->DrawBackground = true; + + // Set up the geometry + double size[2]; + this->GetSize(size); + this->Position2Coordinate->SetValue(0.04*size[0], 0.04*size[1]); + this->ProportionalResizeOff(); + this->Moving = 1; + this->SetShowBorder(vtkBorderRepresentation::BORDER_ACTIVE); + + // Create the geometry in canonical coordinates + this->Points = vtkPoints::New(); + this->Points->SetDataTypeToDouble(); + this->Points->SetNumberOfPoints(10); + this->Points->SetPoint(0, 0.2, 0.2, 0.0); + this->Points->SetPoint(1, 0.2, PROGRESS_BAR_HEIGHT, 0.0); + this->Points->SetPoint(2, PROGRESS_BAR_WIDTH, + PROGRESS_BAR_HEIGHT, 0.0); + this->Points->SetPoint(3, PROGRESS_BAR_WIDTH, 0.2, 0.0); + double progressPoint = 0.2 + + (this->ProgressRate * (PROGRESS_BAR_WIDTH - 0.2)); + this->Points->SetPoint(4, 0.2, 0.2, 0.0); + this->Points->SetPoint(5, 0.2, PROGRESS_BAR_HEIGHT, 0.0); + this->Points->SetPoint(6, progressPoint, PROGRESS_BAR_HEIGHT, 0.0); + this->Points->SetPoint(7, progressPoint, 0.2, 0.0); + + // Frame + vtkNew lines; + vtkIdType linesIds[5] = {0, 1, 2, 3, 0}; + lines->InsertNextCell(5, linesIds); + + // Progress bar + vtkNew polys; + vtkIdType polysIds[4] = {4, 5, 6, 7}; + polys->InsertNextCell(4, polysIds); + + vtkNew polydata; + polydata->SetPoints(this->Points); + polydata->SetLines(lines.Get()); + polydata->SetPolys(polys.Get()); + + // Create cell data to color cells + this->ProgressBarData = vtkUnsignedCharArray::New(); + this->ProgressBarData->SetName("Color"); + this->ProgressBarData->SetNumberOfComponents(3); + this->ProgressBarData->SetNumberOfTuples(8); + polydata->GetPointData()->SetScalars(this->ProgressBarData); + + // Add a transform to position progress bar + // and a mapper and actor + vtkNew transformFilter; + transformFilter->SetTransform(this->BWTransform); + transformFilter->SetInputData(polydata.Get()); + vtkNew mapper; + mapper->SetInputConnection( + transformFilter->GetOutputPort()); + this->Property = vtkProperty2D::New(); + this->Actor = vtkActor2D::New(); + this->Actor->SetMapper(mapper.Get()); + this->Actor->SetProperty(this->Property); + + // Background cell + vtkNew background; + background->InsertNextCell(4, linesIds); + + // Background polydata + vtkNew backgroundPolydata; + backgroundPolydata->SetPoints(this->Points); + backgroundPolydata->SetPolys(background.Get()); + + // Create cell data to color background + this->BackgroundData = vtkUnsignedCharArray::New(); + this->BackgroundData->SetNumberOfComponents(3); + this->BackgroundData->SetNumberOfTuples(4); + backgroundPolydata->GetPointData()->SetScalars(this->BackgroundData); + + // Add transform, mapper and actor + vtkNew backgroundTransformFilter; + backgroundTransformFilter->SetTransform(this->BWTransform); + backgroundTransformFilter->SetInputData(backgroundPolydata.Get()); + vtkNew backgroundMapper; + backgroundMapper->SetInputConnection( + backgroundTransformFilter->GetOutputPort()); + this->BackgroundActor = vtkActor2D::New(); + this->BackgroundActor->SetMapper(backgroundMapper.Get()); +} + +//------------------------------------------------------------------------- +vtkProgressBarRepresentation::~vtkProgressBarRepresentation() +{ + this->Points->Delete(); + this->ProgressBarData->Delete(); + this->BackgroundData->Delete(); + this->Property->Delete(); + this->Actor->Delete(); + this->BackgroundActor->Delete(); +} + +//------------------------------------------------------------------------- +void vtkProgressBarRepresentation::BuildRepresentation() +{ + // Reposition progress bar points + double progressPoint = 0.2 + + (this->ProgressRate * (PROGRESS_BAR_WIDTH - 0.2)); + this->Points->SetPoint(6, progressPoint, PROGRESS_BAR_HEIGHT, 0.0); + this->Points->SetPoint(7, progressPoint, 0.2, 0.0); + this->Points->Modified(); + + // Set color + double backgroundColor[3] = { this->BackgroundColor[0] * 255, + this->BackgroundColor[1] * 255, this->BackgroundColor[2] * 255}; + double progressBarColor[3] = {this->ProgressBarColor[0] * 255, + this->ProgressBarColor[1] * 255, this->ProgressBarColor[2] * 255}; + for (int i = 0; i < 4; i++) + { + this->ProgressBarData->SetTuple(i, backgroundColor); + this->BackgroundData->SetTuple(i, backgroundColor); + this->ProgressBarData->SetTuple(i+4, progressBarColor); + } + + // Note that the transform is updated by the superclass + this->Superclass::BuildRepresentation(); +} + +//------------------------------------------------------------------------- +void vtkProgressBarRepresentation::GetSize(double size[2]) +{ + size[0] = PROGRESS_BAR_WIDTH + 0.2; + size[1] = PROGRESS_BAR_HEIGHT + 0.2; +} + +//------------------------------------------------------------------------- +void vtkProgressBarRepresentation::GetActors2D(vtkPropCollection *pc) +{ + if (this->DrawBackground) + { + pc->AddItem(this->BackgroundActor); + } + pc->AddItem(this->Actor); + this->Superclass::GetActors2D(pc); +} + +//------------------------------------------------------------------------- +void vtkProgressBarRepresentation::ReleaseGraphicsResources(vtkWindow *w) +{ + if (this->DrawBackground) + { + this->BackgroundActor->ReleaseGraphicsResources(w); + } + this->Actor->ReleaseGraphicsResources(w); + this->Superclass::ReleaseGraphicsResources(w); +} + +//------------------------------------------------------------------------- +int vtkProgressBarRepresentation::RenderOverlay(vtkViewport *w) +{ + int count = this->Superclass::RenderOverlay(w); + if (this->DrawBackground) + { + count += this->BackgroundActor->RenderOverlay(w); + } + count += this->Actor->RenderOverlay(w); + return count; +} + +//------------------------------------------------------------------------- +int vtkProgressBarRepresentation::RenderOpaqueGeometry(vtkViewport *w) +{ + int count = this->Superclass::RenderOpaqueGeometry(w); + if (this->DrawBackground) + { + count += this->BackgroundActor->RenderOpaqueGeometry(w); + } + count += this->Actor->RenderOpaqueGeometry(w); + return count; +} + +//----------------------------------------------------------------------------- +int vtkProgressBarRepresentation::RenderTranslucentPolygonalGeometry( + vtkViewport *w) +{ + int count = this->Superclass::RenderTranslucentPolygonalGeometry(w); + if (this->DrawBackground) + { + count += this->BackgroundActor->RenderTranslucentPolygonalGeometry(w); + } + count += this->Actor->RenderTranslucentPolygonalGeometry(w); + return count; +} + +//----------------------------------------------------------------------------- +int vtkProgressBarRepresentation::HasTranslucentPolygonalGeometry() +{ + int result = this->Superclass::HasTranslucentPolygonalGeometry(); + if (this->DrawBackground) + { + result |= this->BackgroundActor->HasTranslucentPolygonalGeometry(); + } + result |= this->Actor->HasTranslucentPolygonalGeometry(); + return result; +} + +//------------------------------------------------------------------------- +void vtkProgressBarRepresentation::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + + if (this->Property) + { + os << indent << "Property:\n"; + this->Property->PrintSelf(os, indent.GetNextIndent()); + } + else + { + os << indent << "Property: (none)\n"; + } + os << indent << "ProgressRate: " << this->ProgressRate << "\n"; + os << indent << "ProgressBarColor: " << this->ProgressBarColor[0] << " " + << this->ProgressBarColor[1] << " " <ProgressBarColor[2] << "\n"; + os << indent << "DrawBackground: " << this->DrawBackground << "\n"; + os << indent << "BackgroundColor: " << this->BackgroundColor[0] << " " + << this->BackgroundColor[1] << " " <BackgroundColor[2] << "\n"; +} diff --git a/Interaction/Widgets/vtkProgressBarRepresentation.h b/Interaction/Widgets/vtkProgressBarRepresentation.h new file mode 100644 index 00000000000..6aa625327cc --- /dev/null +++ b/Interaction/Widgets/vtkProgressBarRepresentation.h @@ -0,0 +1,112 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkProgressBarRepresentation.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkProgressBarRepresentation - represent a vtkProgressBarWidget +// .SECTION Description +// This class is used to represent a vtkProgressBarWidget. + +// .SECTION See Also +// vtkProgressBarWidget + +#ifndef vtkProgressBarRepresentation_h +#define vtkProgressBarRepresentation_h + +#include "vtkInteractionWidgetsModule.h" // For export macro +#include "vtkBorderRepresentation.h" + +class vtkActor2D; +class vtkPoints; +class vtkPolyData; +class vtkProperty2D; +class vtkUnsignedCharArray; + +class VTKINTERACTIONWIDGETS_EXPORT vtkProgressBarRepresentation : public vtkBorderRepresentation +{ +public: + // Description: + // Instantiate this class. + static vtkProgressBarRepresentation *New(); + + // Description: + // Standard VTK class methods. + vtkTypeMacro(vtkProgressBarRepresentation, vtkBorderRepresentation); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // By obtaining this property you can specify the properties of the + // representation. + vtkGetObjectMacro(Property, vtkProperty2D); + + // Description: + // Set/Get the progress rate of the progress bar, between 0 and 1 + // default is 0 + vtkSetClampMacro(ProgressRate, double, 0, 1); + vtkGetMacro(ProgressRate, double); + + // Description: + // Set/Get the progress bar color + // Default is pure green + vtkSetVector3Macro(ProgressBarColor, double); + vtkGetVector3Macro(ProgressBarColor, double); + + // Description: + // Set/Get the background color + // Default is white + vtkSetVector3Macro(BackgroundColor, double); + vtkGetVector3Macro(BackgroundColor, double); + + // Description: + // Set/Get background visibility + // Default is off + vtkSetMacro(DrawBackground, bool); + vtkGetMacro(DrawBackground, bool); + vtkBooleanMacro(DrawBackground, bool); + + // Description: + // Satisfy the superclasses' API. + virtual void BuildRepresentation(); + virtual void GetSize(double size[2]); + + // Description: + // These methods are necessary to make this representation behave as + // a vtkProp. + virtual void GetActors2D(vtkPropCollection*); + virtual void ReleaseGraphicsResources(vtkWindow*); + virtual int RenderOverlay(vtkViewport*); + virtual int RenderOpaqueGeometry(vtkViewport*); + virtual int RenderTranslucentPolygonalGeometry(vtkViewport*); + virtual int HasTranslucentPolygonalGeometry(); + +protected: + vtkProgressBarRepresentation(); + ~vtkProgressBarRepresentation(); + + double ProgressRate; + double ProgressBarColor[3]; + double BackgroundColor[3]; + bool DrawBackground; + + vtkPoints *Points; + vtkUnsignedCharArray *BackgroundData; + vtkUnsignedCharArray *ProgressBarData; + vtkProperty2D *Property; + vtkActor2D *Actor; + vtkActor2D *BackgroundActor; + +private: + vtkProgressBarRepresentation(const vtkProgressBarRepresentation&); //Not implemented + void operator=(const vtkProgressBarRepresentation&); //Not implemented +}; + +#endif diff --git a/Interaction/Widgets/vtkProgressBarWidget.cxx b/Interaction/Widgets/vtkProgressBarWidget.cxx new file mode 100644 index 00000000000..919baabe686 --- /dev/null +++ b/Interaction/Widgets/vtkProgressBarWidget.cxx @@ -0,0 +1,46 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkProgressBarWidget.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkProgressBarWidget.h" +#include "vtkProgressBarRepresentation.h" +#include "vtkCallbackCommand.h" +#include "vtkObjectFactory.h" + +vtkStandardNewMacro(vtkProgressBarWidget); + +//------------------------------------------------------------------------- +vtkProgressBarWidget::vtkProgressBarWidget() +{ + this->Selectable = 0; +} + +//------------------------------------------------------------------------- +vtkProgressBarWidget::~vtkProgressBarWidget() +{ +} + +//---------------------------------------------------------------------- +void vtkProgressBarWidget::CreateDefaultRepresentation() +{ + if (!this->WidgetRep) + { + this->WidgetRep = vtkProgressBarRepresentation::New(); + } +} + +//------------------------------------------------------------------------- +void vtkProgressBarWidget::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/Interaction/Widgets/vtkProgressBarWidget.h b/Interaction/Widgets/vtkProgressBarWidget.h new file mode 100644 index 00000000000..8b4866163b3 --- /dev/null +++ b/Interaction/Widgets/vtkProgressBarWidget.h @@ -0,0 +1,67 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkProgressBarWidget.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkProgressBarWidget - 2D widget for placing and manipulating a progress bar +// .SECTION Description +// This class provides support for interactively displaying and manipulating +// a progress bar.A Progress bar is defined by a progress rate and the color of the bar and +// its background. +// This widget allows you to interactively place and resize the progress bar. +// To use this widget, simply create a vtkProgressBarRepresentation (or subclass) +// and associate it with a vtkProgressBarWidget instance. + +// .SECTION See Also +// vtkBorderWidget + +#ifndef vtkProgressBarWidget_h +#define vtkProgressBarWidget_h + +#include "vtkInteractionWidgetsModule.h" // For export macro +#include "vtkBorderWidget.h" + +class vtkProgressBarRepresentation; + +class VTKINTERACTIONWIDGETS_EXPORT vtkProgressBarWidget : public vtkBorderWidget +{ +public: + // Description: + // Instantiate this class. + static vtkProgressBarWidget *New(); + + // Description: + // Standard VTK class methods. + vtkTypeMacro(vtkProgressBarWidget, vtkBorderWidget); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Specify an instance of vtkWidgetRepresentation used to represent this + // widget in the scene. Note that the representation is a subclass of vtkProp + // so it can be added to the renderer independent of the widget. + void SetRepresentation(vtkProgressBarRepresentation *r) + {this->Superclass::SetWidgetRepresentation(reinterpret_cast(r));} + + // Description: + // Create the default widget representation if one is not set. + void CreateDefaultRepresentation(); + +protected: + vtkProgressBarWidget(); + ~vtkProgressBarWidget(); + +private: + vtkProgressBarWidget(const vtkProgressBarWidget&); //Not implemented + void operator=(const vtkProgressBarWidget&); //Not implemented +}; + +#endif diff --git a/Interaction/Widgets/vtkRectilinearWipeRepresentation.h b/Interaction/Widgets/vtkRectilinearWipeRepresentation.h index f45df2b285b..93b9ffb2023 100644 --- a/Interaction/Widgets/vtkRectilinearWipeRepresentation.h +++ b/Interaction/Widgets/vtkRectilinearWipeRepresentation.h @@ -93,7 +93,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkRectilinearWipeRepresentation : public vtk virtual void WidgetInteraction(double eventPos[2]); virtual int ComputeInteractionState(int X, int Y, int modify=0); -//BTX // Enums define the state of the prop relative to the mouse pointer // position. Used by ComputeInteractionState() to communicate with the // widget. @@ -104,7 +103,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkRectilinearWipeRepresentation : public vtk MovingVPane, MovingCenter }; -//ETX // Description: // Methods to make this class behave as a vtkProp. diff --git a/Interaction/Widgets/vtkResliceCursorPolyDataAlgorithm.h b/Interaction/Widgets/vtkResliceCursorPolyDataAlgorithm.h index 2fadf576e92..0afe65bcb55 100644 --- a/Interaction/Widgets/vtkResliceCursorPolyDataAlgorithm.h +++ b/Interaction/Widgets/vtkResliceCursorPolyDataAlgorithm.h @@ -53,9 +53,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkResliceCursorPolyDataAlgorithm : public vt vtkSetMacro(ReslicePlaneNormal,int); vtkGetMacro(ReslicePlaneNormal,int); -//BTX enum {XAxis=0,YAxis,ZAxis}; -//ETX // Description: // Set the planes that correspond to the reslice axes. diff --git a/Interaction/Widgets/vtkSeedWidget.h b/Interaction/Widgets/vtkSeedWidget.h index deec99aa395..4ebe7535004 100644 --- a/Interaction/Widgets/vtkSeedWidget.h +++ b/Interaction/Widgets/vtkSeedWidget.h @@ -161,7 +161,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSeedWidget : public vtkAbstractWidget vtkGetMacro( WidgetState, int ); // The state of the widget - //BTX + enum { Start = 1, @@ -169,7 +169,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSeedWidget : public vtkAbstractWidget PlacedSeeds = 4, MovingSeed = 8 }; - //ETX protected: vtkSeedWidget(); diff --git a/Interaction/Widgets/vtkSliderRepresentation.h b/Interaction/Widgets/vtkSliderRepresentation.h index 88a6b931716..feee66be07e 100644 --- a/Interaction/Widgets/vtkSliderRepresentation.h +++ b/Interaction/Widgets/vtkSliderRepresentation.h @@ -129,7 +129,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSliderRepresentation : public vtkWidgetRep virtual double GetPickedT() {return this->PickedT;} -//BTX // Enums are used to describe what is selected enum _InteractionState { @@ -139,7 +138,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSliderRepresentation : public vtkWidgetRep RightCap, Slider }; -//ETX protected: vtkSliderRepresentation(); diff --git a/Interaction/Widgets/vtkSphereRepresentation.cxx b/Interaction/Widgets/vtkSphereRepresentation.cxx index 644527c7419..f4df6a24382 100644 --- a/Interaction/Widgets/vtkSphereRepresentation.cxx +++ b/Interaction/Widgets/vtkSphereRepresentation.cxx @@ -12,35 +12,33 @@ PURPOSE. See the above copyright notice for more information. =========================================================================*/ -#include "vtkSphereRepresentation.h" #include "vtkActor.h" -#include "vtkSphere.h" -#include "vtkSphereSource.h" -#include "vtkPickingManager.h" -#include "vtkPolyDataMapper.h" -#include "vtkPolyData.h" +#include "vtkActor2D.h" +#include "vtkAssemblyPath.h" #include "vtkCallbackCommand.h" +#include "vtkCamera.h" +#include "vtkCellArray.h" +#include "vtkCellPicker.h" +#include "vtkCursor3D.h" +#include "vtkDoubleArray.h" +#include "vtkInteractorObserver.h" +#include "vtkLineSource.h" +#include "vtkMath.h" +#include "vtkObjectFactory.h" +#include "vtkPickingManager.h" #include "vtkPolyData.h" +#include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" -#include "vtkInteractorObserver.h" -#include "vtkMath.h" -#include "vtkCellArray.h" -#include "vtkCellPicker.h" -#include "vtkTransform.h" -#include "vtkDoubleArray.h" #include "vtkSphere.h" -#include "vtkCamera.h" -#include "vtkAssemblyPath.h" +#include "vtkSphereRepresentation.h" +#include "vtkSphereSource.h" #include "vtkTextMapper.h" -#include "vtkActor2D.h" #include "vtkTextProperty.h" -#include "vtkLineSource.h" +#include "vtkTransform.h" #include "vtkWindow.h" -#include "vtkObjectFactory.h" - vtkStandardNewMacro(vtkSphereRepresentation); @@ -110,6 +108,18 @@ vtkSphereRepresentation::vtkSphereRepresentation() this->RadialLineActor->SetMapper(this->RadialLineMapper); this->RadialLineActor->SetProperty(this->RadialLineProperty); + // Represent the center cursor + this->CenterCursor = 0; + this->CenterCursorSource = vtkCursor3D::New(); + this->CenterCursorSource->AllOff(); + this->CenterCursorSource->AxesOn(); + this->CenterCursorSource->TranslationModeOn(); + this->CenterMapper = vtkPolyDataMapper::New(); + this->CenterMapper->SetInputConnection( + this->CenterCursorSource->GetOutputPort()); + this->CenterActor = vtkActor::New(); + this->CenterActor->SetMapper(this->CenterMapper); + // Define the point coordinates double bounds[6]; bounds[0] = -0.5; @@ -162,6 +172,11 @@ vtkSphereRepresentation::~vtkSphereRepresentation() this->RadialLineMapper->Delete(); this->RadialLineActor->Delete(); + // The cursor + this->CenterCursorSource->Delete(); + this->CenterMapper->Delete(); + this->CenterActor->Delete(); + if ( this->SphereProperty ) { this->SphereProperty->Delete(); @@ -267,6 +282,7 @@ void vtkSphereRepresentation::Scale(double *p1, double *p2, this->HandlePosition[1] = c[1]+sf*(this->HandlePosition[1]-c[1]); this->HandlePosition[2] = c[2]+sf*(this->HandlePosition[2]-c[2]); this->HandleSource->SetCenter(this->HandlePosition); + this->AdaptCenterCursorBounds(); } //---------------------------------------------------------------------- @@ -362,6 +378,7 @@ void vtkSphereRepresentation::Translate(double *p1, double *p2) } this->SphereSource->SetCenter(center1); + this->CenterCursorSource->SetFocalPoint(center1); this->HandleSource->SetCenter(HandlePosition); } @@ -419,6 +436,9 @@ void vtkSphereRepresentation::PlaceWidget(double center[3], double handle[3]) this->HandleSource->SetCenter(handle); this->HandleSource->Update(); + this->CenterCursorSource->SetFocalPoint(center); + this->CenterCursorSource->Update(); + this->HandleDirection[0] = handle[0] - center[0]; this->HandleDirection[1] = handle[1] - center[1]; this->HandleDirection[2] = handle[2] - center[2]; @@ -457,6 +477,10 @@ void vtkSphereRepresentation::SetCenter(double center[3]) } this->SphereSource->Update(); + + this->CenterCursorSource->SetFocalPoint(center); + this->CenterCursorSource->Update(); + this->Modified(); } } @@ -545,6 +569,9 @@ void vtkSphereRepresentation::PlaceWidget(double bds[6]) this->SphereSource->SetRadius(radius); this->SphereSource->Update(); + this->CenterCursorSource->SetFocalPoint(center); + this->CenterCursorSource->Update(); + // place the handle this->PlaceHandle(center,radius); @@ -616,6 +643,20 @@ int vtkSphereRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUse return this->InteractionState; } +//---------------------------------------------------------------------- +void vtkSphereRepresentation::AdaptCenterCursorBounds() +{ + double center[3], newBounds[6]; + this->CenterCursorSource->GetFocalPoint(center); + double radius = this->SizeHandlesInPixels(2.0,center); + for (int i=0; i<3; i++) + { + newBounds[2*i] = center[i] - radius; + newBounds[2*i+1] = center[i] + radius; + } + this->CenterCursorSource->SetModelBounds(newBounds); +} + //---------------------------------------------------------------------- void vtkSphereRepresentation::SetInteractionState(int state) { @@ -677,6 +718,7 @@ void vtkSphereRepresentation::BuildRepresentation() vtkInteractorObserver::ComputeWorldToDisplay(this->Renderer, hc[0], hc[1], hc[2], tc); this->HandleTextActor->GetPositionCoordinate()->SetValue(tc[0]+10,tc[1]+10); } + this->AdaptCenterCursorBounds(); } //---------------------------------------------------------------------------- @@ -686,6 +728,7 @@ void vtkSphereRepresentation::ReleaseGraphicsResources(vtkWindow *w) this->HandleActor->ReleaseGraphicsResources(w); this->HandleTextActor->ReleaseGraphicsResources(w); this->RadialLineActor->ReleaseGraphicsResources(w); + this->CenterActor->ReleaseGraphicsResources(w); } //---------------------------------------------------------------------------- @@ -706,6 +749,10 @@ int vtkSphereRepresentation::RenderOpaqueGeometry(vtkViewport *v) { count += this->RadialLineActor->RenderOpaqueGeometry(v); } + if (this->CenterCursor) + { + count += this->CenterActor->RenderOpaqueGeometry(v); + } return count; } @@ -727,6 +774,10 @@ int vtkSphereRepresentation::RenderTranslucentPolygonalGeometry(vtkViewport *v) { count += this->RadialLineActor->RenderTranslucentPolygonalGeometry(v); } + if (this->CenterCursor) + { + count += this->CenterActor->RenderTranslucentPolygonalGeometry(v); + } return count; } @@ -766,6 +817,10 @@ int vtkSphereRepresentation::HasTranslucentPolygonalGeometry() { result |= this->RadialLineActor->HasTranslucentPolygonalGeometry(); } + if (this->CenterCursor) + { + result |= this->CenterActor->HasTranslucentPolygonalGeometry(); + } return result; } @@ -858,6 +913,7 @@ void vtkSphereRepresentation::PrintSelf(ostream& os, vtkIndent indent) os << indent << "Handle Text: " << this->HandleText << "\n"; os << indent << "Radial Line: " << this->RadialLine << "\n"; + os << indent << "Center Cursor: " << this->CenterCursor << "\n"; if ( this->HandleTextProperty ) { diff --git a/Interaction/Widgets/vtkSphereRepresentation.h b/Interaction/Widgets/vtkSphereRepresentation.h index ceacf80994e..dec551fa468 100644 --- a/Interaction/Widgets/vtkSphereRepresentation.h +++ b/Interaction/Widgets/vtkSphereRepresentation.h @@ -63,6 +63,7 @@ class vtkTextMapper; class vtkActor2D; class vtkTextProperty; class vtkLineSource; +class vtkCursor3D; #define VTK_SPHERE_OFF 0 #define VTK_SPHERE_WIREFRAME 1 @@ -171,6 +172,13 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSphereRepresentation : public vtkWidgetRep vtkGetMacro(RadialLine,int); vtkBooleanMacro(RadialLine,int); + // Description: + // Enable/disable a center cursor + // Default is disabled + vtkSetMacro(CenterCursor, bool); + vtkGetMacro(CenterCursor, bool); + vtkBooleanMacro(CenterCursor, bool); + // Description: // Grab the polydata (including points) that defines the sphere. The // polydata consists of n+1 points, where n is the resolution of the @@ -269,6 +277,10 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSphereRepresentation : public vtkWidgetRep void PlaceHandle(double *center, double radius); virtual void SizeHandles(); + // Method to adapt the center cursor bounds + // so it always have the same pixel size on screen + virtual void AdaptCenterCursorBounds(); + // Properties used to control the appearance of selected objects and // the manipulator in general. vtkProperty *SphereProperty; @@ -299,6 +311,12 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSphereRepresentation : public vtkWidgetRep vtkPolyDataMapper *RadialLineMapper; vtkActor *RadialLineActor; + // Managing the center cursor + vtkActor *CenterActor; + vtkPolyDataMapper *CenterMapper; + vtkCursor3D *CenterCursorSource; + bool CenterCursor; + private: vtkSphereRepresentation(const vtkSphereRepresentation&); //Not implemented void operator=(const vtkSphereRepresentation&); //Not implemented diff --git a/Interaction/Widgets/vtkSplineRepresentation.cxx b/Interaction/Widgets/vtkSplineRepresentation.cxx index 7eefeea2fcc..5fb6800db92 100644 --- a/Interaction/Widgets/vtkSplineRepresentation.cxx +++ b/Interaction/Widgets/vtkSplineRepresentation.cxx @@ -129,7 +129,7 @@ void vtkSplineRepresentation::SetParametricSpline(vtkParametricSpline* spline) //---------------------------------------------------------------------------- vtkDoubleArray* vtkSplineRepresentation::GetHandlePositions() { - return vtkDoubleArray::SafeDownCast( + return vtkArrayDownCast( this->ParametricSpline->GetPoints()->GetData()); } diff --git a/Interaction/Widgets/vtkSplineRepresentation.h b/Interaction/Widgets/vtkSplineRepresentation.h index 3686622f418..6d0df6714c0 100644 --- a/Interaction/Widgets/vtkSplineRepresentation.h +++ b/Interaction/Widgets/vtkSplineRepresentation.h @@ -99,7 +99,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSplineRepresentation : public vtkCurveRepr // are specified. virtual void BuildRepresentation(); -//BTX protected: vtkSplineRepresentation(); ~vtkSplineRepresentation(); @@ -117,7 +116,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSplineRepresentation : public vtkCurveRepr private: vtkSplineRepresentation(const vtkSplineRepresentation&); // Not implemented. void operator=(const vtkSplineRepresentation&); // Not implemented. -//ETX + }; #endif diff --git a/Interaction/Widgets/vtkSplineWidget2.h b/Interaction/Widgets/vtkSplineWidget2.h index 2dc7623ab1d..4da292b4494 100644 --- a/Interaction/Widgets/vtkSplineWidget2.h +++ b/Interaction/Widgets/vtkSplineWidget2.h @@ -49,7 +49,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSplineWidget2 : public vtkAbstractWidget // Create the default widget representation if one is not set. By default, // this is an instance of the vtkSplineRepresentation class. void CreateDefaultRepresentation(); -//BTX + protected: vtkSplineWidget2(); ~vtkSplineWidget2(); @@ -67,7 +67,7 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkSplineWidget2 : public vtkAbstractWidget private: vtkSplineWidget2(const vtkSplineWidget2&); // Not implemented. void operator=(const vtkSplineWidget2&); // Not implemented. -//ETX + }; #endif diff --git a/Interaction/Widgets/vtkTextRepresentation.h b/Interaction/Widgets/vtkTextRepresentation.h index fb33cc6dd70..2caa5126870 100644 --- a/Interaction/Widgets/vtkTextRepresentation.h +++ b/Interaction/Widgets/vtkTextRepresentation.h @@ -72,7 +72,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkTextRepresentation : public vtkBorderRepre virtual int RenderTranslucentPolygonalGeometry(vtkViewport*); virtual int HasTranslucentPolygonalGeometry(); - //BTX enum { AnyLocation = 0, @@ -83,7 +82,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkTextRepresentation : public vtkBorderRepre UpperRightCorner, UpperCenter }; - //ETX // Description: // Set the text position, by enumeration ( diff --git a/Interaction/Widgets/vtkWidgetCallbackMapper.h b/Interaction/Widgets/vtkWidgetCallbackMapper.h index a737edfe0b6..371b74870ae 100644 --- a/Interaction/Widgets/vtkWidgetCallbackMapper.h +++ b/Interaction/Widgets/vtkWidgetCallbackMapper.h @@ -52,11 +52,9 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkWidgetCallbackMapper : public vtkObject void SetEventTranslator(vtkWidgetEventTranslator *t); vtkGetObjectMacro(EventTranslator,vtkWidgetEventTranslator); -//BTX // Description: // Convenient typedef for working with callbacks. typedef void (*CallbackType)(vtkAbstractWidget*); -//ETX // Description: // This class works with the class vtkWidgetEventTranslator to set up the diff --git a/Interaction/Widgets/vtkWidgetEvent.h b/Interaction/Widgets/vtkWidgetEvent.h index 5689764cb47..27ef9fb245b 100644 --- a/Interaction/Widgets/vtkWidgetEvent.h +++ b/Interaction/Widgets/vtkWidgetEvent.h @@ -35,7 +35,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkWidgetEvent : public vtkObject vtkTypeMacro(vtkWidgetEvent,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); -//BTX // Description: // All the widget events are defined here. enum WidgetEventIds { @@ -64,7 +63,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkWidgetEvent : public vtkObject Left, Right }; -//ETX // Description: // Convenience methods for translating between event names and event ids. diff --git a/Interaction/Widgets/vtkWidgetEventTranslator.h b/Interaction/Widgets/vtkWidgetEventTranslator.h index e2c80ad18ac..514899da5a0 100644 --- a/Interaction/Widgets/vtkWidgetEventTranslator.h +++ b/Interaction/Widgets/vtkWidgetEventTranslator.h @@ -88,13 +88,11 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkWidgetEventTranslator : public vtkObject // translated). void ClearEvents(); -//BTX // Description: // Add the events in the current translation table to the interactor. void AddEventsToParent(vtkAbstractWidget*, vtkCallbackCommand*, float priority); void AddEventsToInteractor(vtkRenderWindowInteractor*, vtkCallbackCommand*, float priority); -//ETX protected: // Constructors/destructors made public for widgets to use diff --git a/Interaction/Widgets/vtkWidgetSet.h b/Interaction/Widgets/vtkWidgetSet.h index 9dd48b7257e..6e51370991c 100644 --- a/Interaction/Widgets/vtkWidgetSet.h +++ b/Interaction/Widgets/vtkWidgetSet.h @@ -96,7 +96,6 @@ class vtkAbstractWidget; -//BTX // Pointer to a member function that takes a vtkAbstractWidget (the active // child) and another vtkAbstractWidget (the widget to dispatch an action) // to. All "Action" functions in a widget must conform to this signature. @@ -104,7 +103,6 @@ template< class TWidget > struct ActionFunction { typedef void (TWidget::*TActionFunctionPointer)(TWidget *dispatcher); }; -//ETX class VTKINTERACTIONWIDGETS_EXPORT vtkWidgetSet : public vtkObject { @@ -139,7 +137,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkWidgetSet : public vtkObject // Get the Nth widget in the set. vtkAbstractWidget *GetNthWidget( unsigned int ); - //BTX // TODO: Move this to the protected section. The class vtkAbstractWidget // should be a friend of this class. typedef std::vector< vtkAbstractWidget * > WidgetContainerType; @@ -174,7 +171,6 @@ class VTKINTERACTIONWIDGETS_EXPORT vtkWidgetSet : public vtkObject if (caller != w) ((*w).*(action))(caller); } } - //ETX protected: vtkWidgetSet(); diff --git a/Parallel/Core/CMakeLists.txt b/Parallel/Core/CMakeLists.txt index 1f34372d7be..cb7c019e798 100644 --- a/Parallel/Core/CMakeLists.txt +++ b/Parallel/Core/CMakeLists.txt @@ -4,8 +4,10 @@ set(Module_SRCS vtkDummyController.cxx vtkMultiProcessController.cxx vtkMultiProcessStream.cxx + vtkPDirectory.cxx vtkProcess.cxx vtkProcessGroup.cxx + vtkPSystemTools.cxx vtkSocketCommunicator.cxx vtkSocketController.cxx vtkSubCommunicator.cxx diff --git a/Parallel/Core/vtkCommunicator.cxx b/Parallel/Core/vtkCommunicator.cxx index 3be13e60636..e2e2567d331 100644 --- a/Parallel/Core/vtkCommunicator.cxx +++ b/Parallel/Core/vtkCommunicator.cxx @@ -1037,7 +1037,7 @@ int vtkCommunicator::GatherVElementalDataObject( for (int i = 0; i < this->NumberOfProcesses; ++i) { if (! vtkCommunicator::UnMarshalDataObject( - vtkCharArray::SafeDownCast(recvBuffers[i].GetPointer()), + vtkArrayDownCast(recvBuffers[i].GetPointer()), receiveData[i])) { return 0; diff --git a/Parallel/Core/vtkCommunicator.h b/Parallel/Core/vtkCommunicator.h index 8f9c8529a25..6756b056d75 100644 --- a/Parallel/Core/vtkCommunicator.h +++ b/Parallel/Core/vtkCommunicator.h @@ -62,8 +62,6 @@ class VTKPARALLELCORE_EXPORT vtkCommunicator : public vtkObject // Tells you which process [0, NumProcess) you are in. vtkGetMacro(LocalProcessId, int); -//BTX - enum Tags { BROADCAST_TAG = 10, @@ -115,8 +113,6 @@ class VTKPARALLELCORE_EXPORT vtkCommunicator : public vtkObject virtual ~Operation() {} }; -//ETX - // Description: // This method sends a data object to a destination. // Tag eliminates ambiguity @@ -187,10 +183,8 @@ class VTKPARALLELCORE_EXPORT vtkCommunicator : public vtkObject int Send(const unsigned long long* data, vtkIdType length, int remoteHandle, int tag) { return this->SendVoidArray(data, length, VTK_UNSIGNED_LONG_LONG, remoteHandle, tag); } -//BTX - int Send(const vtkMultiProcessStream& stream, int remoteId, int tag); -//ETX + int Send(const vtkMultiProcessStream& stream, int remoteId, int tag); // Description: // This method receives a data object from a corresponding send. It blocks @@ -268,9 +262,8 @@ class VTKPARALLELCORE_EXPORT vtkCommunicator : public vtkObject int Receive(unsigned long long* data, vtkIdType maxlength, int remoteHandle, int tag) { return this->ReceiveVoidArray(data, maxlength, VTK_UNSIGNED_LONG_LONG, remoteHandle, tag); } -//BTX + int Receive(vtkMultiProcessStream& stream, int remoteId, int tag); -//ETX // Description: // Returns the number of words received by the most recent Receive(). @@ -339,9 +332,8 @@ class VTKPARALLELCORE_EXPORT vtkCommunicator : public vtkObject } int Broadcast(vtkDataObject *data, int srcProcessId); int Broadcast(vtkDataArray *data, int srcProcessId); -//BTX + int Broadcast(vtkMultiProcessStream& stream, int srcProcessId); -//ETX // Description: // Gather collects arrays in the process with id \c destProcessId. Each @@ -1277,7 +1269,6 @@ class VTKPARALLELCORE_EXPORT vtkCommunicator : public vtkObject static void SetUseCopy(int useCopy); -//BTX // Description: // Determine the global bounds for a set of processes. BBox is // initially set (outside of the call to the local bounds of the process @@ -1295,7 +1286,6 @@ class VTKPARALLELCORE_EXPORT vtkCommunicator : public vtkObject int hasBoundsTag = 288402, int localBoundsTag = 288403, int globalBoundsTag = 288404); -//ETX // Description: // Some helper functions when dealing with heap tree - based diff --git a/Parallel/Core/vtkMultiProcessController.h b/Parallel/Core/vtkMultiProcessController.h index 3d2f542d164..44250521e69 100644 --- a/Parallel/Core/vtkMultiProcessController.h +++ b/Parallel/Core/vtkMultiProcessController.h @@ -61,7 +61,6 @@ class vtkOutputWindow; class vtkProcessGroup; class vtkProcess; -//BTX // The type of function that gets called when new processes are initiated. typedef void (*vtkProcessFunctionType)(vtkMultiProcessController *controller, void *userData); @@ -70,8 +69,6 @@ typedef void (*vtkProcessFunctionType)(vtkMultiProcessController *controller, typedef void (*vtkRMIFunctionType)(void *localArg, void *remoteArg, int remoteArgLength, int remoteProcessId); -//ETX - class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject { @@ -111,7 +108,6 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject void SetNumberOfProcesses(int num); int GetNumberOfProcesses(); - //BTX // Description: // Set the SingleMethod to f() and the UserData of the // for the method to be executed by all of the processes @@ -124,7 +120,6 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject // some function pointer and user data, a vtkProcess object is passed // where the method to execute is Execute() and the data the object itself. void SetSingleProcessObject(vtkProcess *p); - //ETX // Description: // Execute the SingleMethod (as define by SetSingleMethod) using @@ -132,14 +127,12 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject // all the processes finish executing their methods. virtual void SingleMethodExecute() = 0; - //BTX // Description: // Set the MultipleMethod to f() and the UserData of the // for the method to be executed by the process index // when MultipleMethodExecute is called. This is for having each // process start with a different function and data argument. void SetMultipleMethod(int index, vtkProcessFunctionType, void *data); - //ETX // Description: // Execute the MultipleMethods (as define by calling SetMultipleMethod @@ -190,7 +183,7 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject int localKey); //------------------ RMIs -------------------- - //BTX + // Description: // Register remote method invocation in the receiving process // which makes the call. It must have a unique tag as an RMI id. @@ -234,8 +227,6 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject // Remove a callback. Returns true is the remove was successful. virtual bool RemoveRMICallback(unsigned long id); - //ETX - // Description: // A method to trigger a method invocation in another process. void TriggerRMI(int remoteProcessId, void *arg, int argLength, int tag); @@ -315,8 +306,6 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject static int GetRMITag() { return RMI_TAG; } static int GetRMIArgTag() { return RMI_ARG_TAG; } -//BTX - enum Errors { RMI_NO_ERROR, @@ -338,8 +327,6 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject XML_WRITER_DATA_INFO = 4 }; -//ETX - // Description: // This method can be used to synchronize processes. void Barrier(); @@ -376,7 +363,6 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject int Send(vtkDataObject *data, int remoteId, int tag); int Send(vtkDataArray *data, int remoteId, int tag); -//BTX // Description: // Send a stream to another process. vtkMultiProcessStream makes it possible // to send data with arbitrary length and different base types to the other @@ -384,7 +370,6 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject // arguments, it's generally more efficient to push the arguments into the // stream and the send the stream over. int Send(const vtkMultiProcessStream& stream, int remoteId, int tag); -//ETX // Description: // This method receives data from a corresponding send. It blocks @@ -414,11 +399,11 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject int Receive(unsigned long long* data, vtkIdType maxLength, int remoteProcessId, int tag); int Receive(vtkDataObject* data, int remoteId, int tag); int Receive(vtkDataArray* data, int remoteId, int tag); -//BTX + // Description: // Receive a stream from the other processes. int Receive(vtkMultiProcessStream& stream, int remoteId, int tag); -//ETX + vtkDataObject *ReceiveDataObject(int remoteId, int tag); // Description: @@ -488,11 +473,10 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject int Broadcast(vtkDataArray *data, int srcProcessId) { return this->Communicator->Broadcast(data, srcProcessId); } -//BTX + int Broadcast(vtkMultiProcessStream& stream, int srcProcessId) { return this->Communicator->Broadcast(stream, srcProcessId); } -//ETX // Description: // Gather collects arrays in the process with id \c destProcessId. Each @@ -1171,7 +1155,6 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject operation, destProcessId); } -//BTX // Description: // Reduce an array to the given destination process. This version of Reduce // takes a custom operation as a subclass of vtkCommunicator::Operation. @@ -1267,7 +1250,6 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject return this->Communicator->Reduce(sendBuffer, recvBuffer, operation, destProcessId); } -//ETX // Description: // Same as Reduce except that the result is placed in all of the processes. @@ -1348,7 +1330,7 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject int operation) { return this->Communicator->AllReduce(sendBuffer, recvBuffer, operation); } -//BTX + int AllReduce(const int *sendBuffer, int *recvBuffer, vtkIdType length, vtkCommunicator::Operation *operation) { return this->Communicator->AllReduce(sendBuffer, recvBuffer, length, @@ -1426,7 +1408,6 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject vtkCommunicator::Operation *operation) { return this->Communicator->AllReduce(sendBuffer, recvBuffer, operation); } -//ETX // Internally implemented RMI to break the process loop. @@ -1487,10 +1468,9 @@ class VTKPARALLELCORE_EXPORT vtkMultiProcessController : public vtkObject unsigned long RMICount; -//BTX class vtkInternal; vtkInternal *Internal; -//ETX + }; diff --git a/Parallel/Core/vtkPDirectory.cxx b/Parallel/Core/vtkPDirectory.cxx new file mode 100644 index 00000000000..4b920b3212a --- /dev/null +++ b/Parallel/Core/vtkPDirectory.cxx @@ -0,0 +1,242 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkPDirectory.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + + =========================================================================*/ +#include "vtkPDirectory.h" + +#include +#include "vtkObjectFactory.h" +#include "vtkPSystemTools.h" +#include "vtkStringArray.h" +#include +#include +#include + +vtkStandardNewMacro(vtkPDirectory); + +//---------------------------------------------------------------------------- +vtkPDirectory::vtkPDirectory() +{ + this->Files = vtkStringArray::New(); +} + +//---------------------------------------------------------------------------- +vtkPDirectory::~vtkPDirectory() +{ + this->Files->Delete(); + this->Files = 0; +} + +//---------------------------------------------------------------------------- +bool vtkPDirectory::Load(const std::string& name) +{ + this->Clear(); + + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + + long numFiles = 0; + if(controller->GetLocalProcessId() == 0) + { + vtksys::Directory dir; + if (dir.Load(name) == false) + { + numFiles = -1; // failure + controller->Broadcast(&numFiles, 1, 0); + return false; + } + + for(unsigned long i=0;iFiles->InsertNextValue(dir.GetFile(i)); + } + numFiles = static_cast(dir.GetNumberOfFiles()); + controller->Broadcast(&numFiles, 1, 0); + for(long i=0;iFiles->GetValue(i), 0); + } + } + else + { + controller->Broadcast(&numFiles, 1, 0); + if(numFiles == -1) + { + return false; + } + for(long i=0;iFiles->InsertNextValue(str); + } + } + + this->Path = name; + return true; +} + +//---------------------------------------------------------------------------- +int vtkPDirectory::Open(const char* name) +{ + return static_cast(this->Load(name)); +} + +//---------------------------------------------------------------------------- +vtkIdType vtkPDirectory::GetNumberOfFiles() const +{ + return this->Files->GetNumberOfTuples(); +} + +//---------------------------------------------------------------------------- +const char* vtkPDirectory::GetFile(vtkIdType index) const +{ + if ( index >= this->Files->GetNumberOfTuples() ) + { + return NULL; + } + return this->Files->GetValue(index).c_str(); +} + +//---------------------------------------------------------------------------- +int vtkPDirectory::FileIsDirectory(const char *name) +{ + // The vtksys::SystemTools::FileIsDirectory() + // does not equal the following code (it probably should), + // and it will broke KWWidgets. Reverse back to 1.30 + // return vtksys::SystemTools::FileIsDirectory(name); + + if (name == 0) + { + return 0; + } + + int result = 0; + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + + if(controller->GetLocalProcessId() == 0) + { + int absolutePath = 0; +#if defined(_WIN32) + if (name[0] == '/' || name[0] == '\\') + { + absolutePath = 1; + } + else + { + for (int i = 0; name[i] != '\0'; i++) + { + if (name[i] == ':') + { + absolutePath = 1; + break; + } + else if (name[i] == '/' || name[i] == '\\') + { + break; + } + } + } +#else + if (name[0] == '/') + { + absolutePath = 1; + } +#endif + + char *fullPath; + + int n = 0; + if (!absolutePath && !this->Path.empty()) + { + n = static_cast(this->Path.size()); + } + + int m = static_cast(strlen(name)); + + fullPath = new char[n+m+2]; + + if (!absolutePath && !this->Path.empty()) + { + strcpy(fullPath, this->Path.c_str()); +#if defined(_WIN32) + if (fullPath[n-1] != '/' + && fullPath[n-1] != '\\') + { +#if !defined(__CYGWIN__) + fullPath[n++] = '\\'; +#else + fullPath[n++] = '/'; +#endif + } +#else + if (fullPath[n-1] != '/') + { + fullPath[n++] = '/'; + } +#endif + } + + strcpy(&fullPath[n], name); + + struct stat fs; + if(stat(fullPath, &fs) == 0) + { +#if defined(_WIN32) + result = ((fs.st_mode & _S_IFDIR) != 0); +#else + result = S_ISDIR(fs.st_mode); +#endif + } + + delete [] fullPath; + } + + controller->Broadcast(&result, 1, 0); + + return result; +} + +//---------------------------------------------------------------------------- +const char* vtkPDirectory::GetPath() const +{ + return this->Path.c_str(); +} + +//---------------------------------------------------------------------------- +void vtkPDirectory::Clear() +{ + this->Path.clear(); + this->Files->Reset(); +} + +//---------------------------------------------------------------------------- +void vtkPDirectory::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os << indent << "Files: (" << this->Files << ")\n"; + if(this->Path.empty()) + { + os << indent << "Directory not open\n"; + return; + } + + os << indent << "Directory for: " << this->Path << "\n"; + os << indent << "Contains the following files:\n"; + indent = indent.GetNextIndent(); + for(int i = 0; i < this->Files->GetNumberOfValues(); i++) + { + os << indent << this->Files->GetValue(i) << "\n"; + } +} diff --git a/Parallel/Core/vtkPDirectory.h b/Parallel/Core/vtkPDirectory.h new file mode 100644 index 00000000000..ab107ed5abf --- /dev/null +++ b/Parallel/Core/vtkPDirectory.h @@ -0,0 +1,91 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkPDirectory.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + + =========================================================================*/ +// .NAME vtkPDirectory -- parallel wrapper for VTK Directory and vtkDirectory +// .SECTION Description +// vtkPDirectory provides a portable way of finding the names of the files +// in a system directory where process 0 finds the information and +// broadcasts it to other processes. It tries to replicate the API for both +// Directory and vtkDirectory though there are slight mismatches between the +// two. This is a blocking collective operation. + +#ifndef vtkPDirectory_h +#define vtkPDirectory_h + +#include "vtkParallelCoreModule.h" // For export macro +#include "vtkObject.h" +#include // for string functions in Directory + +class vtkStringArray; + +class VTKPARALLELCORE_EXPORT vtkPDirectory : public vtkObject +{ + public: + static vtkPDirectory *New(); + vtkTypeMacro(vtkPDirectory,vtkObject); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Open/Load the specified directory and load the names of the files + // in that directory. false/0 is returned if the directory can not be + // opened, true/1 if it is opened. The reason that there are two versions + // of this is that Directory uses Load() and vtkDirectory uses Open() + // for this functionality. + bool Load(const std::string&); + int Open(const char* dir); + + // Description: + // Return the number of files in the current directory. + vtkIdType GetNumberOfFiles() const; + + // Description: + // Return the file at the given index, the indexing is 0 based + const char* GetFile(vtkIdType index) const; + + // Description: + // Return true if the file is a directory. If the file is not an + // absolute path, it is assumed to be relative to the opened + // directory. If no directory has been opened, it is assumed to + // be relative to the current working directory. + int FileIsDirectory(const char *name); + + // Description: + // Get an array that contains all the file names. + vtkGetObjectMacro(Files, vtkStringArray); + + // Description: + // Return the path to Open'ed directory + const char* GetPath() const; + + // Description: + // Clear the internal structure. Used internally at beginning of Load(...) + // to clear the cache. + void Clear(); + + protected: + vtkPDirectory(); + ~vtkPDirectory(); + + private: + // Array of Files + vtkStringArray *Files; // VTK array of files + + // Path to Open'ed directory + std::string Path; + + vtkPDirectory(const vtkPDirectory&); // Not implemented. + void operator=(const vtkPDirectory&); // Not implemented. +}; // End Class: vtkPDirectory + +#endif diff --git a/Parallel/Core/vtkPSystemTools.cxx b/Parallel/Core/vtkPSystemTools.cxx new file mode 100644 index 00000000000..09b9f8a7d24 --- /dev/null +++ b/Parallel/Core/vtkPSystemTools.cxx @@ -0,0 +1,200 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkPSystemTools.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkPSystemTools.h" + +#include +#include "vtkObjectFactory.h" +#include + +vtkStandardNewMacro(vtkPSystemTools); + +//---------------------------------------------------------------------------- +void vtkPSystemTools::BroadcastString(std::string& str, int proc) +{ + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + + vtkIdType size = static_cast(str.size()); + controller->Broadcast(&size, 1, proc); + + str.resize(size); + if(size) + { + controller->Broadcast(&str[0], size, proc); + } +} + +//---------------------------------------------------------------------------- +std::string vtkPSystemTools::CollapseFullPath(const std::string& in_relative) +{ + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + std::string returnString; + if(controller->GetLocalProcessId() == 0) + { + returnString = vtksys::SystemTools::CollapseFullPath(in_relative, 0); + } + vtkPSystemTools::BroadcastString(returnString, 0); + + return returnString; +} + +//---------------------------------------------------------------------------- +std::string vtkPSystemTools::CollapseFullPath(const std::string& in_path, + const char* in_base) +{ + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + std::string returnString; + if(controller->GetLocalProcessId() == 0) + { + returnString = vtksys::SystemTools::CollapseFullPath(in_path, in_base); + } + vtkPSystemTools::BroadcastString(returnString, 0); + + return returnString; +} + +//---------------------------------------------------------------------------- +bool vtkPSystemTools::FileExists(const char* filename) +{ + if(!filename) + { + return false; + } + return vtkPSystemTools::FileExists(std::string(filename)); +} + +//---------------------------------------------------------------------------- +bool vtkPSystemTools::FileExists(const std::string& filename) +{ + if(filename.empty()) + { + return false; + } + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + int exists = 0; + if(controller->GetLocalProcessId() == 0) + { + exists = vtksys::SystemTools::FileExists(filename); + } + controller->Broadcast(&exists, 1, 0); + return exists != 0; +} + +//---------------------------------------------------------------------------- +bool vtkPSystemTools::FileExists(const char* filename, bool isFile) +{ + if(!filename) + { + return false; + } + return vtkPSystemTools::FileExists(std::string(filename), isFile); +} + +//---------------------------------------------------------------------------- +bool vtkPSystemTools::FileExists(const std::string& filename, bool isFile) +{ + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + int exists = 0; + if(controller->GetLocalProcessId() == 0) + { + exists = vtksys::SystemTools::FileExists(filename, isFile); + } + controller->Broadcast(&exists, 1, 0); + return exists != 0; +} + +//---------------------------------------------------------------------------- +bool vtkPSystemTools::FileIsDirectory(const std::string& inName) +{ + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + int isDirectory = 0; + if(controller->GetLocalProcessId() == 0) + { + isDirectory = vtksys::SystemTools::FileIsDirectory(inName); + } + controller->Broadcast(&isDirectory, 1, 0); + return isDirectory != 0; +} + +//---------------------------------------------------------------------------- +bool vtkPSystemTools::FindProgramPath(const char* argv0, + std::string& pathOut, + std::string& errorMsg, + const char* exeName, + const char* buildDir, + const char* installPrefix ) +{ + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + int retVal = 1; + if(controller->GetLocalProcessId() == 0) + { + retVal = static_cast( + vtksys::SystemTools::FindProgramPath( + argv0, pathOut, errorMsg, exeName, buildDir, installPrefix)); + } + controller->Broadcast(&retVal, 1, 0); + // if the retVal on proc 0 is non-zero then only information is + // put in pathOut. Otherwise information is put in errorMsg. + if(retVal) + { + vtkPSystemTools::BroadcastString(pathOut, 0); + } + else + { + vtkPSystemTools::BroadcastString(errorMsg, 0); + } + return retVal != 0; +} + +//---------------------------------------------------------------------------- +std::string vtkPSystemTools::GetCurrentWorkingDirectory(bool collapse) +{ + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + std::string returnString; + if(controller->GetLocalProcessId() == 0) + { + returnString = vtksys::SystemTools::GetCurrentWorkingDirectory(collapse); + } + vtkPSystemTools::BroadcastString(returnString, 0); + return returnString; +} + +//---------------------------------------------------------------------------- +std::string vtkPSystemTools::GetProgramPath(const std::string& path) +{ + vtkMultiProcessController* controller = + vtkMultiProcessController::GetGlobalController(); + std::string programPath; + if(controller->GetLocalProcessId() == 0) + { + programPath = vtksys::SystemTools::GetProgramPath(path); + } + vtkPSystemTools::BroadcastString(programPath, 0); + + return programPath; +} + +//---------------------------------------------------------------------------- +void vtkPSystemTools::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); +} diff --git a/Parallel/Core/vtkPSystemTools.h b/Parallel/Core/vtkPSystemTools.h new file mode 100644 index 00000000000..c136206c17e --- /dev/null +++ b/Parallel/Core/vtkPSystemTools.h @@ -0,0 +1,107 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkPSystemTools.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + + =========================================================================*/ +// .NAME vtkPSystemTools - System tools for file system introspection +// .SECTION Description +// A class with only static methods for doing parallel file system +// introspection. It limits doing file stats on process 0 and +// broadcasting the results to other processes. It is built on VTK's +// SystemTools class and uses the global controller for communication. +// It uses blocking collective communication operations. + +#ifndef vtkPSystemTools_h +#define vtkPSystemTools_h + +#include "vtkParallelCoreModule.h" // For export macro +#include "vtkObject.h" +#include // for string functions in SystemTools + +class VTKPARALLELCORE_EXPORT vtkPSystemTools : public vtkObject +{ + public: + static vtkPSystemTools *New(); + vtkTypeMacro(vtkPSystemTools,vtkObject); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Given a string on process proc, broadcast that string to + // all of the other processes. This method does not have a + // correspondence to anything in SystemTools. + + static void BroadcastString(std::string&, int proc); + + // Description: + // Given a path to a file or directory, convert it to a full path. + // This collapses away relative paths relative to the cwd argument + // (which defaults to the current working directory). The full path + // is returned. + + static std::string CollapseFullPath(const std::string& in_relative); + static std::string CollapseFullPath(const std::string& in_relative, + const char* in_base); + + // Description: + // Return true if a file exists in the current directory. + // If isFile = true, then make sure the file is a file and + // not a directory. If isFile = false, then return true + // if it is a file or a directory. Note that the file will + // also be checked for read access. (Currently, this check + // for read access is only done on POSIX systems.) + static bool FileExists(const char* filename, bool isFile); + static bool FileExists(const std::string& filename, bool isFile); + static bool FileExists(const char* filename); + static bool FileExists(const std::string& filename); + + // Description: + // Return true if the file is a directory + static bool FileIsDirectory(const std::string& name); + + // Description: + // Given argv[0] for a unix program find the full path to a running + // executable. argv0 can be null for windows WinMain programs + // in this case GetModuleFileName will be used to find the path + // to the running executable. If argv0 is not a full path, + // then this will try to find the full path. If the path is not + // found false is returned, if found true is returned. An error + // message of the attempted paths is stored in errorMsg. + // exeName is the name of the executable. + // buildDir is a possibly null path to the build directory. + // installPrefix is a possibly null pointer to the install directory. + static bool FindProgramPath(const char* argv0, + std::string& pathOut, + std::string& errorMsg, + const char* exeName = 0, + const char* buildDir = 0, + const char* installPrefix = 0); + + // Description: + // Get current working directory CWD + static std::string GetCurrentWorkingDirectory(bool collapse =true); + + // Description: + // Given the path to a program executable, get the directory part of + // the path with the file stripped off. If there is no directory + // part, the empty string is returned. + static std::string GetProgramPath(const std::string&); + +protected: + vtkPSystemTools() {} + ~vtkPSystemTools() {} + +private: + vtkPSystemTools(const vtkPSystemTools&); // Not implemented. + void operator=(const vtkPSystemTools&); // Not implemented. +}; + +#endif diff --git a/Parallel/Core/vtkSocketCommunicator.h b/Parallel/Core/vtkSocketCommunicator.h index 2a87eec321d..cae1c3771ef 100644 --- a/Parallel/Core/vtkSocketCommunicator.h +++ b/Parallel/Core/vtkSocketCommunicator.h @@ -143,13 +143,11 @@ class VTKPARALLELCORE_EXPORT vtkSocketCommunicator : public vtkCommunicator vtkBooleanMacro(PerformHandshake, int); vtkGetMacro(PerformHandshake, int); - //BTX // Description: // Get/Set the output stream to which communications should be // logged. This is intended as a debugging feature. virtual void SetLogStream(ostream* stream); virtual ostream* GetLogStream(); - //ETX // Description: // Log messages to the given file. The file is truncated unless the @@ -210,7 +208,6 @@ class VTKPARALLELCORE_EXPORT vtkSocketCommunicator : public vtkCommunicator // Returns true if there are any messages in the receive buffer. bool HasBufferredMessages(); -//BTX protected: vtkClientSocket* Socket; @@ -270,7 +267,6 @@ class VTKPARALLELCORE_EXPORT vtkSocketCommunicator : public vtkCommunicator class vtkMessageBuffer; vtkMessageBuffer* ReceivedMessageBuffer; -//ETX }; #endif diff --git a/Parallel/Core/vtkSocketController.h b/Parallel/Core/vtkSocketController.h index 085cb87a061..78e8bf66cba 100644 --- a/Parallel/Core/vtkSocketController.h +++ b/Parallel/Core/vtkSocketController.h @@ -107,8 +107,6 @@ class VTKPARALLELCORE_EXPORT vtkSocketController : public vtkMultiProcessControl // deleting this controller. vtkMultiProcessController *CreateCompliantController(); -//BTX - enum Consts { ENDIAN_TAG=1010580540, // 0x3c3c3c3c IDTYPESIZE_TAG=1027423549, // 0x3d3d3d3d @@ -116,8 +114,6 @@ class VTKPARALLELCORE_EXPORT vtkSocketController : public vtkMultiProcessControl HASH_TAG=0x3f3f3f3f }; -//ETX - protected: vtkSocketController(); diff --git a/Parallel/Core/vtkSubGroup.h b/Parallel/Core/vtkSubGroup.h index 82206832555..bce21e05036 100644 --- a/Parallel/Core/vtkSubGroup.h +++ b/Parallel/Core/vtkSubGroup.h @@ -52,10 +52,9 @@ class VTKPARALLELCORE_EXPORT vtkSubGroup : public vtkObject virtual void PrintSelf(ostream &os, vtkIndent indent); static vtkSubGroup *New(); -//BTX // The wrapper gets confused here and falls down. enum {MINOP = 1, MAXOP = 2, SUMOP = 3}; -//ETX + // Description: // Initialize a communication subgroup for the processes // with rank p0 through p1 of the given communicator. (So diff --git a/Parallel/MPI/Testing/Cxx/CMakeLists.txt b/Parallel/MPI/Testing/Cxx/CMakeLists.txt index f28542c27e1..f899d2a5a07 100644 --- a/Parallel/MPI/Testing/Cxx/CMakeLists.txt +++ b/Parallel/MPI/Testing/Cxx/CMakeLists.txt @@ -13,6 +13,8 @@ vtk_add_test_mpi(${vtk-module}CxxTests-MPI tests vtk_add_test_mpi(${vtk-module}CxxTests-MPI no_data_tests GenericCommunicator.cxx MPIController.cxx + PDirectory.cxx + PSystemTools.cxx TestNonBlockingCommunication.cxx TestProcess.cxx ${extra_opengl_tests} diff --git a/Parallel/MPI/Testing/Cxx/ExerciseMultiProcessController.cxx b/Parallel/MPI/Testing/Cxx/ExerciseMultiProcessController.cxx index b6a9fcbc0d3..22c1e1e04fb 100644 --- a/Parallel/MPI/Testing/Cxx/ExerciseMultiProcessController.cxx +++ b/Parallel/MPI/Testing/Cxx/ExerciseMultiProcessController.cxx @@ -220,8 +220,8 @@ static int CompareFieldData(vtkFieldData *fd1, vtkFieldData *fd2) // the same order. if (!array1->GetName()) continue; vtkAbstractArray *array2 = fd2->GetAbstractArray(array1->GetName()); - if (!CompareDataArrays(vtkDataArray::SafeDownCast(array1), - vtkDataArray::SafeDownCast(array2))) return 0; + if (!CompareDataArrays(vtkArrayDownCast(array1), + vtkArrayDownCast(array2))) return 0; } return 1; diff --git a/Parallel/MPI/Testing/Cxx/PDirectory.cxx b/Parallel/MPI/Testing/Cxx/PDirectory.cxx new file mode 100644 index 00000000000..24c81ee39c5 --- /dev/null +++ b/Parallel/MPI/Testing/Cxx/PDirectory.cxx @@ -0,0 +1,73 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: PDirectory.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include + +#include "vtkMPIController.h" +#include "vtkPDirectory.h" +#include "vtkPSystemTools.h" + +#include "vtkSmartPointer.h" +#define VTK_CREATE(type, name) \ + vtkSmartPointer name = vtkSmartPointer::New() + +int PDirectory(int argc, char* argv[]) +{ + // This is here to avoid false leak messages from vtkDebugLeaks when + // using mpich. It appears that the root process which spawns all the + // main processes waits in MPI_Init() and calls exit() when + // the others are done, causing apparent memory leaks for any objects + // created before MPI_Init(). + MPI_Init(&argc, &argv); + + VTK_CREATE(vtkMPIController, controller); + + controller->Initialize(&argc, &argv, 1); + controller->SetGlobalController(controller); + + int retVal = 0; // success + + std::string str = vtkPSystemTools::GetCurrentWorkingDirectory(); + + VTK_CREATE(vtkPDirectory, directory); + + if(!directory->Load(str)) + { + vtkGenericWarningMacro("Could not load directory"); + retVal++; + } + + if(directory->GetNumberOfFiles() < 3) + { + vtkGenericWarningMacro("Missing files"); + retVal++; + } + + bool hasFile = false; + for(vtkIdType i=0;iGetNumberOfFiles();i++) + { + hasFile = hasFile || (strcmp(directory->GetFile(i), "cmake_install.cmake") == 0); + } + if(!hasFile) + { + vtkGenericWarningMacro("Missing cmake_install.cmake"); + retVal++; + } + + controller->SetGlobalController(NULL); + controller->Finalize(); + + return retVal; +} diff --git a/Parallel/MPI/Testing/Cxx/PSystemTools.cxx b/Parallel/MPI/Testing/Cxx/PSystemTools.cxx new file mode 100644 index 00000000000..566bb4420c0 --- /dev/null +++ b/Parallel/MPI/Testing/Cxx/PSystemTools.cxx @@ -0,0 +1,83 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: PSystemTools.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include + +#include "vtkMPIController.h" +#include "vtkPSystemTools.h" + +#include "vtkSmartPointer.h" +#define VTK_CREATE(type, name) \ + vtkSmartPointer name = vtkSmartPointer::New() + +int PSystemTools(int argc, char* argv[]) +{ + // This is here to avoid false leak messages from vtkDebugLeaks when + // using mpich. It appears that the root process which spawns all the + // main processes waits in MPI_Init() and calls exit() when + // the others are done, causing apparent memory leaks for any objects + // created before MPI_Init(). + MPI_Init(&argc, &argv); + + VTK_CREATE(vtkMPIController, controller); + + controller->Initialize(&argc, &argv, 1); + controller->SetGlobalController(controller); + + int retVal = 0; // success + + std::string str; + if(controller->GetLocalProcessId() == 0) + { + str = "test"; + } + vtkPSystemTools::BroadcastString(str, 0); + if(str != "test") + { + vtkGenericWarningMacro("BroadcastString failed for process " << + controller->GetLocalProcessId()); + retVal++; + } + + str = vtkPSystemTools::GetCurrentWorkingDirectory(); + std::string substr = str.substr(str.size()-24, str.size()); + if(substr != "Parallel/MPI/Testing/Cxx") + { + vtkGenericWarningMacro("GetCurrentWorkingDirectory failed for process " << + controller->GetLocalProcessId()); + retVal++; + } + + if(!vtkPSystemTools::FileIsDirectory(str)) + { + vtkGenericWarningMacro("FileIsDirectory failed for process " << + controller->GetLocalProcessId()); + retVal++; + } + + str += "/cmake_install.cmake"; + if(!vtkPSystemTools::FileExists(str)) + { + vtkGenericWarningMacro("FileExists failed for process " << + controller->GetLocalProcessId()); + retVal++; + } + + + controller->SetGlobalController(NULL); + controller->Finalize(); + + return retVal; +} diff --git a/Parallel/MPI/vtkMPICommunicator.h b/Parallel/MPI/vtkMPICommunicator.h index 22b7a865591..fa30a829b24 100644 --- a/Parallel/MPI/vtkMPICommunicator.h +++ b/Parallel/MPI/vtkMPICommunicator.h @@ -46,7 +46,6 @@ class vtkMPICommunicatorReceiveDataInfo; class VTKPARALLELMPI_EXPORT vtkMPICommunicator : public vtkCommunicator { public: -//BTX class VTKPARALLELMPI_EXPORT Request { @@ -61,8 +60,6 @@ class VTKPARALLELMPI_EXPORT vtkMPICommunicator : public vtkCommunicator vtkMPICommunicatorOpaqueRequest* Req; }; -//ETX - vtkTypeMacro( vtkMPICommunicator,vtkCommunicator); void PrintSelf(ostream& os, vtkIndent indent); @@ -235,7 +232,6 @@ class VTKPARALLELMPI_EXPORT vtkMPICommunicator : public vtkCommunicator // given the by the pre-allocated completed array. int TestSome(const int count,Request requests[], int& NCompleted,int *completed); -//BTX friend class vtkMPIController; @@ -246,8 +242,6 @@ class VTKPARALLELMPI_EXPORT vtkMPICommunicator : public vtkCommunicator int InitializeExternal(vtkMPICommunicatorOpaqueComm *comm); -//ETX - static char* Allocate(size_t size); static void Free(char* ptr); diff --git a/Parallel/MPI/vtkMPIController.h b/Parallel/MPI/vtkMPIController.h index f8750328b7e..1263a6abd43 100644 --- a/Parallel/MPI/vtkMPIController.h +++ b/Parallel/MPI/vtkMPIController.h @@ -123,8 +123,6 @@ class VTKPARALLELMPI_EXPORT vtkMPIController : public vtkMultiProcessController virtual vtkMPIController *PartitionController(int localColor, int localKey); -//BTX - // Description: // This method sends data to another process (non-blocking). // Tag eliminates ambiguity when multiple sends or receives @@ -276,7 +274,7 @@ class VTKPARALLELMPI_EXPORT vtkMPIController : public vtkMultiProcessController // are given in the completed user-supplied vtkIntArray. bool TestSome(const int count,vtkMPICommunicator::Request requests[], vtkIntArray *completed ); -//ETX + static const char* GetProcessorName(); // Description: @@ -285,7 +283,7 @@ class VTKPARALLELMPI_EXPORT vtkMPIController : public vtkMultiProcessController static void SetUseSsendForRMI(int use_send) { vtkMPIController::UseSsendForRMI = (use_send != 0)? 1: 0; } static int GetUseSsendForRMI() { return vtkMPIController::UseSsendForRMI; } -//BTX + protected: vtkMPIController(); ~vtkMPIController(); @@ -323,7 +321,7 @@ class VTKPARALLELMPI_EXPORT vtkMPIController : public vtkMultiProcessController private: vtkMPIController(const vtkMPIController&); // Not implemented. void operator=(const vtkMPIController&); // Not implemented. -//ETX + }; diff --git a/Remote/WikiExamples.remote.cmake b/Remote/WikiExamples.remote.cmake index 88251fd3fa1..f96b2c019d0 100644 --- a/Remote/WikiExamples.remote.cmake +++ b/Remote/WikiExamples.remote.cmake @@ -6,8 +6,8 @@ # If the environement var WikiExamplesTag exists, use it if (NOT DEFINED ENV{WikiExamplesTag}) - # February 29, 2016 - set(GIT_TAG ab816c494f60b7e94c992e9e5dabcadd28227dc1) + # April 19, 2016 + set(GIT_TAG 533e7047fc8bbec29cfe82686cd66eec9b94ba0c) else() set(GIT_TAG $ENV{WikiExamplesTag}) endif() @@ -15,7 +15,5 @@ endif() vtk_fetch_module(WikiExamples "A collection of examples that illustrate how to use VTK." GIT_REPOSITORY https://github.com/lorensen/VTKWikiExamples.git - # February 14, 2016 - # New baselines GIT_TAG ${GIT_TAG} ) diff --git a/Remote/vtkDICOM.remote.cmake b/Remote/vtkDICOM.remote.cmake index 91b7ecb2368..23ab0306f76 100644 --- a/Remote/vtkDICOM.remote.cmake +++ b/Remote/vtkDICOM.remote.cmake @@ -5,6 +5,6 @@ vtk_fetch_module(vtkDICOM "Dicom classes and utilities" GIT_REPOSITORY https://github.com/dgobbi/vtk-dicom - # vtk-dicom tag v0.7.4 (Jan 29, 2016) - GIT_TAG 4a7aff1210b8f58b80c8da66d8b761ee94594f4e + # vtk-dicom tag v0.7.8 (May 27, 2016) + GIT_TAG b21075408c74ef8a2211ed7b51bc9de85e2238c1 ) diff --git a/Rendering/Annotation/Testing/Cxx/CMakeLists.txt b/Rendering/Annotation/Testing/Cxx/CMakeLists.txt index f1824708f06..bea2d55b37d 100644 --- a/Rendering/Annotation/Testing/Cxx/CMakeLists.txt +++ b/Rendering/Annotation/Testing/Cxx/CMakeLists.txt @@ -1,12 +1,21 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests + TestAxisActor.cxx + TestAxisActor2D.cxx TestAxisActor3D.cxx + TestAxisActorText3D.cxx TestBarChartActor.cxx TestCaptionActor2D.cxx TestConvexHull2D.cxx,NO_VALID TestCornerAnnotation.cxx - TestEmptyCornerAnnotation.cxx TestCubeAxes2DMode.cxx TestCubeAxes3.cxx + TestCubeAxesInnerGridAll.cxx + TestCubeAxesInnerGridClosest.cxx + TestCubeAxesInnerGridFurthest.cxx + TestCubeAxesIntersectionPoint.cxx + TestCubeAxesOrientedBoundingBox.cxx + TestCubeAxesSticky.cxx + TestCubeAxesStickyCentered.cxx TestCubeAxesWithGridLines.cxx TestCubeAxesWithXInnerGrids.cxx TestCubeAxesWithXInnerPolys.cxx @@ -17,6 +26,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestCubeAxesWithZInnerGrids.cxx TestCubeAxesWithZInnerPolys.cxx TestCubeAxesWithZLines.cxx + TestEmptyCornerAnnotation.cxx TestLegendBoxActor.cxx TestLegendBoxActor2.cxx TestLegendScaleActor.cxx @@ -25,13 +35,6 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestScalarBar.cxx TestScalarBarAboveBelow.cxx TestSpiderPlotActor.cxx - TestCubeAxesOrientedBoundingBox.cxx - TestCubeAxesIntersectionPoint.cxx - TestCubeAxesInnerGridAll.cxx - TestCubeAxesInnerGridClosest.cxx - TestCubeAxesInnerGridFurthest.cxx - TestCubeAxesSticky.cxx - TestCubeAxesStickyCentered.cxx TestXYPlotActor.cxx ) diff --git a/Rendering/Annotation/Testing/Cxx/TestAxisActor.cxx b/Rendering/Annotation/Testing/Cxx/TestAxisActor.cxx new file mode 100644 index 00000000000..00f357f03cf --- /dev/null +++ b/Rendering/Annotation/Testing/Cxx/TestAxisActor.cxx @@ -0,0 +1,6 @@ +#include "TestAxisActorInternal.h" + +int TestAxisActor(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) +{ + return TestAxisActorInternal(0, 0); +} diff --git a/Rendering/Annotation/Testing/Cxx/TestAxisActor2D.cxx b/Rendering/Annotation/Testing/Cxx/TestAxisActor2D.cxx new file mode 100644 index 00000000000..bfe74aa6bd1 --- /dev/null +++ b/Rendering/Annotation/Testing/Cxx/TestAxisActor2D.cxx @@ -0,0 +1,6 @@ +#include "TestAxisActorInternal.h" + +int TestAxisActor2D(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) +{ + return TestAxisActorInternal(1, 0); +} diff --git a/Rendering/Annotation/Testing/Cxx/TestAxisActorInternal.h b/Rendering/Annotation/Testing/Cxx/TestAxisActorInternal.h new file mode 100644 index 00000000000..bf66aa05046 --- /dev/null +++ b/Rendering/Annotation/Testing/Cxx/TestAxisActorInternal.h @@ -0,0 +1,160 @@ +#ifndef TestAxisActorInternal_h +#define TestAxisActorInternal_h + +#include "vtkAxisActor.h" +#include "vtkCamera.h" +#include "vtkNew.h" +#include "vtkPolyDataMapper.h" +#include "vtkProperty.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkRenderer.h" +#include "vtkSphereSource.h" +#include "vtkStringArray.h" +#include "vtkTextProperty.h" + +inline int TestAxisActorInternal(int use2dMode, int use3dProp) +{ + vtkNew labels; + labels->SetNumberOfTuples(6); + labels->SetValue(0, "0"); + labels->SetValue(1, "2"); + labels->SetValue(2, "4"); + labels->SetValue(3, "6"); + labels->SetValue(4, "8"); + labels->SetValue(5, "10"); + + vtkNew textProp1; + textProp1->SetColor(0., 0., 1.); + textProp1->SetOpacity(0.9); + + vtkNew textProp2; + textProp2->SetColor(1., 0., 0.); + textProp2->SetOpacity(0.6); + + vtkNew textProp3; + textProp3->SetColor(0., 1., 0.); + textProp3->SetOpacity(1); + + vtkNew prop1; + prop1->SetColor(1., 0., 1.); + + vtkNew prop2; + prop2->SetColor(1., 1., 0.); + + vtkNew prop3; + prop3->SetColor(0., 1., 1.); + + //------------- X Axis ------------- + vtkNew axisXActor; + axisXActor->SetUse2DMode(use2dMode); + axisXActor->SetUseTextActor3D(use3dProp); + axisXActor->GetProperty()->SetAmbient(1); + axisXActor->GetProperty()->SetDiffuse(0); + axisXActor->SetPoint1(0, 0, 0); + axisXActor->SetPoint2(10, 0, 0); + axisXActor->SetTitle("X Axis"); + axisXActor->SetBounds(0, 10, 0, 0, 0, 0); + axisXActor->SetTickLocationToBoth(); + axisXActor->SetAxisTypeToX(); + axisXActor->SetRange(0, 10); + axisXActor->SetLabels(labels.Get()); + axisXActor->SetDeltaRangeMajor(2); + axisXActor->SetDeltaRangeMinor(0.5); + axisXActor->SetExponent("+00"); + axisXActor->SetExponentVisibility(true); + axisXActor->SetTitleScale(0.8); + axisXActor->SetLabelScale(0.5); + axisXActor->SetTitleOffset(3); + axisXActor->SetExponentOffset(3); + axisXActor->SetLabelOffset(5); + axisXActor->SetTitleTextProperty(textProp1.Get()); + axisXActor->SetLabelTextProperty(textProp2.Get()); + axisXActor->SetAxisMainLineProperty(prop1.Get()); + axisXActor->SetAxisMajorTicksProperty(prop2.Get()); + axisXActor->SetAxisMinorTicksProperty(prop3.Get()); + + //------------- Y Axis ------------- + vtkNew axisYActor; + axisYActor->SetUse2DMode(use2dMode); + axisYActor->SetUseTextActor3D(use3dProp); + axisYActor->GetProperty()->SetAmbient(1); + axisYActor->GetProperty()->SetDiffuse(0); + axisYActor->SetPoint1(0, 0, 0); + axisYActor->SetPoint2(0, 10, 0); + axisYActor->SetTitle("Y Axis"); + axisYActor->SetBounds(0, 0, 0, 10, 0, 0); + axisYActor->SetTickLocationToInside(); + axisYActor->SetAxisTypeToY(); + axisYActor->SetRange(0.1, 500); + axisYActor->SetMajorRangeStart(0.1); + axisYActor->SetMinorRangeStart(0.1); + axisYActor->SetMinorTicksVisible(true); + axisYActor->SetTitleAlignLocation(vtkAxisActor::VTK_ALIGN_TOP); + axisYActor->SetExponent("+00"); + axisYActor->SetExponentVisibility(true); + axisYActor->SetExponentLocation(vtkAxisActor::VTK_ALIGN_TOP); + axisYActor->SetTitleScale(0.8); + axisYActor->SetLabelScale(0.5); + axisYActor->SetTitleOffset(3); + axisYActor->SetExponentOffset(5); + axisYActor->SetLabelOffset(5); + axisYActor->SetTitleTextProperty(textProp2.Get()); + axisYActor->SetLog(true); + axisYActor->SetAxisLinesProperty(prop1.Get()); + + //------------- Z Axis ------------- + vtkNew axisZActor; + axisZActor->SetUse2DMode(use2dMode); + axisZActor->SetUseTextActor3D(use3dProp); + axisZActor->GetProperty()->SetAmbient(1); + axisZActor->GetProperty()->SetDiffuse(0); + axisZActor->SetPoint1(0, 0, 0); + axisZActor->SetPoint2(0, 0, 10); + axisZActor->SetTitle("Z Axis"); + axisZActor->SetBounds(0, 0, 0, 0, 0, 10); + axisZActor->SetTickLocationToOutside(); + axisZActor->SetAxisTypeToZ(); + axisZActor->SetRange(0, 10); + axisZActor->SetTitleAlignLocation(vtkAxisActor::VTK_ALIGN_POINT2); + axisZActor->SetExponent("+00"); + axisZActor->SetExponentVisibility(true); + axisZActor->SetExponentLocation(vtkAxisActor::VTK_ALIGN_POINT1); + axisZActor->SetTitleScale(0.8); + axisZActor->SetLabelScale(0.5); + axisZActor->SetTitleOffset(3); + axisZActor->SetExponentOffset(3); + axisZActor->SetLabelOffset(5); + axisZActor->SetTitleTextProperty(textProp3.Get()); + axisZActor->SetMajorTickSize(3); + axisZActor->SetMinorTickSize(1); + axisZActor->SetDeltaRangeMajor(2); + axisZActor->SetDeltaRangeMinor(0.1); + + vtkNew renderer; + vtkNew renderWindow; + renderWindow->AddRenderer(renderer.Get()); + vtkNew renderWindowInteractor; + renderWindowInteractor->SetRenderWindow(renderWindow.Get()); + renderer->AddActor(axisXActor.Get()); + renderer->AddActor(axisYActor.Get()); + renderer->AddActor(axisZActor.Get()); + renderer->SetBackground(.5, .5, .5); + + vtkCamera* camera = renderer->GetActiveCamera(); + axisXActor->SetCamera(camera); + axisYActor->SetCamera(camera); + axisZActor->SetCamera(camera); + renderWindow->SetSize(300, 300); + + camera->SetPosition(-10.0, 22.0, -29); + camera->SetFocalPoint(-2, 8.5, -9.); + + renderWindow->SetMultiSamples(0); + renderWindow->Render(); + renderWindowInteractor->Start(); + + return EXIT_SUCCESS; +} + +#endif diff --git a/Rendering/Annotation/Testing/Cxx/TestAxisActorText3D.cxx b/Rendering/Annotation/Testing/Cxx/TestAxisActorText3D.cxx new file mode 100644 index 00000000000..82a17438932 --- /dev/null +++ b/Rendering/Annotation/Testing/Cxx/TestAxisActorText3D.cxx @@ -0,0 +1,6 @@ +#include "TestAxisActorInternal.h" + +int TestAxisActorText3D(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) +{ + return TestAxisActorInternal(0, 1); +} diff --git a/Rendering/Annotation/Testing/Cxx/TestPolarAxes.cxx b/Rendering/Annotation/Testing/Cxx/TestPolarAxes.cxx index 583038fe172..44e44774f04 100644 --- a/Rendering/Annotation/Testing/Cxx/TestPolarAxes.cxx +++ b/Rendering/Annotation/Testing/Cxx/TestPolarAxes.cxx @@ -17,11 +17,11 @@ #include "vtkBYUReader.h" #include "vtkCamera.h" -#include "vtkPolarAxesActor.h" #include "vtkLight.h" #include "vtkLODActor.h" #include "vtkNew.h" #include "vtkOutlineFilter.h" +#include "vtkPolarAxesActor.h" #include "vtkPolyDataMapper.h" #include "vtkPolyDataNormals.h" #include "vtkProperty.h" @@ -35,88 +35,86 @@ #include "vtkTestUtilities.h" //---------------------------------------------------------------------------- -int TestPolarAxes( int argc, char* argv[] ) +int TestPolarAxes(int argc, char* argv[]) { vtkNew reader; - char* fname = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/teapot.g" ); - reader->SetGeometryFileName( fname ); + char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/teapot.g"); + reader->SetGeometryFileName(fname); delete [] fname; vtkNew normals; - normals->SetInputConnection( reader->GetOutputPort() ); + normals->SetInputConnection(reader->GetOutputPort()); vtkNew readerMapper; - readerMapper->SetInputConnection( normals->GetOutputPort() ); + readerMapper->SetInputConnection(normals->GetOutputPort()); vtkNew readerActor; - readerActor->SetMapper( readerMapper.GetPointer() ); - readerActor->GetProperty()->SetDiffuseColor( .5, .8, .3 ); + readerActor->SetMapper(readerMapper.GetPointer()); + readerActor->GetProperty()->SetDiffuseColor(.5, .8, .3); vtkNew outline; - outline->SetInputConnection(normals->GetOutputPort() ); + outline->SetInputConnection(normals->GetOutputPort()); vtkNew mapOutline; - mapOutline->SetInputConnection( outline->GetOutputPort() ); + mapOutline->SetInputConnection(outline->GetOutputPort()); vtkNew outlineActor; - outlineActor->SetMapper( mapOutline.GetPointer() ); - outlineActor->GetProperty()->SetColor( 1., 1., 1. ); + outlineActor->SetMapper(mapOutline.GetPointer()); + outlineActor->GetProperty()->SetColor(1., 1., 1.); vtkNew camera; - camera->SetClippingRange( 1., 100. ); - camera->SetFocalPoint( 0., .5, 0. ); - camera->SetPosition( 5., 6., 14. ); + camera->SetClippingRange(1., 100.); + camera->SetFocalPoint(0., .5, 0.); + camera->SetPosition(5., 6., 14.); vtkNew light; - light->SetFocalPoint( 0.21406, 1.5, 0.0 ); - light->SetPosition( 7., 7., 4. ); + light->SetFocalPoint(0.21406, 1.5, 0.0); + light->SetPosition(7., 7., 4.); vtkNew renderer; - renderer->SetActiveCamera( camera.GetPointer() ); - renderer->AddLight( light.GetPointer() ); + renderer->SetActiveCamera(camera.GetPointer()); + renderer->AddLight(light.GetPointer()); // Update normals in order to get correct bounds for polar axes normals->Update(); vtkNew polaxes; - polaxes->SetBounds( normals->GetOutput()->GetBounds() ); - polaxes->SetPole( .5, 1., 3. ); - polaxes->SetAutoScaleRadius( false ); - polaxes->SetMaximumRadius( 3. ); - polaxes->SetMinimumAngle( -60. ); - polaxes->SetMaximumAngle( 210. ); - polaxes->SetNumberOfRadialAxes( 10 ); - polaxes->SetCamera( renderer->GetActiveCamera() ); - polaxes->SetPolarLabelFormat( "%6.1f" ); - polaxes->GetRadialAxesProperty()->SetColor( .0, .0, 1. ); - polaxes->GetPolarArcsProperty()->SetColor( 1., .0, 0. ); - polaxes->GetPolarAxisProperty()->SetColor( .2, .2, .2 ); - polaxes->GetPolarAxisTitleTextProperty()->SetColor( .2, .2, .2 ); - polaxes->GetPolarAxisLabelTextProperty()->SetColor( .2, .2, .2 ); - polaxes->SetNumberOfPolarAxisTicks( 9 ); - polaxes->SetAutoSubdividePolarAxis( false ); - polaxes->SetScreenSize( 9.0 ); + polaxes->SetBounds(normals->GetOutput()->GetBounds()); + polaxes->SetPole(.5, 1., 3.); + polaxes->SetAutoScaleRadius(false); + polaxes->SetMaximumRadius(3.); + polaxes->SetMinimumAngle(-60.); + polaxes->SetMaximumAngle(210.); + polaxes->SetNumberOfRadialAxes(10); + polaxes->SetCamera(renderer->GetActiveCamera()); + polaxes->SetPolarLabelFormat("%6.1f"); + polaxes->GetLastRadialAxisProperty()->SetColor(.0, .0, 1.); + polaxes->GetSecondaryRadialAxesProperty()->SetColor(.0, .0, 1.); + polaxes->GetPolarArcsProperty()->SetColor(1., .0, 0.); + polaxes->GetSecondaryPolarArcsProperty()->SetColor(1., 1., 1.); + polaxes->GetPolarAxisProperty()->SetColor(.2, .2, .2); + polaxes->GetPolarAxisTitleTextProperty()->SetColor(.2, .2, .2); + polaxes->GetPolarAxisLabelTextProperty()->SetColor(.2, .2, .2); + polaxes->SetNumberOfPolarAxisTicks(9); + polaxes->SetAutoSubdividePolarAxis(false); + polaxes->SetScreenSize(9.0); vtkNew renWin; - renWin->SetMultiSamples( 0 ); - renWin->AddRenderer( renderer.GetPointer() ); - renWin->SetWindowName( "VTK - Polar Axes" ); - renWin->SetSize( 600, 600 ); + renWin->SetMultiSamples(0); + renWin->AddRenderer(renderer.GetPointer()); + renWin->SetWindowName("VTK - Polar Axes"); + renWin->SetSize(600, 600); vtkNew iren; - iren->SetRenderWindow( renWin.GetPointer() ); + iren->SetRenderWindow(renWin.GetPointer()); - renderer->SetBackground( .8, .8, .8 ); - renderer->AddViewProp( readerActor.GetPointer() ); - renderer->AddViewProp( outlineActor.GetPointer() ); - renderer->AddViewProp( polaxes.GetPointer() ); + renderer->SetBackground(.8, .8, .8); + renderer->AddViewProp(readerActor.GetPointer()); + renderer->AddViewProp(outlineActor.GetPointer()); + renderer->AddViewProp(polaxes.GetPointer()); renWin->Render(); - int retVal = vtkRegressionTestImage( renWin.GetPointer() ); - if ( retVal == vtkRegressionTester::DO_INTERACTOR ) - { - iren->Start(); - } + iren->Start(); - return !retVal; + return EXIT_SUCCESS; } diff --git a/Rendering/Annotation/Testing/Cxx/TestScalarBarAboveBelow.cxx b/Rendering/Annotation/Testing/Cxx/TestScalarBarAboveBelow.cxx index c12ab3c62cb..16959e3ec6f 100644 --- a/Rendering/Annotation/Testing/Cxx/TestScalarBarAboveBelow.cxx +++ b/Rendering/Annotation/Testing/Cxx/TestScalarBarAboveBelow.cxx @@ -90,5 +90,6 @@ int TestScalarBarAboveBelow(int vtkNotUsed(argc), char *vtkNotUsed(argv)[]) renderWindow->SetMultiSamples(0); renderWindow->Render(); renderWindowInteractor->Start(); + return EXIT_SUCCESS; } diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestAxisActor.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestAxisActor.png.md5 new file mode 100644 index 00000000000..c6e5e507212 --- /dev/null +++ b/Rendering/Annotation/Testing/Data/Baseline/TestAxisActor.png.md5 @@ -0,0 +1 @@ +f9ce966005110e197cfc0f8bf2e9c500 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestAxisActor2D.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestAxisActor2D.png.md5 new file mode 100644 index 00000000000..c64b7d2d65b --- /dev/null +++ b/Rendering/Annotation/Testing/Data/Baseline/TestAxisActor2D.png.md5 @@ -0,0 +1 @@ +35e16dc323e773d7d554f3fdb5368d7f diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestAxisActor3D.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestAxisActor3D.png.md5 index ea8cf9434c1..58b10f70158 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestAxisActor3D.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestAxisActor3D.png.md5 @@ -1 +1 @@ -4c2eb306867d637866e1d0c3a1c55d27 +806bfb59c25f444c633a7db29b52d443 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestAxisActorText3D.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestAxisActorText3D.png.md5 new file mode 100644 index 00000000000..44bc639fb4c --- /dev/null +++ b/Rendering/Annotation/Testing/Data/Baseline/TestAxisActorText3D.png.md5 @@ -0,0 +1 @@ +77817ec27ff9a8ff59c8243fc27b35d8 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxes3.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxes3.png.md5 index b0457ad7abe..c18b377c4a7 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxes3.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxes3.png.md5 @@ -1 +1 @@ -c700c7b40176fa188b0da816b8bbb0b9 +d3f032419c92ec2564144d6953526b61 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridAll.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridAll.png.md5 index 3ad6c60e6e7..53a179d1ef4 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridAll.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridAll.png.md5 @@ -1 +1 @@ -4b94e1b2064e6c640a6f5a5fe0cba742 +12196e21d71b26787a44b164cdd1dd2c diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridClosest.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridClosest.png.md5 index 47597e1185b..30730950f2d 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridClosest.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridClosest.png.md5 @@ -1 +1 @@ -1ffc8ccafbd05df7a7c94fb88762451e +047e940a1c255045489e8017359a3cb8 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridFurthest.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridFurthest.png.md5 index 23fcda58d85..8b6f99e3a73 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridFurthest.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesInnerGridFurthest.png.md5 @@ -1 +1 @@ -dc5a3945e333a404261b6c52e706a695 +c906101cabced038ce75597d4fb3d6d2 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesIntersectionPoint.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesIntersectionPoint.png.md5 index 46b2d1962a4..c72031be612 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesIntersectionPoint.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesIntersectionPoint.png.md5 @@ -1 +1 @@ -96f82f92b8d31e9db70fed13819c2f9e +325f4f4fb460535589c16dcaaabc33af diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesOrientedBoundingBox.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesOrientedBoundingBox.png.md5 index 3ad6c60e6e7..53a179d1ef4 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesOrientedBoundingBox.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesOrientedBoundingBox.png.md5 @@ -1 +1 @@ -4b94e1b2064e6c640a6f5a5fe0cba742 +12196e21d71b26787a44b164cdd1dd2c diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesSticky.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesSticky.png.md5 index f9a7f865756..2d2d1a2d455 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesSticky.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesSticky.png.md5 @@ -1 +1 @@ -c95c5d499e5836be139ee687477fe4a7 +d13447d7f195692418c468cc99d1dae8 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesStickyCentered.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesStickyCentered.png.md5 index e7486a6cace..5005fcd784a 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesStickyCentered.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesStickyCentered.png.md5 @@ -1 +1 @@ -e0919c053f6080ca8d0125508c9ed2a2 +e355792d11b82226cd281c24d2e520a1 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithGridLines.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithGridLines.png.md5 index 36b497cf62f..840c0930b54 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithGridLines.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithGridLines.png.md5 @@ -1 +1 @@ -c89f95753df6e4268f83855a5e865735 +11c95fd323f07b683a68688531a36b46 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerGrids.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerGrids.png.md5 index 58b28c1f6b6..d7ecfec06da 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerGrids.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerGrids.png.md5 @@ -1 +1 @@ -5116f11b9146375df2489884229bded0 +a9adf9acbe385505c02469ee0776af70 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerPolys.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerPolys.png.md5 index 74aeb69e859..a10665885c2 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerPolys.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerPolys.png.md5 @@ -1 +1 @@ -eca7de481f3bd888bc6ef851547e1c5d +c7be265986a2d3cd8e6854ac08d0d092 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerPolys_1.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerPolys_1.png.md5 index f6b96948b8e..9c55c4cb705 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerPolys_1.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXInnerPolys_1.png.md5 @@ -1 +1 @@ -1a3263fb4ddef12f1523042cc06905e9 +6ae5fe452c6b67256120550a6d91f2b1 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXLines.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXLines.png.md5 index e6a5936594b..6e097b09218 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXLines.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXLines.png.md5 @@ -1 +1 @@ -62510648f6422c433b439f9b4900a7b2 +62561b891e3dcd5d9a0745a14c87f5aa diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXLines_1.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXLines_1.png.md5 index 63860ba7d04..c97a86acad7 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXLines_1.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithXLines_1.png.md5 @@ -1 +1 @@ -8013507c5529ab828bce33cd1c475d88 +40e29a940c6c87fe3e6538c89ecba5e0 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerGrids.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerGrids.png.md5 index b758a767a09..d09498e6c9e 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerGrids.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerGrids.png.md5 @@ -1 +1 @@ -6ac833a66966e30c3e3786e366ed3709 +86b6ee55e755d70ba5af5fa34607dbd5 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerPolys.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerPolys.png.md5 index a5aca09a864..65ed3ca203f 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerPolys.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerPolys.png.md5 @@ -1 +1 @@ -0833e886b5e31fb541f196e0368bdca9 +2d0b7ec8c47f06177e52f0b6777ea2a9 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerPolys_1.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerPolys_1.png.md5 index 7661bb5d0cb..1d94ec47459 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerPolys_1.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYInnerPolys_1.png.md5 @@ -1 +1 @@ -9f40e20a14aa377464f954e896d0fe77 +2ae9b39f8a20bdcf9d99479c84b0b8a8 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYLines.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYLines.png.md5 index 4a2624fce8c..f6d80425c52 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYLines.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYLines.png.md5 @@ -1 +1 @@ -ab717ea746594380e68d787f6508c22d +f30c259889426ac7052e7ab12db450bb diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYLines_1.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYLines_1.png.md5 index a5ed0b793d9..9eea70249e7 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYLines_1.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithYLines_1.png.md5 @@ -1 +1 @@ -a72e76899218d5d6272fc4bd2ab362ba +4f68d352fcaa90314ef3a6731bdab24f diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZInnerGrids.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZInnerGrids.png.md5 index ed41599150b..6beb3604d1b 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZInnerGrids.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZInnerGrids.png.md5 @@ -1 +1 @@ -d1e3d067d33b3316c0efa76e847ab41e +ea070ade0cb25acbc4108004e1ed123c diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZInnerPolys.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZInnerPolys.png.md5 index 3fa47e58a86..9ba0e35e011 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZInnerPolys.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZInnerPolys.png.md5 @@ -1 +1 @@ -a9220b5d85ad43ce5d265ae10e9d763a +b139616a77957db9bf662ba5d4c06e81 diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZLines.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZLines.png.md5 index 5a648c5d894..afa848ecdca 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZLines.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestCubeAxesWithZLines.png.md5 @@ -1 +1 @@ -ae7e743aebeb584e14778a045376b0f8 +2703396f303a4e501f199daf287a4e7b diff --git a/Rendering/Annotation/Testing/Data/Baseline/TestPolarAxes.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/TestPolarAxes.png.md5 index fc0e4fd4a58..355b474617c 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/TestPolarAxes.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/TestPolarAxes.png.md5 @@ -1 +1 @@ -d64f6a0f7e410f8f512a52d497dceb94 +db3f42a9131ba4ea88ea532533e88ad6 diff --git a/Rendering/Annotation/Testing/Data/Baseline/cubeAxes2.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/cubeAxes2.png.md5 index e31f303a3fa..f3fca3de7fb 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/cubeAxes2.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/cubeAxes2.png.md5 @@ -1 +1 @@ -53dc189b6649f24afaaf77e94906350e +6963ecad889c00371a51052611968468 diff --git a/Rendering/Annotation/Testing/Data/Baseline/cubeAxes2_1.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/cubeAxes2_1.png.md5 new file mode 100644 index 00000000000..907a75916ac --- /dev/null +++ b/Rendering/Annotation/Testing/Data/Baseline/cubeAxes2_1.png.md5 @@ -0,0 +1 @@ +9f0c04abb78067ad596fc8cc5cb90030 diff --git a/Rendering/Annotation/Testing/Data/Baseline/cubeAxes3.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/cubeAxes3.png.md5 index 6988ddeb93f..4246211f75d 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/cubeAxes3.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/cubeAxes3.png.md5 @@ -1 +1 @@ -4b2f163f87d9efaec21bc7951109aee6 +10aa76e821c2ba0b82869987c7deda97 diff --git a/Rendering/Annotation/Testing/Data/Baseline/xyPlot.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/xyPlot.png.md5 index fe89cacd880..37e5f75ae7d 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/xyPlot.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/xyPlot.png.md5 @@ -1 +1 @@ -9644ca55b5f36bf84fc6daa8a21e3636 +3c7cc0e255587e1d6448ac10917bbade diff --git a/Rendering/Annotation/Testing/Data/Baseline/xyPlot2.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/xyPlot2.png.md5 index ada5c1678c5..f7b4a3e7d25 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/xyPlot2.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/xyPlot2.png.md5 @@ -1 +1 @@ -463d81760506b3a65fdbd4920ac76f81 +d0c7450aeb92c82ed09f4225dc3b332c diff --git a/Rendering/Annotation/Testing/Data/Baseline/xyPlot2_1.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/xyPlot2_1.png.md5 index e29946b846a..19dfa598e5f 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/xyPlot2_1.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/xyPlot2_1.png.md5 @@ -1 +1 @@ -2eb3c74177942200df52da0ec3dcc7cb +b76ef3e2ab1fc094cb535aa7b46d7e18 diff --git a/Rendering/Annotation/Testing/Data/Baseline/xyPlot3.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/xyPlot3.png.md5 index df49d27bbeb..496bde6da20 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/xyPlot3.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/xyPlot3.png.md5 @@ -1 +1 @@ -3b6ccfe9711670c60eb1b1f375172b77 +07750215c24a941e83fd37e5641d82c5 diff --git a/Rendering/Annotation/Testing/Data/Baseline/xyPlot4.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/xyPlot4.png.md5 index ada5c1678c5..f7b4a3e7d25 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/xyPlot4.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/xyPlot4.png.md5 @@ -1 +1 @@ -463d81760506b3a65fdbd4920ac76f81 +d0c7450aeb92c82ed09f4225dc3b332c diff --git a/Rendering/Annotation/Testing/Data/Baseline/xyPlot4_1.png.md5 b/Rendering/Annotation/Testing/Data/Baseline/xyPlot4_1.png.md5 index e29946b846a..19dfa598e5f 100644 --- a/Rendering/Annotation/Testing/Data/Baseline/xyPlot4_1.png.md5 +++ b/Rendering/Annotation/Testing/Data/Baseline/xyPlot4_1.png.md5 @@ -1 +1 @@ -2eb3c74177942200df52da0ec3dcc7cb +b76ef3e2ab1fc094cb535aa7b46d7e18 diff --git a/Rendering/Annotation/vtkAxesActor.h b/Rendering/Annotation/vtkAxesActor.h index eaf70ea1da7..e70f98091db 100644 --- a/Rendering/Annotation/vtkAxesActor.h +++ b/Rendering/Annotation/vtkAxesActor.h @@ -226,7 +226,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxesActor : public vtkProp3D vtkGetMacro(AxisLabels, int); vtkBooleanMacro(AxisLabels, int); -//BTX enum { CYLINDER_SHAFT, @@ -240,7 +239,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxesActor : public vtkProp3D SPHERE_TIP, USER_DEFINED_TIP }; -//ETX protected: vtkAxesActor(); diff --git a/Rendering/Annotation/vtkAxisActor.cxx b/Rendering/Annotation/vtkAxisActor.cxx index fee788dd778..7e00699e91b 100644 --- a/Rendering/Annotation/vtkAxisActor.cxx +++ b/Rendering/Annotation/vtkAxisActor.cxx @@ -8,9 +8,9 @@ All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkAxisActor.h" @@ -19,32 +19,37 @@ #include "vtkCellArray.h" #include "vtkCoordinate.h" #include "vtkFollower.h" -#include "vtkTextRenderer.h" #include "vtkMath.h" +#include "vtkNew.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProp3DAxisFollower.h" #include "vtkProperty.h" #include "vtkProperty2D.h" +#include "vtkRenderer.h" #include "vtkStringArray.h" #include "vtkTextActor.h" #include "vtkTextActor3D.h" #include "vtkTextProperty.h" +#include "vtkTextRenderer.h" +#include "vtkTransform.h" #include "vtkVectorText.h" #include "vtkViewport.h" #include "vtkWindow.h" -#define VTK_MAX_TICKS 1000 +#define VTK_MAX_TICKS 1000 + +#include vtkStandardNewMacro(vtkAxisActor); vtkCxxSetObjectMacro(vtkAxisActor, Camera, vtkCamera); -vtkCxxSetObjectMacro(vtkAxisActor,LabelTextProperty,vtkTextProperty); -vtkCxxSetObjectMacro(vtkAxisActor,TitleTextProperty,vtkTextProperty); +vtkCxxSetObjectMacro(vtkAxisActor, LabelTextProperty, vtkTextProperty); +vtkCxxSetObjectMacro(vtkAxisActor, TitleTextProperty, vtkTextProperty); -// **************************************************************** +//----------------------------------------------------------------------------- // Instantiate this object. -// **************************************************************** +//----------------------------------------------------------------------------- vtkAxisActor::vtkAxisActor() { @@ -58,6 +63,7 @@ vtkAxisActor::vtkAxisActor() this->Camera = NULL; this->Title = NULL; + this->Exponent = NULL; this->MinorTicksVisible = 1; this->MajorTickSize = 1.0; this->MinorTickSize = 0.5; @@ -65,8 +71,11 @@ vtkAxisActor::vtkAxisActor() this->Range[0] = 0.0; this->Range[1] = 1.0; this->ScreenSize = 10.; - this->LabelOffset = 20.; + this->LabelOffset = 30.; this->TitleOffset = 20.; + this->ExponentOffset = 20.; + this->TitleAlignLocation = VTK_ALIGN_BOTTOM; + this->ExponentLocation = VTK_ALIGN_POINT2; this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1; this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1; @@ -76,9 +85,9 @@ vtkAxisActor::vtkAxisActor() sprintf(this->LabelFormat, "%s", "%-#6.3g"); this->TitleTextProperty = vtkTextProperty::New(); - this->TitleTextProperty->SetColor(0.,0.,0.); + this->TitleTextProperty->SetColor(0., 0., 0.); this->TitleTextProperty->SetFontFamilyToArial(); - this->TitleTextProperty->SetFontSize(18); + this->TitleTextProperty->SetFontSize(18.); this->TitleTextProperty->SetVerticalJustificationToCentered(); this->TitleTextProperty->SetJustificationToCentered(); @@ -90,6 +99,7 @@ vtkAxisActor::vtkAxisActor() this->TitleActor->SetAxis(this); this->TitleActor->SetMapper(this->TitleMapper); this->TitleActor->SetEnableDistanceLOD(0); + this->TitleProp3D = vtkProp3DAxisFollower::New(); this->TitleProp3D->SetAxis(this); this->TitleProp3D->SetEnableDistanceLOD(0); @@ -106,17 +116,48 @@ vtkAxisActor::vtkAxisActor() this->LabelActors2D = NULL; this->LabelTextProperty = vtkTextProperty::New(); - this->LabelTextProperty->SetColor(0.,0.,0.); + this->LabelTextProperty->SetColor(0., 0., 0.); this->LabelTextProperty->SetFontFamilyToArial(); - this->LabelTextProperty->SetFontSize(14); + this->LabelTextProperty->SetFontSize(14.); this->LabelTextProperty->SetVerticalJustificationToBottom(); this->LabelTextProperty->SetJustificationToLeft(); + this->ExponentVector = vtkVectorText::New(); + this->ExponentMapper = vtkPolyDataMapper::New(); + this->ExponentMapper->SetInputConnection(this->ExponentVector->GetOutputPort()); + this->ExponentActor = vtkAxisFollower::New(); + this->ExponentActor->SetAxis(this); + this->ExponentActor->SetMapper(this->ExponentMapper); + this->ExponentActor->SetEnableDistanceLOD(0); + this->ExponentActor2D = vtkTextActor::New(); + + this->ExponentProp3D = vtkProp3DAxisFollower::New(); + this->ExponentProp3D->SetAxis(this); + this->ExponentProp3D->SetEnableDistanceLOD(0); + this->ExponentActor3D = vtkTextActor3D::New(); + this->ExponentProp3D->SetProp3D(this->ExponentActor3D); + + // Main line of axis this->AxisLines = vtkPolyData::New(); this->AxisLinesMapper = vtkPolyDataMapper::New(); this->AxisLinesMapper->SetInputData(this->AxisLines); this->AxisLinesActor = vtkActor::New(); this->AxisLinesActor->SetMapper(this->AxisLinesMapper); + + // Major ticks + this->AxisMajorTicks = vtkPolyData::New(); + this->AxisMajorTicksMapper = vtkPolyDataMapper::New(); + this->AxisMajorTicksMapper->SetInputData(this->AxisMajorTicks); + this->AxisMajorTicksActor = vtkActor::New(); + this->AxisMajorTicksActor->SetMapper(this->AxisMajorTicksMapper); + + // Minor ticks + this->AxisMinorTicks = vtkPolyData::New(); + this->AxisMinorTicksMapper = vtkPolyDataMapper::New(); + this->AxisMinorTicksMapper->SetInputData(this->AxisMinorTicks); + this->AxisMinorTicksActor = vtkActor::New(); + this->AxisMinorTicksActor->SetMapper(this->AxisMinorTicksMapper); + this->Gridlines = vtkPolyData::New(); this->GridlinesMapper = vtkPolyDataMapper::New(); this->GridlinesMapper->SetInputData(this->Gridlines); @@ -137,6 +178,7 @@ vtkAxisActor::vtkAxisActor() this->TickVisibility = 1; this->LabelVisibility = 1; this->TitleVisibility = 1; + this->ExponentVisibility = false; this->DrawGridlines = 0; this->DrawGridlinesOnly = 0; @@ -149,6 +191,7 @@ vtkAxisActor::vtkAxisActor() this->DrawGridpolys = 0; this->AxisType = VTK_AXIS_TYPE_X; + this->Log = false; // // AxisPosition denotes which of the four possibilities in relation // to the bounding box. An x-Type axis with min min, means the x-axis @@ -177,14 +220,12 @@ vtkAxisActor::vtkAxisActor() this->AxisHasZeroLength = false; this->MinorStart = 0.; - //this->MajorStart = 0.; - for(int i=0;i<3;i++) + for (int i = 0;i<3;i++) { this->MajorStart[i] = 0.; } this->DeltaMinor = 1.; - //this->DeltaMajor = 1.; - for(int i=0;i<3;i++) + for (int i = 0;i<3;i++) { this->DeltaMajor[i] = 1.; } @@ -194,8 +235,8 @@ vtkAxisActor::vtkAxisActor() this->DeltaRangeMinor = 1.; this->DeltaRangeMajor = 1.; - this->CalculateTitleOffset = 1; - this->CalculateLabelOffset = 1; + this->CalculateTitleOffset = 0; + this->CalculateLabelOffset = 0; // Instance variables specific to 2D mode this->Use2DMode = 0; @@ -210,11 +251,11 @@ vtkAxisActor::vtkAxisActor() this->LastMaxDisplayCoordinate[1] = 0; this->LastMaxDisplayCoordinate[2] = 0; - // 0: All locations + // 0: All locations this->DrawGridlinesLocation = this->LastDrawGridlinesLocation = 0; // reset the base - for(int i=0;i<3;i++) + for (int i = 0;i<3;i++) { this->AxisBaseForX[i] = this->AxisBaseForY[i] = this->AxisBaseForZ[i] = 0.0; } @@ -222,7 +263,7 @@ vtkAxisActor::vtkAxisActor() this->AxisOnOrigin = 0; } -// **************************************************************** +//----------------------------------------------------------------------------- vtkAxisActor::~vtkAxisActor() { this->SetCamera(NULL); @@ -270,6 +311,35 @@ vtkAxisActor::~vtkAxisActor() delete [] this->Title; this->Title = NULL; + delete [] this->Exponent; + this->Exponent = NULL; + + // delete exponent components + if (this->ExponentVector) + { + this->ExponentVector->Delete(); + this->ExponentVector = NULL; + } + if (this->ExponentMapper) + { + this->ExponentMapper->Delete(); + this->ExponentMapper = NULL; + } + if (this->ExponentActor) + { + this->ExponentActor->Delete(); + this->ExponentActor = NULL; + } + this->ExponentProp3D->Delete(); + this->ExponentProp3D = NULL; + this->ExponentActor3D->Delete(); + this->ExponentActor3D = NULL; + if (this->ExponentActor2D) + { + this->ExponentActor2D->Delete(); + this->ExponentActor2D = NULL; + } + if (this->TitleTextProperty) { this->TitleTextProperty->Delete(); @@ -278,7 +348,7 @@ vtkAxisActor::~vtkAxisActor() if (this->LabelMappers != NULL) { - for (int i=0; i < this->NumberOfLabelsBuilt; i++) + for (int i = 0; i < this->NumberOfLabelsBuilt; i++) { this->LabelVectors[i]->Delete(); this->LabelMappers[i]->Delete(); @@ -307,6 +377,7 @@ vtkAxisActor::~vtkAxisActor() this->LabelTextProperty = NULL; } + // main line of the axis if (this->AxisLines) { this->AxisLines->Delete(); @@ -323,6 +394,40 @@ vtkAxisActor::~vtkAxisActor() this->AxisLinesActor = NULL; } + //major ticks components + if (this->AxisMajorTicks) + { + this->AxisMajorTicks->Delete(); + this->AxisMajorTicks = NULL; + } + if (this->AxisMajorTicksMapper) + { + this->AxisMajorTicksMapper->Delete(); + this->AxisMajorTicksMapper = NULL; + } + if (this->AxisMajorTicksActor) + { + this->AxisMajorTicksActor->Delete(); + this->AxisMajorTicksActor = NULL; + } + + //minor ticks components + if (this->AxisMinorTicks) + { + this->AxisMinorTicks->Delete(); + this->AxisMinorTicks = NULL; + } + if (this->AxisMinorTicksMapper) + { + this->AxisMinorTicksMapper->Delete(); + this->AxisMinorTicksMapper = NULL; + } + if (this->AxisMinorTicksActor) + { + this->AxisMinorTicksActor->Delete(); + this->AxisMinorTicksActor = NULL; + } + if (this->Gridlines) { this->Gridlines->Delete(); @@ -398,14 +503,19 @@ vtkAxisActor::~vtkAxisActor() } } -// **************************************************************** +//----------------------------------------------------------------------------- void vtkAxisActor::ReleaseGraphicsResources(vtkWindow *win) { this->TitleActor->ReleaseGraphicsResources(win); this->TitleProp3D->ReleaseGraphicsResources(win); this->TitleActor3D->ReleaseGraphicsResources(win); this->TitleActor2D->ReleaseGraphicsResources(win); - for (int i=0; i < this->NumberOfLabelsBuilt; i++) + this->ExponentActor->ReleaseGraphicsResources(win); + this->ExponentProp3D->ReleaseGraphicsResources(win); + this->ExponentActor3D->ReleaseGraphicsResources(win); + this->ExponentActor2D->ReleaseGraphicsResources(win); + + for (int i = 0; i < this->NumberOfLabelsBuilt; i++) { this->LabelActors[i]->ReleaseGraphicsResources(win); this->LabelProps3D[i]->ReleaseGraphicsResources(win); @@ -413,15 +523,18 @@ void vtkAxisActor::ReleaseGraphicsResources(vtkWindow *win) this->LabelActors2D[i]->ReleaseGraphicsResources(win); } this->AxisLinesActor->ReleaseGraphicsResources(win); + this->AxisMajorTicksActor->ReleaseGraphicsResources(win); + this->AxisMinorTicksActor->ReleaseGraphicsResources(win); + this->GridlinesActor->ReleaseGraphicsResources(win); this->InnerGridlinesActor->ReleaseGraphicsResources(win); this->GridpolysActor->ReleaseGraphicsResources(win); } -// **************************************************************** +//----------------------------------------------------------------------------- int vtkAxisActor::RenderOpaqueGeometry(vtkViewport *viewport) { - int i, renderedSomething=0; + int renderedSomething = 0; this->BuildAxis(viewport, false); @@ -429,7 +542,7 @@ int vtkAxisActor::RenderOpaqueGeometry(vtkViewport *viewport) if (!this->AxisHasZeroLength) { - if(this->DrawGridlinesOnly && this->DrawGridlines) + if (this->DrawGridlinesOnly && this->DrawGridlines) { // Exit !!!! return this->GridlinesActor->RenderOpaqueGeometry(viewport); @@ -449,21 +562,26 @@ int vtkAxisActor::RenderOpaqueGeometry(vtkViewport *viewport) renderedSomething += this->TitleActor->RenderOpaqueGeometry(viewport); } } - if (this->AxisVisibility || this->TickVisibility) + if (this->AxisVisibility) { renderedSomething += this->AxisLinesActor->RenderOpaqueGeometry(viewport); + if (this->TickVisibility) + { + renderedSomething += this->AxisMajorTicksActor->RenderOpaqueGeometry(viewport); + renderedSomething += this->AxisMinorTicksActor->RenderOpaqueGeometry(viewport); + } } - if(this->DrawGridlines) + if (this->DrawGridlines) { renderedSomething += this->GridlinesActor->RenderOpaqueGeometry(viewport); } - if(this->DrawInnerGridlines) + if (this->DrawInnerGridlines) { renderedSomething += this->InnerGridlinesActor->RenderOpaqueGeometry(viewport); } if (this->LabelVisibility) { - for (i=0; iNumberOfLabelsBuilt; i++) + for (int i = 0; iNumberOfLabelsBuilt; i++) { if (this->Use2DMode) { @@ -481,27 +599,43 @@ int vtkAxisActor::RenderOpaqueGeometry(vtkViewport *viewport) this->LabelActors[i]->RenderOpaqueGeometry(viewport); } } + + if (this->ExponentVisibility && this->Exponent != NULL && this->Exponent[0] != 0) + { + if (this->Use2DMode) + { + renderedSomething += this->ExponentActor2D->RenderOpaqueGeometry(viewport); + } + else if (this->UseTextActor3D) + { + renderedSomething += this->ExponentProp3D->RenderOpaqueGeometry(viewport); + } + else + { + renderedSomething += this->ExponentActor->RenderOpaqueGeometry(viewport); + } + } } } return renderedSomething; } -// **************************************************************** +//----------------------------------------------------------------------------- // Build the translucent poly actors and render. -// **************************************************************** +//----------------------------------------------------------------------------- int vtkAxisActor::RenderTranslucentGeometry(vtkViewport *viewport) { return this->RenderTranslucentPolygonalGeometry(viewport); } -// **************************************************************** +//----------------------------------------------------------------------------- // Build the translucent poly actors and render. -// **************************************************************** +//----------------------------------------------------------------------------- int vtkAxisActor::RenderTranslucentPolygonalGeometry(vtkViewport *viewport) { - int renderedSomething=0; + int renderedSomething = 0; this->BuildAxis(viewport, false); @@ -509,7 +643,7 @@ int vtkAxisActor::RenderTranslucentPolygonalGeometry(vtkViewport *viewport) if (!this->AxisHasZeroLength && !this->DrawGridlinesOnly) { - if(this->DrawGridpolys) + if (this->DrawGridpolys) { renderedSomething += this->GridpolysActor->RenderTranslucentPolygonalGeometry(viewport); } @@ -530,7 +664,7 @@ int vtkAxisActor::RenderTranslucentPolygonalGeometry(vtkViewport *viewport) } if (this->LabelVisibility) { - for (int i=0; iNumberOfLabelsBuilt; i++) + for (int i = 0; iNumberOfLabelsBuilt; i++) { if (this->Use2DMode) { @@ -548,36 +682,54 @@ int vtkAxisActor::RenderTranslucentPolygonalGeometry(vtkViewport *viewport) this->LabelActors[i]->RenderTranslucentPolygonalGeometry(viewport); } } + if (this->ExponentVisibility) + { + if (this->Use2DMode) + { + renderedSomething += this->ExponentActor2D->RenderTranslucentPolygonalGeometry(viewport); + } + else if (this->UseTextActor3D) + { + renderedSomething += this->ExponentProp3D->RenderTranslucentPolygonalGeometry(viewport); + } + else + { + renderedSomething += this->ExponentActor->RenderTranslucentPolygonalGeometry(viewport); + } + } } } return renderedSomething; } -// **************************************************************** +//----------------------------------------------------------------------------- // Render the 2d annotations. -// **************************************************************** +//----------------------------------------------------------------------------- int vtkAxisActor::RenderOverlay(vtkViewport *viewport) { - int i, renderedSomething=0; + int renderedSomething = 0; // Everything is built, just have to render if (!this->AxisHasZeroLength && !this->DrawGridlinesOnly) { - if (this->Use2DMode) - { - renderedSomething += this->TitleActor2D->RenderOverlay(viewport); - } - else if (this->UseTextActor3D) - { - renderedSomething += this->TitleProp3D->RenderOverlay(viewport); - } - else + if (this->TitleVisibility) { - renderedSomething += this->TitleActor->RenderOverlay(viewport); + if (this->Use2DMode) + { + renderedSomething += this->TitleActor2D->RenderOverlay(viewport); + } + else if (this->UseTextActor3D) + { + renderedSomething += this->TitleProp3D->RenderOverlay(viewport); + } + else + { + renderedSomething += this->TitleActor->RenderOverlay(viewport); + } } if (this->LabelVisibility) { - for (i=0; iNumberOfLabelsBuilt; i++) + for (int i = 0; iNumberOfLabelsBuilt; i++) { if (this->Use2DMode) { @@ -592,18 +744,31 @@ int vtkAxisActor::RenderOverlay(vtkViewport *viewport) renderedSomething += this->LabelActors[i]->RenderOverlay(viewport); } } + if (this->ExponentVisibility) + { + if (this->Use2DMode) + { + renderedSomething += this->ExponentActor2D->RenderOverlay(viewport); + } + else if (this->UseTextActor3D) + { + renderedSomething += this->ExponentProp3D->RenderOverlay(viewport); + } + else + { + renderedSomething += this->ExponentActor->RenderOverlay(viewport); + } + } } } - return renderedSomething; } -// ************************************************************************** +//-----------------------------------------------------------------------------* int vtkAxisActor::HasTranslucentPolygonalGeometry() { if (this->Visibility && !this->AxisHasZeroLength) { - if (this->TitleVisibility) { if (this->Use2DMode) @@ -662,6 +827,30 @@ int vtkAxisActor::HasTranslucentPolygonalGeometry() } // end if } // end for } // end 3D + if (this->ExponentVisibility) + { + if (this->Use2DMode) + { + if (this->ExponentActor2D->HasTranslucentPolygonalGeometry()) + { + return 1; + } + } + else if (this->UseTextActor3D) + { + if (this->ExponentProp3D->HasTranslucentPolygonalGeometry()) + { + return 1; + } + } + else + { + if (this->ExponentActor->HasTranslucentPolygonalGeometry()) + { + return 1; + } + } + } } // end label vis if (this->AxisLinesActor->HasTranslucentPolygonalGeometry()) @@ -669,34 +858,43 @@ int vtkAxisActor::HasTranslucentPolygonalGeometry() return 1; } + if (this->TickVisibility && + this->AxisMajorTicksActor->HasTranslucentPolygonalGeometry()) + { + return 1; + } + if (this->TickVisibility && + this->AxisMinorTicksActor->HasTranslucentPolygonalGeometry()) + { + return 1; + } + if (this->DrawGridlines && - this->GridlinesActor->HasTranslucentPolygonalGeometry()) + this->GridlinesActor->HasTranslucentPolygonalGeometry()) { return 1; } if (this->DrawInnerGridlines && - this->InnerGridlinesActor->HasTranslucentPolygonalGeometry()) + this->InnerGridlinesActor->HasTranslucentPolygonalGeometry()) { return 1; } if (this->DrawGridpolys && - this->GridpolysActor->HasTranslucentPolygonalGeometry()) + this->GridpolysActor->HasTranslucentPolygonalGeometry()) { return 1; } return this->Superclass::HasTranslucentPolygonalGeometry(); - } // end this vis - return 0; } -// ************************************************************************** +//-----------------------------------------------------------------------------* // Perform some initialization, determine which Axis type we are -// ************************************************************************** +//-----------------------------------------------------------------------------* void vtkAxisActor::BuildAxis(vtkViewport *viewport, bool force) { // We'll do our computation in world coordinates. First determine the @@ -712,23 +910,43 @@ void vtkAxisActor::BuildAxis(vtkViewport *viewport, bool force) // if (p1[0] == p2[0] && p1[1] == p2[1] && p1[2] == p2[2]) { - vtkDebugMacro(<<"Axis has zero length, not building."); + vtkDebugMacro(<< "Axis has zero length, not building."); this->AxisHasZeroLength = true; return; } this->AxisHasZeroLength = false; if (!force && this->GetMTime() < this->BuildTime.GetMTime() && - viewport->GetMTime() < this->BuildTime.GetMTime()) + viewport->GetMTime() < this->BuildTime.GetMTime()) { return; //already built } - vtkDebugMacro(<<"Rebuilding axis"); + if (this->Log) + { + if (this->Range[0] <= 0.0) + { + vtkWarningMacro(<< "Range value undefined for log scale enabled. " + << "Current Range: (" << this->Range[0] << ", " << this->Range[1] << ")" + << "Range[0] must be > 0.0. " + << "."); + return; + } + if (this->MinorRangeStart <= 0.0 || this->MajorRangeStart <= 0.0) + { + vtkWarningMacro(<< "MinorRangeStart value or MajorRangeStart value undefined for log scale enabled" + << "MinorRangeStart: " << this->MinorRangeStart << ", MajorRangeStart: " << this->MajorRangeStart << ". " + << "MinorRangeStart and MajorRangeStart must be > 0.0. " + << "."); + return; + } + } + + vtkDebugMacro(<< "Rebuilding axis"); if (force || this->GetProperty()->GetMTime() > this->BuildTime.GetMTime()) { - //this->AxisLinesActor->SetProperty(this->GetProperty()); + //this->AxisLinesActor->SetProperty(this->GetProperty()); this->TitleActor->SetProperty(this->GetProperty()); this->TitleActor->GetProperty()->SetColor(this->TitleTextProperty->GetColor()); this->TitleActor->GetProperty()->SetOpacity(this->TitleTextProperty->GetOpacity()); @@ -760,25 +978,44 @@ void vtkAxisActor::BuildAxis(vtkViewport *viewport, bool force) this->BuildLabels2D(viewport, force || ticksRebuilt); } + if (this->Title != NULL && this->Title[0] != 0) + { + this->InitTitle(); + } + + if (this->ExponentVisibility && this->Exponent != NULL && this->Exponent[0] != 0) + { + this->InitExponent(); + } + if (this->Title != NULL && this->Title[0] != 0) { this->BuildTitle(force || ticksRebuilt); - if( this->Use2DMode == 1 ) + if (this->Use2DMode == 1) { this->BuildTitle2D(viewport, force || ticksRebuilt); } } - this->LastAxisPosition = this->AxisPosition; + if (this->ExponentVisibility && this->Exponent != NULL && this->Exponent[0] != 0) + { + // build exponent + this->BuildExponent(force); + if (this->Use2DMode == 1) + { + this->BuildExponent2D(viewport, force); + } + } + this->LastAxisPosition = this->AxisPosition; this->LastRange[0] = this->Range[0]; this->LastRange[1] = this->Range[1]; this->BuildTime.Modified(); } -// **************************************************************** +//----------------------------------------------------------------------------- // Set label values and properties. -// **************************************************************** +//----------------------------------------------------------------------------- void vtkAxisActor::BuildLabels(vtkViewport *viewport, bool force) { @@ -787,6 +1024,7 @@ vtkAxisActor::BuildLabels(vtkViewport *viewport, bool force) return; } + double maxLabelScale = 0.0; for (int i = 0; i < this->NumberOfLabelsBuilt; i++) { this->LabelActors[i]->SetCamera(this->Camera); @@ -809,30 +1047,36 @@ vtkAxisActor::BuildLabels(vtkViewport *viewport, bool force) const double labelActors3DWidth = static_cast(labelActors3DBounds[1] - labelActors3DBounds[0]); - this->LabelActors3D[i]->SetScale( labelActorsWidth / labelActors3DWidth ); - } - if(!this->GetCalculateLabelOffset()) - { - this->LabelActors[i]->SetAutoCenter(1); - this->LabelProps3D[i]->SetAutoCenter(1); + if (labelActorsWidth / labelActors3DWidth > maxLabelScale) + { + maxLabelScale = labelActorsWidth / labelActors3DWidth; + } } + + this->LabelActors[i]->SetAutoCenter(1); + this->LabelProps3D[i]->SetAutoCenter(1); + } + + for (int i = 0; i < this->NumberOfLabelsBuilt; i++) + { + this->LabelActors3D[i]->SetScale(maxLabelScale); } if (force || this->BuildTime.GetMTime() < this->BoundsTime.GetMTime() || - this->AxisPosition != this->LastAxisPosition || - this->LastRange[0] != this->Range[0] || - this->LastRange[1] != this->Range[1]) + this->AxisPosition != this->LastAxisPosition || + this->LastRange[0] != this->Range[0] || + this->LastRange[1] != this->Range[1]) { this->SetLabelPositions(viewport, force); } } -static const int vtkAxisActorMultiplierTable1[4] = { -1, -1, 1, 1}; -static const int vtkAxisActorMultiplierTable2[4] = { -1, 1, 1, -1}; +static const int vtkAxisActorMultiplierTable1[4] = { -1, -1, 1, 1}; +static const int vtkAxisActorMultiplierTable2[4] = { -1, 1, 1, -1}; -// ******************************************************************* +//----------------------------------------------------------------------------- // Determine and set scale factor and position for labels. -// ******************************************************************* +//----------------------------------------------------------------------------- void vtkAxisActor::SetLabelPositions(vtkViewport *viewport, bool force) { if (!force && (!this->LabelVisibility || this->NumberOfLabelsBuilt == 0)) @@ -840,32 +1084,6 @@ void vtkAxisActor::SetLabelPositions(vtkViewport *viewport, bool force) return; } - double bounds[6], center[3], tick[3], pos[3]; - int i = 0; - int xmult = 0; - int ymult = 0; - double labelAngle = vtkMath::RadiansFromDegrees(this->LabelTextProperty->GetOrientation()); - double labelCos = fabs(cos(labelAngle)); - double labelSin = fabs(sin(labelAngle)); - - - switch (this->AxisType) - { - case VTK_AXIS_TYPE_X : - xmult = 0; - ymult = vtkAxisActorMultiplierTable1[this->AxisPosition]; - break; - case VTK_AXIS_TYPE_Y : - xmult = vtkAxisActorMultiplierTable1[this->AxisPosition]; - ymult = 0; - break; - case VTK_AXIS_TYPE_Z : - xmult = vtkAxisActorMultiplierTable1[this->AxisPosition]; - ymult = vtkAxisActorMultiplierTable2[this->AxisPosition]; - break; - } - - int ptIdx; // // xadjust & yadjust are used for positioning the label correctly // depending upon the 'orientation' of the axis as determined @@ -873,54 +1091,73 @@ void vtkAxisActor::SetLabelPositions(vtkViewport *viewport, bool force) // double displayBounds[6] = { 0., 0., 0., 0., 0., 0.}; this->TransformBounds(viewport, displayBounds); - double xadjust = (displayBounds[0] > displayBounds[1] ? -1 : 1); - double yadjust = (displayBounds[2] > displayBounds[3] ? -1 : 1); - for (i=0; i < this->NumberOfLabelsBuilt && + double bounds[6], tickBottom[3], tickTop[3], pos[3]; + double labelAngle = vtkMath::RadiansFromDegrees(this->LabelTextProperty->GetOrientation()); + double labelCos = fabs(cos(labelAngle)); + double labelSin = fabs(sin(labelAngle)); + vtkAxisFollower* pAxisFollower = NULL; + + for (int i = 0; i < this->NumberOfLabelsBuilt && i < this->MajorTickPts->GetNumberOfPoints(); i++) { - ptIdx = 4*i + 1; - this->MajorTickPts->GetPoint(ptIdx, tick); + int ptIdx = 4 * i; + this->MajorTickPts->GetPoint(ptIdx, tickTop); + this->MajorTickPts->GetPoint(ptIdx + 1, tickBottom); - this->LabelActors[i]->GetMapper()->GetBounds(bounds); + pAxisFollower = this->LabelActors[i]; - if(this->CalculateLabelOffset) + // get Label actor Transform matrix + vtkRenderer* ren = vtkRenderer::SafeDownCast(viewport); + if (ren) { - double halfWidth = 0.5 * ((bounds[1] - bounds[0]) * labelCos + (bounds[3] - bounds[2]) * labelSin); - double halfHeight = 0.5 * ((bounds[1] - bounds[0]) * labelSin + (bounds[3] - bounds[2]) * labelCos); + pAxisFollower->ComputeTransformMatrix(ren); + } + + // WARNING: calling GetBounds() before ComputeTransformMatrix(), prevent this->Transform to be updated - center[0] = tick[0] + xmult * (halfWidth + this->MinorTickSize); - center[1] = tick[1] + ymult * (halfHeight + this->MinorTickSize); - center[2] = tick[2]; + // previous version: this->LabelActors[i]->GetMapper()->GetBounds(bounds); didn't include scale labels + // vtkProp3D::GetBounds() include previous transform (scale, orientation, translation) + pAxisFollower->GetBounds(bounds); + double labelWidth = (bounds[1] - bounds[0]); + double labelHeight = (bounds[3] - bounds[2]); + + if (this->CalculateLabelOffset) + { + vtkWarningMacro("CalculateLabelOffset flag is now deprecated and has no effect"); + } - pos[0] = (center[0] - xadjust *halfWidth); - pos[1] = (center[1] - yadjust *halfHeight); - pos[2] = center[2]; + if (this->TickVisibility) + { + pos[0] = tickBottom[0]; + pos[1] = tickBottom[1]; + pos[2] = tickBottom[2]; } else { - pos[0] = tick[0]; - pos[1] = tick[1]; - pos[2] = tick[2]; - - double delta = 0.5 * ((bounds[1] - bounds[0]) * labelSin + (bounds[3] - bounds[2]) * labelCos); - this->LabelActors[i]->SetScreenOffset(this->LabelOffset + (delta) * this->ScreenSize); - this->LabelProps3D[i]->SetScreenOffset(this->LabelOffset + (delta) * this->ScreenSize); + pos[0] = (tickTop[0] + tickBottom[0]) / 2; + pos[1] = (tickTop[1] + tickBottom[1]) / 2; + pos[2] = (tickTop[2] + tickBottom[2]) / 2; } - this->LabelActors[i]->SetPosition(pos[0], pos[1], pos[2]); + double delta = 0.5 * (labelWidth * labelSin + labelHeight * labelCos); + pAxisFollower->SetScreenOffset(this->LabelOffset + (delta) * this->ScreenSize); + this->LabelProps3D[i]->SetScreenOffset(this->LabelOffset + (delta) * this->ScreenSize); + + pAxisFollower->SetPosition(pos[0], pos[1], pos[2]); this->LabelProps3D[i]->SetPosition(pos[0], pos[1], pos[2]); } } -// ******************************************************************* +//----------------------------------------------------------------------------- // Set 2D label values and properties. -// ******************************************************************* -void -vtkAxisActor::BuildLabels2D(vtkViewport *viewport, bool force) +//----------------------------------------------------------------------------- +void vtkAxisActor::BuildLabels2D(vtkViewport *viewport, bool force) { if (!force && (!this->LabelVisibility || this->NumberOfLabelsBuilt == 0)) + { return; + } for (int i = 0; i < this->NumberOfLabelsBuilt; i++) { @@ -936,15 +1173,15 @@ vtkAxisActor::BuildLabels2D(vtkViewport *viewport, bool force) } } - -// ******************************************************************* +//----------------------------------------------------------------------------- // Determine and set scale factor and position for 2D labels. -// ******************************************************************* -void -vtkAxisActor::SetLabelPositions2D(vtkViewport *viewport, bool force) +//----------------------------------------------------------------------------- +void vtkAxisActor::SetLabelPositions2D(vtkViewport *viewport, bool force) { - if (!force && (!this->LabelVisibility || this->NumberOfLabelsBuilt == 0) ) - return; + if (!force && (!this->LabelVisibility || this->NumberOfLabelsBuilt == 0)) + { + return; + } int xmult = 0; int ymult = 0; @@ -966,9 +1203,11 @@ vtkAxisActor::SetLabelPositions2D(vtkViewport *viewport, bool force) xcoeff = 1.0; ycoeff = 0.5; break; + default: + // shouldn't get here + break; } - int ptIdx; // // xadjust & yadjust are used for positioning the label correctly @@ -992,7 +1231,7 @@ vtkAxisActor::SetLabelPositions2D(vtkViewport *viewport, bool force) vtkWindow *win = viewport->GetVTKWindow(); if (!win) { - vtkErrorMacro(<<"No render window available: cannot determine DPI."); + vtkErrorMacro(<< "No render window available: cannot determine DPI."); return; } @@ -1012,104 +1251,190 @@ vtkAxisActor::SetLabelPositions2D(vtkViewport *viewport, bool force) int bbox[4]; if (!tren->GetBoundingBox(this->LabelActors2D[i]->GetTextProperty(), - this->LabelActors2D[i]->GetInput(), bbox, - win->GetDPI())) + this->LabelActors2D[i]->GetInput(), bbox, + win->GetDPI())) { vtkErrorMacro(<< "Unable to calculate bounding box for label " - << this->LabelActors2D[i]->GetInput()); + << this->LabelActors2D[i]->GetInput()); continue; } - double width = (bbox[1]-bbox[0]); - double height = (bbox[3]-bbox[2]); + double width = (bbox[1] -bbox[0]); + double height = (bbox[3] -bbox[2]); pos[0] = (transpos[0] - xadjust*width*xcoeff); pos[1] = (transpos[1] - yadjust*height*ycoeff); - this->LabelActors2D[i]->SetPosition( pos[0], pos[1] ); + + this->LabelActors2D[i]->SetPosition(pos[0], pos[1]); } } +//----------------------------------------------------------------------------- +void vtkAxisActor::InitTitle() +{ + // ---------- Title ---------- + // Classic + // Source => Mapper => Actor + // TitleVector => TitleMapper => TitleActor + + // Text 3D + // vtkTextActor3D::TitleActor3D _ vtkProp3DAxisFollower::TitleProp3D + // relation: TitleProp3D->SetProp3D(this->TitleActor3D) + this->TitleVector->SetText(this->Title); + this->TitleActor3D->SetInput(this->Title); + + this->TitleActor->SetProperty(this->GetProperty()); + this->TitleActor->GetProperty()->SetColor(this->TitleTextProperty->GetColor()); + this->TitleActor->GetProperty()->SetOpacity(this->TitleTextProperty->GetOpacity()); + + this->TitleActor3D->SetTextProperty(this->TitleTextProperty); + + this->TitleActor->SetCamera(this->Camera); + this->TitleProp3D->SetCamera(this->Camera); + + // axis follower origin is on top-left corner, auto-center put it on the center of the label + this->TitleActor->SetAutoCenter(1); + this->TitleProp3D->SetAutoCenter(1); +} + +//----------------------------------------------------------------------------- +void vtkAxisActor::InitExponent() +{ + std::stringstream expStr; + expStr << "e" << this->Exponent; + this->ExponentVector->SetText(expStr.str().c_str()); + this->ExponentActor3D->SetInput(expStr.str().c_str()); + this->ExponentActor->SetProperty(this->GetProperty()); + this->ExponentActor3D->SetTextProperty(this->TitleTextProperty); + this->ExponentActor->SetCamera(this->Camera); + this->ExponentProp3D->SetCamera(this->Camera); + this->ExponentActor->SetAutoCenter(1); + this->ExponentProp3D->SetAutoCenter(1); +} -// ********************************************************************** +//----------------------------------------------------------------------------- // Determines scale and position for the Title. Currently, // title can only be centered with respect to its axis. -// ********************************************************************** +//----------------------------------------------------------------------------- void vtkAxisActor::BuildTitle(bool force) { this->NeedBuild2D = false; + if (!force && !this->TitleVisibility) { return; } - double labBounds[6], titleBounds[6], center[3], pos[3]; - double labHeight, maxHeight = 0, labWidth, maxWidth = 0; - double halfTitleWidth, halfTitleHeight; + + if (!force && this->TitleTextTime.GetMTime() < this->BuildTime.GetMTime() && + this->BoundsTime.GetMTime() < this->BuildTime.GetMTime() && + this->LabelBuildTime.GetMTime() < this->BuildTime.GetMTime()) + { + return; + } + + // Text property + this->TitleActor->GetProperty()->SetColor(this->TitleTextProperty->GetColor()); + this->TitleActor->GetProperty()->SetOpacity(this->TitleTextProperty->GetOpacity()); + + // ---------- labels size ---------- + // local orientation (in the plane of the label) double labelAngle = vtkMath::RadiansFromDegrees(this->LabelTextProperty->GetOrientation()); - double labelCos = fabs(cos(labelAngle)); - double labelSin = fabs(sin(labelAngle)); + double labelCos = fabs(cos(labelAngle)), labelSin = fabs(sin(labelAngle)); + double labBounds[6]; + double offset[2] = {0, this->TitleOffset}; + + // find max height label (with the label text property considered) + // only when title is on bottom + if (this->LabelVisibility && + this->TitleAlignLocation != VTK_ALIGN_TOP) + { + double labelMaxHeight, labHeight; + labelMaxHeight = labHeight = 0; + for (int i = 0; i < this->NumberOfLabelsBuilt; i++) + { + this->LabelActors[i]->GetMapper()->GetBounds(labBounds); + + // labels actor aren't oriented yet, width and height are considered in + // their local coordinate system + // however, LabelTextProperty can orient it, but locally (in its plane) + labHeight = + (labBounds[1] - labBounds[0]) * labelSin + + (labBounds[3] - labBounds[2]) * labelCos; + labelMaxHeight = (labHeight > labelMaxHeight ? labHeight : labelMaxHeight); + } + offset[1] += this->LabelOffset + this->ScreenSize * labelMaxHeight; + } + + // ---------- title size ---------- + double titleBounds[6]; + this->TitleActor->GetMapper()->GetBounds(titleBounds); + double halfTitleHeight = + (titleBounds[3] - titleBounds[2]) * 0.5; + double halfTitleWidth = + (titleBounds[1] - titleBounds[0]) * 0.5; + offset[1] += this->ScreenSize * halfTitleHeight; double *p1 = this->Point1Coordinate->GetValue(); double *p2 = this->Point2Coordinate->GetValue(); - int xmult = 0; - int ymult = 0; - - if (!force && this->LabelBuildTime.GetMTime() < this->BuildTime.GetMTime() && - this->BoundsTime.GetMTime() < this->BuildTime.GetMTime() && - this->AxisPosition == this->LastAxisPosition && - this->TitleTextTime.GetMTime() < this->BuildTime.GetMTime()) + double pos[3]; + if (this->CalculateTitleOffset) { - return; + vtkWarningMacro("CalculateTitleOffset flag is now deprecated and has no effect"); } - - this->NeedBuild2D = true; - switch (this->AxisType) + int vertOffsetSign = 1; + switch (this->TitleAlignLocation) { - case VTK_AXIS_TYPE_X : - xmult = 0; - ymult = vtkAxisActorMultiplierTable1[this->AxisPosition]; + case (VTK_ALIGN_TOP): + vertOffsetSign = -1; + VTK_FALLTHROUGH; + // NO BREAK + case (VTK_ALIGN_BOTTOM): + // Position to center of axis + for (int i = 0; i < 3; i++) + { + pos[i] = p1[i] + (p2[i] - p1[i]) / 2.0; + } break; - case VTK_AXIS_TYPE_Y : - xmult = vtkAxisActorMultiplierTable1[this->AxisPosition]; - ymult = 0; + case (VTK_ALIGN_POINT1): + // Position to p1 + for (int i = 0; i < 3; i++) + { + pos[i] = p1[i]; + } + offset[0] += this->ScreenSize * halfTitleWidth + 3; break; - case VTK_AXIS_TYPE_Z : - xmult = vtkAxisActorMultiplierTable1[this->AxisPosition]; - ymult = vtkAxisActorMultiplierTable2[this->AxisPosition]; + case (VTK_ALIGN_POINT2): + // Position to p2 + for (int i = 0; i < 3; i++) + { + pos[i] = p2[i]; + } + offset[0] += this->ScreenSize * halfTitleWidth + 3; + break; + default: + // shouldn't get there break; } - // - // Title should be in relation to labels (if any) - // so find out information about them. - // - for (int i = 0; i < this->NumberOfLabelsBuilt; i++) + + if (this->TickVisibility && + (this->TickLocation == VTK_TICKS_BOTH + || (this->TickLocation == VTK_TICKS_INSIDE && + this->TitleAlignLocation == VTK_ALIGN_TOP) || + (this->TickLocation == VTK_TICKS_OUTSIDE && + this->TitleAlignLocation != VTK_ALIGN_TOP))) { - this->LabelActors[i]->GetMapper()->GetBounds(labBounds); - labWidth = (labBounds[1] - labBounds[0]) * labelCos + (labBounds[3] - labBounds[2]) * labelSin; - maxWidth = (labWidth > maxWidth ? labWidth : maxWidth); - labHeight = (labBounds[1] - labBounds[0]) * labelSin + (labBounds[3] - labBounds[2]) * labelCos; - maxHeight = (labHeight > maxHeight ? labHeight : maxHeight); + for (int i = 0; i < 3; i++) + { + pos[i] += vertOffsetSign * this->TickVector[i]; + } } - this->TitleVector->SetText(this->Title); - this->TitleActor3D->SetInput( this->Title ); - - this->TitleActor->GetProperty()->SetColor(this->TitleTextProperty->GetColor()); - this->TitleActor->SetCamera(this->Camera); - this->TitleProp3D->SetCamera(this->Camera); - this->TitleActor->GetMapper()->GetBounds(titleBounds); + offset[1] *= vertOffsetSign; + this->TitleActor->SetScreenOffsetVector(offset); + this->TitleProp3D->SetScreenOffsetVector(offset); - if(!this->GetCalculateTitleOffset()) + if (this->UseTextActor3D) { - this->TitleActor->SetAutoCenter(1); - this->TitleProp3D->SetAutoCenter(1); - } - - if (this->UseTextActor3D) - { - double titleActorBounds[6]; - this->TitleActor->GetMapper()->GetBounds(titleActorBounds); - const double titleActorWidth = (titleActorBounds[1] - titleActorBounds[0]); - int titleActor3DBounds[4]; this->TitleActor3D->GetBoundingBox(titleActor3DBounds); const double titleActor3DWidth = @@ -1117,42 +1442,155 @@ void vtkAxisActor::BuildTitle(bool force) // Convert from font coordinate system to world coordinate system: this->TitleActor3D->SetScale( - titleActorWidth / titleActor3DWidth); + (titleBounds[1] - titleBounds[0]) / titleActor3DWidth); } + this->TitleActor->SetPosition(pos); + this->TitleProp3D->SetPosition(pos); +} - center[0] = p1[0] + (p2[0] - p1[0]) / 2.0; - center[1] = p1[1] + (p2[1] - p1[1]) / 2.0; - center[2] = p1[2] + (p2[2] - p1[2]) / 2.0; +//----------------------------------------------------------------------------- +void vtkAxisActor::BuildExponent(bool force) +{ + if (!force && (!this->ExponentVisibility || !this->Exponent)) + { + return; + } - halfTitleHeight = (titleBounds[3] - titleBounds[2]) * 0.5; - if(this->CalculateTitleOffset) + if (!force && this->ExponentTextTime.GetMTime() < this->BuildTime.GetMTime() && + this->BoundsTime.GetMTime() < this->BuildTime.GetMTime() && + this->LabelBuildTime.GetMTime() < this->BuildTime.GetMTime()) { - halfTitleWidth = (titleBounds[1] - titleBounds[0]) * 0.5; - center[0] += xmult * (halfTitleWidth + maxWidth); - center[1] += ymult * (halfTitleHeight + 2*maxHeight); + return; } - else + + // Text property + this->ExponentActor->GetProperty()->SetColor(this->TitleTextProperty->GetColor()); + this->ExponentActor->GetProperty()->SetOpacity(this->TitleTextProperty->GetOpacity()); + + // ---------- labels size ---------- + // local orientation (in the plane of the label) + double labelAngle = vtkMath::RadiansFromDegrees(this->LabelTextProperty->GetOrientation()); + double labelCos = fabs(cos(labelAngle)), labelSin = fabs(sin(labelAngle)); + double labBounds[6]; + double offset[2] = { 0, this->ExponentOffset}; + + // find max height label (with the label text property considered) + // only when title is on bottom + if (this->LabelVisibility && + this->ExponentLocation != VTK_ALIGN_TOP) + { + double labelMaxHeight, labHeight; + labelMaxHeight = labHeight = 0; + for (int i = 0; i < this->NumberOfLabelsBuilt; i++) + { + this->LabelActors[i]->GetMapper()->GetBounds(labBounds); + + // labels actor aren't oriented yet, width and height are considered in + // their local coordinate system + // however, LabelTextProperty can orient it, but locally (in its plane) + labHeight = + (labBounds[1] - labBounds[0]) * labelSin + + (labBounds[3] - labBounds[2]) * labelCos; + labelMaxHeight = (labHeight > labelMaxHeight ? labHeight : labelMaxHeight); + } + offset[1] += this->LabelOffset + this->ScreenSize * labelMaxHeight; + } + + // ---------- title size ---------- + double titleBounds[6]; + this->TitleActor->GetMapper()->GetBounds(titleBounds); + if (this->TitleVisibility && + this->TitleAlignLocation == this->ExponentLocation) + { + offset[1] += this->TitleOffset + this->ScreenSize * titleBounds[3] - titleBounds[2]; + } + + // ---------- exponent size ---------- + double exponentBounds[6]; + this->ExponentActor->GetMapper()->GetBounds(exponentBounds); + double halfExponentHeight = (exponentBounds[3] - exponentBounds[2]) * 0.5; + double halfExponentWidth = (exponentBounds[1] - exponentBounds[0]) * 0.5; + offset[1] += this->ScreenSize * halfExponentHeight; + + double *p1 = this->Point1Coordinate->GetValue(); + double *p2 = this->Point2Coordinate->GetValue(); + double pos[3]; + + int offsetSign = 1; + switch (this->ExponentLocation) + { + case (VTK_ALIGN_TOP): + offsetSign = -1; + VTK_FALLTHROUGH; + // NO BREAK + case (VTK_ALIGN_BOTTOM): + // Position to center of axis + for (int i = 0; i < 3; i++) + { + pos[i] = p1[i] + (p2[i] - p1[i]) / 2.0; + } + break; + case (VTK_ALIGN_POINT1): + // Position to p1 + for (int i = 0; i < 3; i++) + { + pos[i] = p1[i]; + } + offset[0] += this->ScreenSize * halfExponentWidth + 3; + break; + case (VTK_ALIGN_POINT2): + // Position to p2 + for (int i = 0; i < 3; i++) + { + pos[i] = p2[i]; + } + offset[0] += this->ScreenSize * halfExponentWidth + 3; + break; + default: + // shouldn't get there + break; + } + + if (this->TickVisibility && + (this->TickLocation == VTK_TICKS_BOTH + || (this->TickLocation == VTK_TICKS_INSIDE && + this->ExponentLocation == VTK_ALIGN_TOP) || + (this->TickLocation == VTK_TICKS_OUTSIDE && + this->ExponentLocation != VTK_ALIGN_TOP))) { - this->TitleActor->SetScreenOffset(this->TitleOffset + - this->LabelOffset + this->ScreenSize * (maxHeight + halfTitleHeight)); - this->TitleProp3D->SetScreenOffset(this->TitleOffset + - this->LabelOffset + this->ScreenSize * (maxHeight + halfTitleHeight)); + for (int i = 0; i < 3; i++) + { + pos[i] += offsetSign * this->TickVector[i]; + } } - pos[0] = center[0]; - pos[1] = center[1]; - pos[2] = center[2]; + // Offset is: ExponentOffset + TitleOffset is visible + LabelOffset if visible + // + ScreenSize of all + offset[1] *= offsetSign; + this->ExponentActor->SetScreenOffsetVector(offset); + this->ExponentProp3D->SetScreenOffsetVector(offset); + + if (this->UseTextActor3D) + { + int exponentActor3DBounds[4]; + this->ExponentActor3D->GetBoundingBox(exponentActor3DBounds); + const double exponentActor3DWidth = + static_cast(exponentActor3DBounds[1] - exponentActor3DBounds[0]); + + // Convert from font coordinate system to world coordinate system: + this->ExponentActor3D->SetScale( + (exponentBounds[1] - exponentBounds[0]) / exponentActor3DWidth); + } - this->TitleActor->SetPosition(pos[0], pos[1], pos[2]); - this->TitleProp3D->SetPosition(pos[0], pos[1], pos[2]); + this->ExponentActor->SetPosition(pos); + this->ExponentProp3D->SetPosition(pos); } -// ********************************************************************** +//----------------------------------------------------------------------------- // Determines scale and position for the 2D Title. Currently, // title can only be centered with respect to its axis. -// ********************************************************************** -void -vtkAxisActor::BuildTitle2D(vtkViewport *viewport, bool force) +//----------------------------------------------------------------------------- +void vtkAxisActor::BuildTitle2D(vtkViewport *viewport, bool force) { if (!this->NeedBuild2D && !force && !this->TitleVisibility) { @@ -1160,9 +1598,9 @@ vtkAxisActor::BuildTitle2D(vtkViewport *viewport, bool force) } // for textactor instead of follower - this->TitleActor2D->SetInput( this->TitleVector->GetText() ); - this->TitleActor2D->GetProperty()->SetColor( this->TitleTextProperty->GetColor() ); - this->TitleActor2D->GetProperty()->SetOpacity( this->TitleTextProperty->GetOpacity() ); + this->TitleActor2D->SetInput(this->TitleVector->GetText()); + this->TitleActor2D->GetProperty()->SetColor(this->TitleTextProperty->GetColor()); + this->TitleActor2D->GetProperty()->SetOpacity(this->TitleTextProperty->GetOpacity()); this->TitleActor2D->GetTextProperty()->ShallowCopy(this->TitleTextProperty); if (this->AxisType == VTK_AXIS_TYPE_Y) @@ -1183,19 +1621,33 @@ vtkAxisActor::BuildTitle2D(vtkViewport *viewport, bool force) // stuff for 2D axis with TextActor double transpos[3]; double* pos = this->TitleActor->GetPosition(); - viewport->SetWorldPoint(pos[0], pos[1], pos[2], 1.0); + viewport->SetWorldPoint(pos[0], pos[1], pos[2], 1.0); viewport->WorldToDisplay(); viewport->GetDisplayPoint(transpos); + + int offsetSign = 1; + if (this->TitleAlignLocation == VTK_ALIGN_TOP) + { + offsetSign = -1; + } + if (this->AxisType == VTK_AXIS_TYPE_X) { - transpos[1] += this->VerticalOffsetXTitle2D; + transpos[1] += offsetSign * this->VerticalOffsetXTitle2D; } else if (this->AxisType == VTK_AXIS_TYPE_Y) { - transpos[0] += this->HorizontalOffsetYTitle2D; + transpos[0] += offsetSign * this->HorizontalOffsetYTitle2D; + } + if (transpos[1] < 10.) + { + transpos[1] = 10.; + } + if (transpos[0] < 10.) + { + transpos[0] = 10.; } - if (transpos[1] < 10.) transpos[1] = 10.; - if (transpos[0] < 10.) transpos[0] = 10.; + if (this->SaveTitlePosition == 0) { this->TitleActor2D->SetPosition(transpos[0], transpos[1]); @@ -1204,18 +1656,90 @@ vtkAxisActor::BuildTitle2D(vtkViewport *viewport, bool force) { if (this->SaveTitlePosition == 1) { - TitleConstantPosition[0] = transpos[0]; - TitleConstantPosition[1] = transpos[1]; + this->TitleConstantPosition[0] = transpos[0]; + this->TitleConstantPosition[1] = transpos[1]; this->SaveTitlePosition = 2; } - this->TitleActor2D->SetPosition(TitleConstantPosition[0], TitleConstantPosition[1]); + this->TitleActor2D->SetPosition(this->TitleConstantPosition[0], this->TitleConstantPosition[1]); + } + this->RotateActor2DFromAxisProjection(this->TitleActor2D); +} + +//----------------------------------------------------------------------------- +void vtkAxisActor::BuildExponent2D(vtkViewport *viewport, bool force) +{ + if (!this->NeedBuild2D && !force && !this->LabelVisibility) + { + return; + } + + // for textactor instead of follower + this->ExponentActor2D->SetInput(this->ExponentVector->GetText()); + this->ExponentActor2D->GetProperty()->SetColor(this->TitleTextProperty->GetColor()); + this->ExponentActor2D->GetProperty()->SetOpacity(this->TitleTextProperty->GetOpacity()); + this->ExponentActor2D->GetTextProperty()->ShallowCopy(this->TitleTextProperty); + + if (this->AxisType == VTK_AXIS_TYPE_Y) + { + if (strlen(this->ExponentActor2D->GetInput()) > 2) + { + // warning : orientation have to be set on vtkTextActor and not on the vtkTextActor's vtkTextProperty + // otherwise there is a strange effect (first letter is not align with the others) + this->ExponentActor2D->SetOrientation(90); + } + else + { + // if in the previous rendering, the orientation was set. + this->ExponentActor2D->SetOrientation(0); + } + } + + // stuff for 2D axis with TextActor + double transpos[3]; + double* pos = this->ExponentActor->GetPosition(); + viewport->SetWorldPoint(pos[0], pos[1], pos[2], 1.0); + viewport->WorldToDisplay(); + viewport->GetDisplayPoint(transpos); + + int offsetSign = 1; + if (this->ExponentLocation == VTK_ALIGN_TOP) + { + offsetSign = -1; + } + + int titleMult = 1; + if (this->TitleVisibility && + this->TitleAlignLocation == this->ExponentLocation) + { + titleMult = 2; + } + + if (this->AxisType == VTK_AXIS_TYPE_X) + { + transpos[1] += offsetSign * titleMult * this->VerticalOffsetXTitle2D; + } + else if (this->AxisType == VTK_AXIS_TYPE_Y) + { + transpos[0] += offsetSign * titleMult * this->HorizontalOffsetYTitle2D; + } + if (transpos[1] < 10.) + { + transpos[1] = 10.; } + if (transpos[0] < 10.) + { + transpos[0] = 10.; + } + + this->ExponentActor2D->SetPosition(transpos[0], transpos[1]); + + this->RotateActor2DFromAxisProjection(this->ExponentActor2D); } -// +//----------------------------------------------------------------------------- // Transform the bounding box to display coordinates. Used // in determining orientation of the axis. -// +//----------------------------------------------------------------------------- void vtkAxisActor::TransformBounds(vtkViewport *viewport, double bnds[6]) { double minPt[3], maxPt[3], transMinPt[3], transMaxPt[3]; @@ -1241,48 +1765,32 @@ void vtkAxisActor::TransformBounds(vtkViewport *viewport, double bnds[6]) bnds[5] = transMaxPt[2]; } -inline double ffix(double value) -{ - int ivalue = static_cast(value); - return static_cast(ivalue); -} - -inline double fsign(double value, double sign) -{ - value = fabs(value); - if (sign < 0.) - { - value *= -1.; - } - return value; -} - -// **************************************************************** +//----------------------------------------------------------------------------- void vtkAxisActor::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf(os,indent); + this->Superclass::PrintSelf(os, indent); os << indent << "Title: " << (this->Title ? this->Title : "(none)") << "\n"; os << indent << "Number Of Labels Built: " - << this->NumberOfLabelsBuilt << "\n"; + << this->NumberOfLabelsBuilt << "\n"; os << indent << "Range: (" - << this->Range[0] << ", " - << this->Range[1] << ")\n"; + << this->Range[0] << ", " + << this->Range[1] << ")\n"; os << indent << "UseTextActor3D: " << this->UseTextActor3D << "\n"; os << indent << "Label Format: " << this->LabelFormat << "\n"; os << indent << "Axis Visibility: " - << (this->AxisVisibility ? "On\n" : "Off\n"); + << (this->AxisVisibility ? "On\n" : "Off\n"); os << indent << "Tick Visibility: " - << (this->TickVisibility ? "On\n" : "Off\n"); + << (this->TickVisibility ? "On\n" : "Off\n"); os << indent << "Label Visibility: " - << (this->LabelVisibility ? "On\n" : "Off\n"); + << (this->LabelVisibility ? "On\n" : "Off\n"); os << indent << "Title Visibility: " - << (this->TitleVisibility ? "On\n" : "Off\n"); + << (this->TitleVisibility ? "On\n" : "Off\n"); os << indent << "Point1 Coordinate: " << this->Point1Coordinate << "\n"; this->Point1Coordinate->PrintSelf(os, indent.GetNextIndent()); @@ -1304,13 +1812,13 @@ void vtkAxisActor::PrintSelf(ostream& os, vtkIndent indent) break; default: // shouldn't get here - ; + break; } os << indent << "DeltaMajor: " - << this->DeltaMajor[0] << "," - << this->DeltaMajor[1] << "," - << this->DeltaMajor[2] << endl; + << this->DeltaMajor[0] << "," + << this->DeltaMajor[1] << "," + << this->DeltaMajor[2] << endl; os << indent << "DeltaMinor: " << this->DeltaMinor << endl; os << indent << "DeltaRangeMajor: " << this->DeltaRangeMajor << endl; os << indent << "DeltaRangeMinor: " << this->DeltaRangeMinor << endl; @@ -1320,7 +1828,7 @@ void vtkAxisActor::PrintSelf(ostream& os, vtkIndent indent) os << indent << "MinorTicksVisible: " << this->MinorTicksVisible << endl; os << indent << "TitleActor: "; - if(this->TitleActor) + if (this->TitleActor) { os << indent << "TitleActor: (" << this->TitleActor << ")\n"; } @@ -1345,9 +1853,9 @@ void vtkAxisActor::PrintSelf(ostream& os, vtkIndent indent) os << indent << "DrawGridlines: " << this->DrawGridlines << endl; os << indent << "MajorStart: " - << this->MajorStart[0] << "," - << this->MajorStart[1] << "," - << this->MajorStart[2] << endl; + << this->MajorStart[0] << "," + << this->MajorStart[1] << "," + << this->MajorStart[2] << endl; os << indent << "AxisPosition: " << this->AxisPosition << endl; @@ -1371,25 +1879,25 @@ void vtkAxisActor::PrintSelf(ostream& os, vtkIndent indent) os << indent << "VerticalOffsetXTitle2D" << this->VerticalOffsetXTitle2D << endl; os << indent << "HorizontalOffsetYTitle2D" << this->HorizontalOffsetYTitle2D << endl; os << indent << "LastMinDisplayCoordinates: (" - << this->LastMinDisplayCoordinate[0] << ", " - << this->LastMinDisplayCoordinate[1] << ", " - << this->LastMinDisplayCoordinate[2] << ")" << endl; + << this->LastMinDisplayCoordinate[0] << ", " + << this->LastMinDisplayCoordinate[1] << ", " + << this->LastMinDisplayCoordinate[2] << ")" << endl; os << indent << "LastMaxDisplayCoordinates: (" - << this->LastMaxDisplayCoordinate[0] << ", " - << this->LastMaxDisplayCoordinate[1] << ", " - << this->LastMaxDisplayCoordinate[2] << ")" << endl; - } + << this->LastMaxDisplayCoordinate[0] << ", " + << this->LastMaxDisplayCoordinate[1] << ", " + << this->LastMaxDisplayCoordinate[2] << ")" << endl; +} -// ************************************************************************** +//----------------------------------------------------------------------------- // Sets text string for label vectors. Allocates memory if necessary. -// ************************************************************************** +//----------------------------------------------------------------------------- void vtkAxisActor::SetLabels(vtkStringArray *labels) { // // If the number of labels has changed, re-allocate the correct // amount of memory. // - int i, numLabels = labels->GetNumberOfValues(); + int numLabels = labels->GetNumberOfValues(); if (numLabels < 0) { vtkErrorMacro(<< "Number of labels " << numLabels << " is invalid"); @@ -1399,7 +1907,7 @@ void vtkAxisActor::SetLabels(vtkStringArray *labels) { if (this->LabelMappers != NULL) { - for (i = 0; i < this->NumberOfLabelsBuilt; i++) + for (int i = 0; i < this->NumberOfLabelsBuilt; i++) { this->LabelVectors[i]->Delete(); this->LabelMappers[i]->Delete(); @@ -1423,7 +1931,7 @@ void vtkAxisActor::SetLabels(vtkStringArray *labels) this->LabelActors3D = new vtkTextActor3D * [numLabels]; this->LabelActors2D = new vtkTextActor * [numLabels]; - for (i = 0; i < numLabels; i++) + for (int i = 0; i < numLabels; i++) { this->LabelVectors[i] = vtkVectorText::New(); this->LabelMappers[i] = vtkPolyDataMapper::New(); @@ -1449,7 +1957,7 @@ void vtkAxisActor::SetLabels(vtkStringArray *labels) // // Set the label vector text. // - for (i = 0; i < numLabels; i++) + for (int i = 0; i < numLabels; i++) { this->LabelVectors[i]->SetText(labels->GetValue(i).c_str()); this->LabelActors3D[i]->SetInput(this->LabelVectors[i]->GetText()); @@ -1459,30 +1967,51 @@ void vtkAxisActor::SetLabels(vtkStringArray *labels) this->LabelBuildTime.Modified(); } -// ************************************************************************** +//-----------------------------------------------------------------------------* // Creates Poly data (lines) from tickmarks (minor/major), gridlines, and axis. -// ************************************************************************** +//-----------------------------------------------------------------------------* void vtkAxisActor::SetAxisPointsAndLines() { - vtkPoints *pts = vtkPoints::New(); - vtkCellArray *lines = vtkCellArray::New(); + vtkPoints *mainLinePts = vtkPoints::New(); + vtkPoints *axisMajorTicksPts = vtkPoints::New(); + vtkPoints *axisMinorTicksPts = vtkPoints::New(); + + vtkCellArray *mainLine = vtkCellArray::New(); + vtkCellArray *axisMajorTicksLines = vtkCellArray::New(); + vtkCellArray *axisMinorTicksLines = vtkCellArray::New(); + vtkCellArray *gridlines = vtkCellArray::New(); vtkCellArray *innerGridlines = vtkCellArray::New(); vtkCellArray *polys = vtkCellArray::New(); - this->AxisLines->SetPoints(pts); - this->AxisLines->SetLines(lines); + + this->AxisLines->SetPoints(mainLinePts); + this->AxisLines->SetLines(mainLine); + + this->AxisMajorTicks->SetPoints(axisMajorTicksPts); + this->AxisMajorTicks->SetLines(axisMajorTicksLines); + + this->AxisMinorTicks->SetPoints(axisMinorTicksPts); + this->AxisMinorTicks->SetLines(axisMinorTicksLines); + this->Gridlines->SetPoints(this->GridlinePts); this->Gridlines->SetLines(gridlines); this->InnerGridlines->SetPoints(this->InnerGridlinePts); this->InnerGridlines->SetLines(innerGridlines); this->Gridpolys->SetPoints(this->GridpolyPts); this->Gridpolys->SetPolys(polys); - pts->Delete(); - lines->Delete(); + + mainLinePts->Delete(); + axisMajorTicksPts->Delete(); + axisMinorTicksPts->Delete(); + + mainLine->Delete(); + axisMajorTicksLines->Delete(); + axisMinorTicksLines->Delete(); + gridlines->Delete(); innerGridlines->Delete(); polys->Delete(); - int i, numMinorTickPts, numGridlines, numInnerGridlines, numMajorTickPts, numGridpolys, numLines; + int numMinorTickPts, numGridlines, numInnerGridlines, numMajorTickPts, numGridpolys, numLines; vtkIdType ptIds[2]; vtkIdType polyPtIds[4]; @@ -1492,57 +2021,66 @@ void vtkAxisActor::SetAxisPointsAndLines() { // In 2D mode, the minorTickPts for yz portion or xz portion have been removed. numMinorTickPts = this->MinorTickPts->GetNumberOfPoints(); - for (i = 0; i < numMinorTickPts; i++) + for (int i = 0; i < numMinorTickPts; i++) { - pts->InsertNextPoint(this->MinorTickPts->GetPoint(i)); + axisMinorTicksPts->InsertNextPoint(this->MinorTickPts->GetPoint(i)); } } numMajorTickPts = this->MajorTickPts->GetNumberOfPoints(); if (this->Use2DMode == 0) { - for (i = 0; i < numMajorTickPts; i++) + for (int i = 0; i < numMajorTickPts; i++) { - pts->InsertNextPoint(this->MajorTickPts->GetPoint(i)); + axisMajorTicksPts->InsertNextPoint(this->MajorTickPts->GetPoint(i)); } } else { // In 2D mode, we don't need the pts for the xz portion or yz portion of the major tickmarks // majorTickPts not modified because all points are used for labels' positions. - for (i = 0; i < numMajorTickPts; i+=4) + for (int i = 0; i < numMajorTickPts; i += 4) { - pts->InsertNextPoint(this->MajorTickPts->GetPoint(i)); - pts->InsertNextPoint(this->MajorTickPts->GetPoint(i+1)); + axisMajorTicksPts->InsertNextPoint(this->MajorTickPts->GetPoint(i)); + axisMajorTicksPts->InsertNextPoint(this->MajorTickPts->GetPoint(i + 1)); } } } - // create lines - numLines = pts->GetNumberOfPoints() / 2; - for (i=0; i < numLines; i++) + // create major ticks lines + numLines = axisMajorTicksPts->GetNumberOfPoints() / 2; + for (int i = 0; i < numLines; i++) { ptIds[0] = 2*i; ptIds[1] = 2*i + 1; - lines->InsertNextCell(2, ptIds); + axisMajorTicksLines->InsertNextCell(2, ptIds); + } + + // create major ticks lines + numLines = axisMinorTicksPts->GetNumberOfPoints() / 2; + for (int i = 0; i < numLines; i++) + { + ptIds[0] = 2*i; + ptIds[1] = 2*i + 1; + axisMinorTicksLines->InsertNextCell(2, ptIds); } if (this->AxisVisibility) { //first axis point - ptIds[0] = pts->InsertNextPoint(this->Point1Coordinate->GetValue()); + ptIds[0] = mainLinePts->InsertNextPoint(this->Point1Coordinate->GetValue()); //last axis point - ptIds[1] = pts->InsertNextPoint(this->Point2Coordinate->GetValue()); - lines->InsertNextCell(2, ptIds); + ptIds[1] = mainLinePts->InsertNextPoint(this->Point2Coordinate->GetValue()); + mainLine->InsertNextCell(2, ptIds); } // create grid lines if (this->DrawGridlines && this->AxisOnOrigin == 0) { - numGridlines = this->GridlinePts->GetNumberOfPoints()/2; + numGridlines = this->GridlinePts->GetNumberOfPoints() / 2; int start = - (this->DrawGridlinesLocation == 0 || this->DrawGridlinesLocation == 1) - ? 0 : 1; + (this->DrawGridlinesLocation == 0 || this->DrawGridlinesLocation == 1) + ? 0 : 1; int increment = (this->DrawGridlinesLocation == 0) ? 1 : 2; - for (i = start; i < numGridlines; i+=increment) + for (int i = start; i < numGridlines; i += increment) { ptIds[0] = 2*i; ptIds[1] = 2*i + 1; @@ -1553,8 +2091,8 @@ void vtkAxisActor::SetAxisPointsAndLines() // create inner grid lines if (this->DrawInnerGridlines && this->AxisOnOrigin == 0) { - numInnerGridlines = this->InnerGridlinePts->GetNumberOfPoints()/2; - for (i=0; i < numInnerGridlines; i++) + numInnerGridlines = this->InnerGridlinePts->GetNumberOfPoints() / 2; + for (int i = 0; i < numInnerGridlines; i++) { ptIds[0] = 2*i; ptIds[1] = 2*i + 1; @@ -1565,26 +2103,26 @@ void vtkAxisActor::SetAxisPointsAndLines() // create polys (grid polys) if (this->DrawGridpolys && this->AxisOnOrigin == 0) { - numGridpolys = this->GridpolyPts->GetNumberOfPoints()/4; - for (i = 0; i < numGridpolys; i++) + numGridpolys = this->GridpolyPts->GetNumberOfPoints() / 4; + for (int i = 0; i < numGridpolys; i++) { polyPtIds[0] = 4*i; polyPtIds[1] = 4*i + 1; polyPtIds[2] = 4*i + 2; polyPtIds[3] = 4*i + 3; - polys->InsertNextCell(4,polyPtIds); + polys->InsertNextCell(4, polyPtIds); } } } -// ********************************************************************* +//-----------------------------------------------------------------------------** // Returns true if any tick vis attribute has changed since last check. -// ********************************************************************* +//-----------------------------------------------------------------------------** bool vtkAxisActor::TickVisibilityChanged() { bool retVal = (this->TickVisibility != this->LastTickVisibility) || - (this->DrawGridlines != this->LastDrawGridlines) || - (this->MinorTicksVisible != this->LastMinorTicksVisible); + (this->DrawGridlines != this->LastDrawGridlines) || + (this->MinorTicksVisible != this->LastMinorTicksVisible); this->LastTickVisibility = this->TickVisibility; this->LastDrawGridlines = this->DrawGridlines; @@ -1593,9 +2131,9 @@ bool vtkAxisActor::TickVisibilityChanged() return retVal; } -// ********************************************************************* +//-----------------------------------------------------------------------------** // Set the bounds for this actor to use. Sets timestamp BoundsModified. -// ********************************************************************* +//-----------------------------------------------------------------------------** void vtkAxisActor::SetBounds(const double b[6]) { @@ -1604,7 +2142,7 @@ vtkAxisActor::SetBounds(const double b[6]) (this->Bounds[2] != b[2]) || (this->Bounds[3] != b[3]) || (this->Bounds[4] != b[4]) || - (this->Bounds[5] != b[5]) ) + (this->Bounds[5] != b[5])) { for (int i = 0; i < 6; i++) { @@ -1614,9 +2152,9 @@ vtkAxisActor::SetBounds(const double b[6]) } } -// ********************************************************************* +//-----------------------------------------------------------------------------** // Retrieves the bounds of this actor. -// ********************************************************************* +//-----------------------------------------------------------------------------** void vtkAxisActor:: SetBounds(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax) { @@ -1625,7 +2163,7 @@ SetBounds(double xmin, double xmax, double ymin, double ymax, double zmin, doubl (this->Bounds[2] != ymin) || (this->Bounds[3] != ymax) || (this->Bounds[4] != zmin) || - (this->Bounds[5] != zmax) ) + (this->Bounds[5] != zmax)) { this->Bounds[0] = xmin; this->Bounds[1] = xmax; @@ -1638,17 +2176,17 @@ SetBounds(double xmin, double xmax, double ymin, double ymax, double zmin, doubl } } -// ********************************************************************* +//-----------------------------------------------------------------------------** // Retrieves the bounds of this actor. -// ********************************************************************* +//-----------------------------------------------------------------------------** double* vtkAxisActor::GetBounds() { return this->Bounds; } -// ********************************************************************* +//-----------------------------------------------------------------------------** // Retrieves the bounds of this actor. -// ********************************************************************* +//-----------------------------------------------------------------------------** void vtkAxisActor::GetBounds(double b[6]) { @@ -1658,9 +2196,9 @@ void vtkAxisActor::GetBounds(double b[6]) } } -// ********************************************************************* +//-----------------------------------------------------------------------------** // Method: vtkAxisActor::ComputeMaxLabelLength -// ********************************************************************* +//-----------------------------------------------------------------------------** double vtkAxisActor::ComputeMaxLabelLength(const double vtkNotUsed(center)[3]) { double bounds[6]; @@ -1690,9 +2228,9 @@ double vtkAxisActor::ComputeMaxLabelLength(const double vtkNotUsed(center)[3]) return sqrt(maxXSize*maxXSize + maxYSize*maxYSize); } -// ********************************************************************* +//-----------------------------------------------------------------------------** // Method: vtkAxisActor::ComputeTitleLength -// ********************************************************************* +//-----------------------------------------------------------------------------** double vtkAxisActor::ComputeTitleLength(const double vtkNotUsed(center)[3]) { double bounds[6]; @@ -1721,30 +2259,32 @@ double vtkAxisActor::ComputeTitleLength(const double vtkNotUsed(center)[3]) return length; } -// ********************************************************************* +//-----------------------------------------------------------------------------** void vtkAxisActor::SetLabelScale(const double s) { - for (int i=0; i < this->NumberOfLabelsBuilt; i++) + for (int i = 0; i < this->NumberOfLabelsBuilt; i++) { this->SetLabelScale(i, s); } } -// ********************************************************************* +//-----------------------------------------------------------------------------** void vtkAxisActor::SetLabelScale(int label, const double s) { this->LabelActors[label]->SetScale(s); this->LabelProps3D[label]->SetScale(s); } -// ********************************************************************* +//-----------------------------------------------------------------------------** void vtkAxisActor::SetTitleScale(const double s) { this->TitleActor->SetScale(s); this->TitleProp3D->SetScale(s); + this->ExponentActor->SetScale(s); + this->ExponentProp3D->SetScale(s); } -// ********************************************************************* +//-----------------------------------------------------------------------------** void vtkAxisActor::SetTitle(const char *t) { if (this->Title == NULL && t == NULL) @@ -1758,7 +2298,7 @@ void vtkAxisActor::SetTitle(const char *t) delete [] this->Title; if (t) { - this->Title = new char[strlen(t)+1]; + this->Title = new char[strlen(t) + 1]; strcpy(this->Title, t); } else @@ -1769,115 +2309,170 @@ void vtkAxisActor::SetTitle(const char *t) this->Modified(); } -// **************************************************************************** +void vtkAxisActor::SetExponent(const char *t) +{ + if (this->Exponent == NULL && t == NULL) + { + return; + } + if (this->Exponent && t && (!strcmp(this->Exponent, t))) + { + return; + } + delete [] this->Exponent; + if (t) + { + this->Exponent = new char[strlen(t) + 1]; + strcpy(this->Exponent, t); + } + else + { + this->Exponent = NULL; + } + this->ExponentTextTime.Modified(); + this->Modified(); +} + +//----------------------------------------------------------------------------- void vtkAxisActor::SetAxisLinesProperty(vtkProperty *prop) { - this->AxisLinesActor->SetProperty(prop); + this->SetAxisMainLineProperty(prop); + this->SetAxisMajorTicksProperty(prop); + this->SetAxisMinorTicksProperty(prop); this->Modified(); } -// **************************************************************************** +//----------------------------------------------------------------------------- vtkProperty* vtkAxisActor::GetAxisLinesProperty() { return this->AxisLinesActor->GetProperty(); } -// **************************************************************************** +//----------------------------------------------------------------------------- +void vtkAxisActor::SetAxisMainLineProperty(vtkProperty *prop) +{ + this->AxisLinesActor->SetProperty(prop); + this->Modified(); +} + +vtkProperty* vtkAxisActor::GetAxisMainLineProperty() +{ + return this->GetAxisLinesProperty(); +} + +//----------------------------------------------------------------------------- +void vtkAxisActor::SetAxisMajorTicksProperty(vtkProperty *prop) +{ + this->AxisMajorTicksActor->SetProperty(prop); + this->Modified(); +} + +//----------------------------------------------------------------------------- +vtkProperty* vtkAxisActor::GetAxisMajorTicksProperty() +{ + return this->AxisMajorTicksActor->GetProperty(); +} + +//----------------------------------------------------------------------------- +void vtkAxisActor::SetAxisMinorTicksProperty(vtkProperty *prop) +{ + this->AxisMinorTicksActor->SetProperty(prop); + this->Modified(); +} + +//----------------------------------------------------------------------------- +vtkProperty* vtkAxisActor::GetAxisMinorTicksProperty() +{ + return this->AxisMinorTicksActor->GetProperty(); +} + +//----------------------------------------------------------------------------- void vtkAxisActor::SetGridlinesProperty(vtkProperty *prop) { this->GridlinesActor->SetProperty(prop); this->Modified(); } -// **************************************************************************** +//----------------------------------------------------------------------------- vtkProperty* vtkAxisActor::GetGridlinesProperty() { return this->GridlinesActor->GetProperty(); } -// **************************************************************************** +//----------------------------------------------------------------------------- void vtkAxisActor::SetInnerGridlinesProperty(vtkProperty *prop) { this->InnerGridlinesActor->SetProperty(prop); this->Modified(); } -// **************************************************************************** +//----------------------------------------------------------------------------- vtkProperty* vtkAxisActor::GetInnerGridlinesProperty() { return this->InnerGridlinesActor->GetProperty(); } -// **************************************************************************** +//----------------------------------------------------------------------------- void vtkAxisActor::SetGridpolysProperty(vtkProperty *prop) { this->GridpolysActor->SetProperty(prop); this->Modified(); } -// **************************************************************************** +//----------------------------------------------------------------------------- vtkProperty* vtkAxisActor::GetGridpolysProperty() { return this->GridpolysActor->GetProperty(); } -// **************************************************************************** +//----------------------------------------------------------------------------- vtkProperty* vtkAxisActor::NewTitleProperty() { vtkProperty *newProp = vtkProperty::New(); newProp->DeepCopy(this->GetProperty()); newProp->SetColor(this->TitleTextProperty->GetColor()); - // We pass the opacity in the line offset. - //newProp->SetOpacity(this->TitleTextProperty->GetLineOffset()); return newProp; } -// **************************************************************************** +//----------------------------------------------------------------------------- vtkProperty* vtkAxisActor::NewLabelProperty() { vtkProperty *newProp = vtkProperty::New(); newProp->DeepCopy(this->GetProperty()); newProp->SetColor(this->LabelTextProperty->GetColor()); - // We pass the opacity in the line offset. - //newProp->SetOpacity(this->LabelTextProperty->GetLineOffset()); return newProp; } - -// **************************************************************************** -double vtkAxisActor::GetDeltaMajor(int axis){ - if(axis>=0 && axis<=2) - { - return (this->DeltaMajor[axis]); - } - return 0; +//----------------------------------------------------------------------------- +double vtkAxisActor::GetDeltaMajor(int axis) +{ + return (axis >= 0 && axis <= 2) ? this->DeltaMajor[axis] : 0; } -void vtkAxisActor::SetDeltaMajor(int axis, double value){ - if(axis>=0 && axis<=2) +//----------------------------------------------------------------------------- +void vtkAxisActor::SetDeltaMajor(int axis, double value) +{ + if (axis >= 0 && axis <= 2) { this->DeltaMajor[axis] = value; } } -// **************************************************************************** -double vtkAxisActor::GetMajorStart(int axis){ - if(axis>=0 && axis<=2) - { - return (this->MajorStart[axis]); - } - return 0; +//----------------------------------------------------------------------------- +double vtkAxisActor::GetMajorStart(int axis) +{ + return (axis >= 0 && axis <= 2) ? this->MajorStart[axis] : 0; } -// **************************************************************************** +//----------------------------------------------------------------------------- void vtkAxisActor::SetMajorStart(int axis, double value){ - if(axis>=0 && axis<=2) + if (axis >= 0 && axis <= 2) { this->MajorStart[axis] = value; } } -// **************************************************************************** +//----------------------------------------------------------------------------- bool vtkAxisActor::BoundsDisplayCoordinateChanged(vtkViewport *viewport) { double transMinPt[3], transMaxPt[3]; @@ -1888,15 +2483,14 @@ bool vtkAxisActor::BoundsDisplayCoordinateChanged(vtkViewport *viewport) viewport->WorldToDisplay(); viewport->GetDisplayPoint(transMaxPt); - if( this->LastMinDisplayCoordinate[0] != transMinPt[0] - || this->LastMinDisplayCoordinate[1] != transMinPt[1] - || this->LastMinDisplayCoordinate[2] != transMinPt[2] - || this->LastMaxDisplayCoordinate[0] != transMaxPt[0] - || this->LastMaxDisplayCoordinate[1] != transMaxPt[1] - || this->LastMaxDisplayCoordinate[2] != transMaxPt[2] ) + if (this->LastMinDisplayCoordinate[0] != transMinPt[0] + || this->LastMinDisplayCoordinate[1] != transMinPt[1] + || this->LastMinDisplayCoordinate[2] != transMinPt[2] + || this->LastMaxDisplayCoordinate[0] != transMaxPt[0] + || this->LastMaxDisplayCoordinate[1] != transMaxPt[1] + || this->LastMaxDisplayCoordinate[2] != transMaxPt[2]) { - int i = 0; - for( i=0 ; i<3 ; ++i ) + for (int i = 0 ; i<3 ; ++i) { this->LastMinDisplayCoordinate[i] = transMinPt[i]; this->LastMaxDisplayCoordinate[i] = transMaxPt[i]; @@ -1908,11 +2502,12 @@ bool vtkAxisActor::BoundsDisplayCoordinateChanged(vtkViewport *viewport) } //--------------------------------------------------------------------------- // endpoint-related methods +//----------------------------------------------------------------------------- vtkCoordinate* vtkAxisActor::GetPoint1Coordinate() { vtkDebugMacro(<< this->GetClassName() << " (" << this - << "): returning Point1 Coordinate address " - << this->Point1Coordinate ); + << "): returning Point1 Coordinate address " + << this->Point1Coordinate); return this->Point1Coordinate; } @@ -1920,8 +2515,8 @@ vtkCoordinate* vtkAxisActor::GetPoint1Coordinate() vtkCoordinate* vtkAxisActor::GetPoint2Coordinate() { vtkDebugMacro(<< this->GetClassName() << " (" << this - << "): returning Point2 Coordinate address " - << this->Point2Coordinate ); + << "): returning Point2 Coordinate address " + << this->Point2Coordinate); return this->Point2Coordinate; } @@ -1948,38 +2543,25 @@ double* vtkAxisActor::GetPoint2() { return this->Point2Coordinate->GetValue(); } -// ************************************************************************** + +//----------------------------------------------------------------------------- // Creates points for ticks (minor, major, gridlines) in correct position // for a generic axis. -// ************************************************************************** +//----------------------------------------------------------------------------- bool vtkAxisActor::BuildTickPoints(double p1[3], double p2[3], bool force) { // Prevent any unwanted computation if (!force && (this->AxisPosition == this->LastAxisPosition) && - (this->TickLocation == this->LastTickLocation ) && - (this->BoundsTime.GetMTime() < this->BuildTime.GetMTime()) && - (this->Point1Coordinate->GetMTime() < this->BuildTickPointsTime.GetMTime()) && - (this->Point2Coordinate->GetMTime() < this->BuildTickPointsTime.GetMTime()) && - (this->Range[0] == this->LastRange[0]) && - (this->Range[1] == this->LastRange[1])) + (this->TickLocation == this->LastTickLocation) && + (this->BoundsTime.GetMTime() < this->BuildTime.GetMTime()) && + (this->Point1Coordinate->GetMTime() < this->BuildTickPointsTime.GetMTime()) && + (this->Point2Coordinate->GetMTime() < this->BuildTickPointsTime.GetMTime()) && + (this->Range[0] == this->LastRange[0]) && + (this->Range[1] == this->LastRange[1])) { return false; } - // Local tmp vars - double uPointInside[3], vPointInside[3], uPointOutside[3], vPointOutside[3]; - double gridPointClosest[3], gridPointFarest[3], gridPointU[3], gridPointV[3]; - double innerGridPointClosestU[3], innerGridPointClosestV[3]; - double innerGridPointFarestU[3], innerGridPointFarestV[3]; - double deltaVector[3]; - double axisLength, axisShift, rangeScale, nbIterationAsDouble; - int nbTicks, i, nbIteration, uIndex, vIndex; - uIndex = vIndex = 0; - bool hasOrthogonalVectorBase = - (this->AxisBaseForX[0] == 1 && this->AxisBaseForX[1] == 0 && this->AxisBaseForX[2] == 0 - && this->AxisBaseForY[0] == 0 && this->AxisBaseForY[1] == 1 && this->AxisBaseForY[2] == 0 - && this->AxisBaseForZ[0] == 0 && this->AxisBaseForZ[1] == 0 && this->AxisBaseForZ[2] == 1); - // Reset previous objects this->MinorTickPts->Reset(); this->MajorTickPts->Reset(); @@ -1990,154 +2572,156 @@ bool vtkAxisActor::BuildTickPoints(double p1[3], double p2[3], bool force) // As we assume that the Axis is not necessery alined to the absolute X/Y/Z // axis, we will convert the absolut XYZ information to relative one // using a base composed as follow (axis, u, v) - double uGridLength, vGridLength; - uGridLength = vGridLength = 0; - double *axisVector, *uVector, *vVector; - axisVector = uVector = vVector = NULL; - int uMult = vtkAxisActorMultiplierTable1[this->AxisPosition]; - int vMult = vtkAxisActorMultiplierTable2[this->AxisPosition]; - switch(this->AxisType) - { - case VTK_AXIS_TYPE_X: - uGridLength = this->GridlineYLength; - vGridLength = this->GridlineZLength; - axisVector = this->AxisBaseForX; - uVector = this->AxisBaseForY; - vVector = this->AxisBaseForZ; - uIndex = 1; vIndex = 2; - break; - case VTK_AXIS_TYPE_Y: - uGridLength = this->GridlineXLength; - vGridLength = this->GridlineZLength; - uVector = this->AxisBaseForX; - axisVector = this->AxisBaseForY; - vVector = this->AxisBaseForZ; - uIndex = 0; vIndex = 2; - break; - case VTK_AXIS_TYPE_Z: - uGridLength = this->GridlineXLength; - vGridLength = this->GridlineYLength; - uVector = this->AxisBaseForX; - vVector = this->AxisBaseForY; - axisVector = this->AxisBaseForZ; - uIndex = 0; vIndex = 1; - break; - } - - // ************************************************************************** - // Build Minor Ticks - // ************************************************************************** - { - // - Initialize all points to be on the axis - for(i=0;i<3;i++) - { - uPointInside[i] = vPointInside[i] = uPointOutside[i] = vPointOutside[i] = p1[i]; - deltaVector[i] = (p2[i] - p1[i]); - } - axisLength = vtkMath::Norm(deltaVector); - rangeScale = axisLength/(this->Range[1] - this->Range[0]); + double coordSystem[3][3]; //axisVector, uVector, vVector - // - Reduce the deltaVector to correspond to a tick step - vtkMath::Normalize(deltaVector); - for(i=0;i<3;i++) + switch (this->AxisType) { - deltaVector[i] *= this->DeltaMinor; - } + case VTK_AXIS_TYPE_X: + memcpy(&coordSystem[0], this->AxisBaseForX, 3*sizeof(double)); + memcpy(&coordSystem[1], this->AxisBaseForY, 3*sizeof(double)); + memcpy(&coordSystem[2], this->AxisBaseForZ, 3*sizeof(double)); + break; - // - Move outside points if needed (Axis -> Outside) - if (this->TickLocation == VTK_TICKS_OUTSIDE || this->TickLocation == VTK_TICKS_BOTH) - { - for(i=0;i<3;i++) - { - uPointOutside[i] += uVector[i] * uMult * this->MinorTickSize; - vPointOutside[i] += vVector[i] * vMult * this->MinorTickSize; - } - } + case VTK_AXIS_TYPE_Y: + memcpy(&coordSystem[0], this->AxisBaseForY, 3*sizeof(double)); + memcpy(&coordSystem[1], this->AxisBaseForX, 3*sizeof(double)); + memcpy(&coordSystem[2], this->AxisBaseForZ, 3*sizeof(double)); + break; - // - Move inside points if needed (Axis -> Inside) - if (this->TickLocation == VTK_TICKS_INSIDE || this->TickLocation == VTK_TICKS_BOTH) - { - for(i=0;i<3;i++) - { - uPointInside[i] -= uVector[i] * uMult * this->MinorTickSize; - vPointInside[i] -= vVector[i] * vMult * this->MinorTickSize; - } - } + case VTK_AXIS_TYPE_Z: + memcpy(&coordSystem[0], this->AxisBaseForZ, 3*sizeof(double)); + memcpy(&coordSystem[1], this->AxisBaseForX, 3*sizeof(double)); + memcpy(&coordSystem[2], this->AxisBaseForY, 3*sizeof(double)); + break; - // - Add the initial shift if any - axisShift = (this->MinorRangeStart - this->Range[0])*rangeScale; - for(i=0;i<3;i++) - { - uPointInside[i] += axisVector[i] * axisShift; - vPointInside[i] += axisVector[i] * axisShift; - uPointOutside[i] += axisVector[i] * axisShift; - vPointOutside[i] += axisVector[i] * axisShift; + default: + // shouldn't get here + break; } - // - Insert tick points along the axis using the deltaVector - nbIterationAsDouble = axisLength / vtkMath::Norm(deltaVector); - nbIteration = vtkMath::Floor(nbIterationAsDouble+2*DBL_EPSILON); - nbIteration = (nbIteration < VTK_MAX_TICKS) ? nbIteration : VTK_MAX_TICKS; - for (nbTicks = 0; nbTicks < nbIteration; nbTicks++) + //-----------------------------------------------------------------------------* + // Build Minor Ticks + //-----------------------------------------------------------------------------* + if (this->Log) { - // axis/u side - this->MinorTickPts->InsertNextPoint(uPointInside); - this->MinorTickPts->InsertNextPoint(uPointOutside); - vtkMath::Add(deltaVector, uPointInside, uPointInside); - vtkMath::Add(deltaVector, uPointOutside, uPointOutside); - if( this->Use2DMode == 0 ) - { - // axis/v side - this->MinorTickPts->InsertNextPoint(vPointInside); - this->MinorTickPts->InsertNextPoint(vPointOutside); - vtkMath::Add(deltaVector, vPointInside, vPointInside); - vtkMath::Add(deltaVector, vPointOutside, vPointOutside); - } + this->BuildMinorTicksLog(p1, p2, coordSystem); } - } - // ************************************************************************** - // Build Gridline + GridPoly points + InnerGrid (Only for Orthonormal base) - // ************************************************************************** - { - // - Initialize all points to be on the axis - for(i=0;i<3;i++) + else { - gridPointClosest[i] = gridPointFarest[i] = gridPointU[i] = gridPointV[i] = p1[i]; - deltaVector[i] = (p2[i] - p1[i]); + this->BuildMinorTicks(p1, p2, coordSystem); } - // - Reduce the deltaVector to correspond to a major tick step - vtkMath::Normalize(deltaVector); - for(i=0;i<3;i++) + //-----------------------------------------------------------------------------* + // Build Gridline + GridPoly points + InnerGrid (Only for Orthonormal base) + //-----------------------------------------------------------------------------* + if (!this->Log) { - deltaVector[i] *= this->DeltaMajor[this->AxisType]; + BuildAxisGridLines(p1, p2, coordSystem); } - // - Move base points - for(i=0;i<3;i++) + //-----------------------------------------------------------------------------* + // Build Major ticks + //-----------------------------------------------------------------------------* + if (this->Log) { - gridPointU[i] -= uVector[i] * uMult * uGridLength; - gridPointV[i] -= vVector[i] * vMult * vGridLength; - gridPointFarest[i] -= uVector[i] * uMult * uGridLength + vVector[i] * vMult * vGridLength; + BuildMajorTicksLog(p1, p2, coordSystem); } - - // - Add the initial shift if any - axisShift = (this->MajorRangeStart - this->Range[0])*rangeScale; - for(i=0;i<3;i++) + else { - gridPointU[i] += axisVector[i] * axisShift; - gridPointV[i] += axisVector[i] * axisShift; - gridPointFarest[i] += axisVector[i] * axisShift; - gridPointClosest[i] += axisVector[i] * axisShift; + BuildMajorTicks(p1, p2, coordSystem); } - // - Insert Gridlines points along the axis using the DeltaMajor vector - nbIterationAsDouble = (axisLength - axisShift) / vtkMath::Norm(deltaVector); - nbIteration = vtkMath::Floor(nbIterationAsDouble+2*FLT_EPSILON) + 1; - nbIteration = (nbIteration < VTK_MAX_TICKS) ? nbIteration : VTK_MAX_TICKS; - for (nbTicks = 0; nbTicks < nbIteration; nbTicks++) - { + this->BuildTickPointsTime.Modified(); + this->LastTickLocation = this->TickLocation; + return true; +} + +//----------------------------------------------------------------------------- +void vtkAxisActor::BuildAxisGridLines(double p1[3], double p2[3], double localCoordSys[3][3]) +{ + int uIndex = 0, vIndex = 0; + double uGridLength = 0.0, vGridLength = 0.0; + double gridPointClosest[3], gridPointFarest[3], gridPointU[3], gridPointV[3]; + double innerGridPointClosestU[3], innerGridPointClosestV[3]; + double innerGridPointFarestU[3], innerGridPointFarestV[3]; + double deltaVector[3]; + + int uMult = vtkAxisActorMultiplierTable1[this->AxisPosition]; + int vMult = vtkAxisActorMultiplierTable2[this->AxisPosition]; + + double* axisVector = localCoordSys[0]; + double* uVector = localCoordSys[1]; + double* vVector = localCoordSys[2]; + + switch (this->AxisType) + { + case VTK_AXIS_TYPE_X: + uGridLength = this->GridlineYLength; + vGridLength = this->GridlineZLength; + uIndex = 1; vIndex = 2; + break; + case VTK_AXIS_TYPE_Y: + uGridLength = this->GridlineXLength; + vGridLength = this->GridlineZLength; + uIndex = 0; vIndex = 2; + break; + case VTK_AXIS_TYPE_Z: + uGridLength = this->GridlineXLength; + vGridLength = this->GridlineYLength; + uIndex = 0; vIndex = 1; + break; + default: + // shouldn't get here + break; + } + + bool hasOrthogonalVectorBase = + this->AxisBaseForX[0] == 1 && this->AxisBaseForX[1] == 0 && this->AxisBaseForX[2] == 0 && + this->AxisBaseForY[0] == 0 && this->AxisBaseForY[1] == 1 && this->AxisBaseForY[2] == 0 && + this->AxisBaseForZ[0] == 0 && this->AxisBaseForZ[1] == 0 && this->AxisBaseForZ[2] == 1; + + // - Initialize all points to be on the axis + for (int i = 0;i<3;i++) + { + gridPointClosest[i] = gridPointFarest[i] = gridPointU[i] = gridPointV[i] = p1[i]; + deltaVector[i] = (p2[i] - p1[i]); + } + + double axisLength = vtkMath::Norm(deltaVector); + double rangeScale = axisLength / (this->Range[1] - this->Range[0]); + + // - Reduce the deltaVector to correspond to a major tick step + vtkMath::Normalize(deltaVector); + for (int i = 0;i<3;i++) + { + deltaVector[i] *= this->DeltaMajor[this->AxisType]; + } + + // - Move base points + for (int i = 0;i<3;i++) + { + gridPointU[i] -= uVector[i] * uMult * uGridLength; + gridPointV[i] -= vVector[i] * vMult * vGridLength; + gridPointFarest[i] -= uVector[i] * uMult * uGridLength + vVector[i] * vMult * vGridLength; + } + + // - Add the initial shift if any + double axisShift = (this->MajorRangeStart - this->Range[0])*rangeScale; + for (int i = 0;i<3;i++) + { + gridPointU[i] += axisVector[i] * axisShift; + gridPointV[i] += axisVector[i] * axisShift; + gridPointFarest[i] += axisVector[i] * axisShift; + gridPointClosest[i] += axisVector[i] * axisShift; + } + + // - Insert Gridlines points along the axis using the DeltaMajor vector + double nbIterationAsDouble = (axisLength - axisShift) / vtkMath::Norm(deltaVector); + int nbIteration = vtkMath::Floor(nbIterationAsDouble + 2*FLT_EPSILON) + 1; + nbIteration = (nbIteration < VTK_MAX_TICKS) ? nbIteration : VTK_MAX_TICKS; + for (int nbTicks = 0; nbTicks < nbIteration; nbTicks++) + { // Closest U this->GridlinePts->InsertNextPoint(gridPointClosest); this->GridlinePts->InsertNextPoint(gridPointU); @@ -2161,7 +2745,7 @@ bool vtkAxisActor::BuildTickPoints(double p1[3], double p2[3], bool force) this->GridpolyPts->InsertNextPoint(gridPointV); // Move forward along the axis - for(i=0;i<3;i++) + for (int i = 0;i<3;i++) { gridPointClosest[i] += deltaVector[i]; gridPointU[i] += deltaVector[i]; @@ -2175,67 +2759,196 @@ bool vtkAxisActor::BuildTickPoints(double p1[3], double p2[3], bool force) // We can only handle inner grid line with orthonormal base, otherwise // we would need to change the API of AxisActor which we don't want for // backward compatibility. - if(hasOrthogonalVectorBase) + if (hasOrthogonalVectorBase) { double axis, u, v; axis = this->MajorStart[this->AxisType]; innerGridPointClosestU[vIndex] = this->GetBounds()[vIndex*2]; - innerGridPointFarestU[vIndex] = this->GetBounds()[vIndex*2+1]; + innerGridPointFarestU[vIndex] = this->GetBounds()[vIndex*2 + 1]; innerGridPointClosestV[uIndex] = this->GetBounds()[uIndex*2]; - innerGridPointFarestV[uIndex] = this->GetBounds()[uIndex*2+1]; + innerGridPointFarestV[uIndex] = this->GetBounds()[uIndex*2 + 1]; while (axis <= p2[this->AxisType]) + { + innerGridPointClosestU[this->AxisType] + = innerGridPointClosestV[this->AxisType] + = innerGridPointFarestU[this->AxisType] + = innerGridPointFarestV[this->AxisType] + = axis; + + // u lines + u = this->MajorStart[uIndex]; + while (u <= p2[uIndex] && this->DeltaMajor[uIndex] > 0) { - innerGridPointClosestU[this->AxisType] - = innerGridPointClosestV[this->AxisType] - = innerGridPointFarestU[this->AxisType] - = innerGridPointFarestV[this->AxisType] - = axis; - - // u lines - u = this->MajorStart[uIndex]; - while (u <= p2[uIndex] && this->DeltaMajor[uIndex] > 0) - { - innerGridPointClosestU[uIndex] - = innerGridPointFarestU[uIndex] - = u; - this->InnerGridlinePts->InsertNextPoint(innerGridPointClosestU); - this->InnerGridlinePts->InsertNextPoint(innerGridPointFarestU); - u += this->DeltaMajor[uIndex]; - } - - // v lines - v = this->MajorStart[vIndex]; - while (v <= p2[vIndex] && this->DeltaMajor[vIndex] > 0) - { - innerGridPointClosestV[vIndex] - = innerGridPointFarestV[vIndex] - = v; - this->InnerGridlinePts->InsertNextPoint(innerGridPointClosestV); - this->InnerGridlinePts->InsertNextPoint(innerGridPointFarestV); - v += this->DeltaMajor[vIndex]; - } + innerGridPointClosestU[uIndex] = innerGridPointFarestU[uIndex] = u; + this->InnerGridlinePts->InsertNextPoint(innerGridPointClosestU); + this->InnerGridlinePts->InsertNextPoint(innerGridPointFarestU); + u += this->DeltaMajor[uIndex]; + } - axis += this->DeltaMajor[this->AxisType]; + // v lines + v = this->MajorStart[vIndex]; + while (v <= p2[vIndex] && this->DeltaMajor[vIndex] > 0) + { + innerGridPointClosestV[vIndex] = innerGridPointFarestV[vIndex] = v; + this->InnerGridlinePts->InsertNextPoint(innerGridPointClosestV); + this->InnerGridlinePts->InsertNextPoint(innerGridPointFarestV); + v += this->DeltaMajor[vIndex]; } + + axis += this->DeltaMajor[this->AxisType]; + } } - } - // ************************************************************************** - // Build Major ticks - // ************************************************************************** - { +} + +//----------------------------------------------------------------------------- +void vtkAxisActor::BuildMinorTicks(double p1[3], double p2[3], double localCoordSys[3][3]) +{ + // (p2 - p1) vector + double deltaVector[3]; + + // inside point: point shifted toward x,y,z direction + // outside points: point shifted toward -x,-y,-z direction + double vPointInside[3], vPointOutside[3], uPointInside[3], uPointOutside[3]; + + int uMult = vtkAxisActorMultiplierTable1[this->AxisPosition]; + int vMult = vtkAxisActorMultiplierTable2[this->AxisPosition]; + + double* axisVector = localCoordSys[0]; + double* uVector = localCoordSys[1]; + double* vVector = localCoordSys[2]; + + // - Initialize all points to be on the axis + for (int i = 0;i<3;i++) + { + uPointInside[i] = vPointInside[i] = uPointOutside[i] = vPointOutside[i] = p1[i]; + deltaVector[i] = (p2[i] - p1[i]); + } + + double axisLength = vtkMath::Norm(deltaVector); + double rangeScale = axisLength / (this->Range[1] - this->Range[0]); + + // - Move outside points if needed (Axis -> Outside) + if (this->TickLocation == VTK_TICKS_OUTSIDE || this->TickLocation == VTK_TICKS_BOTH) + { + for (int i = 0;i<3;i++) + { + uPointOutside[i] += uVector[i] * uMult * this->MinorTickSize; + vPointOutside[i] += vVector[i] * vMult * this->MinorTickSize; + } + } + + // - Move inside points if needed (Axis -> Inside) + if (this->TickLocation == VTK_TICKS_INSIDE || this->TickLocation == VTK_TICKS_BOTH) + { + for (int i = 0;i<3;i++) + { + uPointInside[i] -= uVector[i] * uMult * this->MinorTickSize; + vPointInside[i] -= vVector[i] * vMult * this->MinorTickSize; + } + } + + // - Add the initial shift if any + double axisShift = (this->MinorRangeStart - this->Range[0])*rangeScale; + axisLength -= axisShift; + for (int i = 0;i<3;i++) + { + uPointInside[i] += axisVector[i] * axisShift; + vPointInside[i] += axisVector[i] * axisShift; + uPointOutside[i] += axisVector[i] * axisShift; + vPointOutside[i] += axisVector[i] * axisShift; + } + + // - Reduce the deltaVector to correspond to a tick step + vtkMath::Normalize(deltaVector); + double deltaMinor = this->DeltaRangeMinor * rangeScale; + + if (deltaMinor <= 0.0) + { + return; + } + + // - Insert tick points along the axis using the deltaVector + + // step is a multiple of deltaMajor value + // currentStep as well, except for the last value, it doesn't exceed axisLength + + double step = 0.0, currentStep = 0.0; + double tickPoint[3]; + while (currentStep < axisLength) + { + currentStep = (step > axisLength) ? axisLength : step; + + // axis/u side + for (int i = 0;i<3;i++) + { + tickPoint[i] = deltaVector[i] * currentStep + uPointInside[i]; + } + this->MinorTickPts->InsertNextPoint(tickPoint); + + // axis/u side + for (int i = 0;i<3;i++) + { + tickPoint[i] = deltaVector[i] * currentStep + uPointOutside[i]; + } + this->MinorTickPts->InsertNextPoint(tickPoint); + + // axis/v side + for (int i = 0;i<3;i++) + { + tickPoint[i] = deltaVector[i] * currentStep + vPointInside[i]; + } + this->MinorTickPts->InsertNextPoint(tickPoint); + + // axis/v side + for (int i = 0;i<3;i++) + tickPoint[i] = deltaVector[i] * currentStep + vPointOutside[i]; + this->MinorTickPts->InsertNextPoint(tickPoint); + + step += deltaMinor; + } +} + +//----------------------------------------------------------------------------- +void vtkAxisActor::BuildMajorTicks(double p1[3], double p2[3], + double localCoordSys[3][3]) +{ + double deltaVector[3]; + double* axisVector = localCoordSys[0]; + double* uVector = localCoordSys[1]; + double* vVector = localCoordSys[2]; + + // inside point: point shifted toward x,y,z direction + // outside points: point shifted toward -x,-y,-z direction + double vPointInside[3], vPointOutside[3], uPointInside[3], uPointOutside[3]; + + int uMult = vtkAxisActorMultiplierTable1[this->AxisPosition]; + int vMult = vtkAxisActorMultiplierTable2[this->AxisPosition]; + + // init deltaVector + for (int i = 0;i<3;i++) + { + deltaVector[i] = (p2[i] - p1[i]); + } + + double axisLength = vtkMath::Norm(deltaVector); + + //factor of conversion world coord <-> range + double rangeScale = axisLength / (this->Range[1] - this->Range[0]); + // Delta vector is already initialized with the Major tick scale // - Initialize all points to be on the axis - for(i=0;i<3;i++) + for (int i = 0;i<3;i++) { uPointInside[i] = vPointInside[i] = uPointOutside[i] = vPointOutside[i] = p1[i]; + this->TickVector[i] = uVector[i] * uMult * this->MajorTickSize; } // - Move outside points if needed (Axis -> Outside) if (this->TickLocation == VTK_TICKS_OUTSIDE || this->TickLocation == VTK_TICKS_BOTH) { - for(i=0;i<3;i++) + for (int i = 0;i<3;i++) { - uPointOutside[i] += uVector[i] * uMult * this->MajorTickSize; + uPointOutside[i] += this->TickVector[i]; vPointOutside[i] += vVector[i] * vMult * this->MajorTickSize; } } @@ -2243,15 +2956,17 @@ bool vtkAxisActor::BuildTickPoints(double p1[3], double p2[3], bool force) // - Move inside points if needed (Axis -> Inside) if (this->TickLocation == VTK_TICKS_INSIDE || this->TickLocation == VTK_TICKS_BOTH) { - for(i=0;i<3;i++) + for (int i = 0;i<3;i++) { - uPointInside[i] -= uVector[i] * uMult * this->MajorTickSize; + uPointInside[i] -= this->TickVector[i]; vPointInside[i] -= vVector[i] * vMult * this->MajorTickSize; } } // - Add the initial shift if any - for(i=0;i<3;i++) + double axisShift = (this->MajorRangeStart - this->Range[0])*rangeScale; + axisLength -= axisShift; + for (int i = 0;i<3;i++) { uPointInside[i] += axisVector[i] * axisShift; vPointInside[i] += axisVector[i] * axisShift; @@ -2259,24 +2974,333 @@ bool vtkAxisActor::BuildTickPoints(double p1[3], double p2[3], bool force) vPointOutside[i] += axisVector[i] * axisShift; } + // - Reduce the deltaVector to correspond to a major tick step + vtkMath::Normalize(deltaVector); + double deltaMajor = this->DeltaRangeMajor * rangeScale; + + if (deltaMajor <= 0.0) + { + return; + } + // - Insert tick points along the axis using the deltaVector - for (nbTicks = 0; nbTicks < nbIteration; nbTicks++) + + // step is a multiple of deltaMajor value + // currentStep as well, except for the last value, it doesn't exceed axisLength + + double step = 0.0, currentStep = 0.0; + double tickPoint[3]; + while (currentStep < axisLength) { + currentStep = (step > axisLength) ? axisLength : step; + // axis/u side - this->MajorTickPts->InsertNextPoint(uPointInside); - this->MajorTickPts->InsertNextPoint(uPointOutside); - vtkMath::Add(deltaVector, uPointInside, uPointInside); - vtkMath::Add(deltaVector, uPointOutside, uPointOutside); + for (int i = 0;i<3;i++) + tickPoint[i] = deltaVector[i] * currentStep + uPointInside[i]; + this->MajorTickPts->InsertNextPoint(tickPoint); + + // axis/u side + for (int i = 0;i<3;i++) + tickPoint[i] = deltaVector[i] * currentStep + uPointOutside[i]; + this->MajorTickPts->InsertNextPoint(tickPoint); + + // axis/v side + for (int i = 0;i<3;i++) + tickPoint[i] = deltaVector[i] * currentStep + vPointInside[i]; + this->MajorTickPts->InsertNextPoint(tickPoint); // axis/v side - this->MajorTickPts->InsertNextPoint(vPointInside); - this->MajorTickPts->InsertNextPoint(vPointOutside); - vtkMath::Add(deltaVector, vPointInside, vPointInside); - vtkMath::Add(deltaVector, vPointOutside, vPointOutside); + for (int i = 0;i<3;i++) + tickPoint[i] = deltaVector[i] * currentStep + vPointOutside[i]; + this->MajorTickPts->InsertNextPoint(tickPoint); + + step += deltaMajor; } - } +} - this->BuildTickPointsTime.Modified(); - this->LastTickLocation = this->TickLocation; - return true; +//----------------------------------------------------------------------------- +void vtkAxisActor::BuildMinorTicksLog(double p1[3], double p2[3], + double localCoordSys[3][3]) +{ + double deltaVector[3]; + + double* axisVector = localCoordSys[0]; + double* uVector = localCoordSys[1]; + double* vVector = localCoordSys[2]; + + // inside point: point shifted toward x,y,z direction + // outside points: point shifted toward -x,-y,-z direction + double uPointInside[3], vPointInside[3], uPointOutside[3], vPointOutside[3]; + + for (int i = 0; i<3; i++) + { + uPointInside[i] = vPointInside[i] = uPointOutside[i] = vPointOutside[i] = p1[i]; + deltaVector[i] = (p2[i] - p1[i]); + } + + double axisLength = vtkMath::Norm(deltaVector); + + //factor of conversion world coord <-> range + double rangeScale = axisLength / log10(this->Range[1] / this->Range[0]); + + vtkMath::Normalize(deltaVector); + + int uMult = vtkAxisActorMultiplierTable1[this->AxisPosition]; + int vMult = vtkAxisActorMultiplierTable2[this->AxisPosition]; + // - Move outside points if needed (Axis -> Outside) + if (this->TickLocation == VTK_TICKS_OUTSIDE || this->TickLocation == VTK_TICKS_BOTH) + { + for (int i = 0;i<3;i++) + { + uPointOutside[i] += uVector[i] * uMult * this->MinorTickSize; + vPointOutside[i] += vVector[i] * vMult * this->MinorTickSize; + } + } + + // - Move inside points if needed (Axis -> Inside) + if (this->TickLocation == VTK_TICKS_INSIDE || this->TickLocation == VTK_TICKS_BOTH) + { + for (int i = 0;i<3;i++) + { + uPointInside[i] -= uVector[i] * uMult * this->MinorTickSize; + vPointInside[i] -= vVector[i] * vMult * this->MinorTickSize; + } + } + + // - Add the initial shift if any + double axisShift = log10(this->MinorRangeStart / this->Range[0])*rangeScale; + axisLength -= axisShift; + for (int i = 0;i<3;i++) + { + uPointInside[i] += axisVector[i] * axisShift; + vPointInside[i] += axisVector[i] * axisShift; + uPointOutside[i] += axisVector[i] * axisShift; + vPointOutside[i] += axisVector[i] * axisShift; + } + + double base = 10.0, index; + double step, tickRangeVal, tickVal; + + //pre set values + double log10Range0 = log10(this->Range[0]), log10Range1 = log10(this->Range[1]); + double lowBound = pow(base, floor(log10Range0)), upBound = pow(base, ceil(log10Range1)); + + double minorTickPoint[3], minorTickOnAxis[3]; + + // step match the minor tick log step, varying between each major tick. + // for log10: minor step is 0.1 between 0.1 and 1.0, then 1.0 between 1.0 and 10.0, and so on + for (step = lowBound; step < upBound; step *= base) + { + // number of minor tick between two major tick. for log10, index goes to 2.0 to 9.0 + for (index = 2.0; index < base; index += 1.0) + { + tickRangeVal = index * step; + + // particular cases: + if (tickRangeVal <= Range[0]) + { + continue; + } + + // over upper bound + if (tickRangeVal >= Range[1]) + { + break; + } + + tickVal = (log10(tickRangeVal) - log10Range0)*rangeScale; + + //set tick point on axis (not inserted) + for (int i = 0; i<3; i++) + { + minorTickOnAxis[i] = deltaVector[i]*(tickVal); + } + //vtkMath::Add(minorTickOnAxis, p1, minorTickOnAxis); // handled later + + //u inside point + vtkMath::Add(minorTickOnAxis, uPointInside, minorTickPoint); + this->MinorTickPts->InsertNextPoint(minorTickPoint); + + //u outside point + vtkMath::Add(minorTickOnAxis, uPointOutside, minorTickPoint); + this->MinorTickPts->InsertNextPoint(minorTickPoint); + + if (this->Use2DMode == 0) + { + //v inside point + vtkMath::Add(minorTickOnAxis, vPointInside, minorTickPoint); + this->MinorTickPts->InsertNextPoint(minorTickPoint); + + //v outside point + vtkMath::Add(minorTickOnAxis, vPointOutside, minorTickPoint); + this->MinorTickPts->InsertNextPoint(minorTickPoint); + } + } + } +} + +//----------------------------------------------------------------------------- +void vtkAxisActor::BuildMajorTicksLog(double p1[3], double p2[3], double localCoordSys[3][3]) +{ + double deltaVector[3]; + + double* axisVector = localCoordSys[0]; + double* uVector = localCoordSys[1]; + double* vVector = localCoordSys[2]; + + // inside point: point shifted toward x,y,z direction + // outside points: point shifted toward -x,-y,-z direction + double vPointInside[3], vPointOutside[3], uPointInside[3], uPointOutside[3]; + + for (int i = 0; i<3; i++) + { + uPointInside[i] = vPointInside[i] = uPointOutside[i] = vPointOutside[i] = p1[i]; + deltaVector[i] = (p2[i] - p1[i]); + } + + // length of axis (wold coord system) + double axisLength = vtkMath::Norm(deltaVector); + + //factor of conversion world coord <-> range + double rangeScale = axisLength / log10(this->Range[1] / this->Range[0]); + + vtkMath::Normalize(deltaVector); + + int uMult = vtkAxisActorMultiplierTable1[this->AxisPosition]; + int vMult = vtkAxisActorMultiplierTable2[this->AxisPosition]; + + for (int i = 0;i<3;i++) + { + this->TickVector[i] = uVector[i] * uMult * this->MajorTickSize; + } + + // - Move outside points if needed (Axis -> Outside) + if (this->TickLocation == VTK_TICKS_OUTSIDE || this->TickLocation == VTK_TICKS_BOTH) + { + for (int i = 0;i<3;i++) + { + uPointOutside[i] += this->TickVector[i]; + vPointOutside[i] += vVector[i] * vMult * this->MajorTickSize; + } + } + + // - Move inside points if needed (Axis -> Inside) + if (this->TickLocation == VTK_TICKS_INSIDE || this->TickLocation == VTK_TICKS_BOTH) + { + for (int i = 0;i<3;i++) + { + uPointInside[i] -= this->TickVector[i]; + vPointInside[i] -= vVector[i] * vMult * this->MajorTickSize; + } + } + + // - Add the initial shift if any + double axisShift = log10(this->MajorRangeStart / this->Range[0])*rangeScale; + axisLength -= axisShift; + for (int i = 0;i<3;i++) + { + uPointInside[i] += axisVector[i] * axisShift; + vPointInside[i] += axisVector[i] * axisShift; + uPointOutside[i] += axisVector[i] * axisShift; + vPointOutside[i] += axisVector[i] * axisShift; + } + + double base = 10.0; + double indexTickRangeValue; + double tickVal, tickRangeVal; + double log10Range0 = log10(this->Range[0]), log10Range1 = log10(this->Range[1]); + double lowBound = pow(base, (int)floor(log10Range0)), upBound = pow(base, (int)ceil(log10Range1)); + + double majorTickOnAxis[3], majorTickPoint[3]; + for (indexTickRangeValue = lowBound; indexTickRangeValue <= upBound; indexTickRangeValue *= base) + { + tickRangeVal = indexTickRangeValue; + + if (indexTickRangeValue < this->Range[0]) + { + tickRangeVal = this->Range[0]; + } + else if (indexTickRangeValue > this->Range[1]) + { + tickRangeVal = this->Range[1]; + } + + tickVal = (log10(tickRangeVal) - log10Range0)*rangeScale; + + for (int i = 0; i<3; i++) + { + majorTickOnAxis[i] = deltaVector[i]*tickVal; + } + + //u inside point + vtkMath::Add(majorTickOnAxis, uPointInside, majorTickPoint); + this->MajorTickPts->InsertNextPoint(majorTickPoint); + + //u outside point + vtkMath::Add(majorTickOnAxis, uPointOutside, majorTickPoint); + this->MajorTickPts->InsertNextPoint(majorTickPoint); + + //v inside point + vtkMath::Add(majorTickOnAxis, vPointInside, majorTickPoint); + this->MajorTickPts->InsertNextPoint(majorTickPoint); + + //v outside point + vtkMath::Add(majorTickOnAxis, vPointOutside, majorTickPoint); + this->MajorTickPts->InsertNextPoint(majorTickPoint); + } +} + +//----------------------------------------------------------------------------- +void vtkAxisActor::RotateActor2DFromAxisProjection(vtkTextActor* pActor2D) +{ + double *p1 = this->Point1Coordinate->GetValue(); + double *p2 = this->Point2Coordinate->GetValue(); + + vtkMatrix4x4* matModelView = this->Camera->GetModelViewTransformMatrix(); + double near = this->Camera->GetClippingRange()[0]; + + // Need view coordinate points. + double viewPt1[4] = {p1[0], p1[1], p1[2], 1.0}; + double viewPt2[4] = {p2[0], p2[1], p2[2], 1.0}; + + matModelView->MultiplyPoint(viewPt1, viewPt1); + matModelView->MultiplyPoint(viewPt2, viewPt2); + + if (viewPt1[2] == 0.0 || viewPt2[2] == 0.0) + { + return; + } + + double p1Pjt[3] = { -near* viewPt1[0] / viewPt1[2], -near* viewPt1[1] / viewPt1[2], -near}; + double p2Pjt[3] = { -near* viewPt2[0] / viewPt2[2], -near* viewPt2[1] / viewPt2[2], -near}; + + double axisOnScreen[2] = {p2Pjt[0] - p1Pjt[0], p2Pjt[1] - p1Pjt[1]}; + double x[2] = {1.0, 0.0}, y[2] = {0.0, 1.0}; + + double dotProd = vtkMath::Dot2D(x, axisOnScreen); + + double orient = 0.0; + if (vtkMath::Norm2D(axisOnScreen) == 0.0) + { + pActor2D->SetOrientation(0.0); + return; + } + else + { + orient = acos(dotProd / vtkMath::Norm2D(axisOnScreen)); + orient = vtkMath::DegreesFromRadians(orient); + } + + // adjust angle + if (vtkMath::Dot2D(y, axisOnScreen) < 0.0) + { + orient *= -1.0; + } + + if (vtkMath::Dot2D(x, axisOnScreen) < 0.0) + { + orient += 180.0; + } + + pActor2D->SetOrientation(orient); } diff --git a/Rendering/Annotation/vtkAxisActor.h b/Rendering/Annotation/vtkAxisActor.h index b61aaa4bec7..fe9f4231b67 100644 --- a/Rendering/Annotation/vtkAxisActor.h +++ b/Rendering/Annotation/vtkAxisActor.h @@ -1,5 +1,4 @@ /*========================================================================= - Program: Visualization Toolkit Module: vtkAxisActor.h Language: C++ @@ -40,7 +39,7 @@ PURPOSE. See the above copyright notice for more information. // Eric Brugger, Claire Guilbaud, Nicolas Dolegieviez, Will Schroeder, // Karthik Krishnan, Aashish Chaudhary, Philippe Pebay, David Gobbi, // David Partyka, Utkarsh Ayachit David Cole, Francois Bertel, and Mark Olesen -// Part of this work was supported by CEA/DIF - Commissariat a l'Energie Atomique, +// Part of this work was supported by CEA/DIF - Commissariat a l'Energie Atomique, // Centre DAM Ile-De-France, BP12, F-91297 Arpajon, France. // // .SECTION See Also @@ -69,8 +68,8 @@ class vtkVectorText; class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor { - public: - vtkTypeMacro(vtkAxisActor,vtkActor); +public: + vtkTypeMacro(vtkAxisActor, vtkActor); void PrintSelf(ostream& os, vtkIndent indent); // Description: @@ -81,7 +80,7 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor // Specify the position of the first point defining the axis. virtual vtkCoordinate *GetPoint1Coordinate(); virtual void SetPoint1(double x[3]) - { this->SetPoint1(x[0], x[1], x[2]); } + { this->SetPoint1(x[0], x[1], x[2]); } virtual void SetPoint1(double x, double y, double z); virtual double *GetPoint1(); @@ -89,15 +88,15 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor // Specify the position of the second point defining the axis. virtual vtkCoordinate *GetPoint2Coordinate(); virtual void SetPoint2(double x[3]) - { this->SetPoint2(x[0], x[1], x[2]); } + { this->SetPoint2(x[0], x[1], x[2]); } virtual void SetPoint2(double x, double y, double z); virtual double *GetPoint2(); // Description: // Specify the (min,max) axis range. This will be used in the generation // of labels, if labels are visible. - vtkSetVector2Macro(Range,double); - vtkGetVectorMacro(Range,double,2); + vtkSetVector2Macro(Range, double); + vtkGetVectorMacro(Range, double, 2); // Description: // Set or get the bounds for this Actor as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). @@ -131,6 +130,11 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor void SetTitle(const char *t); vtkGetStringMacro(Title); + // Description: + // Set/Get the common exponent of the labels values + void SetExponent(const char *t); + vtkGetStringMacro(Exponent); + // Description: // Set/Get the size of the major tick marks vtkSetMacro(MajorTickSize, double); @@ -142,23 +146,25 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkGetMacro(MinorTickSize, double); enum TickLocation - { + { VTK_TICKS_INSIDE = 0, VTK_TICKS_OUTSIDE = 1, VTK_TICKS_BOTH = 2 - }; + }; // Description: // Set/Get the location of the ticks. + // Inside: tick end toward positive direction of perpendicular axes. + // Outside: tick end toward negative direction of perpendicular axes. vtkSetClampMacro(TickLocation, int, VTK_TICKS_INSIDE, VTK_TICKS_BOTH); vtkGetMacro(TickLocation, int); void SetTickLocationToInside(void) - { this->SetTickLocation(VTK_TICKS_INSIDE); }; + { this->SetTickLocation(VTK_TICKS_INSIDE); }; void SetTickLocationToOutside(void) - { this->SetTickLocation(VTK_TICKS_OUTSIDE); }; + { this->SetTickLocation(VTK_TICKS_OUTSIDE); }; void SetTickLocationToBoth(void) - { this->SetTickLocation(VTK_TICKS_BOTH); }; + { this->SetTickLocation(VTK_TICKS_BOTH); }; // Description: // Set/Get visibility of the axis line. @@ -167,7 +173,7 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkBooleanMacro(AxisVisibility, int); // Description: - // Set/Get visibility of the axis tick marks. + // Set/Get visibility of the axis major tick marks. vtkSetMacro(TickVisibility, int); vtkGetMacro(TickVisibility, int); vtkBooleanMacro(TickVisibility, int); @@ -184,21 +190,62 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkGetMacro(TitleVisibility, int); vtkBooleanMacro(TitleVisibility, int); + // Description: + // Set/Get visibility of the axis detached exponent. + vtkSetMacro(ExponentVisibility, bool); + vtkGetMacro(ExponentVisibility, bool); + vtkBooleanMacro(ExponentVisibility, bool); + + enum AlignLocation + { + VTK_ALIGN_TOP = 0, + VTK_ALIGN_BOTTOM = 1, + VTK_ALIGN_POINT1 = 2, + VTK_ALIGN_POINT2 = 3 + }; + + // Description: + // Get/Set the alignement of the title related to the axis. + // Possible Alignment: VTK_ALIGN_TOP, VTK_ALIGN_BOTTOM, VTK_ALIGN_POINT1, VTK_ALIGN_POINT2 + vtkSetClampMacro(TitleAlignLocation, int, VTK_ALIGN_TOP, VTK_ALIGN_POINT2); + vtkGetMacro(TitleAlignLocation, int); + + // Description: + // Get/Set the location of the Detached Exponent related to the axis. + // Possible Location: VTK_ALIGN_TOP, VTK_ALIGN_BOTTOM, VTK_ALIGN_POINT1, VTK_ALIGN_POINT2 + vtkSetClampMacro(ExponentLocation, int, VTK_ALIGN_TOP, VTK_ALIGN_POINT2); + vtkGetMacro(ExponentLocation, int); + // Description: // Set/Get the axis title text property. virtual void SetTitleTextProperty(vtkTextProperty *p); - vtkGetObjectMacro(TitleTextProperty,vtkTextProperty); + vtkGetObjectMacro(TitleTextProperty, vtkTextProperty); // Description: // Set/Get the axis labels text property. virtual void SetLabelTextProperty(vtkTextProperty *p); - vtkGetObjectMacro(LabelTextProperty,vtkTextProperty); + vtkGetObjectMacro(LabelTextProperty, vtkTextProperty); // Description: - // Get/Set axis actor property (axis and its ticks) + // Get/Set axis actor property (axis and its ticks) (kept for compatibility) void SetAxisLinesProperty(vtkProperty *); vtkProperty* GetAxisLinesProperty(); + // Description: + // Get/Set main line axis actor property + void SetAxisMainLineProperty(vtkProperty *); + vtkProperty* GetAxisMainLineProperty(); + + // Description: + // Get/Set axis actor property (axis and its ticks) + void SetAxisMajorTicksProperty(vtkProperty *); + vtkProperty* GetAxisMajorTicksProperty(); + + // Description: + // Get/Set axis actor property (axis and its ticks) + void SetAxisMinorTicksProperty(vtkProperty *); + vtkProperty* GetAxisMinorTicksProperty(); + // Description: // Get/Set gridlines actor property (outer grid lines) void SetGridlinesProperty(vtkProperty *); @@ -253,11 +300,11 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkBooleanMacro(DrawGridpolys, int); enum AxisType - { + { VTK_AXIS_TYPE_X = 0, VTK_AXIS_TYPE_Y = 1, VTK_AXIS_TYPE_Z = 2 - }; + }; // Description: // Set/Get the type of this axis. @@ -268,12 +315,18 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor void SetAxisTypeToZ(void) { this->SetAxisType(VTK_AXIS_TYPE_Z); }; enum AxisPosition - { + { VTK_AXIS_POS_MINMIN = 0, VTK_AXIS_POS_MINMAX = 1, VTK_AXIS_POS_MAXMAX = 2, VTK_AXIS_POS_MAXMIN = 3 - }; + }; + + // Description: + // Set/Get The type of scale, enable logarithmic scale or linear by default + vtkSetMacro(Log, bool); + vtkGetMacro(Log, bool); + vtkBooleanMacro(Log, bool); // Description: // Set/Get the position of this axis (in relation to an an @@ -286,13 +339,13 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkGetMacro(AxisPosition, int); void SetAxisPositionToMinMin(void) - { this->SetAxisPosition(VTK_AXIS_POS_MINMIN); }; + { this->SetAxisPosition(VTK_AXIS_POS_MINMIN); }; void SetAxisPositionToMinMax(void) - { this->SetAxisPosition(VTK_AXIS_POS_MINMAX); }; + { this->SetAxisPosition(VTK_AXIS_POS_MINMAX); }; void SetAxisPositionToMaxMax(void) - { this->SetAxisPosition(VTK_AXIS_POS_MAXMAX); }; + { this->SetAxisPosition(VTK_AXIS_POS_MAXMAX); }; void SetAxisPositionToMaxMin(void) - { this->SetAxisPosition(VTK_AXIS_POS_MAXMIN); }; + { this->SetAxisPosition(VTK_AXIS_POS_MAXMIN); }; // Description: // Set/Get the camera for this axis. The camera is used by the @@ -314,10 +367,9 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor // resources to release. void ReleaseGraphicsResources(vtkWindow *); -//BTX double ComputeMaxLabelLength(const double [3]); double ComputeTitleLength(const double [3]); -//ETX + void SetLabelScale(const double scale); void SetLabelScale(int labelIndex, const double scale); void SetTitleScale(const double scale); @@ -328,13 +380,13 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkSetMacro(MinorStart, double); vtkGetMacro(MinorStart, double); double GetMajorStart(int axis); - void SetMajorStart(int axis,double value); + void SetMajorStart(int axis, double value); //vtkSetMacro(MajorStart, double); //vtkGetMacro(MajorStart, double); vtkSetMacro(DeltaMinor, double); vtkGetMacro(DeltaMinor, double); double GetDeltaMajor(int axis); - void SetDeltaMajor(int axis,double value); + void SetDeltaMajor(int axis, double value); //vtkSetMacro(DeltaMajor, double); //vtkGetMacro(DeltaMajor, double); @@ -352,17 +404,18 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkSetMacro(DeltaRangeMajor, double); vtkGetMacro(DeltaRangeMajor, double); -//BTX void SetLabels(vtkStringArray *labels); -//ETX void BuildAxis(vtkViewport *viewport, bool); -//BTX // Description: // Get title actor and it is responsible for drawing // title text. - vtkGetObjectMacro(TitleActor, vtkAxisFollower); + vtkGetObjectMacro(TitleActor, vtkAxisFollower); + + // Description: + // Get exponent follower actor + vtkGetObjectMacro(ExponentActor, vtkAxisFollower); // Description: // Get label actors responsigle for drawing label text. @@ -374,7 +427,7 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor // Description: // Get title actor and it is responsible for drawing // title text. - vtkGetObjectMacro(TitleProp3D, vtkProp3DAxisFollower); + vtkGetObjectMacro(TitleProp3D, vtkProp3DAxisFollower); // Description: // Get label actors responsigle for drawing label text. @@ -382,7 +435,11 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor { return this->LabelProps3D; } -//ETX + + // Description: + // Get title actor and it is responsible for drawing + // title text. + vtkGetObjectMacro(ExponentProp3D, vtkProp3DAxisFollower); // Description: // Get total number of labels built. Once built @@ -440,8 +497,8 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor // Description: // Notify the axes that is not part of a cube anymore - vtkSetMacro(AxisOnOrigin,int); - vtkGetMacro(AxisOnOrigin,int); + vtkSetMacro(AxisOnOrigin, int); + vtkGetMacro(AxisOnOrigin, int); // Description: // Set/Get the offsets used to position texts. @@ -449,14 +506,17 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkGetMacro(LabelOffset, double); vtkSetMacro(TitleOffset, double); vtkGetMacro(TitleOffset, double); + vtkSetMacro(ExponentOffset, double); + vtkGetMacro(ExponentOffset, double); vtkSetMacro(ScreenSize, double); vtkGetMacro(ScreenSize, double); - protected: +protected: vtkAxisActor(); ~vtkAxisActor(); char *Title; + char *Exponent; double Range[2]; double LastRange[2]; char *LabelFormat; @@ -464,8 +524,23 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor int NumberOfLabelsBuilt; int MinorTicksVisible; int LastMinorTicksVisible; + + // Description: + // The location of the ticks. + // Inside: tick end toward positive direction of perpendicular axes. + // Outside: tick end toward negative direction of perpendicular axes. int TickLocation; + // Description: + // Hold the alignement property of the title related to the axis. + // Possible Alignment: VTK_ALIGN_BOTTOM, VTK_ALIGN_TOP, VTK_ALIGN_POINT1, VTK_ALIGN_POINT2. + int TitleAlignLocation; + + // Description: + // Hold the alignement property of the exponent coming from the label values. + // Possible Alignment: VTK_ALIGN_BOTTOM, VTK_ALIGN_TOP, VTK_ALIGN_POINT1, VTK_ALIGN_POINT2. + int ExponentLocation; + int DrawGridlines; int DrawGridlinesOnly; int LastDrawGridlines; @@ -486,16 +561,19 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor int LastTickVisibility; int LabelVisibility; int TitleVisibility; + bool ExponentVisibility; + bool Log; int AxisType; int AxisPosition; - double Bounds[6]; + double Bounds[6]; + // coordinate system for axisAxtor, relative to world coordinates double AxisBaseForX[3]; double AxisBaseForY[3]; double AxisBaseForZ[3]; - private: +private: vtkAxisActor(const vtkAxisActor&); // Not implemented void operator=(const vtkAxisActor&); // Not implemented @@ -506,12 +584,50 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor void SetLabelPositions(vtkViewport *, bool); void SetLabelPositions2D(vtkViewport *, bool); + // Description: + // Set orientation of the actor 2D (follower) to keep the axis orientation and stay on the right size + void RotateActor2DFromAxisProjection(vtkTextActor* pActor2D); + + // Description: + // Init the geometry of the title. (no positioning or orientation) + void InitTitle(); + + // Description: + // Init the geometry of the common exponent of the labels values. (no positioning or orientation) + void InitExponent(); + + // Description: + // This methdod set the text and set the base position of the follower from the axis + // The position will be modified in vtkAxisFollower::Render() sub-functions according to the camera position + // for convenience purpose. void BuildTitle(bool); + + // Description: + // Build the actor to display the exponent in case it should appear next to the title or next to p2 coordinate. + void BuildExponent(bool force); + + void BuildExponent2D(vtkViewport *viewport, bool force); + void BuildTitle2D(vtkViewport *viewport, bool); void SetAxisPointsAndLines(void); + bool BuildTickPoints(double p1[3], double p2[3], bool force); + // Build major ticks for linear scale. + void BuildMajorTicks(double p1[3], double p2[3], double localCoordSys[3][3]); + + // Build major ticks for logarithmic scale. + void BuildMajorTicksLog(double p1[3], double p2[3], double localCoordSys[3][3]); + + // Build minor ticks for linear scale. + void BuildMinorTicks(double p1[3], double p2[3], double localCoordSys[3][3]); + + // Build minor ticks for logarithmic scale enabled + void BuildMinorTicksLog(double p1[3], double p2[3], double localCoordSys[3][3]); + + void BuildAxisGridLines(double p1[3], double p2[3], double localCoordSys[3][3]); + bool TickVisibilityChanged(void); vtkProperty *NewTitleProperty(); vtkProperty2D *NewTitleProperty2D(); @@ -534,7 +650,13 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor // For the ticks, w.r.t to the set range double MajorRangeStart; double MinorRangeStart; + + // Description: + // step between 2 minor ticks, in range value (values displayed on the axis) double DeltaRangeMinor; + + // Description: + // step between 2 major ticks, in range value (values displayed on the axis) double DeltaRangeMajor; int LastAxisPosition; @@ -556,6 +678,15 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkTextActor3D *TitleActor3D; vtkTextProperty *TitleTextProperty; + // Description: + // Mapper/Actor used to display a common exponent of the label values + vtkVectorText *ExponentVector; + vtkPolyDataMapper *ExponentMapper; + vtkAxisFollower *ExponentActor; + vtkTextActor *ExponentActor2D; + vtkProp3DAxisFollower *ExponentProp3D; + vtkTextActor3D *ExponentActor3D; + vtkVectorText **LabelVectors; vtkPolyDataMapper **LabelMappers; vtkAxisFollower **LabelActors; @@ -564,9 +695,16 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkTextActor3D **LabelActors3D; vtkTextProperty *LabelTextProperty; + // Main line axis vtkPolyData *AxisLines; vtkPolyDataMapper *AxisLinesMapper; vtkActor *AxisLinesActor; + + // Ticks of the axis + vtkPolyData *AxisMajorTicks, *AxisMinorTicks; + vtkPolyDataMapper *AxisMajorTicksMapper, *AxisMinorTicksMapper; + vtkActor *AxisMajorTicksActor, *AxisMinorTicksActor; + vtkPolyData *Gridlines; vtkPolyDataMapper *GridlinesMapper; vtkActor *GridlinesActor; @@ -583,6 +721,7 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor vtkTimeStamp BoundsTime; vtkTimeStamp LabelBuildTime; vtkTimeStamp TitleTextTime; + vtkTimeStamp ExponentTextTime; int AxisOnOrigin; @@ -610,24 +749,26 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor : public vtkActor // val = 0 : no need to save position (doesn't stick actors in a position) // val = 1 : positions have to be saved during the next render pass // val = 2 : positions are saved; use them - int SaveTitlePosition; + int SaveTitlePosition; // Description: // Constant position for the title (used in 2D mode only) - double TitleConstantPosition[2]; + double TitleConstantPosition[2]; // Description: // True if the 2D title has to be built, false otherwise bool NeedBuild2D; - double LastMinDisplayCoordinate[3]; - double LastMaxDisplayCoordinate[3]; + double LastMinDisplayCoordinate[3]; + double LastMaxDisplayCoordinate[3]; + double TickVector[3]; // Description: // Offsets used to position text. - double ScreenSize; - double LabelOffset; - double TitleOffset; + double ScreenSize; + double LabelOffset; + double TitleOffset; + double ExponentOffset; }; #endif diff --git a/Rendering/Annotation/vtkAxisActor2D.h b/Rendering/Annotation/vtkAxisActor2D.h index da090e707bc..1995fe6433d 100644 --- a/Rendering/Annotation/vtkAxisActor2D.h +++ b/Rendering/Annotation/vtkAxisActor2D.h @@ -291,7 +291,7 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisActor2D : public vtkActor2D // Description: // Specify whether to size the fonts relative to the viewport or relative to - // length of the axis. By default, fonts are resized relative to the axis. + // length of the axis. By default, fonts are resized relative to the viewport. vtkSetMacro(SizeFontRelativeToAxis,int); vtkGetMacro(SizeFontRelativeToAxis,int); vtkBooleanMacro(SizeFontRelativeToAxis,int); diff --git a/Rendering/Annotation/vtkAxisFollower.cxx b/Rendering/Annotation/vtkAxisFollower.cxx index 07284e8b6c6..b053cfcadcd 100644 --- a/Rendering/Annotation/vtkAxisFollower.cxx +++ b/Rendering/Annotation/vtkAxisFollower.cxx @@ -73,7 +73,8 @@ vtkAxisFollower::vtkAxisFollower() : vtkFollower() this->EnableViewAngleLOD = 1; this->ViewAngleLODThreshold = 0.34; - this->ScreenOffset = 10.0; + this->ScreenOffsetVector[0] = 0.0; + this->ScreenOffsetVector[1] = 10.0; this->Axis = NULL; @@ -326,8 +327,10 @@ void vtkAxisFollower::ComputeRotationAndTranlation(vtkRenderer *ren, double tran double rX[3], double rY[3], double rZ[3], vtkAxisActor *axis) { - double autoScaleFactor = - this->AutoScale(ren, this->Camera, this->ScreenOffset, this->Position); + double autoScaleHoriz = + this->AutoScale(ren, this->Camera, this->ScreenOffsetVector[0], this->Position); + double autoScaleVert = + this->AutoScale(ren, this->Camera, this->ScreenOffsetVector[1], this->Position); double dop[3]; this->Camera->GetDirectionOfProjection(dop); @@ -337,11 +340,8 @@ void vtkAxisFollower::ComputeRotationAndTranlation(vtkRenderer *ren, double tran double dotVal = vtkMath::Dot(rZ, dop); - double origRy[3] = {0.0, 0.0, 0.0}; - - origRy[0] = rY[0]; - origRy[1] = rY[1]; - origRy[2] = rY[2]; + double origRx[3] = {rX[0], rX[1], rX[2]}; + double origRy[3] = {rY[0], rY[1], rY[2]}; // NOTE: Basically the idea here is that dotVal will be positive // only when we have projection direction aligned with our z directon @@ -363,26 +363,23 @@ void vtkAxisFollower::ComputeRotationAndTranlation(vtkRenderer *ren, double tran // we compare our vertical vector with these vectors and if it aligns then we // translate in opposite direction. int axisPosition = this->Axis->GetAxisPosition(); + int vertSign; + double vertDotVal1 = vtkMath::Dot(AxisAlignedY[this->Axis->GetAxisType()][axisPosition][0], origRy) ; + double vertDotVal2 = vtkMath::Dot(AxisAlignedY[this->Axis->GetAxisType()][axisPosition][1], origRy) ; - double dotVal1 = vtkMath::Dot(AxisAlignedY[this->Axis->GetAxisType()][axisPosition][0], origRy) ; - double dotVal2 = vtkMath::Dot(AxisAlignedY[this->Axis->GetAxisType()][axisPosition][1], origRy) ; - - if(fabs(dotVal1) > fabs(dotVal2)) + if(fabs(vertDotVal1) > fabs(vertDotVal2)) { - int sign = (dotVal1 > 0 ? -1 : 1); - - translation[0] = origRy[0] * autoScaleFactor * sign; - translation[1] = origRy[1] * autoScaleFactor * sign; - translation[2] = origRy[2] * autoScaleFactor * sign; + vertSign = (vertDotVal1 > 0 ? -1 : 1); } else { - int sign = (dotVal2 > 0 ? -1 : 1); - - translation[0] = origRy[0] * autoScaleFactor * sign; - translation[1] = origRy[1] * autoScaleFactor * sign; - translation[2] = origRy[2] * autoScaleFactor * sign; + vertSign = (vertDotVal2 > 0 ? -1 : 1); } + + int horizSign = this->TextUpsideDown ? -1 : 1; + translation[0] = origRy[0] * autoScaleVert * vertSign + origRx[0] * autoScaleHoriz * horizSign; + translation[1] = origRy[1] * autoScaleVert * vertSign + origRx[1] * autoScaleHoriz * horizSign; + translation[2] = origRy[2] * autoScaleVert * vertSign + origRx[2] * autoScaleHoriz * horizSign; } //---------------------------------------------------------------------- @@ -497,7 +494,7 @@ void vtkAxisFollower::PrintSelf(ostream& os, vtkIndent indent) os << indent << "DistanceLODThreshold: (" << this->DistanceLODThreshold << ")\n"; os << indent << "EnableViewAngleLOD: (" << this->EnableViewAngleLOD << ")\n"; os << indent << "ViewAngleLODThreshold: (" << this->ViewAngleLODThreshold << ")\n"; - os << indent << "ScreenOffset: ("<< this->ScreenOffset << ")\n"; + os << indent << "ScreenOffsetVector: ("<< this->ScreenOffsetVector[0] << " "<< this->ScreenOffsetVector[1] << ")\n"; if ( this->Axis ) { @@ -509,6 +506,18 @@ void vtkAxisFollower::PrintSelf(ostream& os, vtkIndent indent) } } +//---------------------------------------------------------------------- +void vtkAxisFollower::SetScreenOffset(double offset) +{ + this->SetScreenOffsetVector(1, offset); +} + +//---------------------------------------------------------------------- +double vtkAxisFollower::GetScreenOffset() +{ + return this->GetScreenOffsetVector()[1]; +} + //---------------------------------------------------------------------- int vtkAxisFollower::RenderOpaqueGeometry(vtkViewport *vp) { @@ -602,7 +611,7 @@ void vtkAxisFollower::ShallowCopy(vtkProp *prop) this->SetDistanceLODThreshold(f->GetDistanceLODThreshold()); this->SetEnableViewAngleLOD(f->GetEnableViewAngleLOD()); this->SetViewAngleLODThreshold(f->GetViewAngleLODThreshold()); - this->SetScreenOffset(f->GetScreenOffset()); + this->SetScreenOffsetVector(f->GetScreenOffsetVector()); this->SetAxis(f->GetAxis()); } diff --git a/Rendering/Annotation/vtkAxisFollower.h b/Rendering/Annotation/vtkAxisFollower.h index b4330f4dc0e..9004aa96442 100644 --- a/Rendering/Annotation/vtkAxisFollower.h +++ b/Rendering/Annotation/vtkAxisFollower.h @@ -23,7 +23,6 @@ // .SECTION see also // vtkActor vtkFollower vtkCamera vtkAxisActor vtkCubeAxesActor - #ifndef vtkAxisFollower_h #define vtkAxisFollower_h @@ -89,8 +88,15 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisFollower : public vtkFollower // Description: // Set/Get the desired screen offset from the axis. - vtkSetMacro(ScreenOffset, double); - vtkGetMacro(ScreenOffset, double); + // Convenience method, using a zero horizontal offset + double GetScreenOffset(); + void SetScreenOffset(double offset); + + // Description: + // Set/Get the desired screen offset from the axis. + // first component is horizontal, second is vertical. + vtkSetVector2Macro(ScreenOffsetVector, double); + vtkGetVector2Macro(ScreenOffsetVector, double); // Description: // This causes the actor to be rendered. It in turn will render the actor's @@ -123,7 +129,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisFollower : public vtkFollower vtkAxisActor *axis1, double *dop, vtkRenderer *ren); - void ComputeRotationAndTranlation(vtkRenderer *ren, double translation[3], double Rx[3], double Ry[3], double Rz[3], vtkAxisActor *axis); @@ -132,7 +137,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisFollower : public vtkFollower void ComputerAutoCenterTranslation(const double& autoScaleFactor, double translation[3]); - int TestDistanceVisibility(); void ExecuteViewAngleVisibility(double normal[3]); @@ -146,11 +150,10 @@ class VTKRENDERINGANNOTATION_EXPORT vtkAxisFollower : public vtkFollower int EnableViewAngleLOD; double ViewAngleLODThreshold; - double ScreenOffset; + double ScreenOffsetVector[2]; vtkWeakPointer Axis; - private: int TextUpsideDown; diff --git a/Rendering/Annotation/vtkCaptionActor2D.h b/Rendering/Annotation/vtkCaptionActor2D.h index 3e9884cac75..331ee1a5ad9 100644 --- a/Rendering/Annotation/vtkCaptionActor2D.h +++ b/Rendering/Annotation/vtkCaptionActor2D.h @@ -162,7 +162,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkCaptionActor2D : public vtkActor2D vtkGetMacro(AttachEdgeOnly,int); vtkBooleanMacro(AttachEdgeOnly,int); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS. @@ -182,7 +181,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkCaptionActor2D : public vtkActor2D // Description: // Does this prop have some translucent polygonal geometry? virtual int HasTranslucentPolygonalGeometry(); -//ETX protected: vtkCaptionActor2D(); diff --git a/Rendering/Annotation/vtkCubeAxesActor2D.h b/Rendering/Annotation/vtkCubeAxesActor2D.h index 3a084c535b1..fdb41357835 100644 --- a/Rendering/Annotation/vtkCubeAxesActor2D.h +++ b/Rendering/Annotation/vtkCubeAxesActor2D.h @@ -46,10 +46,6 @@ #include "vtkRenderingAnnotationModule.h" // For export macro #include "vtkActor2D.h" -#define VTK_FLY_OUTER_EDGES 0 -#define VTK_FLY_CLOSEST_TRIAD 1 -#define VTK_FLY_NONE 2 - class vtkAlgorithmOutput; class vtkAxisActor2D; class vtkCamera; @@ -137,6 +133,13 @@ class VTKRENDERINGANNOTATION_EXPORT vtkCubeAxesActor2D : public vtkActor2D virtual void SetCamera(vtkCamera*); vtkGetObjectMacro(Camera,vtkCamera); + enum FlyMode + { + VTK_FLY_OUTER_EDGES = 0, + VTK_FLY_CLOSEST_TRIAD = 1, + VTK_FLY_NONE = 2 + }; + // Description: // Specify a mode to control how the axes are drawn: either outer edges // or closest triad to the camera position, or you may also disable flying diff --git a/Rendering/Annotation/vtkGraphAnnotationLayersFilter.cxx b/Rendering/Annotation/vtkGraphAnnotationLayersFilter.cxx index 54b3a6984ae..a99f282132b 100644 --- a/Rendering/Annotation/vtkGraphAnnotationLayersFilter.cxx +++ b/Rendering/Annotation/vtkGraphAnnotationLayersFilter.cxx @@ -188,7 +188,7 @@ int vtkGraphAnnotationLayersFilter::RequestData(vtkInformation *vtkNotUsed(reque { continue; } - vtkIdTypeArray* vertexIds = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* vertexIds = vtkArrayDownCast( selectionNode->GetSelectionList()); // Get points from graph @@ -226,7 +226,7 @@ int vtkGraphAnnotationLayersFilter::RequestData(vtkInformation *vtkNotUsed(reque static_cast(opacity * 255) }; for (vtkIdType i = 0; i < numberOfCells; ++i) { - outColors->InsertNextTupleValue(outColor); + outColors->InsertNextTypedTuple(outColor); } hullPolyData->GetCellData()->AddArray(outColors); outColors->Delete(); diff --git a/Rendering/Annotation/vtkLeaderActor2D.h b/Rendering/Annotation/vtkLeaderActor2D.h index 022bffe9e3d..452404aa9e8 100644 --- a/Rendering/Annotation/vtkLeaderActor2D.h +++ b/Rendering/Annotation/vtkLeaderActor2D.h @@ -91,12 +91,10 @@ class VTKRENDERINGANNOTATION_EXPORT vtkLeaderActor2D : public vtkActor2D vtkSetClampMacro(LabelFactor, double, 0.1, 2.0); vtkGetMacro(LabelFactor, double); -//BTX // Enums defined to support methods for control of arrow placement and // and appearance of arrow heads. enum {VTK_ARROW_NONE=0,VTK_ARROW_POINT1,VTK_ARROW_POINT2,VTK_ARROW_BOTH}; enum {VTK_ARROW_FILLED=0,VTK_ARROW_OPEN,VTK_ARROW_HOLLOW}; -//ETX // Description: // Control whether arrow heads are drawn on the leader. Arrows may be diff --git a/Rendering/Annotation/vtkLegendBoxActor.cxx b/Rendering/Annotation/vtkLegendBoxActor.cxx index 5c1095e9cf6..2a6d5c46d86 100644 --- a/Rendering/Annotation/vtkLegendBoxActor.cxx +++ b/Rendering/Annotation/vtkLegendBoxActor.cxx @@ -545,7 +545,7 @@ double* vtkLegendBoxActor::GetEntryColor(int i) } else { - return vtkDoubleArray::SafeDownCast(this->Colors)->GetPointer(i*3); + return vtkArrayDownCast(this->Colors)->GetPointer(i*3); } } diff --git a/Rendering/Annotation/vtkLegendBoxActor.h b/Rendering/Annotation/vtkLegendBoxActor.h index 611a26892d0..d585ac20556 100644 --- a/Rendering/Annotation/vtkLegendBoxActor.h +++ b/Rendering/Annotation/vtkLegendBoxActor.h @@ -165,7 +165,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkLegendBoxActor : public vtkActor2D // vtkProp method. void ShallowCopy(vtkProp *prop); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS. @@ -185,7 +184,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkLegendBoxActor : public vtkActor2D // Description: // Does this prop have some translucent polygonal geometry? virtual int HasTranslucentPolygonalGeometry(); -//ETX protected: vtkLegendBoxActor(); diff --git a/Rendering/Annotation/vtkLegendScaleActor.cxx b/Rendering/Annotation/vtkLegendScaleActor.cxx index b867a9ce801..3afe84770f2 100644 --- a/Rendering/Annotation/vtkLegendScaleActor.cxx +++ b/Rendering/Annotation/vtkLegendScaleActor.cxx @@ -399,6 +399,7 @@ void vtkLegendScaleActor::BuildRepresentation(vtkViewport *viewport) this->LegendPoints->SetPoint(7, x1+2*delX,20,0); this->LegendPoints->SetPoint(8, x1+3*delX,20,0); this->LegendPoints->SetPoint(9, x1+4*delX,20,0); + this->LegendPoints->Modified(); // Specify the position of the legend title this->LabelActors[5]->SetPosition(0.5*size[0],22); diff --git a/Rendering/Annotation/vtkLegendScaleActor.h b/Rendering/Annotation/vtkLegendScaleActor.h index 9224a063eeb..1a98e1e7064 100644 --- a/Rendering/Annotation/vtkLegendScaleActor.h +++ b/Rendering/Annotation/vtkLegendScaleActor.h @@ -59,13 +59,11 @@ class VTKRENDERINGANNOTATION_EXPORT vtkLegendScaleActor : public vtkProp vtkTypeMacro(vtkLegendScaleActor,vtkProp); void PrintSelf(ostream& os, vtkIndent indent); -//BTX enum AttributeLocation { DISTANCE=0, XY_COORDINATES=1 }; -//ETX // Description: // Specify the mode for labeling the scale axes. By default, the axes are diff --git a/Rendering/Annotation/vtkPolarAxesActor.cxx b/Rendering/Annotation/vtkPolarAxesActor.cxx index fcec99b457e..16c15fa7e22 100644 --- a/Rendering/Annotation/vtkPolarAxesActor.cxx +++ b/Rendering/Annotation/vtkPolarAxesActor.cxx @@ -14,14 +14,15 @@ =========================================================================*/ #include "vtkPolarAxesActor.h" -#include "vtkArcSource.h" -#include "vtkAxisActor.h" #include "vtkAxisFollower.h" #include "vtkCamera.h" #include "vtkCellArray.h" #include "vtkCoordinate.h" +#include "vtkEllipseArcSource.h" #include "vtkFollower.h" #include "vtkMath.h" +#include "vtkMathUtilities.h" +#include "vtkNew.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" @@ -32,17 +33,21 @@ #include -#define VTK_POLAR_AXES_ACTOR_RTOL ( 1. - 10. * VTK_DBL_EPSILON ) +#define VTK_EXPONENT_AXES_ACTOR_RTOL (1. - 10. * VTK_DBL_EPSILON) vtkStandardNewMacro(vtkPolarAxesActor); -vtkCxxSetObjectMacro(vtkPolarAxesActor, Camera,vtkCamera); -vtkCxxSetObjectMacro(vtkPolarAxesActor,PolarAxisLabelTextProperty,vtkTextProperty); -vtkCxxSetObjectMacro(vtkPolarAxesActor,PolarAxisTitleTextProperty,vtkTextProperty); +vtkCxxSetObjectMacro(vtkPolarAxesActor, Camera, vtkCamera); +vtkCxxSetObjectMacro(vtkPolarAxesActor, PolarAxisLabelTextProperty, vtkTextProperty); +vtkCxxSetObjectMacro(vtkPolarAxesActor, PolarAxisTitleTextProperty, vtkTextProperty); +vtkCxxSetObjectMacro(vtkPolarAxesActor, LastRadialAxisTextProperty, vtkTextProperty); +vtkCxxSetObjectMacro(vtkPolarAxesActor, SecondaryRadialAxesTextProperty, vtkTextProperty); +vtkCxxSetObjectMacro(vtkPolarAxesActor, LastRadialAxisProperty, vtkProperty); +vtkCxxSetObjectMacro(vtkPolarAxesActor, SecondaryRadialAxesProperty, vtkProperty); //----------------------------------------------------------------------------- -void vtkPolarAxesActor::PrintSelf( ostream& os, vtkIndent indent ) +void vtkPolarAxesActor::PrintSelf(ostream& os, vtkIndent indent) { - this->Superclass::PrintSelf( os,indent ); + this->Superclass::PrintSelf(os, indent); os << indent << "Bounds: \n"; os << indent << " Xmin,Xmax: (" << this->Bounds[0] << ", " @@ -55,27 +60,34 @@ void vtkPolarAxesActor::PrintSelf( ostream& os, vtkIndent indent ) os << indent << "ScreenSize: " << this->ScreenSize << "\n"; os << indent << "Number Of Radial Axes: " << this->NumberOfRadialAxes << endl; - os << indent << "Number Of Polar Axis Ticks: " << this->NumberOfPolarAxisTicks << endl; - os << indent << "Auto Subdivide Polar Axis: " - << ( this->AutoSubdividePolarAxis ? "On\n" : "Off\n" ); + + os << indent << "Range: (" + << this->Range[0] << ", " + << this->Range[1] << ")\n"; os << indent << "Pole: (" << this->Pole[0] << ", " << this->Pole[1] << ", " << this->Pole[2] << ")\n"; + os << indent << "Number of radial axes: " << this->NumberOfRadialAxes << endl; + os << indent << "Auto Subdivide Polar Axis: " << this->AutoSubdividePolarAxis << endl; + os << indent << "Abgle between two radial axes: " << this->DeltaAngleRadialAxes << endl; + os << indent << "Minimum Radius: " << this->MinimumRadius << endl; os << indent << "Maximum Radius: " << this->MaximumRadius << endl; - os << indent << "Auto-Scale Radius: " << this->AutoScaleRadius << endl; + os << indent << "Log Scale: " << (this->Log ? "On" : "Off") << endl; + os << indent << "Auto-Scale Radius: " << (this->AutoScaleRadius ? "On" : "Off") << endl; + os << indent << "Ratio: " << this->Ratio << endl; os << indent << "Minimum Angle: " << this->MinimumAngle << endl; os << indent << "Maximum Angle: " << this->MaximumAngle << endl; os << indent << "Smallest Visible Polar Angle: " << this->SmallestVisiblePolarAngle << endl; os << indent << "Radial Units (degrees): " - << ( this->RadialUnits ? "On\n" : "Off\n" ) << endl; + << (this->RadialUnits ? "On\n" : "Off\n") << endl; - if ( this->Camera ) + if (this->Camera) { os << indent << "Camera:\n"; - this->Camera->PrintSelf( os,indent.GetNextIndent() ); + this->Camera->PrintSelf(os, indent.GetNextIndent()); } else { @@ -83,33 +95,120 @@ void vtkPolarAxesActor::PrintSelf( ostream& os, vtkIndent indent ) } os << indent << "EnableDistanceLOD: " - << ( this->EnableDistanceLOD ? "On" : "Off" ) << endl; + << (this->EnableDistanceLOD ? "On" : "Off") << endl; os << indent << "DistanceLODThreshold: " << this->DistanceLODThreshold << "\n"; os << indent << "EnableViewAngleLOD: " - << ( this->EnableViewAngleLOD ? "On" : "Off" ) << endl; + << (this->EnableViewAngleLOD ? "On" : "Off") << endl; os << indent << "ViewAngleLODThreshold: " << this->ViewAngleLODThreshold << "\n"; os << indent << "Polar Axis Title: " << this->PolarAxisTitle << "\n"; os << indent << "Polar Label Format: " << this->PolarLabelFormat << "\n"; + os << indent << "Title Scale: " << this->TitleScale << "\n"; + os << indent << "Label Scale: " << this->LabelScale << "\n"; + os << indent << "Radial Angle Format: " << this->RadialAngleFormat << "\n"; os << indent << "PolarAxisLabelTextProperty: " << this->PolarAxisLabelTextProperty << endl; os << indent << "PolarAxisTitleTextProperty: " << this->PolarAxisTitleTextProperty << endl; + os << indent << "RadialAxisTextProperty: " << this->LastRadialAxisTextProperty << endl; + os << indent << "SecondaryRadialAxesTextProperty: " << this->SecondaryRadialAxesTextProperty << endl; os << indent << "Polar Axis Visibility: " - << ( this->PolarAxisVisibility ? "On\n" : "Off\n" ); + << (this->PolarAxisVisibility ? "On\n" : "Off\n"); os << indent << "Polar Title Visibility: " - << ( this->PolarTitleVisibility ? "On" : "Off" ) << endl; + << (this->PolarTitleVisibility ? "On" : "Off") << endl; os << indent << "Polar Label Visibility: " - << ( this->PolarLabelVisibility ? "On" : "Off" ) << endl; - os << indent << "Polar Tick Visibility: " - << ( this->PolarTickVisibility ? "On" : "Off" ) << endl; + << (this->PolarLabelVisibility ? "On" : "Off") << endl; + if (this->PolarAxisTitleLocation == VTK_TITLE_BOTTOM) + { + os << indent << "Polar Title Location: BOTTOM" << endl; + } + else if (this->PolarAxisTitleLocation == VTK_TITLE_EXTERN) + { + os << indent << "Polar Title Location: EXTERN" << endl; + } + + os << indent << "Polar Label exponent location: "; + + if (this->ExponentLocation == VTK_EXPONENT_BOTTOM) + { + os << " next to the polar axis title." << endl; + } + else if (this->ExponentLocation == VTK_EXPONENT_EXTERN) + { + os << " outer side." << endl; + } + else + { + os << " bound to labels." << endl; + } + + os << indent << "Radial Axes Visibility: " << (this->RadialAxesVisibility ? "On\n" : "Off\n"); + os << indent << "Radial Title Visibility: " << (this->RadialTitleVisibility ? "On" : "Off") << endl; + if (this->RadialAxisTitleLocation == VTK_TITLE_BOTTOM) + { + os << indent << "Radial Title Location: BOTTOM" << endl; + } + else if (this->RadialAxisTitleLocation == VTK_TITLE_EXTERN) + { + os << indent << "Radial Title Location: EXTERN" << endl; + } + + os << indent << "Polar Arcs Visibility: " << (this->PolarArcsVisibility ? "On" : "Off") << endl; + os << indent << "Draw Radial Gridlines: " << (this->DrawRadialGridlines ? "On" : "Off") << endl; + os << indent << "Draw Polar Arcs Gridlines: " << (this->DrawPolarArcsGridlines ? "On" : "Off") << endl; + os << indent << "Draw Radial Axes From Polar Axis: " << (this->RadialAxesOriginToPolarAxis ? "On" : "Off") << endl; + + //--------------------- TICKS ------------------ + os << indent << "TickLocation: " << this->TickLocation << endl; + + os << indent << "Ticks overall enabled: " << (this->PolarTickVisibility ? "On" : "Off") << endl; + os << indent << "Draw Arc Ticks From Polar Axis: " << (this->ArcTicksOriginToPolarAxis ? "On" : "Off") << endl; + + //--- major ticks --- + // polar axis and last radial axis + os << indent << "Axes Major Tick Visibility: " << (this->AxisTickVisibility ? "On" : "Off") << endl; + if (this->AxisTickVisibility && this->PolarTickVisibility) + { + os << indent << "Axes Major Tick Step: " << this->DeltaRangeMajor << endl; + os << indent << "PolarAxis Major Tick Size: " << this->PolarAxisMajorTickSize << endl; + os << indent << "PolarAxis Major Tick Thickness: " << this->PolarAxisMajorTickThickness << endl; + if (this->RadialAxesVisibility) + { + os << indent << "Last Radial Axis Major Ticks Size: " << this->LastRadialAxisMajorTickSize << endl; + os << indent << "Last Radial Axis Major Ticks Thickness: " << this->LastRadialAxisMajorTickThickness << endl; + } + } + + // last arc + os << indent << "Arc Major Ticks Visibility: " << (this->ArcTickVisibility ? "On" : "Off") << endl; + if (this->ArcTickVisibility && this->PolarTickVisibility) + { + os << indent << "Arc Major Angle Step: " << this->DeltaAngleMajor << endl; + os << indent << "Arc Major Ticks Size: " << this->ArcMajorTickSize << endl; + os << indent << "Arc Major Ticks Thickness: " << this->ArcMajorTickThickness << endl; + } - os << indent << "Radial Axes Visibility: " - << ( this->RadialAxesVisibility ? "On\n" : "Off\n" ); - os << indent << "Radial Title Visibility: " - << ( this->RadialTitleVisibility ? "On" : "Off" ) << endl; + //--- minor ticks --- + // polar axis and last radial axis + os << indent << "Axis Minor Ticks Visibility: " << (this->AxisMinorTickVisibility ? "On" : "Off") << endl; + if (this->AxisMinorTickVisibility && this->PolarTickVisibility) + { + os << indent << "Axes Minor Tick Step: " << this->DeltaRangeMinor << endl; + os << indent << "Ratio Between PolarAxis Major and Minor Tick : " << this->PolarAxisTickRatioSize << endl; + os << indent << "Ratio Between PolarAxis Major and Minor Tick Thickness : " << this->PolarAxisTickRatioThickness << endl; + if (this->RadialAxesVisibility) + { + os << indent << "Ratio Between LastAxis Major and Minor Tick : " << this->LastAxisTickRatioSize << endl; + os << indent << "Ratio Between LastAxis Major and Minor Tick Thickness: " << this->LastAxisTickRatioThickness << endl; + } + } + os << indent << "Arc Minor Ticks Visibility: " << (this->ArcMinorTickVisibility ? "On" : "Off") << endl; + if (this->ArcMinorTickVisibility && this->PolarTickVisibility) + { + os << indent << "Arc Minor Angle Step: " << this->DeltaAngleMinor << endl; + os << indent << "Ratio Between Last Arc Major and Minor Tick : " << this->ArcTickRatioSize << endl; + os << indent << "Ratio Between Last Arc Major and Minor Tick Thickness: " << this->ArcTickRatioThickness << endl; + } - os << indent << "Polar Arcs Visibility: " - << ( this->PolarArcsVisibility ? "On" : "Off" ) << endl; } //----------------------------------------------------------------------------- @@ -125,15 +224,26 @@ vtkPolarAxesActor::vtkPolarAxesActor() : vtkActor() this->Pole[1] = 0.; this->Pole[2] = 0.; - // Default number of radial axes - this->NumberOfRadialAxes = VTK_DEFAULT_NUMBER_OF_RADIAL_AXES; - // Invalid default number of polar arcs, and auto-calculate by default - this->NumberOfPolarAxisTicks = -1; this->AutoSubdividePolarAxis = true; - // Default maximum polar radius - this->MaximumRadius = 1.; + // Ratio of the ellipse arc + this->Ratio = 1.0; + + // Polar Axis scale type + this->Log = 0; + + // Default minimum polar radius size + this->MinimumRadius = 0.0; + + // Default maximum polar radius size + this->MaximumRadius = 5.0; + + // Default minimum Range + this->Range[0] = 0.0; + + // Default maximum Range + this->Range[1] = 10.0; // Do not auto-scale radius by default this->AutoScaleRadius = false; @@ -155,27 +265,27 @@ vtkPolarAxesActor::vtkPolarAxesActor() : vtkActor() // Default text screen size this->ScreenSize = 10.0; - // Screen offset for labels - // Pivot point at center of the geometry hence this->ScreenSize * 0.5 - this->LabelScreenOffset = 15.0 + this->ScreenSize * 0.5; - // Text properties of polar axis title and labels, with default color white // Properties of the radial axes, with default color black this->PolarAxisProperty = vtkProperty::New(); - this->PolarAxisProperty->SetColor( 0., 0., 0. ); + this->PolarAxisProperty->SetColor(0., 0., 0.); this->PolarAxisTitleTextProperty = vtkTextProperty::New(); - this->PolarAxisTitleTextProperty->SetColor( 1., 1. ,1. ); + this->PolarAxisTitleTextProperty->SetOpacity(1.0); + this->PolarAxisTitleTextProperty->SetColor(1., 1. , 1.); this->PolarAxisTitleTextProperty->SetFontFamilyToArial(); this->PolarAxisLabelTextProperty = vtkTextProperty::New(); - this->PolarAxisLabelTextProperty->SetColor( 1., 1. ,1. ); + this->PolarAxisLabelTextProperty->SetColor(1., 1. , 1.); this->PolarAxisLabelTextProperty->SetFontFamilyToArial(); // Create and set polar axis of type X this->PolarAxis = vtkAxisActor::New(); this->PolarAxis->SetAxisTypeToX(); - this->PolarAxis->SetAxisPositionToMinMax(); - this->PolarAxis->SetCalculateTitleOffset( 0 ); - this->PolarAxis->SetCalculateLabelOffset( 0 ); + + this->PolarAxis->SetCalculateTitleOffset(0); + this->PolarAxis->SetCalculateLabelOffset(0); + this->PolarAxis->SetTitleOffset(10); + this->PolarAxis->SetLabelOffset(2); + this->PolarAxis->SetExponentOffset(5); // Default distance LOD settings this->EnableDistanceLOD = 1; @@ -185,33 +295,135 @@ vtkPolarAxesActor::vtkPolarAxesActor() : vtkActor() this->EnableViewAngleLOD = 1; this->ViewAngleLODThreshold = .3; - // Properties of the radial axes, with default color black - this->RadialAxesProperty = vtkProperty::New(); - this->RadialAxesProperty->SetColor( 0., 0., 0. ); + this->RadialAxes = NULL; + + // Properties of the last radial axe, with default color black + this->LastRadialAxisProperty = vtkProperty::New(); + this->LastRadialAxisProperty->SetAmbient(1.0); + this->LastRadialAxisProperty->SetDiffuse(0.0); + this->LastRadialAxisProperty->SetColor(0., 0., 0.); + + this->LastRadialAxisTextProperty = vtkTextProperty::New(); + this->LastRadialAxisTextProperty->SetOpacity(1.0); + this->LastRadialAxisTextProperty->SetColor(1., 1. , 1.); + this->LastRadialAxisTextProperty->SetFontFamilyToArial(); + + // Properties of the secondaries radial axes, with default color black + this->SecondaryRadialAxesProperty = vtkProperty::New(); + this->SecondaryRadialAxesProperty->SetAmbient(1.0); + this->SecondaryRadialAxesProperty->SetDiffuse(0.0); + this->SecondaryRadialAxesProperty->SetColor(0., 0., 0.); - // Create and set radial axes of type X - this->CreateRadialAxes(); + this->SecondaryRadialAxesTextProperty = vtkTextProperty::New(); + this->SecondaryRadialAxesTextProperty->SetOpacity(1.0); + this->SecondaryRadialAxesTextProperty->SetColor(1., 1. , 1.); + this->SecondaryRadialAxesTextProperty->SetFontFamilyToArial(); - // Create and set polar arcs and ancillary objects, with default color white + // Create and set principal polar arcs and ancillary objects, with default color white this->PolarArcs = vtkPolyData::New(); this->PolarArcsMapper = vtkPolyDataMapper::New(); - this->PolarArcsMapper->SetInputData( this->PolarArcs ); + this->PolarArcsMapper->SetInputData(this->PolarArcs); this->PolarArcsActor = vtkActor::New(); - this->PolarArcsActor->SetMapper( this->PolarArcsMapper ); - this->PolarArcsActor->GetProperty()->SetColor( 1., 1., 1. ); + this->PolarArcsActor->SetMapper(this->PolarArcsMapper); + this->PolarArcsActor->GetProperty()->SetColor(1., 1., 1.); + + // Create and set secondary polar arcs and ancillary objects, with default color white + this->SecondaryPolarArcs = vtkPolyData::New(); + this->SecondaryPolarArcsMapper = vtkPolyDataMapper::New(); + this->SecondaryPolarArcsMapper->SetInputData(this->SecondaryPolarArcs); + this->SecondaryPolarArcsActor = vtkActor::New(); + this->SecondaryPolarArcsActor->SetMapper(this->SecondaryPolarArcsMapper); + this->SecondaryPolarArcsActor->GetProperty()->SetColor(1., 1., 1.); + + // Create the vtk Object for arc ticks + this->ArcMajorTickPts = vtkPoints::New(); + this->ArcMinorTickPts = vtkPoints::New(); + + this->ArcTickPolyData = vtkPolyData::New(); + this->ArcMinorTickPolyData = vtkPolyData::New(); + + this->ArcTickPolyDataMapper = vtkPolyDataMapper::New(); + this->ArcTickPolyDataMapper->SetInputData(this->ArcTickPolyData); + + this->ArcMinorTickPolyDataMapper = vtkPolyDataMapper::New(); + this->ArcMinorTickPolyDataMapper->SetInputData(this->ArcMinorTickPolyData); + + this->ArcTickActor = vtkActor::New(); + this->ArcTickActor->SetMapper(this->ArcTickPolyDataMapper); + + this->ArcMinorTickActor = vtkActor::New(); + this->ArcMinorTickActor->SetMapper(this->ArcMinorTickPolyDataMapper); // Default title for polar axis (sometimes also called "Radius") this->PolarAxisTitle = new char[16]; sprintf(this->PolarAxisTitle, "%s", "Radial Distance"); + this->PolarLabelFormat = new char[8]; - sprintf( this->PolarLabelFormat, "%s", "%-#6.3g" ); + sprintf(this->PolarLabelFormat, "%s", "%-#6.3g"); + + this->ExponentLocation = VTK_EXPONENT_LABELS; + + this->RadialAngleFormat = new char[8]; + sprintf(this->RadialAngleFormat, "%s", "%-#3.1f"); + + this->RadialAxisTitleLocation = VTK_TITLE_BOTTOM; + this->PolarAxisTitleLocation = VTK_TITLE_BOTTOM; // By default all polar axis features are visible this->PolarAxisVisibility = 1; this->PolarTitleVisibility = 1; this->PolarLabelVisibility = 1; + + this->TickLocation = vtkAxisActor::VTK_TICKS_BOTH; + + this->ArcTicksOriginToPolarAxis = 1.0; + + // ----- tick visibility ----- + // overall visibility this->PolarTickVisibility = 1; + this->AxisTickVisibility = 1; + this->AxisMinorTickVisibility = 0; + + this->ArcTickVisibility = 1; + this->ArcMinorTickVisibility = 0; + + // tick size + this->PolarAxisMajorTickSize = 0.1; + this->PolarAxisTickRatioSize = 0.3; + + this->LastRadialAxisMajorTickSize = 0.1; + this->LastAxisTickRatioSize = 0.3; + + this->ArcMajorTickSize = 0.1; + this->ArcTickRatioSize = 0.3; + + // tick thickness + this->PolarAxisMajorTickThickness = 1.0; + this->PolarAxisTickRatioThickness = 0.5; + + this->LastRadialAxisMajorTickThickness = 1.0; + this->LastAxisTickRatioThickness = 0.5; + + this->ArcMajorTickThickness = 1.0; + this->ArcTickRatioThickness = 0.5; + + // Step between 2 major ticks, in range value (values displayed on the axis). + this->DeltaRangeMajor = 1.0; + + // Step between 2 minor ticks, in range value (values displayed on the axis). + this->DeltaRangeMinor = 0.5 * this->DeltaRangeMajor; + + // Angle between 2 major ticks on the last arc. + this->DeltaAngleMajor = 10.0; + + // Angle between 2 minor ticks on the last arc. + this->DeltaAngleMinor = 0.5 *this->DeltaAngleMajor; + + this->RadialAxesOriginToPolarAxis = 1; + this->DeltaAngleRadialAxes = 45.0; + this->NumberOfRadialAxes = 0; + // By default all radial axes features are visible this->RadialAxesVisibility = 1; this->RadialTitleVisibility = 1; @@ -219,61 +431,81 @@ vtkPolarAxesActor::vtkPolarAxesActor() : vtkActor() // By default polar arcs are visible this->PolarArcsVisibility = 1; + // By default inner radial lines and polar arcs lines are visible + this->DrawRadialGridlines = 1; + this->DrawPolarArcsGridlines = 1; + // Default title scale this->TitleScale = -1.; // Default label scale this->LabelScale = -1.; - - this->RenderCount = 0; - - this->RenderSomething = 0; } //----------------------------------------------------------------------------- vtkPolarAxesActor::~vtkPolarAxesActor() { - this->SetCamera( NULL ); + this->SetCamera(NULL); - if ( this->PolarAxisProperty ) + if (this->PolarAxisProperty) { this->PolarAxisProperty->Delete(); } - if ( this->RadialAxesProperty ) + if (this->LastRadialAxisProperty) + { + this->LastRadialAxisProperty->Delete(); + } + + if (this->SecondaryRadialAxesProperty) { - this->RadialAxesProperty->Delete(); + this->SecondaryRadialAxesProperty->Delete(); } delete [] this->PolarLabelFormat; this->PolarLabelFormat = NULL; + delete [] this->RadialAngleFormat; + this->RadialAngleFormat = NULL; + delete [] this->PolarAxisTitle; this->PolarAxisTitle = NULL; - if ( this->PolarAxisTitleTextProperty ) + if (this->PolarAxisTitleTextProperty) { this->PolarAxisTitleTextProperty->Delete(); this->PolarAxisTitleTextProperty = NULL; } - if ( this->PolarAxisLabelTextProperty ) + if (this->PolarAxisLabelTextProperty) { this->PolarAxisLabelTextProperty->Delete(); this->PolarAxisLabelTextProperty = NULL; } - if ( this->PolarAxis ) + if (this->LastRadialAxisTextProperty) + { + this->LastRadialAxisTextProperty->Delete(); + this->LastRadialAxisTextProperty = NULL; + } + + if (this->SecondaryRadialAxesTextProperty) + { + this->SecondaryRadialAxesTextProperty->Delete(); + this->SecondaryRadialAxesTextProperty = NULL; + } + + if (this->PolarAxis) { this->PolarAxis->Delete(); this->PolarAxis = NULL; } - if ( this->RadialAxes ) + if (this->RadialAxes) { - for ( int i = 0; i < this->NumberOfRadialAxes; ++ i ) + for (int i = 0; i < this->NumberOfRadialAxes; ++ i) { - if ( this->RadialAxes[i] ) + if (this->RadialAxes[i]) { this->RadialAxes[i]->Delete(); this->RadialAxes[i] = NULL; @@ -299,73 +531,153 @@ vtkPolarAxesActor::~vtkPolarAxesActor() this->PolarArcsActor = NULL; } + if (this->SecondaryPolarArcs) + { + this->SecondaryPolarArcs->Delete(); + this->SecondaryPolarArcs = NULL; + } + if (this->SecondaryPolarArcsMapper) + { + this->SecondaryPolarArcsMapper->Delete(); + this->SecondaryPolarArcsMapper = NULL; + } + if (this->SecondaryPolarArcsActor) + { + this->SecondaryPolarArcsActor->Delete(); + this->SecondaryPolarArcsActor = NULL; + } + + // ticks related objects + if (this->ArcMajorTickPts) + { + this->ArcMajorTickPts->Delete(); + this->ArcMajorTickPts = NULL; + } + if (this->ArcMinorTickPts) + { + this->ArcMinorTickPts->Delete(); + this->ArcMinorTickPts = NULL; + } + if (this->ArcTickPolyData) + { + this->ArcTickPolyData->Delete(); + this->ArcTickPolyData = NULL; + } + if (this->ArcMinorTickPolyData) + { + this->ArcMinorTickPolyData->Delete(); + this->ArcMinorTickPolyData = NULL; + } + if (this->ArcTickPolyDataMapper) + { + this->ArcTickPolyDataMapper->Delete(); + this->ArcTickPolyDataMapper = NULL; + } + if (this->ArcMinorTickPolyDataMapper) + { + this->ArcMinorTickPolyDataMapper->Delete(); + this->ArcMinorTickPolyDataMapper = NULL; + } + if (this->ArcTickActor) + { + this->ArcTickActor->Delete(); + this->ArcTickActor = NULL; + } + if (this->ArcMinorTickActor) + { + this->ArcMinorTickActor->Delete(); + this->ArcMinorTickActor = NULL; + } } //----------------------------------------------------------------------------- -int vtkPolarAxesActor::RenderOpaqueGeometry( vtkViewport *viewport ) +int vtkPolarAxesActor::RenderOpaqueGeometry(vtkViewport *viewport) { // Initialization int renderedSomething = 0; - if ( !this->Camera ) + if (!this->Camera) { - vtkErrorMacro( <<"No camera!" ); - this->RenderSomething = 0; + vtkErrorMacro(<< "No camera!"); return renderedSomething; } - this->BuildAxes( viewport ); + this->BuildAxes(viewport); // Render the polar axis - if ( this->PolarAxisVisibility ) + if (this->PolarAxisVisibility) { - renderedSomething += this->PolarAxis->RenderOpaqueGeometry( viewport ); + renderedSomething += this->PolarAxis->RenderOpaqueGeometry(viewport); } // Render the radial axes - if ( this->RadialAxesVisibility ) + if (this->RadialAxesVisibility) { - for ( int i = 0; i < this->NumberOfRadialAxes; ++ i ) + bool isInnerAxis, isAxisVisible; + for (int i = 0; i < this->NumberOfRadialAxes; ++ i) { - renderedSomething += this->RadialAxes[i]->RenderOpaqueGeometry( viewport ); + isInnerAxis = (i != this->NumberOfRadialAxes - 1) || + (vtkMathUtilities::FuzzyCompare(MaximumAngle, MinimumAngle)); + isAxisVisible = !isInnerAxis || this->DrawRadialGridlines; + if (this->RadialAxesVisibility && isAxisVisible) + { + renderedSomething += this->RadialAxes[i]->RenderOpaqueGeometry(viewport); + } } } // Render the polar arcs - if ( this->PolarArcsVisibility ) + if (this->PolarArcsVisibility) { renderedSomething += this->PolarArcsActor->RenderOpaqueGeometry(viewport); - } + renderedSomething += this->SecondaryPolarArcsActor->RenderOpaqueGeometry(viewport); + if (this->PolarTickVisibility) + { + if (this->ArcTickVisibility) + { + renderedSomething += this->ArcTickActor->RenderOpaqueGeometry(viewport); + } + if (this->ArcMinorTickVisibility) + { + renderedSomething += this->ArcMinorTickActor->RenderOpaqueGeometry(viewport); + } + } + } return renderedSomething; } -//----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetScreenSize( double screenSize ) +int vtkPolarAxesActor::RenderOverlay(vtkViewport *viewport) { - this->ScreenSize = screenSize; - // Considering pivot point at center of the geometry, - // hence ( this->ScreenSize * 0.5 ). - this->LabelScreenOffset = 15.0 + this->ScreenSize * 0.5; + int renderedSomething = 0; - vtkAxisFollower** labelActors = this->PolarAxis->GetLabelActors(); - int numberOfLabels = this->PolarAxis->GetNumberOfLabelsBuilt(); - for( int i = 0; i < numberOfLabels; ++ i ) + if (this->PolarAxisVisibility && this->PolarAxis->GetUse2DMode()) { - labelActors[i]->SetScreenOffset( this->LabelScreenOffset ); + renderedSomething += this->PolarAxis->RenderOverlay(viewport); } - this->Modified(); + if (this->RadialAxesVisibility) + { + for (int i = 0; i < this->NumberOfRadialAxes; ++i) + { + if (this->RadialAxes[i]->GetUse2DMode()) + { + renderedSomething += this->RadialAxes[i]->RenderOverlay(viewport); + } + } + } + return renderedSomething; } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::ReleaseGraphicsResources( vtkWindow *win ) +void vtkPolarAxesActor::ReleaseGraphicsResources(vtkWindow *win) { this->PolarAxis->ReleaseGraphicsResources(win); - for ( int i = 0; i < this->NumberOfRadialAxes; ++ i ) + for (int i = 0; i < this->NumberOfRadialAxes; ++ i) { - this->RadialAxes[i]->ReleaseGraphicsResources( win ); + this->RadialAxes[i]->ReleaseGraphicsResources(win); } - this->PolarArcsActor->ReleaseGraphicsResources( win ); + this->SecondaryPolarArcsActor->ReleaseGraphicsResources(win); + this->PolarArcsActor->ReleaseGraphicsResources(win); } //----------------------------------------------------------------------------- @@ -376,13 +688,13 @@ void vtkPolarAxesActor::CalculateBounds() double maxAngle = this->MaximumAngle; // Ensure that angles are not both < -180 nor both > 180 degrees - if ( maxAngle < -180. ) + if (maxAngle < -180.) { // Increment angles modulo 360 degrees minAngle += 360.; maxAngle += 360.; } - else if ( minAngle > 180. ) + else if (minAngle > 180.) { // Decrement angles modulo 360 degrees minAngle -= 360.; @@ -390,21 +702,21 @@ void vtkPolarAxesActor::CalculateBounds() } // Prepare trigonometric quantities - double thetaMin = vtkMath::RadiansFromDegrees( minAngle ); - double cosThetaMin = cos( thetaMin ); - double sinThetaMin = sin( thetaMin ); - double thetaMax = vtkMath::RadiansFromDegrees( maxAngle ); - double cosThetaMax = cos( thetaMax ); - double sinThetaMax = sin( thetaMax ); + double thetaMin = vtkMath::RadiansFromDegrees(minAngle); + double cosThetaMin = cos(thetaMin); + double sinThetaMin = sin(thetaMin); + double thetaMax = vtkMath::RadiansFromDegrees(maxAngle); + double cosThetaMax = cos(thetaMax); + double sinThetaMax = sin(thetaMax); // Calculate extremal cosines across angular sector double minCos; double maxCos; - if ( minAngle * maxAngle < 0. ) + if (minAngle * maxAngle < 0.) { // Angular sector contains null angle maxCos = 1.; - if ( minAngle < 180. && maxAngle > 180. ) + if (minAngle < 180. && maxAngle > 180.) { // Angular sector also contains flat angle minCos = -1.; @@ -416,7 +728,7 @@ void vtkPolarAxesActor::CalculateBounds() } } - else if ( minAngle < 180. && maxAngle > 180. ) + else if (minAngle < 180. && maxAngle > 180.) { // Angular sector does not contain flat angle (and not null angle) minCos = -1.; @@ -432,11 +744,11 @@ void vtkPolarAxesActor::CalculateBounds() // Calculate extremal sines across angular sector double minSin; double maxSin; - if ( minAngle < -90. && maxAngle > -90. ) + if (minAngle < -90. && maxAngle > -90.) { // Angular sector contains negative right angle minSin = -1.; - if ( minAngle < 90. && maxAngle > 90. ) + if (minAngle < 90. && maxAngle > 90.) { // Angular sector also contains positive right angle maxSin = 1.; @@ -447,7 +759,7 @@ void vtkPolarAxesActor::CalculateBounds() maxSin = sinThetaMax > sinThetaMin ? sinThetaMax : sinThetaMin; } } - else if ( minAngle < 90. && maxAngle > 90. ) + else if (minAngle < 90. && maxAngle > 90.) { // Angular sector contains positive right angle (and not negative one) minSin = sinThetaMin < sinThetaMax ? sinThetaMin : sinThetaMax; @@ -479,18 +791,18 @@ void vtkPolarAxesActor::CalculateBounds() } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::GetBounds( double bounds[6]) +void vtkPolarAxesActor::GetBounds(double bounds[6]) { - for ( int i=0; i< 6; i++) + for (int i = 0; i< 6; i++) { bounds[i] = this->Bounds[i]; } } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::GetBounds( double& xmin, double& xmax, - double& ymin, double& ymax, - double& zmin, double& zmax ) +void vtkPolarAxesActor::GetBounds(double& xmin, double& xmax, + double& ymin, double& ymax, + double& zmin, double& zmax) { xmin = this->Bounds[0]; xmax = this->Bounds[1]; @@ -506,423 +818,1407 @@ double *vtkPolarAxesActor::GetBounds() return this->Bounds; } -//----------------------------------------------------------------------------- -void vtkPolarAxesActor::BuildAxes( vtkViewport *viewport ) +bool vtkPolarAxesActor::CheckMembersConsistency() { - if ( ( this->GetMTime() < this->BuildTime.GetMTime() ) ) + if (this->MaximumAngle > 360.0 || this->MinimumAngle > 360.0) { - this->AutoScale( viewport ); - return; + // Incorrect MaximumRadius input + vtkWarningMacro(<< "Cannot draw polar axis, Angle > 360.0: " + << "MinimumAngle : " << this->MinimumAngle << " _ MaximumAngle: " << this->MaximumAngle); + return false; } - if ( this->MaximumAngle < this->MinimumAngle ) + // Min/Max Radius + if (vtkMathUtilities::FuzzyCompare(this->MaximumRadius, this->MinimumRadius)) { - // Incorrect angle input - vtkWarningMacro( << "Cannot draw radial axes: " - << " minimum angle = " - << this->MinimumAngle - << " > maximum angle = " - << this->MaximumAngle - << "."); - return; + // MaximumRadius and this->MinimumRadius are too close + vtkWarningMacro(<< "Maximum and Minimum Radius cannot be distinct: " + << " MinimumRadius: " << this->MinimumRadius << " _ MaximumRadius: " << this->MaximumRadius); + return false; } - if ( this->MaximumAngle - this->MinimumAngle > 360. ) + if (this->MaximumRadius <= 0.0 || this->MinimumRadius < 0.0) { - // Incorrect angle input - vtkWarningMacro( << "Cannot draw radial axes: " - << " angular sector = " - << this->MaximumAngle - this->MinimumAngle - << " > 360 deg." ); - return; + // Incorrect MaximumRadius input + vtkWarningMacro(<< "Cannot draw polar axis, Negative Radius value set: " + << "MinimumRadius : " << this->MinimumRadius << " _ MaximumRadius: " << this->MaximumRadius); + return false; } - // Determine the bounds - this->CalculateBounds(); - - // Set polar axis endpoints - vtkAxisActor* axis = this->PolarAxis; - double ox = this->Pole[0] + this->MaximumRadius; - axis->GetPoint1Coordinate()->SetValue( this->Pole[0], this->Pole[1], this->Pole[2] ); - axis->GetPoint2Coordinate()->SetValue( ox, this->Pole[1], this->Pole[2] ); - - // Set common axis attributes - this->SetCommonAxisAttributes( axis ); - - // Set polar axis lines - axis->SetAxisVisibility( this->PolarAxisVisibility ); - axis->SetAxisLinesProperty( this->PolarAxisProperty ); - - // Set polar axis title - axis->SetTitleVisibility( this->PolarTitleVisibility ); - axis->SetTitle( this->PolarAxisTitle ); - axis->SetTitleTextProperty( this->PolarAxisTitleTextProperty ); - - // Set polar axis ticks (major only) - axis->SetTickVisibility( this->PolarTickVisibility ); - axis->SetTickLocation( vtkAxisActor::VTK_TICKS_BOTH ); - axis->SetMajorTickSize( .02 * this->MaximumRadius ); - - // Set polar axis labels - axis->SetLabelVisibility( this->PolarLabelVisibility ); - axis->SetLabelTextProperty( this->PolarAxisLabelTextProperty ); + // Min/Max Range + if (vtkMathUtilities::FuzzyCompare(this->Range[0], this->Range[1])) + { + // MaximumRadius and this->MinimumRadius are too close + vtkWarningMacro(<< "Maximum and Minimum Range cannot be distinct: " + << " Range[0]: " << this->Range[0] << " _ Range[1]: " << this->Range[1]); + return false; + } - // Build radial axes - this->BuildRadialAxes(); + // Log Mode + if (this->Log != 0 && this->Range[0] <= 0.0) + { + vtkWarningMacro(<< "Scale Set to Linear. Range value undefined for log scale enabled. " + << "Current Range: (" << this->Range[0] << ", " << this->Range[1] << ")" + << "Range must be > 0.0 for log scale to be enabled" + << "."); - // Build polar axis ticks - this->BuildPolarAxisTicks( this->Pole[0] ); + this->Log = 0; + } - // Build polar axis labels - this->BuildPolarAxisLabelsArcs(); + // Range Step + if (this->DeltaRangeMajor <= 0.0 || + (this->DeltaRangeMajor > fabs(this->Range[1] -this->Range[0]) && !AutoSubdividePolarAxis)) + { + vtkWarningMacro(<< "Axis Major Step or Range length invalid: " << "DeltaRangeMajor: " << this->DeltaRangeMajor + << "_ Range length: " << fabs(this->Range[1] -this->Range[0]) + << " _ Enable AutoSubdividePolarAxis to get a proper DeltaRangeMajor or set it yourself"); + return false; + } + if (this->DeltaRangeMinor <= 0.0 || + (this->DeltaRangeMinor > fabs(this->Range[1] -this->Range[0]) && !AutoSubdividePolarAxis)) + { + vtkWarningMacro(<< "Axis Minor Step or range length invalid: " << "DeltaRangeMinor: " << this->DeltaRangeMinor + << "_ Range length: " << fabs(this->Range[1] -this->Range[0]) + << " _ Enable AutoSubdividePolarAxis to get a proper DeltaRangeMinor or set it yourself"); + return false; + } - // Build polar axis - this->PolarAxis->BuildAxis( viewport, true ); + // Angle Step + if (this->DeltaAngleMajor <= 0.0 || this->DeltaAngleMajor >= 360.0 || + this->DeltaAngleMinor <= 0.0 || this->DeltaAngleMinor >= 360.0) + { + vtkWarningMacro(<< "Arc Delta Angle: " << "DeltaAngleMajor: " << this->DeltaAngleMajor + << " _ DeltaAngleMinor: " << this->DeltaAngleMinor << "_ DeltaAngles should be in ]0.0, 360.0[ range. "); + return false; + } - // Scale appropriately - this->AutoScale( viewport ); + // Angle Step + if (this->DeltaAngleRadialAxes <= 0.0 || this->DeltaAngleRadialAxes >= 360.0) + { + vtkWarningMacro(<< "Delta Angle for radial axes: " << "DeltaAngleRadialAxes: " << this->DeltaAngleRadialAxes + << "_ DeltaAngleRadialAxes should be in ]0.0, 360.0[ range. "); + return false; + } - this->RenderSomething = 1; - this->BuildTime.Modified(); + // Tick ratios range check + if (this->PolarAxisTickRatioThickness < (1.0 / VTK_MAXIMUM_RATIO) || this->PolarAxisTickRatioThickness > VTK_MAXIMUM_RATIO || + this->LastAxisTickRatioThickness < (1.0 / VTK_MAXIMUM_RATIO) || this->LastAxisTickRatioThickness > VTK_MAXIMUM_RATIO || + this->ArcTickRatioThickness < (1.0 / VTK_MAXIMUM_RATIO) || this->ArcTickRatioThickness > VTK_MAXIMUM_RATIO || + this->PolarAxisTickRatioSize < (1.0 / VTK_MAXIMUM_RATIO) || this->PolarAxisTickRatioSize > VTK_MAXIMUM_RATIO || + this->LastAxisTickRatioSize < (1.0 / VTK_MAXIMUM_RATIO) || this->LastAxisTickRatioSize > VTK_MAXIMUM_RATIO || + this->ArcTickRatioSize < (1.0 / VTK_MAXIMUM_RATIO) || this->ArcTickRatioSize > VTK_MAXIMUM_RATIO) + { + vtkWarningMacro(<< "A size/thickness ratio between major and minor ticks is way too large: " + << "PolarAxisTickRatioThickness: " << this->PolarAxisTickRatioThickness + << "LastAxisTickRatioThickness: " << this->LastAxisTickRatioThickness + << "ArcTickRatioThickness: " << this->ArcTickRatioThickness + << "PolarAxisTickRatioSize: " << this->PolarAxisTickRatioSize + << "LastAxisTickRatioSize: " << this->LastAxisTickRatioSize + << "ArcTickRatioSize: " << this->ArcTickRatioSize); + return false; + } + return true; } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetCommonAxisAttributes( vtkAxisActor* axis ) +void vtkPolarAxesActor::BuildAxes(vtkViewport *viewport) { - vtkProperty *prop = this->GetProperty(); - prop->SetAmbient( 1.0 ); - prop->SetDiffuse( 0.0 ); - axis->SetProperty( prop ); + if (this->GetMTime() < this->BuildTime.GetMTime()) + { + this->AutoScale(viewport); + return; + } - // Common space and range attributes - axis->SetCamera( this->Camera ); - axis->SetBounds( this->Bounds ); - axis->SetRange( 0., this->MaximumRadius ); + if (this->MaximumRadius - this->MinimumRadius < 0.0) + { + std::swap(this->MinimumRadius, this->MaximumRadius); + } + if (Range[0] > Range[1]) + { + std::swap(Range[0], Range[1]); + } + if (this->DeltaRangeMajor < 0.0) + { + this->DeltaRangeMajor *= -1.0; + } - // No minor ticks for any kind of axes - axis->SetMinorTicksVisible( 0 ); -} + if (this->DeltaRangeMinor < 0.0) + { + this->DeltaRangeMinor *= -1.0; + } -//----------------------------------------------------------------------------- -inline double vtkPolarAxesActor::FFix( double value ) -{ - int ivalue = static_cast( value ); - return ivalue; -} + // ---------- Angles check ----------- + // set angle range [0.0; 360.0] + this->MaximumAngle = std::fmod(this->MaximumAngle, 360); + this->MinimumAngle = std::fmod(this->MinimumAngle, 360); -//----------------------------------------------------------------------------- -inline double vtkPolarAxesActor::FSign( double value, double sign ) -{ - value = fabs( value ); - if ( sign < 0.) + if (this->MaximumAngle < 0.0) { - value *= -1.; + this->MaximumAngle += 360.0; } - return value; -} -//----------------------------------------------------------------------------- -void vtkPolarAxesActor::CreateRadialAxes() -{ - // Create requested number of radial axes - this->RadialAxes = new vtkAxisActor*[this->NumberOfRadialAxes]; - for ( int i = 0; i < this->NumberOfRadialAxes; ++ i ) + // set angle range [0.0; 360.0] + if (this->MinimumAngle < 0.0) { - // Create axis of type X - this->RadialAxes[i] = vtkAxisActor::New(); - vtkAxisActor* axis = this->RadialAxes[i]; - axis->SetAxisTypeToX(); - axis->SetAxisPositionToMinMax(); - axis->SetCalculateTitleOffset( 0 ); - axis->SetCalculateLabelOffset( 0 ); + this->MinimumAngle += 360.0; } -} -//----------------------------------------------------------------------------- -void vtkPolarAxesActor::BuildRadialAxes() -{ - // Base offset for radial axis title followers - double offset = .67 * ( this->LabelScreenOffset + this->ScreenSize * 0.5 ); + // this->MaximumAngle < this->MinimumAngle is possible, no swap - // Create requested number of radial axes - double dAlpha = - ( this->MaximumAngle - this->MinimumAngle ) / ( this->NumberOfRadialAxes - 1. ); - double alpha = this->MinimumAngle; - for ( int i = 0; i < this->NumberOfRadialAxes; ++ i, alpha += dAlpha ) + if (!this->CheckMembersConsistency()) { - // Calculate endpoint coordinates - double alphaRad = vtkMath::RadiansFromDegrees( alpha ); - double x = this->Pole[0] + this->MaximumRadius * cos( alphaRad ); - double y = this->Pole[1] + this->MaximumRadius * sin( alphaRad ); + return; + } - // Set radial axis endpoints - vtkAxisActor* axis = this->RadialAxes[i]; - axis->GetPoint1Coordinate()->SetValue( this->Pole[0], this->Pole[1], this->Pole[2] ); - axis->GetPoint2Coordinate()->SetValue( x, y, this->Pole[2] ); + // Determine the bounds + this->CalculateBounds(); - // Set common axis attributes - this->SetCommonAxisAttributes( axis ); + // Set polar axis endpoints + vtkAxisActor* axis = this->PolarAxis; - // Set radial axis lines - axis->SetAxisVisibility( this->RadialAxesVisibility ); - axis->SetAxisLinesProperty( this->RadialAxesProperty ); + // compute ellipse angle + double miniAngleEllipse = + this->ComputeEllipseAngle(this->MinimumAngle, this->Ratio); - // Set radial axis title with polar angle as title for non-polar axes - if ( this->PolarAxisVisibility && fabs( alpha ) < 2. ) - { - // Prevent conflict between radial and polar axes titles - axis->SetTitleVisibility( false ); + // Set the start point and end point (world coord system) of the Polar Axis. + double startPt[3], endPt[3]; + startPt[0] = this->Pole[0] + this->MinimumRadius * cos(miniAngleEllipse); + startPt[1] = this->Pole[1] + this->MinimumRadius * this->Ratio * sin(miniAngleEllipse); + startPt[2] = this->Pole[2]; - if ( fabs( alpha ) < this->SmallestVisiblePolarAngle ) - { - // Do not show radial axes too close to polar axis - axis->SetAxisVisibility( false ); - } - } - else - { - // Use polar angle as a title for the radial axis - axis->SetTitleVisibility( this->RadialTitleVisibility ); - axis->GetTitleTextProperty()->SetColor( this->RadialAxesProperty->GetColor() ); - std::ostringstream title; - title << alpha - << ( this->RadialUnits ? " deg" : "" ); - axis->SetTitle( title.str().c_str() ); + endPt[0] = this->Pole[0] + this->MaximumRadius * cos(miniAngleEllipse); + endPt[1] = this->Pole[1] + this->MaximumRadius * this->Ratio * sin(miniAngleEllipse); + endPt[2] = this->Pole[2]; - // Update axis title followers - axis->GetTitleActor()->SetAxis( axis ); - axis->GetTitleActor()->SetScreenOffset( offset ); - axis->GetTitleActor()->SetEnableDistanceLOD( this->EnableDistanceLOD ); - axis->GetTitleActor()->SetDistanceLODThreshold( this->DistanceLODThreshold ); - axis->GetTitleActor()->SetEnableViewAngleLOD( this->EnableViewAngleLOD ); - axis->GetTitleActor()->SetViewAngleLODThreshold( this->ViewAngleLODThreshold ); - } + axis->GetPoint1Coordinate()->SetValue(startPt); + axis->GetPoint2Coordinate()->SetValue(endPt); - // No labels nor ticks for radial axes - axis->SetLabelVisibility( 0 ); - axis->SetTickVisibility( 0 ); + // axis Type. We assume the polar graph is built in the local plane x-y + if ((this->MinimumAngle > 45.0 && this->MinimumAngle < 135.0) || + (this->MinimumAngle > 225.0 && this->MinimumAngle < 315.0)) + { + axis->SetAxisTypeToY(); + } + else + { + axis->SetAxisTypeToX(); } -} -//----------------------------------------------------------------------------- -void vtkPolarAxesActor::BuildPolarAxisTicks( double x0 ) -{ - double delta; + // Set axess attributes (range, tick location) + this->SetCommonAxisAttributes(axis); + this->SetPolarAxisAttributes(axis); - if ( this->AutoSubdividePolarAxis - || this->NumberOfPolarAxisTicks < 0 - || this->NumberOfPolarAxisTicks > VTK_MAXIMUM_NUMBER_OF_POLAR_AXIS_TICKS ) - { - // Programatically figure the number of divisions of the polar axis - double pow10 = log10( this->MaximumRadius ); + // ------- Ticks thickness ------- - // Build in numerical tolerance - if ( pow10 != 0.) - { - double eps = 10.0e-10; - pow10 = this->FSign( ( fabs( pow10 ) + eps ), pow10 ); - } + // Polar Axis + this->PolarAxis->GetAxisMajorTicksProperty()->SetLineWidth(this->PolarAxisMajorTickThickness); + double minorThickness = this->PolarAxisTickRatioThickness * this->PolarAxisMajorTickThickness; + if (minorThickness < 1.0) + { + minorThickness = 1.0; + } + this->PolarAxis->GetAxisMinorTicksProperty()->SetLineWidth(minorThickness); - // FFix will move in the wrong direction if pow10 is negative. - if ( pow10 < 0.) - { - pow10 = pow10 - 1.; - } + // Last arc + this->ArcTickActor->GetProperty()->SetLineWidth(this->ArcMajorTickThickness); + minorThickness = std::max(this->ArcMajorTickThickness * this->ArcTickRatioThickness, 1.); - // Find the number of integral points in the interval. - delta = pow( 10., this->FFix( pow10 ) ); - double fnt = this->MaximumRadius / delta; - fnt = this->FFix( fnt ); - int numTicks = fnt <= 0.5 ? - static_cast( this->FFix( fnt ) ) : static_cast( this->FFix( fnt ) + 1 ); + this->ArcMinorTickActor->GetProperty()->SetLineWidth(minorThickness); - // If not enough tick points in this decade, scale down - double div = 1.; - if ( numTicks < 5 ) - { - div = 2.; - } - if ( numTicks <= 2 ) - { - div = 5.; - } - if ( div != 1.) - { - delta /= div; - } + // last polar axis line width is set in BuildRadialAxes() function - // Finally calculate number of tick points - this->NumberOfPolarAxisTicks = 0; - while ( delta * this->NumberOfPolarAxisTicks <= this->MaximumRadius ) - { - ++ this->NumberOfPolarAxisTicks; - } + // Build polar axis ticks + if (this->Log) + { + this->BuildLabelsLog(); + this->BuildPolarArcsLog(); } - else // if ( this->AutoSubdividePolarAxis || this->NumberOfPolarAxisTicks ... ) + else { - // Use pre-set number of arcs when it is valid and no auto-subdivision was requested - delta = this->MaximumRadius / ( this->NumberOfPolarAxisTicks - 1 ); + // Build polar axis labels + this->BuildPolarAxisLabelsArcs(); } - // Set major start and delta corresponding to range and coordinates - this->PolarAxis->SetMajorRangeStart( 0. ); - this->PolarAxis->SetDeltaRangeMajor( delta ); - this->PolarAxis->SetMajorStart( vtkAxisActor::VTK_AXIS_TYPE_X, x0 ); - - // Build in numerical robustness to avoid truncation errors at endpoint - delta *= VTK_POLAR_AXES_ACTOR_RTOL; - this->PolarAxis->SetDeltaMajor( vtkAxisActor::VTK_AXIS_TYPE_X, delta ); -} - + // Set title relative location from the axis + if (this->PolarAxisTitleLocation == VTK_TITLE_BOTTOM) + { + this->PolarAxis->SetTitleAlignLocation(vtkAxisActor::VTK_ALIGN_BOTTOM); + } + else + { + this->PolarAxis->SetTitleAlignLocation(vtkAxisActor::VTK_ALIGN_POINT2); + } + + // Build radial axes + this->BuildRadialAxes(); + + // Build ticks located on the last arc + if (this->PolarTickVisibility) + { + this->BuildArcTicks(); + } + + // color copy + vtkProperty* prop = this->PolarArcsActor->GetProperty(); + double color[3]; + prop->GetColor(color); + this->ArcTickActor->GetProperty()->SetColor(color); + this->ArcMinorTickActor->GetProperty()->SetColor(color); + + // Update axis title follower + vtkAxisFollower* follower = axis->GetTitleActor(); + + follower->SetAxis(axis); + follower->SetEnableDistanceLOD(this->EnableDistanceLOD); + follower->SetDistanceLODThreshold(this->DistanceLODThreshold); + follower->SetEnableViewAngleLOD(this->EnableViewAngleLOD); + follower->SetViewAngleLODThreshold(this->ViewAngleLODThreshold); + + // Update axis title follower + vtkAxisFollower* expFollower = this->PolarAxis->GetExponentActor(); + expFollower->SetAxis(this->PolarAxis); + expFollower->SetEnableDistanceLOD(this->EnableDistanceLOD); + expFollower->SetDistanceLODThreshold(this->DistanceLODThreshold); + expFollower->SetEnableViewAngleLOD(this->EnableViewAngleLOD); + expFollower->SetViewAngleLODThreshold(this->ViewAngleLODThreshold); + + // Update axis label followers + vtkAxisFollower** labelActors = axis->GetLabelActors(); + int numberOfLabels = axis->GetNumberOfLabelsBuilt(); + for (int i = 0; i < numberOfLabels; ++i) + { + labelActors[i]->SetAxis(axis); + labelActors[i]->SetEnableDistanceLOD(this->EnableDistanceLOD); + labelActors[i]->SetDistanceLODThreshold(this->DistanceLODThreshold); + labelActors[i]->SetEnableViewAngleLOD(this->EnableViewAngleLOD); + labelActors[i]->SetViewAngleLODThreshold(this->ViewAngleLODThreshold); + } + + // Build polar axis + this->PolarAxis->BuildAxis(viewport, true); + + // Scale appropriately + this->AutoScale(viewport); + + this->BuildTime.Modified(); +} + +void vtkPolarAxesActor::AutoComputeTicksProperties() +{ + // set major tick size as 0.02 * majorRadius + this->PolarAxisMajorTickSize = 0.02 * this->MaximumRadius; + this->LastRadialAxisMajorTickSize = this->PolarAxisMajorTickSize; + this->ArcMajorTickSize = this->PolarAxisMajorTickSize; + + // set DeltaRangeMajor according to Range[1] magnitude + double rangeLength = fabs(this->PolarAxis->GetRange()[1] - this->PolarAxis->GetRange()[0]); + + // we would like no more than 15 ticks + double threshold = log10(1.5); + double log10RangeLength = log10(rangeLength); + + double stepPow10 = (log10RangeLength - std::floor(log10RangeLength) < threshold) ? std::floor(log10RangeLength) - 1.0: std::floor(log10RangeLength); + + this->DeltaRangeMajor = std::pow(10.0, stepPow10); + this->DeltaRangeMinor = this->DeltaRangeMajor / 2.0; +} +//----------------------------------------------------------------------------- +void vtkPolarAxesActor::SetCommonAxisAttributes(vtkAxisActor* axis) +{ + vtkProperty* prop = this->GetProperty(); + prop->SetAmbient(1.0); + prop->SetDiffuse(0.0); + axis->SetProperty(prop); + + axis->SetScreenSize(this->ScreenSize); + + // Common space and range attributes + axis->SetCamera(this->Camera); + axis->SetBounds(this->Bounds); + + // User defined range + axis->SetRange(this->Range[0], this->Range[1]); + + // Axis scale type + axis->SetLog(this->Log); + + // Major and minor ticks draw begins at Range[0] + axis->SetMajorRangeStart(axis->GetRange()[0]); + axis->SetMinorRangeStart(axis->GetRange()[0]); + + axis->SetCalculateTitleOffset(0); + axis->SetCalculateLabelOffset(0); + + // Set polar axis ticks + axis->SetTickVisibility(this->AxisTickVisibility && this->PolarTickVisibility); + + // Set polar axis minor ticks + axis->SetMinorTicksVisible(this->AxisMinorTickVisibility && this->PolarTickVisibility); + + axis->SetTickLocation(this->TickLocation); +} + +void vtkPolarAxesActor::SetPolarAxisAttributes(vtkAxisActor* axis) +{ + // Set polar axis lines + axis->SetAxisVisibility(this->PolarAxisVisibility); + + // #### Warning #### : Set this property BEFORE apply the ticks thickness of the vtkAxisActor instances + axis->SetAxisLinesProperty(this->PolarAxisProperty); + + // Set polar axis title + axis->SetTitleVisibility(this->PolarTitleVisibility); + axis->SetTitle(this->PolarAxisTitle); + axis->SetTitleTextProperty(this->PolarAxisTitleTextProperty); + + // Set Labels exponent value + if (this->ExponentLocation == VTK_EXPONENT_BOTTOM) + { + axis->SetExponentLocation(vtkAxisActor::VTK_ALIGN_BOTTOM); + axis->SetExponentVisibility(true); + } + else if (this->ExponentLocation == VTK_EXPONENT_EXTERN) + { + axis->SetExponentLocation(vtkAxisActor::VTK_ALIGN_POINT2); + axis->SetExponentVisibility(true); + } + else + { + axis->SetExponentVisibility(false); + } + + // Set polar axis labels + axis->SetLabelVisibility(this->PolarLabelVisibility); + axis->SetLabelTextProperty(this->PolarAxisLabelTextProperty); + + // compute tick length, and delta Range values (if log == 1, deltaRange properties will be overwritten) + if (this->AutoSubdividePolarAxis) + { + this->AutoComputeTicksProperties(); + } + + axis->SetMajorTickSize(this->PolarAxisMajorTickSize); + + axis->SetMinorTickSize(this->PolarAxisTickRatioSize * this->PolarAxisMajorTickSize); + + // Set the value between two ticks + axis->SetDeltaRangeMajor(this->DeltaRangeMajor); + axis->SetDeltaRangeMinor(this->DeltaRangeMinor); +} + +//----------------------------------------------------------------------------- +inline double vtkPolarAxesActor::FFix(double value) +{ + int ivalue = static_cast(value); + return ivalue; +} + +//----------------------------------------------------------------------------- +inline double vtkPolarAxesActor::FSign(double value, double sign) +{ + value = fabs(value); + if (sign < 0.) + { + value *= -1.; + } + return value; +} + +//----------------------------------------------------------------------------- +void vtkPolarAxesActor::CreateRadialAxes(int axisCount) +{ + // If number of radial axes does not change, do nothing + if (this->NumberOfRadialAxes == axisCount) + { + return; + } + + // Delete existing secondary radial axes + if (this->RadialAxes) + { + for (int i = 0; i < this->NumberOfRadialAxes; ++ i) + { + if (this->RadialAxes[i]) + { + this->RadialAxes[i]->Delete(); + this->RadialAxes[i] = NULL; + } + } + delete[] this->RadialAxes; + this->RadialAxes = NULL; + } + + // Create and set n radial axes of type X + this->NumberOfRadialAxes = axisCount; + + // Create requested number of secondary radial axes + this->RadialAxes = new vtkAxisActor* [this->NumberOfRadialAxes]; + for (int i = 0; i < this->NumberOfRadialAxes; ++ i) + { + // Create axis of type X + this->RadialAxes[i] = vtkAxisActor::New(); + vtkAxisActor* axis = this->RadialAxes[i]; + axis->SetAxisTypeToX(); + axis->SetCalculateTitleOffset(0); + axis->SetCalculateLabelOffset(0); + axis->SetLabelOffset(0); + axis->SetTitleOffset(2); + axis->SetLabelVisibility(0); + axis->SetUse2DMode(this->PolarAxis->GetUse2DMode()); + } + + this->Modified(); +} + +//----------------------------------------------------------------------------- +void vtkPolarAxesActor::BuildRadialAxes() +{ + bool originToPolarAxis = this->RadialAxesOriginToPolarAxis != 0.0; + + // set MaximumAngle and MinimumAngle range: [0.0; 360.0] + double angleSection = (this->MaximumAngle > this->MinimumAngle)? + this->MaximumAngle - this->MinimumAngle: 360.0 - fabs(this->MaximumAngle - this->MinimumAngle); + + if (vtkMathUtilities::FuzzyCompare(this->MaximumAngle, this->MinimumAngle) || angleSection == 360.0) + { + angleSection = 360.0; + } + + bool positiveSection = false; + double dAlpha = this->DeltaAngleRadialAxes; + double alphaDeg, currentAlpha; + + // current ellipse angle + double actualAngle; + int i = 0; + + double minorThickness; + + double alphaStart = (originToPolarAxis) ? this->MinimumAngle + dAlpha: std::floor(this->MinimumAngle / dAlpha) * dAlpha + dAlpha; + double alphaStop = angleSection + this->MinimumAngle + dAlpha; + + int n = (angleSection == 360.0)? 0:1; + double intPart, fractPart; + fractPart = modf((alphaStop - alphaStart) / dAlpha, &intPart); + + n += intPart; + + if (fractPart == 0.0) + { + n--; + } + + if (n > VTK_MAXIMUM_NUMBER_OF_RADIAL_AXES) + { + this->DeltaAngleRadialAxes = angleSection / n; + dAlpha = this->DeltaAngleRadialAxes; + } + if (this->DeltaAngleRadialAxes >= angleSection || n == 0) + { + n = 1; + alphaStart = angleSection + this->MinimumAngle; + } + + // init radial axis. Does nothing if number of radial axes doesn't change + this->CreateRadialAxes(n); + + char titleValue[64]; + for (alphaDeg = alphaStart; alphaDeg <= alphaStop && i < this->NumberOfRadialAxes; alphaDeg += dAlpha, i++) + { + currentAlpha = alphaDeg; + + if (currentAlpha > angleSection + this->MinimumAngle) + { + currentAlpha = angleSection + this->MinimumAngle; + } + + // Calculate startpoint coordinates + double thetaEllipse = this->ComputeEllipseAngle(currentAlpha, this->Ratio); + double xStart = this->Pole[0] + this->MinimumRadius * cos(thetaEllipse); + double yStart = this->Pole[1] + this->MinimumRadius * this->Ratio * sin(thetaEllipse); + + // Calculate endpoint coordinates + double xEnd = this->Pole[0] + this->MaximumRadius * cos(thetaEllipse); + double yEnd = this->Pole[1] + this->MaximumRadius * this->Ratio * sin(thetaEllipse); + + // radius angle (different from angle used to compute ellipse point) + actualAngle = vtkMath::DegreesFromRadians(atan2(yEnd - this->Pole[1], xEnd - this->Pole[0])); + + // to keep angle positive for the last ones + if (actualAngle > 0.0 || this->MinimumAngle < 180.0) + { + positiveSection = true; + } + + if (actualAngle < 0.0 && positiveSection) + { + actualAngle += 360.0; + } + + // Set radial axis endpoints + vtkAxisActor* axis = this->RadialAxes[i]; + + // The last arc has its own property + if ((alphaDeg + dAlpha) >= alphaStop) + { + axis->SetAxisLinesProperty(this->LastRadialAxisProperty); + axis->SetTitleTextProperty(this->LastRadialAxisTextProperty); + } + else + { + axis->SetAxisLinesProperty(this->SecondaryRadialAxesProperty); + axis->SetTitleTextProperty(this->SecondaryRadialAxesTextProperty); + } + + axis->GetPoint1Coordinate()->SetValue(xStart, yStart, this->Pole[2]); + axis->GetPoint2Coordinate()->SetValue(xEnd, yEnd, this->Pole[2]); + + // set the range steps + axis->SetDeltaRangeMajor(this->PolarAxis->GetDeltaRangeMajor()); + axis->SetDeltaRangeMinor(this->PolarAxis->GetDeltaRangeMinor()); + + // Set common axis attributes + this->SetCommonAxisAttributes(axis); + + // Set radial axis lines + axis->SetAxisVisibility(this->RadialAxesVisibility); + + // Set title relative location from the axis + if (this->RadialAxisTitleLocation == VTK_TITLE_BOTTOM) + { + axis->SetTitleAlignLocation(vtkAxisActor::VTK_ALIGN_BOTTOM); + } + else + { + axis->SetTitleAlignLocation(vtkAxisActor::VTK_ALIGN_POINT2); + } + + // Set radial axis title with polar angle as title for non-polar axes + if (this->PolarAxisVisibility && fabs(alphaDeg) < 2.) + { + // Prevent conflict between radial and polar axes titles + axis->SetTitleVisibility(false); + + if (fabs(alphaDeg) < this->SmallestVisiblePolarAngle) + { + // Do not show radial axes too close to polar axis + axis->SetAxisVisibility(false); + } + } + else + { + // Use polar angle as a title for the radial axis + axis->SetTitleVisibility(this->RadialTitleVisibility); + axis->GetTitleTextProperty()->SetColor(this->LastRadialAxisProperty->GetColor()); + std::ostringstream title; + + title.setf(std::ios::fixed, std::ios::floatfield); + sprintf(titleValue, this->RadialAngleFormat, actualAngle); + title << titleValue << (this->RadialUnits ? " deg" : ""); + axis->SetTitle(title.str().c_str()); + + // Update axis title followers + axis->GetTitleActor()->SetAxis(axis); + axis->GetTitleActor()->SetEnableDistanceLOD(this->EnableDistanceLOD); + axis->GetTitleActor()->SetDistanceLODThreshold(this->DistanceLODThreshold); + axis->GetTitleActor()->SetEnableViewAngleLOD(this->EnableViewAngleLOD); + axis->GetTitleActor()->SetViewAngleLODThreshold(this->ViewAngleLODThreshold); + } + + // Ticks for the last radial axis + if (angleSection != 360.0 && i == this->NumberOfRadialAxes - 1) + { + // axis Type. We assume the polar graph is built in the local plane x-y + if ((actualAngle > 45.0 && actualAngle < 135.0) || + (actualAngle > 225.0 && actualAngle < 315.0)) + { + axis->SetAxisTypeToY(); + } + else + axis->SetAxisTypeToX(); + + // Set polar axis ticks + axis->SetTickVisibility(this->AxisTickVisibility && this->PolarTickVisibility); + axis->SetMajorTickSize(this->LastRadialAxisMajorTickSize); + + // Set polar axis minor ticks + axis->SetMinorTicksVisible(this->AxisMinorTickVisibility && this->PolarTickVisibility); + axis->SetMinorTickSize(this->LastAxisTickRatioSize * this->LastRadialAxisMajorTickSize); + + // Set the tick orientation + axis->SetTickLocation(this->TickLocation); + + axis->GetAxisMajorTicksProperty()->SetLineWidth(this->LastRadialAxisMajorTickThickness); + minorThickness = this->LastRadialAxisMajorTickThickness * LastAxisTickRatioThickness; + if (minorThickness < 1.0) + { + minorThickness = 1.0; + } + axis->GetAxisMinorTicksProperty()->SetLineWidth(minorThickness); + } + else + { + axis->SetLabelVisibility(0); + axis->SetTickVisibility(0); + } + } +} + +//----------------------------------------------------------------------------- +void vtkPolarAxesActor::BuildArcTicks() +{ + bool originToPolarAxis = this->ArcTicksOriginToPolarAxis != 0.0; + + // set MaximumAngle and MinimumAngle range: [0.0; 360.0] + double angleSection = (this->MaximumAngle > this->MinimumAngle)? + this->MaximumAngle - this->MinimumAngle: 360.0 - fabs(this->MaximumAngle - this->MinimumAngle); + + if (vtkMathUtilities::FuzzyCompare(this->MaximumAngle, this->MinimumAngle) || angleSection == 360.0) + { + angleSection = 360.0; + } + + // Create requested number of radial axes + double dAlpha = this->DeltaAngleMajor; + double alphaStart; + + alphaStart = (originToPolarAxis) ? this->MinimumAngle + dAlpha: std::floor(this->MinimumAngle / dAlpha) * dAlpha + dAlpha; + + for (double alphaDeg = alphaStart; alphaDeg < (angleSection + this->MinimumAngle); alphaDeg += dAlpha) + { + double thetaEllipse = ComputeEllipseAngle(alphaDeg, this->Ratio); + StoreTicksPtsFromParamEllipse(this->MaximumRadius, thetaEllipse, this->ArcMajorTickSize, this->ArcMajorTickPts); + } + + // Copy/paste should be replaced with a python-like generator to provide parameters to StoreTicksPtsFromParamEllipse() + // without running twice through the ellipse + + dAlpha = this->DeltaAngleMinor; + alphaStart = (originToPolarAxis) ? this->MinimumAngle + dAlpha: std::floor(this->MinimumAngle / dAlpha) * dAlpha + dAlpha; + for (double alphaDeg = alphaStart; alphaDeg < (angleSection + this->MinimumAngle); alphaDeg += dAlpha) + { + double thetaEllipse = ComputeEllipseAngle(alphaDeg, this->Ratio); + StoreTicksPtsFromParamEllipse(this->MaximumRadius, thetaEllipse, this->ArcTickRatioSize * this->ArcMajorTickSize, this->ArcMinorTickPts); + } + + // set vtk object to draw the ticks + vtkNew majorPts; + vtkNew minorPts; + vtkNew majorLines; + vtkNew minorLines; + vtkIdType ptIds[2]; + int numTickPts, numLines, i; + this->ArcTickPolyData->SetPoints(majorPts.Get()); + this->ArcTickPolyData->SetLines(majorLines.Get()); + this->ArcMinorTickPolyData->SetPoints(minorPts.Get()); + this->ArcMinorTickPolyData->SetLines(minorLines.Get()); + + if (this->ArcTickVisibility) + { + numTickPts = this->ArcMajorTickPts->GetNumberOfPoints(); + for (i = 0; i < numTickPts; i++) + { + majorPts->InsertNextPoint(this->ArcMajorTickPts->GetPoint(i)); + } + } + if (this->ArcMinorTickVisibility) + { + // In 2D mode, the minorTickPts for yz portion or xz portion have been removed. + numTickPts = this->ArcMinorTickPts->GetNumberOfPoints(); + for (i = 0; i < numTickPts; i++) + { + minorPts->InsertNextPoint(this->ArcMinorTickPts->GetPoint(i)); + } + } + + // create lines + if (this->ArcTickVisibility) + { + numLines = majorPts->GetNumberOfPoints() / 2; + for (i = 0; i < numLines; i++) + { + ptIds[0] = 2 * i; + ptIds[1] = 2 * i + 1; + majorLines->InsertNextCell(2, ptIds); + } + } + if (this->ArcMinorTickVisibility) + { + numLines = minorPts->GetNumberOfPoints() / 2; + for (i = 0; i < numLines; i++) + { + ptIds[0] = 2 * i; + ptIds[1] = 2 * i + 1; + minorLines->InsertNextCell(2, ptIds); + } + } +} + +void vtkPolarAxesActor::StoreTicksPtsFromParamEllipse(double a, double angleEllipseRad, double tickSize, vtkPoints* tickPts) +{ + // plane point: point located in the plane of the ellipse + // normal Dir Point: point located according to the direction of the z vector + + // inside direction: direction from the arc to its center for plane points, and positive z direction + // outside direction: direction from the arc to the outer radial direction for plane points, and negative z direction + + int i; + double planeInPt[3], planeOutPt[3], normalDirPt[3], invNormalDirPt[3]; + + if (!tickPts) + { + return; + } + + double b = a * this->Ratio; + double xArc = this->Pole[0] + a * cos(angleEllipseRad); + double yArc = this->Pole[1] + b * sin(angleEllipseRad); + double ellipsePt[3] = {xArc, yArc, this->Pole[2]}; + + double deltaVector[3] = {a * cos(angleEllipseRad), b * sin(angleEllipseRad), 0.0 }; + vtkMath::Normalize(deltaVector); + + double orthoVector[3] = {0.0, 0.0, 1.0}; + + // init + for (i = 0;i<3;i++) + { + planeInPt[i] = planeOutPt[i] = normalDirPt[i] = invNormalDirPt[i] = ellipsePt[i]; + } + + if (this->TickLocation == vtkAxisActor::VTK_TICKS_INSIDE || this->TickLocation == vtkAxisActor::VTK_TICKS_BOTH) + { + for (i = 0;i<3;i++) + { + planeInPt[i] = ellipsePt[i] - tickSize * deltaVector[i]; + } + + for (i = 0;i<3;i++) + { + normalDirPt[i] = ellipsePt[i] + tickSize * orthoVector[i]; + } + } + + if (this->TickLocation == vtkAxisActor::VTK_TICKS_OUTSIDE || this->TickLocation == vtkAxisActor::VTK_TICKS_BOTH) + { + for (i = 0;i<3;i++) + { + planeOutPt[i] = ellipsePt[i] + tickSize * deltaVector[i]; + } + + for (i = 0;i<3;i++) + { + invNormalDirPt[i] = ellipsePt[i] - tickSize * orthoVector[i]; + } + } + + tickPts->InsertNextPoint(planeInPt); + tickPts->InsertNextPoint(planeOutPt); + tickPts->InsertNextPoint(normalDirPt); + tickPts->InsertNextPoint(invNormalDirPt); +} + //----------------------------------------------------------------------------- void vtkPolarAxesActor::BuildPolarAxisLabelsArcs() { + double angleSection = (this->MaximumAngle > this->MinimumAngle) ? + this->MaximumAngle - this->MinimumAngle: 360.0 - + fabs(this->MaximumAngle - this->MinimumAngle); + + // if Min and max angle are the same, interpret it as 360 segment opening + if (vtkMathUtilities::FuzzyCompare(this->MaximumAngle, this->MinimumAngle)) + { + angleSection = 360.0; + } + + // Prepare trigonometric quantities + vtkIdType arcResolution = static_cast( + angleSection * (VTK_POLAR_ARC_RESOLUTION_PER_DEG / this->Ratio)); + + // Principal Arc points + vtkNew polarArcsPoints; + this->PolarArcs->SetPoints(polarArcsPoints.Get()); + + // Principal Arc lines + vtkNew polarArcsLines; + this->PolarArcs->SetLines(polarArcsLines.Get()); + + // Secondary Arc points + vtkNew secondaryPolarArcsPoints; + this->SecondaryPolarArcs->SetPoints(secondaryPolarArcsPoints.Get()); + + // Secondary Arc lines + vtkNew secondaryPolarArcsLines; + this->SecondaryPolarArcs->SetLines(secondaryPolarArcsLines.Get()); + + vtkAxisActor* axis = this->PolarAxis; + + // Base ellipse arc value, refers to world coordinate system + double axisLength = this->MaximumRadius - this->MinimumRadius; + double rangeLength = axis->GetRange()[1] - axis->GetRange()[0]; + double rangeScale = axisLength / rangeLength; + + // Label values refers to range values + double valueRange = axis->GetRange()[0]; + double currentValue; + double deltaRange = axis->GetDeltaRangeMajor(); + double deltaArc; + // Prepare storage for polar axis labels - vtkStringArray* labels = vtkStringArray::New(); - labels->SetNumberOfValues( this->NumberOfPolarAxisTicks ); + std::list labelValList; + + vtkIdType pointIdOffset = 0; + bool isInnerArc, isArcVisible, isLastArc; + + currentValue = axis->GetRange()[0]; + while (currentValue < axis->GetRange()[1]) + { + currentValue = + (valueRange > axis->GetRange()[1]) ? axis->GetRange()[1]: valueRange; + deltaArc = (currentValue - axis->GetRange()[0]) * rangeScale; + + isInnerArc = + currentValue > axis->GetRange()[0] && currentValue < axis->GetRange()[1]; + isArcVisible = !isInnerArc || this->DrawPolarArcsGridlines; + isLastArc = currentValue == axis->GetRange()[1]; + + // Store value + labelValList.push_back(currentValue); + + // Build polar arcs for non-zero values + if (deltaArc + this->MinimumRadius > 0. && isArcVisible) + { + // Create elliptical polar arc with corresponding to this tick mark + vtkNew arc; + arc->SetCenter(this->Pole); + arc->SetRatio(this->Ratio); + arc->SetNormal(0., 0., 1.); + arc->SetMajorRadiusVector(deltaArc + this->MinimumRadius, 0.0, 0.0); + arc->SetStartAngle(this->MinimumAngle); + arc->SetSegmentAngle(angleSection); + arc->SetResolution(arcResolution); + arc->Update(); + + if (isLastArc) + { + // Add polar arc + vtkPoints* arcPoints = NULL; + vtkIdType nPoints = 0; + vtkIdType* arcPointIds = NULL; + if (arc->GetOutput()->GetNumberOfPoints() > 0) + { + arcPoints = arc->GetOutput()->GetPoints(); + nPoints = arcResolution + 1; + arcPointIds = new vtkIdType[nPoints]; + for (vtkIdType j = 0; j < nPoints; ++ j) + { + polarArcsPoints->InsertNextPoint(arcPoints->GetPoint(j)); + arcPointIds[j] = j; + } + polarArcsLines->InsertNextCell(nPoints, arcPointIds); + } + + // Clean up + delete [] arcPointIds; + } + else + { + // Append new secondary polar arc to existing ones + vtkPoints* arcPoints = NULL; + vtkIdType nPoints = 0; + vtkIdType* arcPointIds = NULL; + if (arc->GetOutput()->GetNumberOfPoints() > 0) + { + arcPoints = arc->GetOutput()->GetPoints(); + nPoints = arcResolution + 1; + arcPointIds = new vtkIdType[nPoints]; + + for (vtkIdType j = 0; j < nPoints; ++ j) + { + secondaryPolarArcsPoints->InsertNextPoint(arcPoints->GetPoint(j)); + arcPointIds[j] = pointIdOffset + j; + } + secondaryPolarArcsLines->InsertNextCell(nPoints, arcPointIds); + } + + // Clean up + delete [] arcPointIds; + + // Update polyline cell offset + pointIdOffset += nPoints; + } + } + + // Move to next value + valueRange += deltaRange; + } + + // set up vtk collection to store labels + vtkNew labels; + + if (this->ExponentLocation != VTK_EXPONENT_LABELS) + { + // it modifies the values of labelValList + std::string commonLbl = FindExponentAndAdjustValues(labelValList); + axis->SetExponent(commonLbl.c_str()); + + this->GetSignificantPartFromValues(labels.Get(), labelValList); + } + else + { + axis->SetExponent(""); + // construct label string array + labels->SetNumberOfValues(labelValList.size()); + + std::list::iterator itList; + std::size_t i = 0; + for (itList = labelValList.begin(); + itList != labelValList.end(); i++, itList++) + { + char label[64]; + sprintf(label, this->PolarLabelFormat, *itList); + labels->SetValue(i, label); + } + } + + // Store labels + axis->SetLabels(labels.Get()); +} + +//----------------------------------------------------------------------------- +void vtkPolarAxesActor::BuildPolarArcsLog() +{ + double angleSection = (this->MaximumAngle > this->MinimumAngle)? + this->MaximumAngle - this->MinimumAngle: 360.0 - + fabs(this->MaximumAngle - this->MinimumAngle); + + // if Min and max angle are the same, interpret it as 360 segment opening + if (vtkMathUtilities::FuzzyCompare(this->MaximumAngle, this->MinimumAngle)) + { + angleSection = 360.0; + } + + vtkIdType arcResolution = + static_cast(angleSection * (VTK_POLAR_ARC_RESOLUTION_PER_DEG / this->Ratio)); + + // Principal Arc points + vtkNew polarArcsPoints; + this->PolarArcs->SetPoints(polarArcsPoints.Get()); + + // Principal Arc lines + vtkNew polarArcsLines; + this->PolarArcs->SetLines(polarArcsLines.Get()); + + // Secondary Arc points + vtkNew secondaryPolarArcsPoints; + this->SecondaryPolarArcs->SetPoints(secondaryPolarArcsPoints.Get()); + + // Secondary Arc lines + vtkNew secondaryPolarArcsLines; + this->SecondaryPolarArcs->SetLines(secondaryPolarArcsLines.Get()); + + //--- prepare significant values ---- + double miniAngleEllipseRad = ComputeEllipseAngle(this->MinimumAngle, this->Ratio); + + // Distance from Pole to Range[0] + vtkAxisActor* axis = this->PolarAxis; + + double deltaVector[3], polarAxisUnitVect[3]; + vtkMath::Subtract(axis->GetPoint2(), axis->GetPoint1(), deltaVector); + vtkMath::Subtract(axis->GetPoint2(), axis->GetPoint1(), polarAxisUnitVect); + vtkMath::Normalize(polarAxisUnitVect); + + // polar axis actor length + double axisLength = vtkMath::Norm(deltaVector); + + // conversion factor + double rangeScaleLog = axisLength / log10(axis->GetRange()[1] / axis->GetRange()[0]); + + // reuse deltaVector + vtkMath::Subtract(axis->GetPoint1(), this->Pole, deltaVector); + double distanceAxisPoint1FromPole = vtkMath::Norm(deltaVector); - // Prepare trigonometric quantities - double thetaPolar = vtkMath::RadiansFromDegrees( this->MinimumAngle ); - double cosThetaPolar = cos( thetaPolar ); - double sinThetaPolar = sin( thetaPolar ); - double angularSector = this->MaximumAngle - this->MinimumAngle; - vtkIdType arcResolution - = static_cast( angularSector * VTK_POLAR_ARC_RESOLUTION_PER_DEG ); - - // Arc points - vtkPoints* polarArcsPoints = vtkPoints::New(); - this->PolarArcs->SetPoints( polarArcsPoints ); - polarArcsPoints->Delete(); - - // Arc lines - vtkCellArray* polarArcsLines = vtkCellArray::New(); - this->PolarArcs->SetLines( polarArcsLines ); - polarArcsLines->Delete(); - - // Retreave label features - vtkAxisActor* axis = this->PolarAxis; - double delta = axis->GetDeltaMajor( vtkAxisActor::VTK_AXIS_TYPE_X ); - double value = axis->GetMajorRangeStart(); + double base = 10.0; + double log10Range0 = log10(axis->GetRange()[0]); + double log10Range1 = log10(axis->GetRange()[1]); + double lowBound = std::pow(base, static_cast(std::floor(log10Range0))); + double upBound = std::pow(base, static_cast(ceil(log10Range1))); + + int i; + double tickVal, tickRangeVal, indexTickRangeValue; - // Now create labels and polar arcs - const char *format = this->PolarLabelFormat; - char label[64]; vtkIdType pointIdOffset = 0; - for ( int i = 0; i < this->NumberOfPolarAxisTicks; ++ i ) + bool isInnerArc, isArcVisible, isLastArc; + double a, b; + double epsilon = 1e-8; + + for (indexTickRangeValue = lowBound; indexTickRangeValue <= upBound; indexTickRangeValue *= base) { - // Store label - sprintf( label, format, value ); - labels->SetValue( i, label ); + // to keep major values as power of 10 + tickRangeVal = indexTickRangeValue; - // Build polar arcs for non-zero values - if ( value > 0. ) + isInnerArc = tickRangeVal > lowBound && tickRangeVal < upBound; + isArcVisible = !isInnerArc || this->DrawPolarArcsGridlines; + isLastArc = tickRangeVal == upBound; + + if (!isArcVisible) { - // Compute polar vector for this tick mark - double xPolar = value * cosThetaPolar; - double yPolar = value * sinThetaPolar; - - // Create polar arc with corresponding to this tick mark - vtkArcSource* arc = vtkArcSource::New(); - arc->UseNormalAndAngleOn(); // Use new arc source API - arc->SetCenter( this->Pole ); - arc->SetNormal( 0., 0., 1. ); - arc->SetPolarVector( xPolar, yPolar, 0. ); - arc->SetAngle( angularSector ); - arc->SetResolution( arcResolution ); - arc->Update(); + continue; + } + + if (tickRangeVal < axis->GetRange()[0]) + { + tickRangeVal = axis->GetRange()[0]; + } + + if (tickRangeVal > axis->GetRange()[1]) + { + tickRangeVal = axis->GetRange()[1]; + } + + // conversion range value to world value + tickVal = (log10(tickRangeVal) - log10Range0) * rangeScaleLog; + + // Vector from Pole to major tick + for (i = 0; i<3; i++) + { + deltaVector[i] = polarAxisUnitVect[i]* (tickVal + distanceAxisPoint1FromPole); + } + + if (vtkMath::Norm(deltaVector) == 0.0) + { + continue; + } + + // epsilon is a very low value. vtkMathUtilities::FuzzyCompare is not fuzzy enough ... + if (fabs(fabs(miniAngleEllipseRad) - vtkMath::Pi() / 2.0) < epsilon) + { + b = deltaVector[1] / sin(miniAngleEllipseRad); + a = b / this->Ratio; + } + else + { + a = deltaVector[0] / cos(miniAngleEllipseRad); + } + // Create elliptical polar arc with corresponding to this tick mark + vtkNew arc; + arc->SetCenter(this->Pole); + arc->SetRatio(this->Ratio); + arc->SetNormal(0., 0., 1.); + arc->SetMajorRadiusVector(a, 0.0, 0.0); + arc->SetStartAngle(this->MinimumAngle); + arc->SetSegmentAngle(angleSection); + arc->SetResolution(arcResolution); + arc->Update(); + + if (isLastArc) + { + // Add principal polar arc + vtkPoints* arcPoints = NULL; + vtkIdType nPoints; + vtkIdType* arcPointIds = NULL; + if (arc->GetOutput()->GetNumberOfPoints() > 0) + { + arcPoints = arc->GetOutput()->GetPoints(); + nPoints = arcResolution + 1; + arcPointIds = new vtkIdType[nPoints]; + for (vtkIdType j = 0; j < nPoints; ++ j) + { + polarArcsPoints->InsertNextPoint(arcPoints->GetPoint(j)); + arcPointIds[j] = j; + } + polarArcsLines->InsertNextCell(nPoints, arcPointIds); + } + // Clean up + delete [] arcPointIds; + } + else + { // Append new polar arc to existing ones - vtkPoints* arcPoints = arc->GetOutput()->GetPoints(); - vtkIdType nPoints = arcResolution + 1; - vtkIdType* arcPointIds = new vtkIdType[nPoints]; - for ( vtkIdType j = 0; j < nPoints; ++ j ) + vtkPoints* arcPoints = NULL; + vtkIdType nPoints = 0; + vtkIdType* arcPointIds = NULL; + if (arc->GetOutput()->GetNumberOfPoints() > 0) { - polarArcsPoints->InsertNextPoint( arcPoints->GetPoint( j ) ); - arcPointIds[j] = pointIdOffset + j; + arcPoints = arc->GetOutput()->GetPoints(); + nPoints = arcResolution + 1; + arcPointIds = new vtkIdType[nPoints]; + for (vtkIdType j = 0; j < nPoints; ++ j) + { + secondaryPolarArcsPoints->InsertNextPoint(arcPoints->GetPoint(j)); + arcPointIds[j] = pointIdOffset + j; + } + secondaryPolarArcsLines->InsertNextCell(nPoints, arcPointIds); } - polarArcsLines->InsertNextCell( nPoints, arcPointIds ); - // Clean up - arc->Delete(); delete [] arcPointIds; // Update polyline cell offset pointIdOffset += nPoints; } + } +} - // Move to next value - value += delta; +//----------------------------------------------------------------------------- +void vtkPolarAxesActor::BuildLabelsLog() +{ + // Prepare storage for polar axis labels + std::list labelValList; + + vtkAxisActor* axis = this->PolarAxis; + double base = 10.0; + + if (axis->GetRange()[0] <= 0.0) + { + return; + } + + // define major ticks label values + double indexTickRangeValue; + double tickRangeVal; + double log10Range0 = log10(axis->GetRange()[0]); + double log10Range1 = log10(axis->GetRange()[1]); + double lowBound = std::pow(base, static_cast(std::floor(log10Range0))); + double upBound = std::pow(base, static_cast(ceil(log10Range1))); + + for (indexTickRangeValue = lowBound; indexTickRangeValue <= upBound; indexTickRangeValue *= base) + { + tickRangeVal = indexTickRangeValue; + + if (indexTickRangeValue < axis->GetRange()[0]) + { + tickRangeVal = axis->GetRange()[0]; + } + + else if (indexTickRangeValue > axis->GetRange()[1]) + { + tickRangeVal = axis->GetRange()[1]; + } + + labelValList.push_back(tickRangeVal); + } + + // set up vtk collection to store labels + vtkNew labels; + + if (this->ExponentLocation != VTK_EXPONENT_LABELS) + { + // it modifies the values of labelValList + std::string commonLbl = FindExponentAndAdjustValues(labelValList); + axis->SetExponent(commonLbl.c_str()); + + this->GetSignificantPartFromValues(labels.Get(), labelValList); + } + else + { + axis->SetExponent(""); + labels->SetNumberOfValues(labelValList.size()); + + std::list::iterator itList; + std::size_t i = 0; + for (itList = labelValList.begin(); + itList != labelValList.end(); i++, itList++) + { + char label[64]; + sprintf(label, this->PolarLabelFormat, *itList); + labels->SetValue(i, label); + } } // Store labels - this->PolarAxis->SetLabels( labels ); + axis->SetLabels(labels.Get()); +} + +//----------------------------------------------------------------------------- +void vtkPolarAxesActor::BuildPolarAxisLabelsArcsLog() +{ + this->BuildPolarArcsLog(); - // Clean up - labels->Delete(); + this->BuildLabelsLog(); // Update axis title follower - vtkAxisFollower* follower = axis->GetTitleActor(); - follower->SetAxis( axis ); - follower->SetScreenOffset( 2. * this->LabelScreenOffset + this->ScreenSize + 5 ); - follower->SetEnableDistanceLOD( this->EnableDistanceLOD ); - follower->SetDistanceLODThreshold( this->DistanceLODThreshold ); - follower->SetEnableViewAngleLOD( this->EnableViewAngleLOD ); - follower->SetViewAngleLODThreshold( this->ViewAngleLODThreshold ); + vtkAxisFollower* follower = this->PolarAxis->GetTitleActor(); + follower->SetAxis(this->PolarAxis); + follower->SetEnableDistanceLOD(this->EnableDistanceLOD); + follower->SetDistanceLODThreshold(this->DistanceLODThreshold); + follower->SetEnableViewAngleLOD(this->EnableViewAngleLOD); + follower->SetViewAngleLODThreshold(this->ViewAngleLODThreshold); + + // Update axis title follower + vtkAxisFollower* expFollower = this->PolarAxis->GetExponentActor(); + expFollower->SetAxis(this->PolarAxis); + expFollower->SetEnableDistanceLOD(this->EnableDistanceLOD); + expFollower->SetDistanceLODThreshold(this->DistanceLODThreshold); + expFollower->SetEnableViewAngleLOD(this->EnableViewAngleLOD); + expFollower->SetViewAngleLODThreshold(this->ViewAngleLODThreshold); // Update axis label followers - vtkAxisFollower** labelActors = axis->GetLabelActors(); - for( int i = 0; i < this->NumberOfPolarAxisTicks; ++ i ) + vtkAxisFollower** labelActors = this->PolarAxis->GetLabelActors(); + int labelCount = this->PolarAxis->GetNumberOfLabelsBuilt(); + for (int i = 0; i < labelCount; ++ i) + { + labelActors[i]->SetAxis(this->PolarAxis); + labelActors[i]->SetEnableDistanceLOD(this->EnableDistanceLOD); + labelActors[i]->SetDistanceLODThreshold(this->DistanceLODThreshold); + labelActors[i]->SetEnableViewAngleLOD(this->EnableViewAngleLOD); + labelActors[i]->SetViewAngleLODThreshold(this->ViewAngleLODThreshold); + } +} + +//----------------------------------------------------------------------------- +std::string vtkPolarAxesActor::FindExponentAndAdjustValues( + std::list& valuesList) +{ + std::list::iterator itDouble; + + double exponentMean = 0.0; + int count = 0; + + // find common exponent + for (itDouble = valuesList.begin(); itDouble != valuesList.end(); itDouble++) + { + if (*itDouble != 0.0) + { + double exponent = std::floor(log10(fabs(*itDouble))); + exponentMean += exponent; + count++; + } + } + + if (count == 0) + { + return ""; + } + + exponentMean /= count; + + // adjust exponent to int value. Round it if fract part != 0.0 + double intPart, fractPart; + fractPart = modf(exponentMean, &intPart); + + if (exponentMean < 0.0) { - labelActors[i]->SetAxis( axis ); - labelActors[i]->SetScreenOffset( this->LabelScreenOffset ); - labelActors[i]->SetEnableDistanceLOD( this->EnableDistanceLOD ); - labelActors[i]->SetDistanceLODThreshold( this->DistanceLODThreshold ); - labelActors[i]->SetEnableViewAngleLOD( this->EnableViewAngleLOD ); - labelActors[i]->SetViewAngleLODThreshold( this->ViewAngleLODThreshold ); + if (fabs(fractPart) >= 0.5) + { + intPart -= 1.0; + } + } + else + { + if (fabs(fractPart) >= 0.5) + { + intPart += 1.0; + } + } + exponentMean = intPart; + + // shift every values + for (itDouble = valuesList.begin(); itDouble != valuesList.end(); itDouble++) + { + if (*itDouble != 0.0) + { + *itDouble /= std::pow(10, exponentMean); + } + } + + // Layout of the exponent: + std::stringstream ss; + int exponentInt = static_cast(fabs(exponentMean)); + + // add sign + ss << (exponentMean >= 0.0 ? "+" : "-"); + + // add 0 for pow < 10 + if (exponentInt < 10.0) + { + ss << "0"; } + + ss << exponentInt; + + return ss.str(); } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::AutoScale( vtkViewport *viewport ) +void vtkPolarAxesActor::GetSignificantPartFromValues(vtkStringArray* valuesStr, + std::list& valuesList) { + if (!valuesStr || valuesList.size() == 0) + { + return; + } + + valuesStr->SetNumberOfValues(valuesList.size()); + + std::list::iterator itList; + std::size_t i = 0; + for (itList = valuesList.begin(); + itList != valuesList.end(); i++, itList++) + { + char label[64]; + if (this->ExponentLocation == VTK_EXPONENT_LABELS) + { + sprintf(label, this->PolarLabelFormat, *itList); + valuesStr->SetValue(i, label); + } + else + { + std::stringstream ss; + if (*itList == 0.0) + { + ss << std::fixed << std::setw(1) << std::setprecision(0) << 0.0; + valuesStr->SetValue(i, ss.str().c_str()); + continue; + } + + // get pow of ten of the value to set the precision of the label + int exponent = static_cast(std::floor(log10(fabs(*itList)))); + if (exponent < 0) + { + ss << std::fixed << std::setw(1) << setprecision(-exponent) << *itList; + } + else + { + ss << std::fixed << setprecision(1) << *itList; + } + + valuesStr->SetValue(i, ss.str().c_str()); + } + } +} +//----------------------------------------------------------------------------- +void vtkPolarAxesActor::AutoScale(vtkViewport *viewport) +{ // Scale polar axis title vtkAxisActor* axis = this->PolarAxis; double newTitleScale - = vtkAxisFollower::AutoScale( viewport, - this->Camera, - this->ScreenSize, - axis->GetTitleActor()->GetPosition() ); - axis->SetTitleScale( newTitleScale ); + = vtkAxisFollower::AutoScale(viewport, + this->Camera, + this->ScreenSize, + axis->GetTitleActor()->GetPosition()); + axis->SetTitleScale(newTitleScale); // Scale polar axis labels - vtkAxisFollower** labelActors = axis->GetLabelActors(); - for( int i = 0; i < axis->GetNumberOfLabelsBuilt(); ++ i ) - { - double newLabelScale - = vtkAxisFollower::AutoScale( viewport, - this->Camera, - this->ScreenSize, - labelActors[i]->GetPosition() ); - labelActors[i]->SetScale( newLabelScale ); - } + axis->SetLabelScale(newTitleScale); // Loop over radial axes - for ( int i = 0; i < this->NumberOfRadialAxes; ++ i ) + for (int i = 0; i < this->NumberOfRadialAxes; ++ i) { axis = this->RadialAxes[i]; // Scale title newTitleScale - = vtkAxisFollower::AutoScale( viewport, - this->Camera, - this->ScreenSize, - axis->GetTitleActor()->GetPosition() ); - axis->SetTitleScale( newTitleScale ); + = vtkAxisFollower::AutoScale(viewport, + this->Camera, + this->ScreenSize, + axis->GetTitleActor()->GetPosition()); + axis->SetTitleScale(newTitleScale); } } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetPole( double p[3] ) +void vtkPolarAxesActor::SetPole(double p[3]) { this->Pole[0] = p[0]; this->Pole[1] = p[1]; @@ -934,7 +2230,7 @@ void vtkPolarAxesActor::SetPole( double p[3] ) } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetPole( double x, double y, double z ) +void vtkPolarAxesActor::SetPole(double x, double y, double z) { this->Pole[0] = x; this->Pole[1] = y; @@ -946,44 +2242,17 @@ void vtkPolarAxesActor::SetPole( double x, double y, double z ) } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetNumberOfRadialAxes( vtkIdType n ) +void vtkPolarAxesActor::SetMinimumRadius(double r) { - // Limit number of redial axes - if ( n > VTK_MAXIMUM_NUMBER_OF_RADIAL_AXES ) - { - n = VTK_MAXIMUM_NUMBER_OF_RADIAL_AXES; - } - - // If number of radial axes does not change, do nothing - if ( this->NumberOfRadialAxes == n ) - { - return; - } - - // Delete existing radial axes - if ( this->RadialAxes ) - { - for ( int i = 0; i < this->NumberOfRadialAxes; ++ i ) - { - if ( this->RadialAxes[i] ) - { - this->RadialAxes[i]->Delete(); - this->RadialAxes[i] = NULL; - } - } - delete [] this->RadialAxes; - this->RadialAxes = NULL; - } - - // Create and set n radial axes of type X - this->NumberOfRadialAxes = n; - this->CreateRadialAxes(); + this->MinimumRadius = r > 0. ? r : 0.; + // Update bounds + this->CalculateBounds(); this->Modified(); } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetMaximumRadius( double r ) +void vtkPolarAxesActor::SetMaximumRadius(double r) { this->MaximumRadius = r > 0. ? r : 0.; @@ -993,13 +2262,13 @@ void vtkPolarAxesActor::SetMaximumRadius( double r ) } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetMinimumAngle( double a ) +void vtkPolarAxesActor::SetMinimumAngle(double a) { - if ( a > 360. ) + if (a > 360.) { this->MinimumAngle = 360.; } - else if ( a < -360. ) + else if (a < -360.) { this->MinimumAngle = -360.; } @@ -1014,13 +2283,13 @@ void vtkPolarAxesActor::SetMinimumAngle( double a ) } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetMaximumAngle( double a ) +void vtkPolarAxesActor::SetMaximumAngle(double a) { - if ( a > 360. ) + if (a > 360.) { this->MaximumAngle = 360.; } - else if ( a < -360. ) + else if (a < -360.) { this->MaximumAngle = -360.; } @@ -1035,40 +2304,225 @@ void vtkPolarAxesActor::SetMaximumAngle( double a ) } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetPolarAxisProperty( vtkProperty *prop ) +void vtkPolarAxesActor::SetUse2DMode(int val) { - this->PolarAxisProperty->DeepCopy( prop ); - this->Modified(); + for (int i = 0; i < this->NumberOfRadialAxes; ++i) + { + this->RadialAxes[i]->SetUse2DMode(val); + } + + this->PolarAxis->SetUse2DMode(val); +} + +//----------------------------------------------------------------------------- +int vtkPolarAxesActor::GetUse2DMode() +{ + return this->PolarAxis->GetUse2DMode(); } //----------------------------------------------------------------------------- -vtkProperty* vtkPolarAxesActor::GetPolarAxisProperty() +void vtkPolarAxesActor::SetPolarAxisProperty(vtkProperty *prop) { - return this->PolarAxisProperty; + this->PolarAxisProperty->DeepCopy(prop); + this->PolarAxisProperty->SetLineWidth(this->PolarAxisMajorTickThickness); + this->Modified(); } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetRadialAxesProperty( vtkProperty *prop ) +void vtkPolarAxesActor::SetPolarArcsProperty(vtkProperty * prop) { - this->RadialAxesProperty->DeepCopy( prop ); + this->PolarArcsActor->SetProperty(prop); this->Modified(); } //----------------------------------------------------------------------------- -vtkProperty* vtkPolarAxesActor::GetRadialAxesProperty() +vtkProperty* vtkPolarAxesActor::GetPolarArcsProperty() { - return this->RadialAxesProperty; + return this->PolarArcsActor->GetProperty(); } //----------------------------------------------------------------------------- -void vtkPolarAxesActor::SetPolarArcsProperty( vtkProperty *prop ) +void vtkPolarAxesActor::SetSecondaryPolarArcsProperty(vtkProperty *prop) { - this->PolarArcsActor->SetProperty(prop); + this->SecondaryPolarArcsActor->SetProperty(prop); this->Modified(); } //----------------------------------------------------------------------------- -vtkProperty* vtkPolarAxesActor::GetPolarArcsProperty() +vtkProperty* vtkPolarAxesActor::GetSecondaryPolarArcsProperty() { - return this->PolarArcsActor->GetProperty(); + return this->SecondaryPolarArcsActor->GetProperty(); +} + +//----------------------------------------------------------------------------- +void vtkPolarAxesActor::SetNumberOfPolarAxisTicks(int tickCountRequired) +{ + double rangeLength = fabs(this->Range[1] - this->Range[0]); + double step = this->ComputeIdealStep( + tickCountRequired - 1, rangeLength, VTK_MAXIMUM_NUMBER_OF_POLAR_AXIS_TICKS - 1); + double tmpRangeMajor = this->DeltaRangeMajor; + double tmpRangeMinor = this->DeltaRangeMinor; + this->DeltaRangeMajor = (step == 0.0) ? rangeLength / 10.0 : step; + this->DeltaRangeMinor = + (step == 0.0) ? (this->DeltaRangeMajor / 2.0) : (step / 2.0); + if (tmpRangeMajor != this->DeltaRangeMajor || tmpRangeMinor != this->DeltaRangeMinor) + { + this->Modified(); + } +} + +//----------------------------------------------------------------------------- +void vtkPolarAxesActor::SetNumberOfRadialAxes(vtkIdType n) +{ + if (n == 0) + { + if (this->DeltaAngleRadialAxes != 45.) + { + this->DeltaAngleRadialAxes = 45.0; + this->Modified(); + return; + } + } + + double angleSection = (this->MaximumAngle > this->MinimumAngle)? + this->MaximumAngle - this->MinimumAngle: 360.0 - + fabs(this->MaximumAngle - this->MinimumAngle); + + // if Min and max angle are the same, interpret it as 360 segment opening + if (vtkMathUtilities::FuzzyCompare(this->MaximumAngle, this->MinimumAngle)) + { + angleSection = 360.0; + } + + double step = this->ComputeIdealStep(n - 1, angleSection); + if (step == 0.0) + { + step = angleSection / n; + } + + if (this->DeltaAngleRadialAxes != step) + { + this->DeltaAngleRadialAxes = step; + this->Modified(); + } +} + +//----------------------------------------------------------------------------- +double vtkPolarAxesActor::ComputeIdealStep( + int subDivsRequired, double rangeLength, int maxSubDivs) +{ + double pow10, pow10Start, pow10End; + double rawStep, roundStep, roundStepSup; + + if (rangeLength == 0.0 || subDivsRequired >= maxSubDivs) + { + return 0.0; + } + + if (subDivsRequired <= 1) + { + return rangeLength; + } + + // range step, if axis range is strictly subdivided by the number of ticks wished + rawStep = rangeLength / subDivsRequired; + + // pow of 10 order of magnitude + pow10Start = std::floor(log10(rawStep)); + pow10End = -10.0; + if (pow10End >= pow10Start) + { + pow10End -= 1.0; + } + + if (rawStep <= std::pow(10, pow10End)) + { + return 0.0; + } + + double dividend = rawStep; + + double pow10Step; + double idealStep = 0.0; + double subdivs = 1.0, subdivsSup = 1.0; + + int currentPow10Multiple; + + for (pow10 = pow10Start; pow10 >= pow10End; pow10 -= 1.0) + { + // 10.0, 1.0, 0.1, ... + pow10Step = std::pow(10.0, pow10); + + // example: 4 = 0.4874 / 0.1 for pow10Step = 0.1 + currentPow10Multiple = static_cast (dividend / pow10Step); + + // 0.4 = 4 * 0.1 + roundStep = currentPow10Multiple * pow10Step; + + // 0.5 = 5 * 0.1 + roundStepSup = (currentPow10Multiple + 1) * pow10Step; + + // currentIdealStep is the previous digits of the ideal step we seek + subdivs = rangeLength / (idealStep + roundStep); + subdivsSup = rangeLength / (idealStep + roundStepSup); + + if (fabs(subdivs - subDivsRequired) < 1.0 || fabs(subdivsSup - subDivsRequired) < 1.0) + { + // if currentStep + the current power of 10, is closer to the require tick count + if (fabs(subdivs - subDivsRequired) > fabs(subdivsSup - subDivsRequired) && + fabs(subdivsSup - subDivsRequired) < 1.0) + { + idealStep += roundStepSup; + } + + // subdivs closer to subdiv than subdivsSup + else + { + idealStep += roundStep; + } + break; + } + + idealStep += roundStep; + + // 0.4874 - 0.4 for roundStep = 0.4 + // remainder becomes dividend + dividend = dividend - roundStep; + } + + // if idealStep is too small + if (static_cast (rangeLength / idealStep) > subDivsRequired) + { + idealStep = rawStep; + } + + return idealStep; +} + +//----------------------------------------------------------------------------- +int vtkPolarAxesActor::GetNumberOfPolarAxisTicks() +{ + double rangeLength = fabs(this->Range[1] - this->Range[0]); + return static_cast((rangeLength / this->DeltaRangeMajor) + 1); +} + +double vtkPolarAxesActor::ComputeEllipseAngle(double angleInDegrees, double ratio) +{ + double miniAngleEllipse; + double minimumAngleRad = vtkMath::RadiansFromDegrees(angleInDegrees); + minimumAngleRad = std::fmod(minimumAngleRad, 2.0 * vtkMath::Pi()); + + // result range: -pi / 2, pi / 2 + miniAngleEllipse = atan(tan(minimumAngleRad) / ratio); + + // ellipse range: 0, 2 * pi + if (minimumAngleRad > vtkMath::Pi() / 2 && minimumAngleRad <= vtkMath::Pi()) + { + miniAngleEllipse += vtkMath::Pi(); + } + else if (minimumAngleRad > vtkMath::Pi() && minimumAngleRad <= 1.5 * vtkMath::Pi()) + { + miniAngleEllipse -= vtkMath::Pi(); + } + return miniAngleEllipse; } diff --git a/Rendering/Annotation/vtkPolarAxesActor.h b/Rendering/Annotation/vtkPolarAxesActor.h index ad742d1385b..3a7b12e08a0 100644 --- a/Rendering/Annotation/vtkPolarAxesActor.h +++ b/Rendering/Annotation/vtkPolarAxesActor.h @@ -22,7 +22,7 @@ All rights reserve // // .SECTION Thanks // This class was written by Philippe Pebay, Kitware SAS 2011. -// This work was supported by CEA/DIF - Commissariat a l'Energie Atomique, +// This work was supported by CEA/DIF - Commissariat a l'Energie Atomique, // Centre DAM Ile-De-France, BP12, F-91297 Arpajon, France. // // .section See Also @@ -34,21 +34,25 @@ All rights reserve #define VTK_MAXIMUM_NUMBER_OF_RADIAL_AXES 50 #define VTK_DEFAULT_NUMBER_OF_RADIAL_AXES 5 #define VTK_MAXIMUM_NUMBER_OF_POLAR_AXIS_TICKS 200 +#define VTK_MAXIMUM_RATIO 1000.0 #define VTK_POLAR_ARC_RESOLUTION_PER_DEG 0.2 #include "vtkRenderingAnnotationModule.h" // For export macro #include "vtkActor.h" +#include "vtkAxisActor.h" // access to enum values +#include // To process exponent list as reference -class vtkAxisActor; class vtkCamera; class vtkPolyData; class vtkPolyDataMapper; +class vtkProperty; +class vtkStringArray; class vtkTextProperty; class VTKRENDERINGANNOTATION_EXPORT vtkPolarAxesActor : public vtkActor { public: - vtkTypeMacro(vtkPolarAxesActor,vtkActor); + vtkTypeMacro(vtkPolarAxesActor, vtkActor); void PrintSelf(ostream& os, vtkIndent indent); // Description: @@ -59,202 +63,437 @@ class VTKRENDERINGANNOTATION_EXPORT vtkPolarAxesActor : public vtkActor // Description: // Draw the polar axes virtual int RenderOpaqueGeometry(vtkViewport*); + virtual int RenderOverlay(vtkViewport*); virtual int RenderTranslucentPolygonalGeometry(vtkViewport*) {return 0;}; // Description: // Explicitly specify the coordinate of the pole. - virtual void SetPole( double[3] ); - virtual void SetPole( double, double, double ); - vtkGetVector3Macro( Pole, double ); + virtual void SetPole(double[3]); + virtual void SetPole(double, double, double); + vtkGetVector3Macro(Pole, double); + + // Description + // Enable/Disable log scale + // Default: true + vtkSetMacro(Log, bool); + vtkGetMacro(Log, bool); + vtkBooleanMacro(Log, bool); // Description: // Gets/Sets the number of radial axes - virtual void SetNumberOfRadialAxes( vtkIdType ); - vtkGetMacro( NumberOfRadialAxes, vtkIdType ); + virtual void SetNumberOfRadialAxes(vtkIdType); + vtkGetMacro(NumberOfRadialAxes, vtkIdType); // Description: - // Gets/Sets the number of ticks and labels along polar axis - // NB: will be overriden if AutoSubdividePolarAxis is true - vtkSetClampMacro( NumberOfPolarAxisTicks, vtkIdType, 0, VTK_MAXIMUM_NUMBER_OF_POLAR_AXIS_TICKS ); - vtkGetMacro( NumberOfPolarAxisTicks, vtkIdType ); + // Set/Get a number of ticks that one would like to display along polar axis + // NB: it modifies DeltaRangeMajor to correspond to this number + virtual void SetNumberOfPolarAxisTicks(int); + int GetNumberOfPolarAxisTicks(); // Description: // Set/Get whether the number of polar axis ticks and arcs should be automatically calculated // Default: true - vtkSetMacro( AutoSubdividePolarAxis, bool ); - vtkGetMacro( AutoSubdividePolarAxis, bool ); - vtkBooleanMacro( AutoSubdividePolarAxis, bool ); + vtkSetMacro(AutoSubdividePolarAxis, bool); + vtkGetMacro(AutoSubdividePolarAxis, bool); + vtkBooleanMacro(AutoSubdividePolarAxis, bool); + + // Description: + // Define the range values displayed on the polar Axis. + vtkSetVector2Macro(Range, double); + vtkGetVectorMacro(Range, double, 2); + + // Description: + // Set/Get the minimal radius of the polar coordinates. + virtual void SetMinimumRadius(double); + vtkGetMacro(MinimumRadius, double); // Description: // Set/Get the maximum radius of the polar coordinates. - virtual void SetMaximumRadius( double ); - vtkGetMacro( MaximumRadius, double ); + virtual void SetMaximumRadius(double); + vtkGetMacro(MaximumRadius, double); // Description: // Turn on and off the auto-scaling of the maximum radius. // Default: false - vtkSetMacro( AutoScaleRadius,bool ); - vtkGetMacro( AutoScaleRadius,bool ); + vtkSetMacro(AutoScaleRadius, bool); + vtkGetMacro(AutoScaleRadius, bool); // Description: // Set/Get the minimum radius of the polar coordinates (in degrees). - virtual void SetMinimumAngle( double ); - vtkGetMacro( MinimumAngle, double ); + virtual void SetMinimumAngle(double); + vtkGetMacro(MinimumAngle, double); // Description: // Set/Get the maximum radius of the polar coordinates (in degrees). - virtual void SetMaximumAngle( double ); - vtkGetMacro( MaximumAngle, double ); + virtual void SetMaximumAngle(double); + vtkGetMacro(MaximumAngle, double); // Description: // Set/Get the minimum radial angle distinguishable from polar axis // NB: This is used only when polar axis is visible // Default: 0.5 - vtkSetClampMacro( SmallestVisiblePolarAngle, double, 0., 5. ); - vtkGetMacro( SmallestVisiblePolarAngle, double ); + vtkSetClampMacro(SmallestVisiblePolarAngle, double, 0., 5.); + vtkGetMacro(SmallestVisiblePolarAngle, double); + + // Description: + // Set/Get the location of the ticks. + // Inside: tick end toward positive direction of perpendicular axes. + // Outside: tick end toward negative direction of perpendicular axes. + vtkSetClampMacro(TickLocation, int, vtkAxisActor::VTK_TICKS_INSIDE, vtkAxisActor::VTK_TICKS_BOTH); + vtkGetMacro(TickLocation, int); // Description: Set/Get whether angle units (degrees) are used to label radial axes // Default: true - vtkSetMacro( RadialUnits, bool ); - vtkGetMacro( RadialUnits, bool ); + vtkSetMacro(RadialUnits, bool); + vtkGetMacro(RadialUnits, bool); // Description: // Explicitly specify the screen size of title and label text. // ScreenSize detemines the size of the text in terms of screen // pixels. // Default: 10.0. - void SetScreenSize( double screenSize ); - vtkGetMacro( ScreenSize, double ); + vtkSetMacro(ScreenSize, double); + vtkGetMacro(ScreenSize, double); // Description: // Set/Get the camera to perform scaling and translation of the // vtkPolarAxesActor. virtual void SetCamera(vtkCamera*); - vtkGetObjectMacro( Camera,vtkCamera ); + vtkGetObjectMacro(Camera, vtkCamera); // Description: // Set/Get the labels for the polar axis. // Default: "Radial Distance". - vtkSetStringMacro( PolarAxisTitle ); - vtkGetStringMacro( PolarAxisTitle ); + vtkSetStringMacro(PolarAxisTitle); + vtkGetStringMacro(PolarAxisTitle); // Description: // Set/Get the format with which to print the polar axis labels. - vtkSetStringMacro( PolarLabelFormat ); - vtkGetStringMacro( PolarLabelFormat ); + vtkSetStringMacro(PolarLabelFormat); + vtkGetStringMacro(PolarLabelFormat); + + enum ExponentLocation + { + VTK_EXPONENT_BOTTOM = 0, + VTK_EXPONENT_EXTERN = 1, + VTK_EXPONENT_LABELS = 2 + }; + + // Description: + // Get/Set the location of the exponent (if any) of the polar axis values. + // Possible location: VTK_EXPONENT_BOTTOM, VTK_EXPONENT_EXTERN, + // VTK_EXPONENT_LABELS + vtkSetClampMacro(ExponentLocation, int, VTK_EXPONENT_BOTTOM, VTK_EXPONENT_LABELS); + vtkGetMacro(ExponentLocation, int); + + // Description: + // String to format angle values displayed on the radial axes. + vtkSetStringMacro(RadialAngleFormat); + vtkGetStringMacro(RadialAngleFormat); // Description: // Release any graphics resources that are being consumed by this actor. // The parameter window could be used to determine which graphic // resources to release. - void ReleaseGraphicsResources( vtkWindow* ); + void ReleaseGraphicsResources(vtkWindow*); // Description: // Enable and disable the use of distance based LOD for titles and labels. - vtkSetMacro( EnableDistanceLOD, int ); - vtkGetMacro( EnableDistanceLOD, int ); + vtkSetMacro(EnableDistanceLOD, int); + vtkGetMacro(EnableDistanceLOD, int); // Description:a // Set distance LOD threshold [0.0 - 1.0] for titles and labels. - vtkSetClampMacro( DistanceLODThreshold, double, 0.0, 1.0 ); - vtkGetMacro( DistanceLODThreshold, double); + vtkSetClampMacro(DistanceLODThreshold, double, 0.0, 1.0); + vtkGetMacro(DistanceLODThreshold, double); // Description: // Enable and disable the use of view angle based LOD for titles and labels. - vtkSetMacro( EnableViewAngleLOD, int ); - vtkGetMacro( EnableViewAngleLOD, int ); + vtkSetMacro(EnableViewAngleLOD, int); + vtkGetMacro(EnableViewAngleLOD, int); // Description: // Set view angle LOD threshold [0.0 - 1.0] for titles and labels. - vtkSetClampMacro( ViewAngleLODThreshold, double, 0., 1. ); - vtkGetMacro( ViewAngleLODThreshold, double ); + vtkSetClampMacro(ViewAngleLODThreshold, double, 0., 1.); + vtkGetMacro(ViewAngleLODThreshold, double); // Description: // Turn on and off the visibility of the polar axis. - vtkSetMacro( PolarAxisVisibility, int ); - vtkGetMacro( PolarAxisVisibility, int ); - vtkBooleanMacro( PolarAxisVisibility, int ); + vtkSetMacro(PolarAxisVisibility, int); + vtkGetMacro(PolarAxisVisibility, int); + vtkBooleanMacro(PolarAxisVisibility, int); + + // Description: + // Turn on and off the visibility of inner radial grid lines + vtkSetMacro(DrawRadialGridlines, int); + vtkGetMacro(DrawRadialGridlines, int); + vtkBooleanMacro(DrawRadialGridlines, int); + + //Description + // Turn on and off the visibility of inner polar arcs grid lines + vtkSetMacro(DrawPolarArcsGridlines, int); + vtkGetMacro(DrawPolarArcsGridlines, int); + vtkBooleanMacro(DrawPolarArcsGridlines, int); // Description: // Turn on and off the visibility of titles for polar axis. - vtkSetMacro( PolarTitleVisibility, int ); - vtkGetMacro( PolarTitleVisibility, int ); - vtkBooleanMacro( PolarTitleVisibility, int ); + vtkSetMacro(PolarTitleVisibility, int); + vtkGetMacro(PolarTitleVisibility, int); + vtkBooleanMacro(PolarTitleVisibility, int); + + enum TitleLocation + { + VTK_TITLE_BOTTOM = 0, + VTK_TITLE_EXTERN = 1 + }; + + // Description: + // Get/Set the alignement of the radial axes title related to the axis. + // Possible Alignment: VTK_TITLE_BOTTOM, VTK_TITLE_EXTERN + vtkSetClampMacro(RadialAxisTitleLocation, int, VTK_TITLE_BOTTOM, VTK_TITLE_EXTERN); + vtkGetMacro(RadialAxisTitleLocation, int); + + // Description: + // Get/Set the alignement of the polar axes title related to the axis. + // Possible Alignment: VTKTITLE_BOTTOM, VTK_TITLE_EXTERN + vtkSetClampMacro(PolarAxisTitleLocation, int, VTK_TITLE_BOTTOM, VTK_TITLE_EXTERN); + vtkGetMacro(PolarAxisTitleLocation, int); // Description: // Turn on and off the visibility of labels for polar axis. - vtkSetMacro( PolarLabelVisibility, int ); - vtkGetMacro( PolarLabelVisibility, int ); - vtkBooleanMacro( PolarLabelVisibility, int ); + vtkSetMacro(PolarLabelVisibility, int); + vtkGetMacro(PolarLabelVisibility, int); + vtkBooleanMacro(PolarLabelVisibility, int); + + // Description: + // If On, the ticks are drawn from the angle of the polarAxis (i.e. this->MinimalRadius) + // and continue counterclockwise with the step DeltaAngle Major/Minor. if Off, the start angle is 0.0, i.e. + // the angle on the major radius of the ellipse. + vtkSetMacro(ArcTicksOriginToPolarAxis, int); + vtkGetMacro(ArcTicksOriginToPolarAxis, int); + vtkBooleanMacro(ArcTicksOriginToPolarAxis, int); + + // Description: + // If On, the radial axes are drawn from the angle of the polarAxis (i.e. this->MinimalRadius) + // and continue counterclockwise with the step DeltaAngleRadialAxes. if Off, the start angle is 0.0, i.e. + // the angle on the major radius of the ellipse. + vtkSetMacro(RadialAxesOriginToPolarAxis, int); + vtkGetMacro(RadialAxesOriginToPolarAxis, int); + vtkBooleanMacro(RadialAxesOriginToPolarAxis, int); + + // Description: + // Turn on and off the overall visibility of ticks. + vtkSetMacro(PolarTickVisibility, int); + vtkGetMacro(PolarTickVisibility, int); + vtkBooleanMacro(PolarTickVisibility, int); + + // Description: + // Turn on and off the visibility of major ticks on polar axis and last radial axis. + vtkSetMacro(AxisTickVisibility, int); + vtkGetMacro(AxisTickVisibility, int); + vtkBooleanMacro(AxisTickVisibility, int); + + // Description: + // Turn on and off the visibility of minor ticks on polar axis and last radial axis. + vtkSetMacro(AxisMinorTickVisibility, int); + vtkGetMacro(AxisMinorTickVisibility, int); + vtkBooleanMacro(AxisMinorTickVisibility, int); + + // Description: + // Turn on and off the visibility of major ticks on the last arc. + vtkSetMacro(ArcTickVisibility, int); + vtkGetMacro(ArcTickVisibility, int); + vtkBooleanMacro(ArcTickVisibility, int); + + // Description: + // Turn on and off the visibility of minor ticks on the last arc. + vtkSetMacro(ArcMinorTickVisibility, int); + vtkGetMacro(ArcMinorTickVisibility, int); + vtkBooleanMacro(ArcMinorTickVisibility, int); + + // Description: + // Set/Get the size of the major ticks on the last arc. + vtkSetMacro(ArcMajorTickSize, double); + vtkGetMacro(ArcMajorTickSize, double); + + // Description: + // Set/Get the size of the major ticks on the polar axis. + vtkSetMacro(PolarAxisMajorTickSize, double); + vtkGetMacro(PolarAxisMajorTickSize, double); + + // Description: + // Set/Get the size of the major ticks on the last radial axis. + vtkSetMacro(LastRadialAxisMajorTickSize, double); + vtkGetMacro(LastRadialAxisMajorTickSize, double); // Description: - // Turn on and off the visibility of ticks for polar axis. - vtkSetMacro( PolarTickVisibility, int ); - vtkGetMacro( PolarTickVisibility, int ); - vtkBooleanMacro( PolarTickVisibility, int ); + // Set/Get the ratio between major and minor Polar Axis ticks size + vtkSetMacro(PolarAxisTickRatioSize, double); + vtkGetMacro(PolarAxisTickRatioSize, double); + + // Description: + // Set/Get the ratio between major and minor Last Radial axis ticks size + vtkSetMacro(LastAxisTickRatioSize, double); + vtkGetMacro(LastAxisTickRatioSize, double); + + // Description: + // Set/Get the ratio between major and minor Arc ticks size + vtkSetMacro(ArcTickRatioSize, double); + vtkGetMacro(ArcTickRatioSize, double); + + // Description: + // Set/Get the size of the thickness of polar axis ticks + vtkSetMacro(PolarAxisMajorTickThickness, double); + vtkGetMacro(PolarAxisMajorTickThickness, double); + + // Description: + // Set/Get the size of the thickness of last radial axis ticks + vtkSetMacro(LastRadialAxisMajorTickThickness, double); + vtkGetMacro(LastRadialAxisMajorTickThickness, double); + + // Description: + // Set/Get the size of the thickness of the last arc ticks + vtkSetMacro(ArcMajorTickThickness, double); + vtkGetMacro(ArcMajorTickThickness, double); + + // Description: + // Set/Get the ratio between major and minor Polar Axis ticks thickness + vtkSetMacro(PolarAxisTickRatioThickness, double); + vtkGetMacro(PolarAxisTickRatioThickness, double); + + // Description: + // Set/Get the ratio between major and minor Last Radial axis ticks thickness + vtkSetMacro(LastAxisTickRatioThickness, double); + vtkGetMacro(LastAxisTickRatioThickness, double); + + // Description: + // Set/Get the ratio between major and minor Arc ticks thickness + vtkSetMacro(ArcTickRatioThickness, double); + vtkGetMacro(ArcTickRatioThickness, double); + + // Description: + // Set/Get the step between 2 major ticks, in range value (values displayed on the axis). + vtkSetMacro(DeltaRangeMajor, double); + vtkGetMacro(DeltaRangeMajor, double); + + // Description: + // Set/Get the step between 2 minor ticks, in range value (values displayed on the axis). + vtkSetMacro(DeltaRangeMinor, double); + vtkGetMacro(DeltaRangeMinor, double); + + // Description: + // Set/Get the angle between 2 major ticks on the last arc. + vtkSetMacro(DeltaAngleMajor, double); + vtkGetMacro(DeltaAngleMajor, double); + + // Description: + // Set/Get the angle between 2 minor ticks on the last arc. + vtkSetMacro(DeltaAngleMinor, double); + vtkGetMacro(DeltaAngleMinor, double); + + // Description: + // Set/Get the angle between 2 radial axes. + vtkSetMacro(DeltaAngleRadialAxes, double); + vtkGetMacro(DeltaAngleRadialAxes, double); + + //------------------------------------------------ // Description: // Turn on and off the visibility of non-polar radial axes. - vtkSetMacro( RadialAxesVisibility, int ); - vtkGetMacro( RadialAxesVisibility, int ); - vtkBooleanMacro( RadialAxesVisibility, int ); + vtkSetMacro(RadialAxesVisibility, int); + vtkGetMacro(RadialAxesVisibility, int); + vtkBooleanMacro(RadialAxesVisibility, int); // Description: // Turn on and off the visibility of titles for non-polar radial axes. - vtkSetMacro( RadialTitleVisibility, int ); - vtkGetMacro( RadialTitleVisibility, int ); - vtkBooleanMacro( RadialTitleVisibility, int ); + vtkSetMacro(RadialTitleVisibility, int); + vtkGetMacro(RadialTitleVisibility, int); + vtkBooleanMacro(RadialTitleVisibility, int); // Description: // Turn on and off the visibility of arcs for polar axis. - vtkSetMacro( PolarArcsVisibility, int ); - vtkGetMacro( PolarArcsVisibility, int ); - vtkBooleanMacro( PolarArcsVisibility, int ); + vtkSetMacro(PolarArcsVisibility, int); + vtkGetMacro(PolarArcsVisibility, int); + vtkBooleanMacro(PolarArcsVisibility, int); + + // Description + // Enable/Disable labels 2D mode (always facing the camera). + void SetUse2DMode(int val); + int GetUse2DMode(); // Description: // Set/Get the polar axis title text property. virtual void SetPolarAxisTitleTextProperty(vtkTextProperty *p); - vtkGetObjectMacro(PolarAxisTitleTextProperty,vtkTextProperty); + vtkGetObjectMacro(PolarAxisTitleTextProperty, vtkTextProperty); // Description: // Set/Get the polar axis labels text property. virtual void SetPolarAxisLabelTextProperty(vtkTextProperty *p); - vtkGetObjectMacro(PolarAxisLabelTextProperty,vtkTextProperty); + vtkGetObjectMacro(PolarAxisLabelTextProperty, vtkTextProperty); + + // Description: + // Set/Get the last radial axis text property. + virtual void SetLastRadialAxisTextProperty(vtkTextProperty *p); + vtkGetObjectMacro(LastRadialAxisTextProperty, vtkTextProperty); + + // Description: + // Set/Get the secondary radial axes text property. + virtual void SetSecondaryRadialAxesTextProperty(vtkTextProperty *p); + vtkGetObjectMacro(SecondaryRadialAxesTextProperty, vtkTextProperty); // Description: // Get/Set polar axis actor properties. virtual void SetPolarAxisProperty(vtkProperty *); - vtkProperty* GetPolarAxisProperty(); + vtkGetObjectMacro(PolarAxisProperty, vtkProperty); // Description: - // Get/Set radial axes actors properties. - virtual void SetRadialAxesProperty(vtkProperty *); - vtkProperty* GetRadialAxesProperty(); + // Get/Set last radial axis actor properties. + virtual void SetLastRadialAxisProperty(vtkProperty* p); + vtkGetObjectMacro(LastRadialAxisProperty, vtkProperty); // Description: - // Get/Set polar arcs actors property - virtual void SetPolarArcsProperty(vtkProperty *); + // Get/Set secondary radial axes actors properties. + virtual void SetSecondaryRadialAxesProperty(vtkProperty* p); + vtkGetObjectMacro(SecondaryRadialAxesProperty, vtkProperty); + + // Description: + // Get/Set principal polar arc actor property. + virtual void SetPolarArcsProperty(vtkProperty* p); vtkProperty* GetPolarArcsProperty(); + // Description: + // Get/Set secondary polar arcs actors property. + virtual void SetSecondaryPolarArcsProperty(vtkProperty* p); + vtkProperty* GetSecondaryPolarArcsProperty(); + // Description: // Explicitly specify the region in space around which to draw the bounds. // The bounds are used only when no Input or Prop is specified. The bounds // are specified according to (xmin,xmax, ymin,ymax, zmin,zmax), making // sure that the min's are less than the max's. - vtkSetVector6Macro(Bounds,double); + vtkSetVector6Macro(Bounds, double); double *GetBounds(); void GetBounds(double& xmin, double& xmax, double& ymin, double& ymax, double& zmin, double& zmax); void GetBounds(double bounds[6]); + // Description: + // Ratio + vtkSetClampMacro(Ratio, double, 0.001, 100.0); + vtkGetMacro(Ratio, double); + protected: vtkPolarAxesActor(); ~vtkPolarAxesActor(); + // Description: + // Check consistency of vtkPolarAxesActor members. + bool CheckMembersConsistency(); + // Description: // Build the axes. // Determine coordinates, position, etc. - void BuildAxes( vtkViewport * ); + void BuildAxes(vtkViewport *); // Description: // Calculate bounds based on maximum radius and angular sector @@ -262,33 +501,74 @@ class VTKRENDERINGANNOTATION_EXPORT vtkPolarAxesActor : public vtkActor // Description: // Send attributes which are common to all axes, both polar and radial - void SetCommonAxisAttributes( vtkAxisActor* ); + void SetCommonAxisAttributes(vtkAxisActor*); + + // Description: + // Set properties specific to PolarAxis + void SetPolarAxisAttributes(vtkAxisActor*); // Description: - // Create requested number of type X axes and set followers - void CreateRadialAxes(); + // Create requested number of type X axes. + void CreateRadialAxes(int axisCount); // Description: // Build requested number of radial axes with respect to specified pole. void BuildRadialAxes(); // Description: - // Prepare ticks on polar axis with respect to coordinate offset - void BuildPolarAxisTicks( double ); + // Set Range and PolarAxis members value to build axis ticks + // this fonction doesn't actually build PolarAxis ticks, it set the DeltaRangeMajor and DeltaMajor attributes + // then PolarAxis itself is in charge of ticks drawing + void AutoComputeTicksProperties(); + + // Description: + // return a step attempting to be as rounded as possible according to input parameters + double ComputeIdealStep(int subDivsRequired, double rangeLength, int maxSubDivs = 1000); + + // Description: + // Build Arc ticks + void BuildArcTicks(); + + // Description: + // Init tick point located on an ellipse at angleEllipseRad angle and according to "a" major radius + void StoreTicksPtsFromParamEllipse(double a, double angleEllipseRad, double tickSize, vtkPoints* tickPts); // Description: // Build polar axis labels and arcs with respect to specified pole. void BuildPolarAxisLabelsArcs(); + // Description: + // Build labels and arcs with log scale axis + void BuildPolarAxisLabelsArcsLog(); + + // Description: + // Define label values + void BuildLabelsLog(); + + void BuildPolarArcsLog(); + + // Description: + // Find a common exponent for label values. + std::string FindExponentAndAdjustValues(std::list& valuesList); + + // Description: + // Yield a string array whith the float part of each values. 0.01e-2 -> 0.0001 + void GetSignificantPartFromValues(vtkStringArray* valuesStr, std::list& valuesList); + // Description: // Convenience methods - double FFix(double ); - double FSign(double, double ); + double FFix(double); + double FSign(double, double); // Description: // Automatically rescale titles and labels // NB: Current implementation only for perspective projections. - void AutoScale( vtkViewport* viewport ); + void AutoScale(vtkViewport* viewport); + + // Description + // convert section angle to an angle applied to ellipse equation. + // the result point with ellipse angle, is the point located on section angle + static double ComputeEllipseAngle(double angleInDegrees, double ratio); // Description: // Coordinates of the pole @@ -297,25 +577,58 @@ class VTKRENDERINGANNOTATION_EXPORT vtkPolarAxesActor : public vtkActor // Description: // Number of radial axes - // Default: VTK_DEFAULT_NUMBER_OF_RADIAL_AXES int NumberOfRadialAxes; // Description: - // Number of polar arcs - int NumberOfPolarAxisTicks; - - // Description: - // Whether the number of polar axis ticks and arcs should be automatically calculated + // Whether the number of polar axis ticks and arcs should be automatically calculated. // Default: TRUE bool AutoSubdividePolarAxis; // Description: - // Maximum polar radius (minimum is always 0) + // Ratio for elliptical representation of the polar axes actor. + double Ratio; + + // Description: + // Define the range values displayed on the polar Axis. + double Range[2]; + + // Description: + // Step between 2 minor ticks, in range value (values displayed on the axis). + double DeltaRangeMinor; + + // Description: + // Step between 2 major ticks, in range value (values displayed on the axis). + double DeltaRangeMajor; + + // Description: + // Angle between 2 minor ticks on the last arc. + double DeltaAngleMinor; + + // Description: + // Angle between 2 major ticks on the last arc. + double DeltaAngleMajor; + + // Description: + // Angle between 2 radial Axes. + double DeltaAngleRadialAxes; + + // Description: + // Minimum polar radius. + // Default: 0.0 + double MinimumRadius; + + // Description: + // Maximum polar radius. // Default: 1 double MaximumRadius; + // Description + // Enable/Disable log scale + // Default: 0 + bool Log; + // Description: - // Auto-scale polar radius (with respect to average length scale of x-y bounding box) + // Auto-scale polar radius (with respect to average length scale of x-y bounding box). bool AutoScaleRadius; // Description: @@ -336,12 +649,17 @@ class VTKRENDERINGANNOTATION_EXPORT vtkPolarAxesActor : public vtkActor // Explicit actor bounds double Bounds[6]; - // Description: - // Structures for polar arcs + // Structures for principal polar arc vtkPolyData *PolarArcs; vtkPolyDataMapper *PolarArcsMapper; vtkActor *PolarArcsActor; + // Description: + // Structures for secondary polar arcs + vtkPolyData *SecondaryPolarArcs; + vtkPolyDataMapper *SecondaryPolarArcsMapper; + vtkActor *SecondaryPolarArcsActor; + // Description: // Camera attached to the polar axes system vtkCamera *Camera; @@ -360,6 +678,10 @@ class VTKRENDERINGANNOTATION_EXPORT vtkPolarAxesActor : public vtkActor char *PolarAxisTitle; char *PolarLabelFormat; + // Description: + // String to format angle values displayed on the radial axes. + char *RadialAngleFormat; + // Description: // Display angle units (degrees) to label radial axes // Default is true @@ -390,33 +712,126 @@ class VTKRENDERINGANNOTATION_EXPORT vtkPolarAxesActor : public vtkActor int PolarAxisVisibility; int PolarTitleVisibility; int PolarLabelVisibility; + + // Description: + // Describes the tick orientation for the graph elements involved by this property. + // The ticks are drawn according to the direction of the 2 orthogonal axes, of the axisBase defined for a vtkAxisActor. + // For an ellipse, tick directions are defined from ellipse center to tick origin and + // the orthogonal direction of the ellipse plane. + int TickLocation; + + // Description: + // Hold visibility for all present ticks int PolarTickVisibility; + // Description: + // If On, the ticks are drawn from the angle of the polarAxis (i.e. this->MinimalRadius) + // and continue counterclockwise with the step DeltaAngle Major/Minor. if Off, the start angle is 0.0, i.e. + // the angle on the major radius of the ellipse. + int ArcTicksOriginToPolarAxis; + + // Description: + // If On, the radial axes are drawn from the angle of the polarAxis (i.e. this->MinimalRadius) + // and continue counterclockwise with the step DeltaAngleRadialAxes. if Off, the start angle is 0.0, i.e. + // the angle on the major radius of the ellipse. + int RadialAxesOriginToPolarAxis; + + // Description: + // Hold visibility of major/minor ticks for the polar axis and the last radial axis + int AxisTickVisibility, AxisMinorTickVisibility; + + // Description: + // Enable / Disable major/minor tick visibility on the last arc displayed + int ArcTickVisibility, ArcMinorTickVisibility; + + // Description: + // Defines the length of the ticks located on the last arc + double PolarAxisMajorTickSize, LastRadialAxisMajorTickSize, ArcMajorTickSize; + + // Description: + // Set the ratios between major tick Size for each ticks location + double PolarAxisTickRatioSize, LastAxisTickRatioSize, ArcTickRatioSize; + + // Description: + // Defines the tickness of the major ticks. + double PolarAxisMajorTickThickness, LastRadialAxisMajorTickThickness, ArcMajorTickThickness; + + // Description: + // Set the ratios between major tick thickness for each ticks location + double PolarAxisTickRatioThickness, LastAxisTickRatioThickness, ArcTickRatioThickness; + // Description: // Visibility of radial axes and their titles int RadialAxesVisibility; int RadialTitleVisibility; + // Description: + // Define the alignement of the title related to the radial axis. (BOTTOM or EXTERN) + int RadialAxisTitleLocation; + + // Description: + // Define the alignement of the title related to the polar axis. (BOTTOM or EXTERN) + int PolarAxisTitleLocation; + + // Description: + // Define the location of the exponent of the labels values, located on the polar axis. + // it could be: LABEL, EXTERN, BOTTOM + int ExponentLocation; + // Description: // Visibility of polar arcs int PolarArcsVisibility; - int RenderCount; + // Description: + // Visibility of the inner axes (overriden to 0 if RadialAxesVisibility is set to 0) + int DrawRadialGridlines; + + // Description: + // Visibility of the inner arcs (overriden to 0 if PolarArcsVisibility is set to 0) + int DrawPolarArcsGridlines; + + // Description: + // Keep the arc major ticks vtkPoints instances + vtkPoints* ArcMajorTickPts; + + // Description: + // Keep the arc minor ticks vtkPoints instances + vtkPoints* ArcMinorTickPts; - int RenderSomething; + // Description: + // vtk object for arc Ticks + vtkPolyData* ArcTickPolyData; + vtkPolyData* ArcMinorTickPolyData; + vtkPolyDataMapper* ArcTickPolyDataMapper; + vtkPolyDataMapper* ArcMinorTickPolyDataMapper; + vtkActor* ArcTickActor; + vtkActor* ArcMinorTickActor; // Description: // Text properties of polar axis title and labels vtkTextProperty *PolarAxisTitleTextProperty; vtkTextProperty *PolarAxisLabelTextProperty; + // Description: + // Text properties of last radial axis + vtkTextProperty *LastRadialAxisTextProperty; + + // Description: + // Text properties of secondary radial axes + vtkTextProperty *SecondaryRadialAxesTextProperty; + // Description: // General properties of polar axis + // Behavior may be override by polar axis ticks 's actor property. vtkProperty* PolarAxisProperty; + // Description: + // General properties of last radial axis + vtkProperty* LastRadialAxisProperty; + // Description: // General properties of radial axes - vtkProperty* RadialAxesProperty; + vtkProperty* SecondaryRadialAxesProperty; vtkTimeStamp BuildTime; @@ -428,18 +843,13 @@ class VTKRENDERINGANNOTATION_EXPORT vtkPolarAxesActor : public vtkActor // Label scale factor double LabelScale; - // Description: - // Label screen offset - double LabelScreenOffset; - // Description: // Text screen size double ScreenSize; private: - vtkPolarAxesActor( const vtkPolarAxesActor& ); // Not implemented - void operator=( const vtkPolarAxesActor& ); // Not implemented + vtkPolarAxesActor(const vtkPolarAxesActor&); // Not implemented + void operator=(const vtkPolarAxesActor&); // Not implemented }; - #endif diff --git a/Rendering/Annotation/vtkProp3DAxisFollower.cxx b/Rendering/Annotation/vtkProp3DAxisFollower.cxx index 729f15bf5cd..230e31824f5 100644 --- a/Rendering/Annotation/vtkProp3DAxisFollower.cxx +++ b/Rendering/Annotation/vtkProp3DAxisFollower.cxx @@ -70,7 +70,8 @@ vtkProp3DAxisFollower::vtkProp3DAxisFollower() this->EnableViewAngleLOD = 1; this->ViewAngleLODThreshold = 0.34; - this->ScreenOffset = 10.0; + this->ScreenOffsetVector[0] = 0.0; + this->ScreenOffsetVector[1] = 10.0; this->Axis = NULL; this->Viewport = NULL; @@ -108,7 +109,6 @@ vtkAxisActor* vtkProp3DAxisFollower::GetAxis() return this->Axis.GetPointer(); } - //---------------------------------------------------------------------- void vtkProp3DAxisFollower::SetViewport(vtkViewport* vp) { @@ -362,22 +362,21 @@ ::ComputeRotationAndTranlation(vtkViewport* viewport, double translation[3], double rX[3], double rY[3], double rZ[3], vtkAxisActor *axis) { - double autoScaleFactor = - this->AutoScale(viewport, this->Camera, this->ScreenOffset, this->Position); + double autoScaleHoriz = + this->AutoScale(viewport, this->Camera, this->ScreenOffsetVector[0], this->Position); + double autoScaleVert = + this->AutoScale(viewport, this->Camera, this->ScreenOffsetVector[1], this->Position); double dop[3]; this->Camera->GetDirectionOfProjection(dop); vtkMath::Normalize(dop); - this->CalculateOrthogonalVectors(rX, rY, rZ, axis, dop, this->Viewport); + this->CalculateOrthogonalVectors(rX, rY, rZ, axis, dop, viewport); double dotVal = vtkMath::Dot(rZ, dop); - double origRy[3] = {0.0, 0.0, 0.0}; - - origRy[0] = rY[0]; - origRy[1] = rY[1]; - origRy[2] = rY[2]; + double origRx[3] = {rX[0], rX[1], rX[2]}; + double origRy[3] = {rY[0], rY[1], rY[2]}; // NOTE: Basically the idea here is that dotVal will be positive // only when we have projection direction aligned with our z directon @@ -399,26 +398,23 @@ ::ComputeRotationAndTranlation(vtkViewport* viewport, double translation[3], // we compare our vertical vector with these vectors and if it aligns then we // translate in opposite direction. int axisPosition = this->Axis->GetAxisPosition(); + int vertSign; + double vertDotVal1 = vtkMath::Dot(AxisAlignedY[this->Axis->GetAxisType()][axisPosition][0], origRy) ; + double vertDotVal2 = vtkMath::Dot(AxisAlignedY[this->Axis->GetAxisType()][axisPosition][1], origRy) ; - double dotVal1 = vtkMath::Dot(AxisAlignedY[this->Axis->GetAxisType()][axisPosition][0], origRy) ; - double dotVal2 = vtkMath::Dot(AxisAlignedY[this->Axis->GetAxisType()][axisPosition][1], origRy) ; - - if(fabs(dotVal1) > fabs(dotVal2)) + if(fabs(vertDotVal1) > fabs(vertDotVal2)) { - int sign = (dotVal1 > 0 ? -1 : 1); - - translation[0] = origRy[0] * autoScaleFactor * sign; - translation[1] = origRy[1] * autoScaleFactor * sign; - translation[2] = origRy[2] * autoScaleFactor * sign; + vertSign = (vertDotVal1 > 0 ? -1 : 1); } else { - int sign = (dotVal2 > 0 ? -1 : 1); - - translation[0] = origRy[0] * autoScaleFactor * sign; - translation[1] = origRy[1] * autoScaleFactor * sign; - translation[2] = origRy[2] * autoScaleFactor * sign; + vertSign = (vertDotVal2 > 0 ? -1 : 1); } + + int horizSign = this->TextUpsideDown ? -1 : 1; + translation[0] = origRy[0] * autoScaleVert * vertSign + origRx[0] * autoScaleHoriz * horizSign; + translation[1] = origRy[1] * autoScaleVert * vertSign + origRx[1] * autoScaleHoriz * horizSign; + translation[2] = origRy[2] * autoScaleVert * vertSign + origRx[2] * autoScaleHoriz * horizSign; } //---------------------------------------------------------------------- @@ -533,7 +529,7 @@ void vtkProp3DAxisFollower::PrintSelf(ostream& os, vtkIndent indent) os << indent << "DistanceLODThreshold: (" << this->DistanceLODThreshold << ")\n"; os << indent << "EnableViewAngleLOD: (" << this->EnableViewAngleLOD << ")\n"; os << indent << "ViewAngleLODThreshold: (" << this->ViewAngleLODThreshold << ")\n"; - os << indent << "ScreenOffset: ("<< this->ScreenOffset << ")\n"; + os << indent << "ScreenOffsetVector: ("<< this->ScreenOffsetVector[0] << " " << this->ScreenOffsetVector[1] << ")\n"; if ( this->Axis ) { @@ -556,7 +552,7 @@ void vtkProp3DAxisFollower::ShallowCopy(vtkProp *prop) this->SetDistanceLODThreshold(f->GetDistanceLODThreshold()); this->SetEnableViewAngleLOD(f->GetEnableViewAngleLOD()); this->SetViewAngleLODThreshold(f->GetViewAngleLODThreshold()); - this->SetScreenOffset(f->GetScreenOffset()); + this->SetScreenOffsetVector(f->GetScreenOffsetVector()); this->SetAxis(f->GetAxis()); } @@ -571,6 +567,18 @@ bool vtkProp3DAxisFollower::IsTextUpsideDown( double* a, double* b ) return (b[0] - a[0]) * cos(angle) - (b[1] - a[1]) * sin(angle) < 0; } +//---------------------------------------------------------------------- +void vtkProp3DAxisFollower::SetScreenOffset(double offset) +{ + this->SetScreenOffsetVector(1, offset); +} + +//---------------------------------------------------------------------- +double vtkProp3DAxisFollower::GetScreenOffset() +{ + return this->GetScreenOffsetVector()[1]; +} + //---------------------------------------------------------------------- int vtkProp3DAxisFollower::RenderOpaqueGeometry(vtkViewport *viewport) { diff --git a/Rendering/Annotation/vtkProp3DAxisFollower.h b/Rendering/Annotation/vtkProp3DAxisFollower.h index 517f870b42e..97fffa6c492 100644 --- a/Rendering/Annotation/vtkProp3DAxisFollower.h +++ b/Rendering/Annotation/vtkProp3DAxisFollower.h @@ -87,10 +87,16 @@ class VTKRENDERINGANNOTATION_EXPORT vtkProp3DAxisFollower vtkSetClampMacro(ViewAngleLODThreshold, double, 0.0, 1.0); vtkGetMacro(ViewAngleLODThreshold, double); + // Description: + // Set/Get the desired screen vertical offset from the axis. + // Convenience method, using a zero horizontal offset + double GetScreenOffset(); + void SetScreenOffset(double offset); + // Description: // Set/Get the desired screen offset from the axis. - vtkSetMacro(ScreenOffset, double); - vtkGetMacro(ScreenOffset, double); + vtkSetVector2Macro(ScreenOffsetVector, double); + vtkGetVector2Macro(ScreenOffsetVector, double); // Description: // Generate the matrix based on ivars. This method overloads its superclasses @@ -126,7 +132,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkProp3DAxisFollower vtkAxisActor *axis1, double *dop, vtkViewport *ren); - void ComputeRotationAndTranlation(vtkViewport *ren, double translation[3], double Rx[3], double Ry[3], double Rz[3], vtkAxisActor *axis); @@ -135,7 +140,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkProp3DAxisFollower void ComputerAutoCenterTranslation(const double& autoScaleFactor, double translation[3]); - int TestDistanceVisibility(); void ExecuteViewAngleVisibility(double normal[3]); @@ -149,7 +153,7 @@ class VTKRENDERINGANNOTATION_EXPORT vtkProp3DAxisFollower int EnableViewAngleLOD; double ViewAngleLODThreshold; - double ScreenOffset; + double ScreenOffsetVector [2]; vtkWeakPointer Axis; vtkWeakPointer Viewport; diff --git a/Rendering/Annotation/vtkScalarBarActor.cxx b/Rendering/Annotation/vtkScalarBarActor.cxx index 0b5bd41f9aa..680927c5a49 100644 --- a/Rendering/Annotation/vtkScalarBarActor.cxx +++ b/Rendering/Annotation/vtkScalarBarActor.cxx @@ -387,6 +387,11 @@ vtkScalarBarActor::~vtkScalarBarActor() //---------------------------------------------------------------------------- int vtkScalarBarActor::RenderOverlay(vtkViewport* viewport) { + if (!this->RebuildLayoutIfNeeded(viewport)) + { + return 0; + } + int renderedSomething = 0; // Is the viewport's RenderWindow capturing GL2PS-special props? We'll need @@ -486,11 +491,8 @@ int vtkScalarBarActor::RenderOverlay(vtkViewport* viewport) return renderedSomething; } -//---------------------------------------------------------------------------- -int vtkScalarBarActor::RenderOpaqueGeometry(vtkViewport* viewport) +int vtkScalarBarActor::RebuildLayoutIfNeeded(vtkViewport* viewport) { - int renderedSomething = 0; - if (!this->LookupTable) { vtkWarningMacro(<< "Need a mapper to render a scalar bar"); @@ -561,6 +563,18 @@ int vtkScalarBarActor::RenderOpaqueGeometry(vtkViewport* viewport) { this->RebuildLayout(viewport); } + return 1; +} + +//---------------------------------------------------------------------------- +int vtkScalarBarActor::RenderOpaqueGeometry(vtkViewport* viewport) +{ + if (!this->RebuildLayoutIfNeeded(viewport)) + { + return 0; + } + + int renderedSomething = 0; // Everything is built, just have to render if (this->Title != NULL) @@ -2295,7 +2309,7 @@ int vtkScalarBarActor::PlaceAnnotationsVertically( ctr); \ ll[1] = lpts->InsertNextPoint(xl1, ctr, 0.); \ llines->InsertNextCell(2, ll); \ - llcolors->InsertNextTupleValue(this->P->AnnotationColors[j].GetData()); \ + llcolors->InsertNextTypedTuple(this->P->AnnotationColors[j].GetData()); \ if (upCum < ctr + hh) upCum = ctr + hh; \ if (dnCum > ctr - hh) dnCum = ctr - hh; @@ -2541,7 +2555,7 @@ struct vtkScalarBarHLabelPlacer pt = pts->InsertNextPoint(label.Anchor[0], other.Y[0], 0.); lines->InsertCellPoint(pt); lines->InsertNextCell(2); - colors->InsertNextTupleValue(color.GetData()); + colors->InsertNextTypedTuple(color.GetData()); curY = other.Y[1]; pt = pts->InsertNextPoint(label.Anchor[0], curY, 0.); lines->InsertCellPoint(pt); @@ -2558,7 +2572,7 @@ struct vtkScalarBarHLabelPlacer // I. Insert first vertex near swatch: lines->InsertNextCell(2); - colors->InsertNextTupleValue(color.GetData()); + colors->InsertNextTypedTuple(color.GetData()); double curY = this->Y0 + this->Dir * this->Pad / 2.; pt = pts->InsertNextPoint(label.Anchor[0], curY, 0.); lines->InsertCellPoint(pt); diff --git a/Rendering/Annotation/vtkScalarBarActor.h b/Rendering/Annotation/vtkScalarBarActor.h index fa766d942f8..adcda2e5eec 100644 --- a/Rendering/Annotation/vtkScalarBarActor.h +++ b/Rendering/Annotation/vtkScalarBarActor.h @@ -187,9 +187,7 @@ class VTKRENDERINGANNOTATION_EXPORT vtkScalarBarActor : public vtkActor2D // Get the texture actor.. you may want to change some properties on it vtkGetObjectMacro(TextureActor, vtkTexturedActor2D); -//BTX enum { PrecedeScalarBar = 0, SucceedScalarBar }; -//ETX // Description: // Should the title and tick marks precede the scalar bar or succeed it? @@ -392,6 +390,13 @@ class VTKRENDERINGANNOTATION_EXPORT vtkScalarBarActor : public vtkActor2D // their placement. virtual void RebuildLayout(vtkViewport* viewport); + // Description: + // Calls RebuildLayout if it is needed such as when + // positions etc have changed. Return 1 on success + // zero on error + virtual int RebuildLayoutIfNeeded(vtkViewport* viewport); + + // Description: // Free internal storage used by the previous layout. virtual void FreeLayoutStorage(); diff --git a/Rendering/Annotation/vtkXYPlotActor.h b/Rendering/Annotation/vtkXYPlotActor.h index 740e31b107e..e6785eb1cd8 100644 --- a/Rendering/Annotation/vtkXYPlotActor.h +++ b/Rendering/Annotation/vtkXYPlotActor.h @@ -394,7 +394,6 @@ class VTKRENDERINGANNOTATION_EXPORT vtkXYPlotActor : public vtkActor2D vtkGetMacro(AdjustTitlePosition, int); vtkBooleanMacro(AdjustTitlePosition, int); -//BTX enum Alignment { AlignLeft = 0x1, AlignRight = 0x2, @@ -409,7 +408,7 @@ enum Alignment { AlignAxisBottom = 0x2000, AlignAxisVCenter = 0x4000 }; -//ETX + // Description: // If AdjustTitlePosition is true, the xyplot actor will // adjust the position of the title automatically depending on the @@ -580,7 +579,6 @@ enum Alignment { // Write the XY Ploat Actor as a CSV (comma separated value) representation. void PrintAsCSV(ostream &os); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS. @@ -598,7 +596,6 @@ enum Alignment { // The parameter window could be used to determine which graphic // resources to release. void ReleaseGraphicsResources(vtkWindow *); -//ETX // Description: // Set/Get the position of the title of X axis. @@ -787,9 +784,8 @@ enum Alignment { void ClipPlotData(int *pos, int *pos2, vtkPolyData *pd); double *TransformPoint(int pos[2], int pos2[2], double x[3], double xNew[3]); -//BTX vtkSmartPointer ActiveCurve; -//ETX + int YAxisTitleSize; int ActiveCurveIndex; int PlotColorIndex; diff --git a/Rendering/Context2D/vtkAbstractContextItem.h b/Rendering/Context2D/vtkAbstractContextItem.h index 3d9a6e78105..a2662e7b44f 100644 --- a/Rendering/Context2D/vtkAbstractContextItem.h +++ b/Rendering/Context2D/vtkAbstractContextItem.h @@ -123,7 +123,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkAbstractContextItem : public vtkObject virtual unsigned int StackUnder(unsigned int child, unsigned int above); -//BTX // Description: // Return true if the supplied x, y coordinate is inside the item. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -182,7 +181,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkAbstractContextItem : public vtkObject // Description: // Key release event. virtual bool KeyReleaseEvent(const vtkContextKeyEvent &key); -//ETX // Description: // Set the vtkContextScene for the item, always set for an item in a scene. @@ -241,7 +239,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkAbstractContextItem : public vtkObject // Set if the item is interactive (should respond to mouse events). vtkSetMacro(Interactive, bool); -//BTX protected: vtkAbstractContextItem(); ~vtkAbstractContextItem(); @@ -271,7 +268,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkAbstractContextItem : public vtkObject private: vtkAbstractContextItem(const vtkAbstractContextItem &); // Not implemented. void operator=(const vtkAbstractContextItem &); // Not implemented. -//ETX + }; #endif //vtkContextItem_h diff --git a/Rendering/Context2D/vtkBlockItem.h b/Rendering/Context2D/vtkBlockItem.h index 0cde10d5670..c14f998bf25 100644 --- a/Rendering/Context2D/vtkBlockItem.h +++ b/Rendering/Context2D/vtkBlockItem.h @@ -40,7 +40,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkBlockItem : public vtkContextItem // Paint event for the item. virtual bool Paint(vtkContext2D *painter); -//BTX // Description: // Returns true if the supplied x, y coordinate is inside the item. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -64,7 +63,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkBlockItem : public vtkContextItem // Description: // Mouse button release event. virtual bool MouseButtonReleaseEvent(const vtkContextMouseEvent &mouse); -//ETX // Description: // Set the block label. @@ -88,11 +86,8 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkBlockItem : public vtkContextItem // Initial value is (0,0,0,0) vtkGetVector4Macro(Dimensions, float); -//BTX void SetScalarFunctor(double (*scalarFunction)(double, double)); -//ETX -//BTX protected: vtkBlockItem(); ~vtkBlockItem(); @@ -109,7 +104,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkBlockItem : public vtkContextItem private: vtkBlockItem(const vtkBlockItem &); // Not implemented. void operator=(const vtkBlockItem &); // Not implemented. -//ETX + }; #endif //vtkBlockItem_h diff --git a/Rendering/Context2D/vtkBrush.h b/Rendering/Context2D/vtkBrush.h index 7a4b0c5e5aa..2392f25d404 100644 --- a/Rendering/Context2D/vtkBrush.h +++ b/Rendering/Context2D/vtkBrush.h @@ -141,7 +141,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkBrush : public vtkObject // Make a deep copy of the supplied brush. void DeepCopy(vtkBrush *brush); -//BTX protected: vtkBrush(); ~vtkBrush(); @@ -155,7 +154,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkBrush : public vtkObject private: vtkBrush(const vtkBrush &); // Not implemented. void operator=(const vtkBrush &); // Not implemented. -//ETX + }; #endif //vtkBrush_h diff --git a/Rendering/Context2D/vtkContext2D.cxx b/Rendering/Context2D/vtkContext2D.cxx index 0bb2ef6fc92..14c7ee3b6ca 100644 --- a/Rendering/Context2D/vtkContext2D.cxx +++ b/Rendering/Context2D/vtkContext2D.cxx @@ -132,7 +132,7 @@ void vtkContext2D::DrawLine(vtkPoints2D *points) vtkErrorMacro(<< "Attempted to paint a line with <2 points."); return; } - float *f = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(points->GetData())->GetPointer(0); this->Device->DrawPoly(f, 2); } @@ -160,7 +160,7 @@ void vtkContext2D::DrawPoly(vtkPoints2D *points) // Construct an array with the correct coordinate packing for OpenGL. int n = static_cast(points->GetNumberOfPoints()); // If the points are of type float then call OpenGL directly - float *f = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(points->GetData())->GetPointer(0); this->DrawPoly(f, n); } @@ -203,7 +203,7 @@ void vtkContext2D::DrawLines(vtkPoints2D *points) // Construct an array with the correct coordinate packing for OpenGL. int n = static_cast(points->GetNumberOfPoints()); // If the points are of type float then call OpenGL directly - float *f = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(points->GetData())->GetPointer(0); this->DrawLines(f, n); } @@ -250,7 +250,7 @@ void vtkContext2D::DrawPoints(vtkPoints2D *points) // Construct an array with the correct coordinate packing for OpenGL. int n = static_cast(points->GetNumberOfPoints()); // If the points are of type float then call OpenGL directly - float *f = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(points->GetData())->GetPointer(0); this->DrawPoints(f, n); } @@ -271,7 +271,7 @@ void vtkContext2D::DrawPointSprites(vtkImageData *sprite, vtkPoints2D *points) // Construct an array with the correct coordinate packing for OpenGL. int n = static_cast(points->GetNumberOfPoints()); // If the points are of type float then call OpenGL directly - float *f = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(points->GetData())->GetPointer(0); this->DrawPointSprites(sprite, f, n); } @@ -289,7 +289,7 @@ void vtkContext2D::DrawPointSprites(vtkImageData *sprite, vtkPoints2D *points, } int nc_comps = static_cast(colors->GetNumberOfComponents()); // If the points are of type float then call OpenGL directly - float *f = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(points->GetData())->GetPointer(0); unsigned char *c = colors->GetPointer(0); this->DrawPointSprites(sprite, f, n, c, nc_comps); } @@ -340,7 +340,7 @@ void vtkContext2D::DrawMarkers(int shape, bool highlight, vtkPoints2D *points) { // Construct an array with the correct coordinate packing for OpenGL. int n = static_cast(points->GetNumberOfPoints()); - float *f = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(points->GetData())->GetPointer(0); this->DrawMarkers(shape, highlight, f, n); } @@ -356,7 +356,7 @@ void vtkContext2D::DrawMarkers(int shape, bool highlight, vtkPoints2D *points, v return; } int nc_comps = static_cast(colors->GetNumberOfComponents()); - float *f = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(points->GetData())->GetPointer(0); unsigned char *c = colors->GetPointer(0); this->DrawMarkers(shape, highlight, f, n, c, nc_comps); } @@ -414,7 +414,7 @@ void vtkContext2D::DrawQuadStrip(vtkPoints2D *points) // Construct an array with the correct coordinate packing for OpenGL. int n = static_cast(points->GetNumberOfPoints()); // If the points are of type float then call OpenGL directly - float *f = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(points->GetData())->GetPointer(0); this->DrawQuadStrip(f, n); } @@ -449,7 +449,7 @@ void vtkContext2D::DrawPolygon(vtkPoints2D *points) // Construct an array with the correct coordinate packing for OpenGL. int n = static_cast(points->GetNumberOfPoints()); // If the points are of type float then call OpenGL directly - float *f = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(points->GetData())->GetPointer(0); this->DrawPolygon(f, n); } @@ -568,7 +568,7 @@ void vtkContext2D::DrawStringRect(vtkPoints2D *rect, const char* string) //----------------------------------------------------------------------------- void vtkContext2D::DrawString(vtkPoints2D *point, const vtkStdString &string) { - float *f = vtkFloatArray::SafeDownCast(point->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(point->GetData())->GetPointer(0); this->DrawString(f[0], f[1], string); } @@ -591,7 +591,7 @@ void vtkContext2D::DrawString(float x, float y, const vtkStdString &string) //----------------------------------------------------------------------------- void vtkContext2D::DrawString(vtkPoints2D *point, const vtkUnicodeString &string) { - float *f = vtkFloatArray::SafeDownCast(point->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(point->GetData())->GetPointer(0); this->DrawString(f[0], f[1], string); } @@ -614,7 +614,7 @@ void vtkContext2D::DrawString(float x, float y, const vtkUnicodeString &string) //----------------------------------------------------------------------------- void vtkContext2D::DrawString(vtkPoints2D *point, const char* string) { - float *f = vtkFloatArray::SafeDownCast(point->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(point->GetData())->GetPointer(0); this->DrawString(f[0], f[1], vtkStdString(string)); } @@ -629,7 +629,7 @@ void vtkContext2D::ComputeStringBounds(const vtkStdString &string, vtkPoints2D *bounds) { bounds->SetNumberOfPoints(2); - float *f = vtkFloatArray::SafeDownCast(bounds->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(bounds->GetData())->GetPointer(0); this->ComputeStringBounds(string, f); } @@ -650,7 +650,7 @@ void vtkContext2D::ComputeStringBounds(const vtkUnicodeString &string, vtkPoints2D *bounds) { bounds->SetNumberOfPoints(2); - float *f = vtkFloatArray::SafeDownCast(bounds->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(bounds->GetData())->GetPointer(0); this->ComputeStringBounds(string, f); } @@ -754,7 +754,7 @@ int vtkContext2D::ComputeFontSizeForBoundedString(const vtkStdString &string, void vtkContext2D::DrawMathTextString(vtkPoints2D *point, const vtkStdString &string) { - float *f = vtkFloatArray::SafeDownCast(point->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(point->GetData())->GetPointer(0); this->DrawMathTextString(f[0], f[1], string); } @@ -778,7 +778,7 @@ void vtkContext2D::DrawMathTextString(float x, float y, //----------------------------------------------------------------------------- void vtkContext2D::DrawMathTextString(vtkPoints2D *point, const char* string) { - float *f = vtkFloatArray::SafeDownCast(point->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(point->GetData())->GetPointer(0); this->DrawMathTextString(f[0], f[1], vtkStdString(string)); } @@ -1001,7 +1001,7 @@ vtkVector2f vtkContext2D::CalculateTextPosition(vtkPoints2D* rect) return vtkVector2f(); } - float *f = vtkFloatArray::SafeDownCast(rect->GetData())->GetPointer(0); + float *f = vtkArrayDownCast(rect->GetData())->GetPointer(0); return this->CalculateTextPosition(f); } diff --git a/Rendering/Context2D/vtkContext2D.h b/Rendering/Context2D/vtkContext2D.h index 47648ab5771..729c6389ab6 100644 --- a/Rendering/Context2D/vtkContext2D.h +++ b/Rendering/Context2D/vtkContext2D.h @@ -55,7 +55,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContext2D : public vtkObject // Creates a 2D Painter object. static vtkContext2D *New(); -//BTX // Description: // Begin painting on a vtkContextDevice2D, no painting can occur before this call // has been made. Only one painter is allowed at a time on any given paint @@ -436,7 +435,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContext2D : public vtkObject vtkGetObjectMacro(Context3D, vtkContext3D) virtual void SetContext3D(vtkContext3D *context); -//BTX protected: vtkContext2D(); ~vtkContext2D(); @@ -465,7 +463,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContext2D : public vtkObject // represent width and height. vtkVector2f CalculateTextPosition(float rect[4]); -//ETX }; inline int vtkContext2D::FloatToInt(float x) diff --git a/Rendering/Context2D/vtkContextClip.h b/Rendering/Context2D/vtkContextClip.h index 7669a1fb375..b2c4110b4c2 100644 --- a/Rendering/Context2D/vtkContextClip.h +++ b/Rendering/Context2D/vtkContextClip.h @@ -60,7 +60,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextClip : public vtkAbstractContextIte virtual float GetWidth() { return Dims[2]; } virtual float GetHeight() { return Dims[3]; } -//BTX protected: vtkContextClip(); ~vtkContextClip(); @@ -70,7 +69,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextClip : public vtkAbstractContextIte private: vtkContextClip(const vtkContextClip &); // Not implemented. void operator=(const vtkContextClip &); // Not implemented. - //ETX + }; inline void vtkContextClip::GetRect(float rect[4]) diff --git a/Rendering/Context2D/vtkContextDevice2D.h b/Rendering/Context2D/vtkContextDevice2D.h index 976b2a4d53b..b25f27d809e 100644 --- a/Rendering/Context2D/vtkContextDevice2D.h +++ b/Rendering/Context2D/vtkContextDevice2D.h @@ -289,7 +289,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextDevice2D : public vtkObject // Initial value is false. virtual bool GetBufferIdMode() const; -//BTX // Description: // Start BufferId creation Mode. // The default implementation is empty. @@ -297,7 +296,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextDevice2D : public vtkObject // \pre bufferId_exists: bufferId!=0 // \post started: GetBufferIdMode() virtual void BufferIdModeBegin(vtkAbstractContextBufferId *bufferId); -//ETX + // Description: // Finalize BufferId creation Mode. It makes sure that the content of the // bufferId passed in argument of BufferIdModeBegin() is correctly set. @@ -318,7 +317,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextDevice2D : public vtkObject } vtkGetMacro(ViewportRect, vtkRecti) -//BTX protected: vtkContextDevice2D(); ~vtkContextDevice2D(); @@ -345,7 +343,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextDevice2D : public vtkObject vtkContextDevice2D(const vtkContextDevice2D &); // Not implemented. void operator=(const vtkContextDevice2D &); // Not implemented. -//ETX }; #endif //vtkContextDevice2D_h diff --git a/Rendering/Context2D/vtkContextItem.h b/Rendering/Context2D/vtkContextItem.h index 712759c40ac..807dd9af5fa 100644 --- a/Rendering/Context2D/vtkContextItem.h +++ b/Rendering/Context2D/vtkContextItem.h @@ -40,7 +40,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextItem : public vtkAbstractContextIte // 1.0 by default. vtkSetMacro(Opacity, double); -//BTX protected: vtkContextItem(); ~vtkContextItem(); @@ -50,7 +49,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextItem : public vtkAbstractContextIte private: vtkContextItem(const vtkContextItem &); // Not implemented. void operator=(const vtkContextItem &); // Not implemented. -//ETX + }; #endif //vtkContextItem_h diff --git a/Rendering/Context2D/vtkContextMapper2D.h b/Rendering/Context2D/vtkContextMapper2D.h index 564d999deaa..e3529176ca7 100644 --- a/Rendering/Context2D/vtkContextMapper2D.h +++ b/Rendering/Context2D/vtkContextMapper2D.h @@ -57,7 +57,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextMapper2D : public vtkAlgorithm return this->vtkAlgorithm::GetInputAbstractArrayToProcess(idx, input); } -//BTX protected: vtkContextMapper2D(); ~vtkContextMapper2D(); @@ -69,7 +68,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextMapper2D : public vtkAlgorithm private: vtkContextMapper2D(const vtkContextMapper2D &); // Not implemented. void operator=(const vtkContextMapper2D &); // Not implemented. -//ETX + }; #endif //vtkContextMapper2D_h diff --git a/Rendering/Context2D/vtkContextScene.h b/Rendering/Context2D/vtkContextScene.h index 47b7c9bbfb1..9c897047791 100644 --- a/Rendering/Context2D/vtkContextScene.h +++ b/Rendering/Context2D/vtkContextScene.h @@ -153,7 +153,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextScene : public vtkObject void SetDirty(bool isDirty); bool GetDirty()const; -//BTX // Description: // Release graphics resources hold by the scene. void ReleaseGraphicsResources(); @@ -300,7 +299,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextScene : public vtkObject const vtkContextMouseEvent& event, MouseEvents eventPtr); void EventCopy(const vtkContextMouseEvent &event); -//ETX + }; #endif //vtkContextScene_h diff --git a/Rendering/Context2D/vtkContextTransform.h b/Rendering/Context2D/vtkContextTransform.h index afdf68f9f23..e94119a53b5 100644 --- a/Rendering/Context2D/vtkContextTransform.h +++ b/Rendering/Context2D/vtkContextTransform.h @@ -140,7 +140,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextTransform : public vtkAbstractConte vtkGetMacro(PanYOnMouseWheel, bool); vtkBooleanMacro(PanYOnMouseWheel, bool); -//BTX // Description: // Returns true if the transform is interactive, false otherwise. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -156,9 +155,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextTransform : public vtkAbstractConte // Description: // Mouse wheel event. Perform pan or zoom as specified by mouse bindings. virtual bool MouseWheelEvent(const vtkContextMouseEvent &mouse, int delta); -//ETX -//BTX protected: vtkContextTransform(); ~vtkContextTransform(); @@ -182,7 +179,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkContextTransform : public vtkAbstractConte private: vtkContextTransform(const vtkContextTransform &); // Not implemented. void operator=(const vtkContextTransform &); // Not implemented. -//ETX + }; #endif //vtkContextTransform_h diff --git a/Rendering/Context2D/vtkImageItem.h b/Rendering/Context2D/vtkImageItem.h index 369de9ac7a8..c914cdf699a 100644 --- a/Rendering/Context2D/vtkImageItem.h +++ b/Rendering/Context2D/vtkImageItem.h @@ -56,7 +56,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkImageItem : public vtkContextItem // Get the position of the bottom corner of the image. vtkGetVector2Macro(Position, float); -//BTX protected: vtkImageItem(); ~vtkImageItem(); @@ -68,7 +67,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkImageItem : public vtkContextItem private: vtkImageItem(const vtkImageItem &); // Not implemented. void operator=(const vtkImageItem &); // Not implemented. -//ETX + }; #endif //vtkImageItem_h diff --git a/Rendering/Context2D/vtkMarkerUtilities.h b/Rendering/Context2D/vtkMarkerUtilities.h index 4d7a7f610c2..4acd0f2cfd1 100644 --- a/Rendering/Context2D/vtkMarkerUtilities.h +++ b/Rendering/Context2D/vtkMarkerUtilities.h @@ -37,7 +37,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkMarkerUtilities : public vtkObject vtkTypeMacro(vtkMarkerUtilities, vtkObject); virtual void PrintSelf(ostream &os, vtkIndent indent); -//BTX // Description: // Enum containing various marker styles that can be used in a plot. enum { @@ -48,13 +47,11 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkMarkerUtilities : public vtkObject CIRCLE, DIAMOND }; -//ETX // Description: // Generate the requested symbol of a particular style and size. static void GenerateMarker(vtkImageData *data, int style, int width); -//BTX protected: vtkMarkerUtilities(); ~vtkMarkerUtilities(); @@ -62,7 +59,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkMarkerUtilities : public vtkObject private: vtkMarkerUtilities(const vtkMarkerUtilities &); // Not implemented. void operator=(const vtkMarkerUtilities &); // Not implemented. -//ETX + }; #endif //vtkMarkerUtilities_h diff --git a/Rendering/Context2D/vtkPen.h b/Rendering/Context2D/vtkPen.h index 4e833923216..29f7f3e50d3 100644 --- a/Rendering/Context2D/vtkPen.h +++ b/Rendering/Context2D/vtkPen.h @@ -38,7 +38,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkPen : public vtkObject static vtkPen *New(); -//BTX // Description: // Enum of the available line types. enum { @@ -48,7 +47,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkPen : public vtkObject DOT_LINE, DASH_DOT_LINE, DASH_DOT_DOT_LINE}; -//ETX // Description: // Set the type of line that the pen should draw. The default is solid (1). @@ -130,7 +128,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkPen : public vtkObject // Make a deep copy of the supplied pen. void DeepCopy(vtkPen *pen); -//BTX protected: vtkPen(); ~vtkPen(); @@ -151,7 +148,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkPen : public vtkObject private: vtkPen(const vtkPen &); // Not implemented. void operator=(const vtkPen &); // Not implemented. -//ETX + }; #endif //vtkPen_h diff --git a/Rendering/Context2D/vtkTooltipItem.h b/Rendering/Context2D/vtkTooltipItem.h index 0ef634a4b2a..1e3380bc288 100644 --- a/Rendering/Context2D/vtkTooltipItem.h +++ b/Rendering/Context2D/vtkTooltipItem.h @@ -79,7 +79,6 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkTooltipItem : public vtkContextItem // Paint event for the tooltip. virtual bool Paint(vtkContext2D *painter); -//BTX protected: vtkTooltipItem(); ~vtkTooltipItem(); @@ -94,7 +93,7 @@ class VTKRENDERINGCONTEXT2D_EXPORT vtkTooltipItem : public vtkContextItem private: vtkTooltipItem(const vtkTooltipItem &); // Not implemented. void operator=(const vtkTooltipItem &); // Not implemented. -//ETX + }; #endif //vtkTooltipItem_h diff --git a/Rendering/ContextOpenGL/vtkOpenGLContextDevice2D.h b/Rendering/ContextOpenGL/vtkOpenGLContextDevice2D.h index c6ae4b60458..0d9d84a8caf 100644 --- a/Rendering/ContextOpenGL/vtkOpenGLContextDevice2D.h +++ b/Rendering/ContextOpenGL/vtkOpenGLContextDevice2D.h @@ -281,7 +281,6 @@ class VTKRENDERINGCONTEXTOPENGL_EXPORT vtkOpenGLContextDevice2D : public vtkCont // resources to release. virtual void ReleaseGraphicsResources(vtkWindow *window); -//BTX protected: vtkOpenGLContextDevice2D(); virtual ~vtkOpenGLContextDevice2D(); @@ -358,7 +357,6 @@ class VTKRENDERINGCONTEXTOPENGL_EXPORT vtkOpenGLContextDevice2D : public vtkCont // not be used directly -- use GetMarker, which caches results, instead. vtkImageData * GenerateMarker(int shape, int size, bool highlight); -//ETX }; #endif //vtkOpenGLContextDevice2D_h diff --git a/Rendering/ContextOpenGL2/vtkOpenGLContextDevice2D.h b/Rendering/ContextOpenGL2/vtkOpenGLContextDevice2D.h index 1c1c2e496f9..3bff2fe50e8 100644 --- a/Rendering/ContextOpenGL2/vtkOpenGLContextDevice2D.h +++ b/Rendering/ContextOpenGL2/vtkOpenGLContextDevice2D.h @@ -291,7 +291,6 @@ class VTKRENDERINGCONTEXTOPENGL2_EXPORT vtkOpenGLContextDevice2D : public vtkCon vtkMatrix4x4 *GetProjectionMatrix(); vtkMatrix4x4 *GetModelMatrix(); -//BTX protected: vtkOpenGLContextDevice2D(); virtual ~vtkOpenGLContextDevice2D(); @@ -441,7 +440,6 @@ class VTKRENDERINGCONTEXTOPENGL2_EXPORT vtkOpenGLContextDevice2D : public vtkCon // not be used directly -- use GetMarker, which caches results, instead. vtkImageData * GenerateMarker(int shape, int size, bool highlight); -//ETX }; #endif //vtkOpenGLContextDevice2D_h diff --git a/Rendering/Core/CMakeLists.txt b/Rendering/Core/CMakeLists.txt index b74c9d2e7f0..ab645c39535 100644 --- a/Rendering/Core/CMakeLists.txt +++ b/Rendering/Core/CMakeLists.txt @@ -23,6 +23,7 @@ set(Module_SRCS vtkDiscretizableColorTransferFunction.cxx vtkDistanceToCamera.cxx vtkFollower.cxx + vtkFrameBufferObjectBase.cxx vtkFrustumCoverageCuller.cxx vtkGenericRenderWindowInteractor.cxx vtkGenericVertexAttributeMapping.cxx @@ -68,6 +69,8 @@ set(Module_SRCS vtkRenderer.cxx vtkRendererDelegate.cxx vtkRendererSource.cxx + vtkRenderPass.cxx + vtkRenderState.cxx vtkRenderWindowCollection.cxx vtkRenderWindow.cxx vtkRenderWindowInteractor.cxx @@ -164,6 +167,7 @@ set_source_files_properties( vtkAbstractPicker vtkAbstractPropPicker vtkCuller + vtkFrameBufferObjectBase vtkGPUInfoList.cxx vtkHardwareSelector vtkImageMapper3D @@ -173,6 +177,8 @@ set_source_files_properties( vtkProp vtkProp3D vtkRendererDelegate + vtkRenderPass + vtkRenderState vtkShader vtkShaderDeviceAdapter vtkShaderDeviceAdapter2 @@ -188,6 +194,7 @@ set_source_files_properties( set_source_files_properties( vtkAbstractInteractionDevice vtkAbstractRenderDevice + vtkRenderState vtkRenderWidget WRAP_EXCLUDE ) diff --git a/Rendering/Core/Testing/Cxx/CMakeLists.txt b/Rendering/Core/Testing/Cxx/CMakeLists.txt index 698b92a3da3..98e448c7c42 100644 --- a/Rendering/Core/Testing/Cxx/CMakeLists.txt +++ b/Rendering/Core/Testing/Cxx/CMakeLists.txt @@ -55,6 +55,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestOrderedTriangulator.cxx TestOpacity.cxx TestOSConeCxx.cxx + TestPickTextActor.cxx,NO_VALID TestPointSelection.cxx,NO_VALID TestPolygonSelection.cxx TestResetCameraVerticalAspectRatio.cxx diff --git a/Rendering/Core/Testing/Cxx/TestBareScalarsToColors.cxx b/Rendering/Core/Testing/Cxx/TestBareScalarsToColors.cxx index 9e63fc8b667..18a990e0f78 100644 --- a/Rendering/Core/Testing/Cxx/TestBareScalarsToColors.cxx +++ b/Rendering/Core/Testing/Cxx/TestBareScalarsToColors.cxx @@ -72,7 +72,7 @@ int TestBareScalarsToColors(int argc, char *argv[]) cval[1] = (ncomp > 2 ? cval[1] : cval[3]); for (int kk = 0; kk < 5; kk++) { - arr->SetTupleValue(i++, cval); + arr->SetTypedTuple(i++, cval); } } } diff --git a/Rendering/Core/Testing/Cxx/TestColorTransferFunctionStringArray.cxx b/Rendering/Core/Testing/Cxx/TestColorTransferFunctionStringArray.cxx index 75b70d23a21..ba096877b26 100644 --- a/Rendering/Core/Testing/Cxx/TestColorTransferFunctionStringArray.cxx +++ b/Rendering/Core/Testing/Cxx/TestColorTransferFunctionStringArray.cxx @@ -66,7 +66,7 @@ int TestColorTransferFunctionStringArray(int vtkNotUsed(argc), char* vtkNotUsed( for (int i = 0; i < sArray->GetNumberOfValues(); ++i) { unsigned char color[4]; - colors->GetTupleValue(i, color); + colors->GetTypedTuple(i, color); if (expectedColors[i][0] != color[0] || expectedColors[i][1] != color[1] || expectedColors[i][2] != color[2] || diff --git a/Rendering/Core/Testing/Cxx/TestDirectScalarsToColors.cxx b/Rendering/Core/Testing/Cxx/TestDirectScalarsToColors.cxx index 5bdb031670c..c768ff6f1ca 100644 --- a/Rendering/Core/Testing/Cxx/TestDirectScalarsToColors.cxx +++ b/Rendering/Core/Testing/Cxx/TestDirectScalarsToColors.cxx @@ -104,7 +104,7 @@ void addViews (vtkRenderWindow* renWin, int typeIndex) } for (int kk = 0; kk < 5; kk++) { - arr->SetTupleValue(i++, cval); + arr->SetTypedTuple(i++, cval); } } } diff --git a/Rendering/Core/Testing/Cxx/TestDiscretizableColorTransferFunctionStringArray.cxx b/Rendering/Core/Testing/Cxx/TestDiscretizableColorTransferFunctionStringArray.cxx index 7250b099d98..8b1b2025614 100644 --- a/Rendering/Core/Testing/Cxx/TestDiscretizableColorTransferFunctionStringArray.cxx +++ b/Rendering/Core/Testing/Cxx/TestDiscretizableColorTransferFunctionStringArray.cxx @@ -65,7 +65,7 @@ int TestDiscretizableColorTransferFunctionStringArray(int vtkNotUsed(argc), char for (int i = 0; i < sArray->GetNumberOfValues(); ++i) { unsigned char color[4]; - colors->GetTupleValue(i, color); + colors->GetTypedTuple(i, color); if (expectedColors[i][0] != color[0] || expectedColors[i][1] != color[1] || expectedColors[i][2] != color[2] || diff --git a/Rendering/Core/Testing/Cxx/TestGlyph3DMapperPicking.cxx b/Rendering/Core/Testing/Cxx/TestGlyph3DMapperPicking.cxx index 25f05814de5..3498d28243a 100644 --- a/Rendering/Core/Testing/Cxx/TestGlyph3DMapperPicking.cxx +++ b/Rendering/Core/Testing/Cxx/TestGlyph3DMapperPicking.cxx @@ -104,7 +104,7 @@ class MyEndPickCommand : public vtkCommand { cout<<"abs is null"<(abs); if(ids==0) { cout<<"ids is null"< 2 ? cval[1] : cval[3]); for (int kk = 0; kk < 5; kk++) { - arr->SetTupleValue(i++, cval); + arr->SetTypedTuple(i++, cval); } } } diff --git a/Rendering/Core/Testing/Cxx/TestMapVectorsToColors.cxx b/Rendering/Core/Testing/Cxx/TestMapVectorsToColors.cxx index cdd86709511..42da2e614d9 100644 --- a/Rendering/Core/Testing/Cxx/TestMapVectorsToColors.cxx +++ b/Rendering/Core/Testing/Cxx/TestMapVectorsToColors.cxx @@ -63,7 +63,7 @@ int TestMapVectorsToColors(int argc, char *argv[]) cval[3] = (j & 3)*f; for (int kk = 0; kk < 5; kk++) { - arr->SetTupleValue(i++, cval); + arr->SetTypedTuple(i++, cval); } } } diff --git a/Rendering/Core/Testing/Cxx/TestPickTextActor.cxx b/Rendering/Core/Testing/Cxx/TestPickTextActor.cxx new file mode 100644 index 00000000000..92a6239a1f3 --- /dev/null +++ b/Rendering/Core/Testing/Cxx/TestPickTextActor.cxx @@ -0,0 +1,56 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestPickTextActor.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This tests picking of text actors. +// +#include "vtkActor2D.h" +#include "vtkNew.h" +#include "vtkPropPicker.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkTextActor.h" + +#include + +int TestPickTextActor(int, char*[]) +{ + vtkNew actor1; + actor1->SetInput("One"); + actor1->SetPosition(140, 140); + + vtkNew actor2; + actor2->SetInput("Two"); + actor2->SetPosition(160, 170); + + vtkNew renderer; + renderer->AddActor(actor1.Get()); + renderer->AddActor(actor2.Get()); + + vtkNew renWin; + renWin->AddRenderer(renderer.Get()); + renWin->Render(); + + vtkNew picker; + picker->Pick(145, 145, 0.0, renderer.Get()); + vtkActor2D* pickedActor = picker->GetActor2D(); + if (pickedActor != actor1.Get()) + { + std::cout << "Incorrect actor picked!" << std::endl; + std::cout << "Should have been " << actor1.Get() << ", but was " << pickedActor << std::endl; + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/Rendering/Core/Testing/Cxx/TestPickingManager.cxx b/Rendering/Core/Testing/Cxx/TestPickingManager.cxx index b16abc6f170..d22577db9bb 100644 --- a/Rendering/Core/Testing/Cxx/TestPickingManager.cxx +++ b/Rendering/Core/Testing/Cxx/TestPickingManager.cxx @@ -53,6 +53,7 @@ class PickingManagerTest bool TestAddPickers(); bool TestRemovePickers(); bool TestRemoveObjects(); + bool TestObjectOwnership(); bool VTKVerify(bool test, const char* errorStr, int line); void PrintErrorMessage(int line, const char* errorStr); @@ -87,6 +88,73 @@ class PickingManagerTest vtkSmartPointer PickingManager; }; +//------------------------------------------------------------------------------ +// Test picking manager client that removes itself from the picking manager +// in its destructor. This mimics the behavior of the VTK widget framework. +class PickingManagerClient : public vtkObject + { + public: + static PickingManagerClient* New(); + vtkTypeMacro(PickingManagerClient, vtkObject); + + void SetPickingManager(vtkPickingManager *pm); + void RegisterPicker(); + vtkPicker* GetPicker(); + + protected: + PickingManagerClient(); + ~PickingManagerClient(); + + private: + vtkPickingManager *PickingManager; + vtkPicker *Picker; + + PickingManagerClient(const PickingManagerClient&); //Not implemented + void operator=(const PickingManagerClient&); //Not implemented + }; + +vtkStandardNewMacro(PickingManagerClient); + +//------------------------------------------------------------------------------ +PickingManagerClient::PickingManagerClient() +{ + this->Picker = vtkPicker::New(); +} + +//------------------------------------------------------------------------------ +PickingManagerClient::~PickingManagerClient() +{ + this->Picker->Delete(); + + if (this->PickingManager) + { + this->PickingManager->RemoveObject(this); + } +} + +//------------------------------------------------------------------------------ +void PickingManagerClient::SetPickingManager(vtkPickingManager *pm) +{ + this->PickingManager = pm; +} + +//------------------------------------------------------------------------------ +void PickingManagerClient::RegisterPicker() +{ + if (!this->PickingManager) + { + return; + } + + this->PickingManager->AddPicker(this->Picker, this); +} + +//------------------------------------------------------------------------------ +vtkPicker* PickingManagerClient::GetPicker() +{ + return this->Picker; +} + //------------------------------------------------------------------------------ int TestPickingManager(int, char*[]) { @@ -98,6 +166,7 @@ int TestPickingManager(int, char*[]) res = res && pickingManagerTest.TestAddPickers(); res = res && pickingManagerTest.TestRemovePickers(); res = res && pickingManagerTest.TestRemoveObjects(); + res = res && pickingManagerTest.TestObjectOwnership(); return res ? EXIT_SUCCESS : EXIT_FAILURE; } @@ -253,6 +322,28 @@ bool PickingManagerTest::TestRemoveObjects() return res; } +//------------------------------------------------------------------------------ +bool PickingManagerTest::TestObjectOwnership() +{ + bool res = true; + + this->PickingManager = vtkSmartPointer::New(); + vtkSmartPointer client = + vtkSmartPointer::New(); + client->SetPickingManager(this->PickingManager.GetPointer()); + client->RegisterPicker(); + + res = VTK_VERIFY(this->CheckState(1, client->GetPicker(), 1), + "Error after client registers picker:") && res; + + client = NULL; + + res = VTK_VERIFY(this->CheckState(0, NULL, 0), + "Error after setting client object to NULL:") && res; + + return res; +} + //------------------------------------------------------------------------------ std::pair, vtkSmartPointer > PickingManagerTest:: AddPickerObject(int pickerType, int objectType) diff --git a/Rendering/Core/Testing/Cxx/TestPointSelection.cxx b/Rendering/Core/Testing/Cxx/TestPointSelection.cxx index 4014f4465e1..c674b8bd9c8 100644 --- a/Rendering/Core/Testing/Cxx/TestPointSelection.cxx +++ b/Rendering/Core/Testing/Cxx/TestPointSelection.cxx @@ -67,7 +67,7 @@ class PointPickCommand : public vtkCommand if (selActor && (selActor->GetMapper() == this->Mapper)) { // Separate the selection ids into atoms and bonds - vtkIdTypeArray *selIds = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray *selIds = vtkArrayDownCast( node->GetSelectionList()); if (selIds) { diff --git a/Rendering/Core/Testing/Cxx/TestPolygonSelection.cxx b/Rendering/Core/Testing/Cxx/TestPolygonSelection.cxx index cba04528748..b441e07243b 100644 --- a/Rendering/Core/Testing/Cxx/TestPolygonSelection.cxx +++ b/Rendering/Core/Testing/Cxx/TestPolygonSelection.cxx @@ -125,7 +125,7 @@ int TestPolygonSelection( int argc, char* argv[] ) { const vtkVector2i &v = points[j]; int pos[2] = {v[0], v[1]}; - polygonPointsArray->SetTupleValue(j, pos); + polygonPointsArray->SetTypedTuple(j, pos); } vtkNew hardSel; diff --git a/Rendering/Core/Testing/Cxx/TestTranslucentImageActorDepthPeeling.cxx b/Rendering/Core/Testing/Cxx/TestTranslucentImageActorDepthPeeling.cxx index a1c3574b9be..6950e19a4d3 100644 --- a/Rendering/Core/Testing/Cxx/TestTranslucentImageActorDepthPeeling.cxx +++ b/Rendering/Core/Testing/Cxx/TestTranslucentImageActorDepthPeeling.cxx @@ -37,7 +37,7 @@ int TestTranslucentImageActorDepthPeeling(int argc, char* argv[]) iren->SetRenderWindow(renWin); renWin->Delete(); - renWin->SetMultiSamples(1); + renWin->SetMultiSamples(0); renWin->SetAlphaBitPlanes(1); vtkRenderer *renderer = vtkRenderer::New(); diff --git a/Rendering/Core/vtkAbstractMapper.cxx b/Rendering/Core/vtkAbstractMapper.cxx index 3c6cde51174..428ddb68f2a 100644 --- a/Rendering/Core/vtkAbstractMapper.cxx +++ b/Rendering/Core/vtkAbstractMapper.cxx @@ -125,7 +125,7 @@ vtkDataArray* vtkAbstractMapper::GetScalars(vtkDataSet *input, { vtkAbstractArray* abstractScalars = vtkAbstractMapper::GetAbstractScalars(input, scalarMode, arrayAccessMode, arrayId, arrayName, cellFlag); - vtkDataArray* scalars = vtkDataArray::SafeDownCast(abstractScalars); + vtkDataArray* scalars = vtkArrayDownCast(abstractScalars); return scalars; } diff --git a/Rendering/Core/vtkAbstractVolumeMapper.h b/Rendering/Core/vtkAbstractVolumeMapper.h index 900ad95c4ea..1802a92e9ca 100644 --- a/Rendering/Core/vtkAbstractVolumeMapper.h +++ b/Rendering/Core/vtkAbstractVolumeMapper.h @@ -91,7 +91,6 @@ class VTKRENDERINGCORE_EXPORT vtkAbstractVolumeMapper : public vtkAbstractMapper // Return the method for obtaining scalar data. const char *GetScalarModeAsString(); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE virtual float GetGradientMagnitudeScale() {return 1.0f;}; @@ -113,8 +112,6 @@ class VTKRENDERINGCORE_EXPORT vtkAbstractVolumeMapper : public vtkAbstractMapper // resources to release. virtual void ReleaseGraphicsResources(vtkWindow *) {} -//ETX - protected: vtkAbstractVolumeMapper(); ~vtkAbstractVolumeMapper(); diff --git a/Rendering/Core/vtkActor2DCollection.h b/Rendering/Core/vtkActor2DCollection.h index 1835f862d40..4d0221b513a 100644 --- a/Rendering/Core/vtkActor2DCollection.h +++ b/Rendering/Core/vtkActor2DCollection.h @@ -70,13 +70,11 @@ class VTKRENDERINGCORE_EXPORT vtkActor2DCollection : public vtkPropCollection // Sort and then render the collection of 2D actors. void RenderOverlay(vtkViewport* viewport); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkActor2D *GetNextActor2D(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkActor2DCollection() {} diff --git a/Rendering/Core/vtkActorCollection.h b/Rendering/Core/vtkActorCollection.h index 1677e187e61..a564421ac64 100644 --- a/Rendering/Core/vtkActorCollection.h +++ b/Rendering/Core/vtkActorCollection.h @@ -60,13 +60,11 @@ class VTKRENDERINGCORE_EXPORT vtkActorCollection : public vtkPropCollection // Apply properties to all actors in this collection. void ApplyProperties(vtkProperty *p); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkActor *GetNextActor(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkActorCollection() {} diff --git a/Rendering/Core/vtkAssembly.h b/Rendering/Core/vtkAssembly.h index 076c54ee611..09767e7a81f 100644 --- a/Rendering/Core/vtkAssembly.h +++ b/Rendering/Core/vtkAssembly.h @@ -140,14 +140,12 @@ class VTKRENDERINGCORE_EXPORT vtkAssembly : public vtkProp3D // Shallow copy of an assembly. Overloads the virtual vtkProp method. void ShallowCopy(vtkProp *prop); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE DO NOT USE THIS // METHOD OUTSIDE OF THE RENDERING PROCESS Overload the superclass' vtkProp // BuildPaths() method. Paths consist of an ordered sequence of actors, // with transformations properly concatenated. void BuildPaths(vtkAssemblyPaths *paths, vtkAssemblyPath *path); -//ETX protected: vtkAssembly(); diff --git a/Rendering/Core/vtkAssemblyPath.h b/Rendering/Core/vtkAssemblyPath.h index 4004dba19ab..f41a42790c8 100644 --- a/Rendering/Core/vtkAssemblyPath.h +++ b/Rendering/Core/vtkAssemblyPath.h @@ -87,13 +87,11 @@ class VTKRENDERINGCORE_EXPORT vtkAssemblyPath : public vtkCollection // of the nodes in this path. virtual unsigned long GetMTime(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkAssemblyNode *GetNextNode(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie)); } - //ETX protected: vtkAssemblyPath(); diff --git a/Rendering/Core/vtkAssemblyPaths.h b/Rendering/Core/vtkAssemblyPaths.h index 15b81fc7fff..bd8c677271c 100644 --- a/Rendering/Core/vtkAssemblyPaths.h +++ b/Rendering/Core/vtkAssemblyPaths.h @@ -59,13 +59,11 @@ class VTKRENDERINGCORE_EXPORT vtkAssemblyPaths : public vtkCollection // of the paths. virtual unsigned long GetMTime(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkAssemblyPath *GetNextPath(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie)); } - //ETX protected: vtkAssemblyPaths() {} diff --git a/Rendering/Core/vtkCamera.h b/Rendering/Core/vtkCamera.h index 696db622fa7..55d35d1ffa6 100644 --- a/Rendering/Core/vtkCamera.h +++ b/Rendering/Core/vtkCamera.h @@ -593,10 +593,9 @@ class VTKRENDERINGCORE_EXPORT vtkCamera : public vtkObject vtkTransform *ModelViewTransform; double FocalDisk; - //BTX + vtkCameraCallbackCommand *UserViewTransformCallbackCommand; friend class vtkCameraCallbackCommand; - //ETX // ViewingRaysMtime keeps track of camera modifications which will // change the calculation of viewing rays for the camera before it is diff --git a/Rendering/Core/vtkCameraInterpolator.h b/Rendering/Core/vtkCameraInterpolator.h index 35043f97636..ce30e384a56 100644 --- a/Rendering/Core/vtkCameraInterpolator.h +++ b/Rendering/Core/vtkCameraInterpolator.h @@ -97,14 +97,12 @@ class VTKRENDERINGCORE_EXPORT vtkCameraInterpolator : public vtkObject // (min,max) values, then t is clamped to lie within this range. void InterpolateCamera(double t, vtkCamera *camera); -//BTX // Description: // Enums to control the type of interpolation to use. enum {INTERPOLATION_TYPE_LINEAR=0, INTERPOLATION_TYPE_SPLINE, INTERPOLATION_TYPE_MANUAL }; -//ETX // Description: // These are convenience methods to switch between linear and spline diff --git a/Rendering/Core/vtkCellPicker.cxx b/Rendering/Core/vtkCellPicker.cxx index 0a635d22566..105ab9fe79e 100644 --- a/Rendering/Core/vtkCellPicker.cxx +++ b/Rendering/Core/vtkCellPicker.cxx @@ -801,6 +801,13 @@ double vtkCellPicker::IntersectVolumeWithLine(const double p1[3], } } } + + // Break if far clipping plane has been reached + if (t >= 1.0) + { + t = 1.0; + break; + } } // End of "while (t <= t2)" // If the ray hit the isosurface, compute the isosurface position diff --git a/Rendering/Core/vtkCullerCollection.h b/Rendering/Core/vtkCullerCollection.h index 52a9a7848c1..352c28b487d 100644 --- a/Rendering/Core/vtkCullerCollection.h +++ b/Rendering/Core/vtkCullerCollection.h @@ -53,7 +53,6 @@ class VTKRENDERINGCORE_EXPORT vtkCullerCollection : public vtkCollection // Get the last Culler in the list. vtkCuller *GetLastItem(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. @@ -61,7 +60,6 @@ class VTKRENDERINGCORE_EXPORT vtkCullerCollection : public vtkCollection { return static_cast(this->GetNextItemAsObject(cookie)); } - //ETX protected: vtkCullerCollection() {} diff --git a/Rendering/Core/vtkDataSetMapper.h b/Rendering/Core/vtkDataSetMapper.h index 7bf5367a0b0..76f12dabd4b 100644 --- a/Rendering/Core/vtkDataSetMapper.h +++ b/Rendering/Core/vtkDataSetMapper.h @@ -64,7 +64,7 @@ class VTKRENDERINGCORE_EXPORT vtkDataSetMapper : public vtkMapper vtkDataSetSurfaceFilter *GeometryExtractor; vtkPolyDataMapper *PolyDataMapper; - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; // see algorithm for more info virtual int FillInputPortInformation(int port, vtkInformation* info); diff --git a/Rendering/Core/vtkDiscretizableColorTransferFunction.cxx b/Rendering/Core/vtkDiscretizableColorTransferFunction.cxx index ffbb84ed4fe..f15463ff8a6 100644 --- a/Rendering/Core/vtkDiscretizableColorTransferFunction.cxx +++ b/Rendering/Core/vtkDiscretizableColorTransferFunction.cxx @@ -347,7 +347,7 @@ vtkUnsignedCharArray* vtkDiscretizableColorTransferFunction::MapScalars( // color and we won't use it for opacity either. bool direct_scalar_mapping = ((colorMode == VTK_COLOR_MODE_DEFAULT && - vtkUnsignedCharArray::SafeDownCast(scalars) != NULL) || + vtkArrayDownCast(scalars) != NULL) || colorMode == VTK_COLOR_MODE_DIRECT_SCALARS); vtkUnsignedCharArray *colors = (this->Discretize || this->IndexedLookup) ? @@ -362,7 +362,7 @@ vtkUnsignedCharArray* vtkDiscretizableColorTransferFunction::MapScalars( (this->EnableOpacityMapping == true) && (this->ScalarOpacityFunction.GetPointer() != NULL)) { - vtkDataArray* da = vtkDataArray::SafeDownCast(scalars); + vtkDataArray* da = vtkArrayDownCast(scalars); this->MapDataArrayToOpacity(da, component, colors); } return colors; diff --git a/Rendering/Core/vtkFrameBufferObjectBase.cxx b/Rendering/Core/vtkFrameBufferObjectBase.cxx new file mode 100644 index 00000000000..5c0cb35c690 --- /dev/null +++ b/Rendering/Core/vtkFrameBufferObjectBase.cxx @@ -0,0 +1,33 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkFrameBufferObjectBase.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkFrameBufferObjectBase.h" + +#include "vtkObjectFactory.h" + +//---------------------------------------------------------------------------- +vtkFrameBufferObjectBase::vtkFrameBufferObjectBase() +{ +} + +//---------------------------------------------------------------------------- +vtkFrameBufferObjectBase::~vtkFrameBufferObjectBase() +{ +} + +// ---------------------------------------------------------------------------- +void vtkFrameBufferObjectBase::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/Rendering/Core/vtkFrameBufferObjectBase.h b/Rendering/Core/vtkFrameBufferObjectBase.h new file mode 100644 index 00000000000..128b0ef53ac --- /dev/null +++ b/Rendering/Core/vtkFrameBufferObjectBase.h @@ -0,0 +1,48 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkFrameBufferObjectBase.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkFrameBufferObjectBase - abstract interface to OpenGL FBOs +// .SECTION Description +// API for classes that encapsulate an OpenGL Frame Buffer Object. + +#ifndef vtkFrameBufferObjectBase_h +#define vtkFrameBufferObjectBase_h + +#include "vtkRenderingCoreModule.h" // For export macro +#include "vtkObject.h" + +class vtkRenderer; +class vtkProp; +class vtkInformation; + +class VTKRENDERINGCORE_EXPORT vtkFrameBufferObjectBase : public vtkObject +{ + public: + vtkTypeMacro(vtkFrameBufferObjectBase, vtkObject); + void PrintSelf(ostream& os, vtkIndent indent); + + virtual int *GetLastSize() = 0; + virtual void GetLastSize (int &_arg1, int &_arg2) = 0; + virtual void GetLastSize (int _arg[2]) = 0; + +protected: + vtkFrameBufferObjectBase(); // no default constructor. + ~vtkFrameBufferObjectBase(); + +private: + vtkFrameBufferObjectBase(const vtkFrameBufferObjectBase &); // Not implemented. + void operator=(const vtkFrameBufferObjectBase &); // Not implemented. +}; + +#endif diff --git a/Rendering/Core/vtkFrustumCoverageCuller.h b/Rendering/Core/vtkFrustumCoverageCuller.h index 043c31b95f0..1401e926edb 100644 --- a/Rendering/Core/vtkFrustumCoverageCuller.h +++ b/Rendering/Core/vtkFrustumCoverageCuller.h @@ -76,7 +76,6 @@ class VTKRENDERINGCORE_EXPORT vtkFrustumCoverageCuller : public vtkCuller {this->SetSortingStyle(VTK_CULLER_SORT_FRONT_TO_BACK);}; const char *GetSortingStyleAsString(void); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THESE METHODS OUTSIDE OF THE RENDERING PROCESS @@ -85,7 +84,6 @@ class VTKRENDERINGCORE_EXPORT vtkFrustumCoverageCuller : public vtkCuller // the render process double Cull( vtkRenderer *ren, vtkProp **propList, int& listLength, int& initialized ); -//ETX protected: vtkFrustumCoverageCuller(); diff --git a/Rendering/Core/vtkGenericVertexAttributeMapping.h b/Rendering/Core/vtkGenericVertexAttributeMapping.h index 73d8263c973..e86e6eb91ba 100644 --- a/Rendering/Core/vtkGenericVertexAttributeMapping.h +++ b/Rendering/Core/vtkGenericVertexAttributeMapping.h @@ -83,7 +83,6 @@ class VTKRENDERINGCORE_EXPORT vtkGenericVertexAttributeMapping : public vtkObjec // Get the component no. at the given index. int GetTextureUnit(unsigned int index); -//BTX protected: vtkGenericVertexAttributeMapping(); ~vtkGenericVertexAttributeMapping(); @@ -94,7 +93,7 @@ class VTKRENDERINGCORE_EXPORT vtkGenericVertexAttributeMapping : public vtkObjec class vtkInternal; vtkInternal* Internal; -//ETX + }; #endif diff --git a/Rendering/Core/vtkGlyph3DMapper.cxx b/Rendering/Core/vtkGlyph3DMapper.cxx index 69d0449ef91..177ecbdc7d2 100644 --- a/Rendering/Core/vtkGlyph3DMapper.cxx +++ b/Rendering/Core/vtkGlyph3DMapper.cxx @@ -214,7 +214,7 @@ vtkDataArray* vtkGlyph3DMapper::GetSelectionIdArray(vtkDataSet* input) // --------------------------------------------------------------------------- vtkUnsignedCharArray* vtkGlyph3DMapper::GetColors(vtkDataSet* input) { - return vtkUnsignedCharArray::SafeDownCast( + return vtkArrayDownCast( input->GetPointData()->GetScalars()); } diff --git a/Rendering/Core/vtkGlyph3DMapper.h b/Rendering/Core/vtkGlyph3DMapper.h index 632a007b65a..37ed59fe024 100644 --- a/Rendering/Core/vtkGlyph3DMapper.h +++ b/Rendering/Core/vtkGlyph3DMapper.h @@ -37,7 +37,7 @@ class VTKRENDERINGCORE_EXPORT vtkGlyph3DMapper : public vtkMapper static vtkGlyph3DMapper* New(); vtkTypeMacro(vtkGlyph3DMapper, vtkMapper); void PrintSelf(ostream& os, vtkIndent indent); - //BTX + enum ArrayIndexes { SCALE = 0, @@ -46,7 +46,6 @@ class VTKRENDERINGCORE_EXPORT vtkGlyph3DMapper : public vtkMapper ORIENTATION = 3, SELECTIONID = 4 }; - //ETX // Description: // Specify a source object at a specified table location. New style. @@ -99,14 +98,13 @@ class VTKRENDERINGCORE_EXPORT vtkGlyph3DMapper : public vtkMapper vtkSetMacro(ScaleFactor, double); vtkGetMacro(ScaleFactor, double); - //BTX enum ScaleModes { NO_DATA_SCALING = 0, SCALE_BY_MAGNITUDE = 1, SCALE_BY_COMPONENTS = 2 }; - //ETX + void SetScaleModeToScaleByMagnitude() { this->SetScaleMode(SCALE_BY_MAGNITUDE); } void SetScaleModeToScaleByVectorComponents() @@ -139,13 +137,12 @@ class VTKRENDERINGCORE_EXPORT vtkGlyph3DMapper : public vtkMapper void SetOrientationModeToRotation() { this->SetOrientationMode(vtkGlyph3DMapper::ROTATION); } const char* GetOrientationModeAsString(); - //BTX + enum OrientationModes { DIRECTION=0, ROTATION=1 }; - //ETX // Description: // Turn on/off clamping of data values to scale with to the specified range. @@ -325,7 +322,7 @@ class VTKRENDERINGCORE_EXPORT vtkGlyph3DMapper : public vtkMapper // selection. virtual bool GetSupportsSelection() { return true; } - //BTX + protected: vtkGlyph3DMapper(); ~vtkGlyph3DMapper(); @@ -370,7 +367,7 @@ class VTKRENDERINGCORE_EXPORT vtkGlyph3DMapper : public vtkMapper // Description: // Returns true when valid bounds are returned. bool GetBoundsInternal(vtkDataSet* ds, double ds_bounds[6]); - //ETX + }; #endif diff --git a/Rendering/Core/vtkGraphMapper.h b/Rendering/Core/vtkGraphMapper.h index bdefbd47a9c..f09aa8bd707 100644 --- a/Rendering/Core/vtkGraphMapper.h +++ b/Rendering/Core/vtkGraphMapper.h @@ -219,7 +219,6 @@ class VTKRENDERINGCORE_EXPORT vtkGraphMapper : public vtkMapper vtkSetStringMacro(IconArrayNameInternal); char* IconArrayNameInternal; - //BTX vtkSmartPointer CircleGlyph; vtkSmartPointer CircleOutlineGlyph; @@ -238,13 +237,12 @@ class VTKRENDERINGCORE_EXPORT vtkGraphMapper : public vtkMapper vtkSmartPointer VertexActor; vtkSmartPointer OutlineActor; vtkSmartPointer IconActor; - //ETX // Color maps vtkLookupTable* EdgeLookupTable; vtkLookupTable* VertexLookupTable; - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; // see algorithm for more info virtual int FillInputPortInformation(int port, vtkInformation* info); diff --git a/Rendering/Core/vtkGraphToGlyphs.h b/Rendering/Core/vtkGraphToGlyphs.h index 62a1aef1633..b48bc70208c 100644 --- a/Rendering/Core/vtkGraphToGlyphs.h +++ b/Rendering/Core/vtkGraphToGlyphs.h @@ -48,7 +48,6 @@ class VTKRENDERINGCORE_EXPORT vtkGraphToGlyphs : public vtkPolyDataAlgorithm vtkTypeMacro(vtkGraphToGlyphs, vtkPolyDataAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); - //BTX enum { VERTEX = 1, @@ -61,7 +60,6 @@ class VTKRENDERINGCORE_EXPORT vtkGraphToGlyphs : public vtkPolyDataAlgorithm DIAMOND, SPHERE }; - //ETX // Description: // The glyph type, specified as one of the enumerated values in this @@ -111,7 +109,6 @@ class VTKRENDERINGCORE_EXPORT vtkGraphToGlyphs : public vtkPolyDataAlgorithm // Set the input type of the algorithm to vtkGraph. int FillInputPortInformation(int port, vtkInformation* info); - //BTX vtkSmartPointer GraphToPoints; vtkSmartPointer GlyphSource; vtkSmartPointer Sphere; @@ -120,7 +117,6 @@ class VTKRENDERINGCORE_EXPORT vtkGraphToGlyphs : public vtkPolyDataAlgorithm int GlyphType; bool Filled; double ScreenSize; - //ETX private: vtkGraphToGlyphs(const vtkGraphToGlyphs&); // Not implemented. diff --git a/Rendering/Core/vtkGraphicsFactory.h b/Rendering/Core/vtkGraphicsFactory.h index e36b6d9d1e4..15c1d666725 100644 --- a/Rendering/Core/vtkGraphicsFactory.h +++ b/Rendering/Core/vtkGraphicsFactory.h @@ -32,6 +32,7 @@ class VTKRENDERINGCORE_EXPORT vtkGraphicsFactory : public vtkObject // Create and return an instance of the named vtk object. // This method first checks the vtkObjectFactory to support // dynamic loading. + VTK_NEWINSTANCE static vtkObject* CreateInstance(const char* vtkclassname); // Description: diff --git a/Rendering/Core/vtkHardwareSelector.cxx b/Rendering/Core/vtkHardwareSelector.cxx index d0ca257f437..0ad76c35798 100644 --- a/Rendering/Core/vtkHardwareSelector.cxx +++ b/Rendering/Core/vtkHardwareSelector.cxx @@ -520,7 +520,7 @@ int vtkHardwareSelector::Render(vtkRenderer* renderer, vtkProp** propArray, return 0; } - int propsRenderered = 0; + int propsRendered = 0; // loop through props and give them a chance to // render themselves as opaque geometry for (int i = 0; i < propArrayCount; i++ ) @@ -535,7 +535,22 @@ int vtkHardwareSelector::Render(vtkRenderer* renderer, vtkProp** propArray, this->Internals->Props[this->PropID] = propArray[i]; if (this->IsPropHit(this->PropID)) { - propsRenderered += propArray[i]->RenderOpaqueGeometry(renderer); + propsRendered += propArray[i]->RenderOpaqueGeometry(renderer); + } + } + + // Render props as volumetric data. + for (int i = 0; i < propArrayCount; i++) + { + if (!propArray[i]->GetPickable() || !propArray[i]->GetSupportsSelection()) + { + continue; + } + this->PropID = this->GetPropID(i, propArray[i]); + this->Internals->Props[this->PropID] = propArray[i]; + if (this->IsPropHit(this->PropID)) + { + propsRendered += propArray[i]->RenderVolumetricGeometry(renderer); } } @@ -553,11 +568,11 @@ int vtkHardwareSelector::Render(vtkRenderer* renderer, vtkProp** propArray, this->Internals->Props[this->PropID] = propArray[i]; if (this->IsPropHit(this->PropID)) { - propsRenderered += propArray[i]->RenderOverlay(renderer); + propsRendered += propArray[i]->RenderOverlay(renderer); } } - return propsRenderered; + return propsRendered; } //---------------------------------------------------------------------------- @@ -628,6 +643,7 @@ vtkHardwareSelector::PixelInformation vtkHardwareSelector::GetPixelInformation( int low24 = this->Convert(display_position, this->PixBuffer[ID_LOW24]); int mid24 = this->Convert(display_position, this->PixBuffer[ID_MID24]); int high16 = this->Convert(display_position, this->PixBuffer[ID_HIGH16]); + // id 0 is reserved for nothing present. info.AttributeID = (this->GetID(low24, mid24, high16) - ID_OFFSET); if (info.AttributeID < 0) @@ -801,7 +817,6 @@ void vtkHardwareSelector::PrintSelf(ostream& os, vtkIndent indent) os << indent << "Area: " << this->Area[0] << ", " << this->Area[1] << ", " << this->Area[2] << ", " << this->Area[3] << endl; os << indent << "Renderer: " << this->Renderer << endl; - os << indent << "UseProcessIdFromData: " << this->UseProcessIdFromData << - endl; + os << indent << "UseProcessIdFromData: " << this->UseProcessIdFromData << endl; } diff --git a/Rendering/Core/vtkHardwareSelector.h b/Rendering/Core/vtkHardwareSelector.h index f5406ccf5e7..988aee37187 100644 --- a/Rendering/Core/vtkHardwareSelector.h +++ b/Rendering/Core/vtkHardwareSelector.h @@ -217,7 +217,6 @@ class VTKRENDERINGCORE_EXPORT vtkHardwareSelector : public vtkObject // ReleasePixBuffers() gets called. vtkProp* GetPropFromID(int id); -//BTX enum PassTypes { PROCESS_PASS, @@ -345,7 +344,7 @@ class VTKRENDERINGCORE_EXPORT vtkHardwareSelector : public vtkObject class vtkInternals; vtkInternals* Internals; -//ETX + }; #endif diff --git a/Rendering/Core/vtkImageSlice.cxx b/Rendering/Core/vtkImageSlice.cxx index 44e891c5638..3d68e23bc63 100644 --- a/Rendering/Core/vtkImageSlice.cxx +++ b/Rendering/Core/vtkImageSlice.cxx @@ -124,7 +124,7 @@ void vtkImageSlice::SetMapper(vtkImageMapper3D *mapper) if (this->Mapper != NULL) { this->Mapper->Register(this); - vtkImageToImageMapper3DFriendship::SetCurrentProp(mapper, this); + vtkImageToImageMapper3DFriendship::SetCurrentProp(this->Mapper, this); } this->Modified(); } diff --git a/Rendering/Core/vtkInteractorObserver.h b/Rendering/Core/vtkInteractorObserver.h index a7dbec2cd17..657d8c8aa24 100644 --- a/Rendering/Core/vtkInteractorObserver.h +++ b/Rendering/Core/vtkInteractorObserver.h @@ -155,7 +155,6 @@ class VTKRENDERINGCORE_EXPORT vtkInteractorObserver : public vtkObject static void ComputeWorldToDisplay(vtkRenderer *ren, double x, double y, double z, double displayPt[3]); - //BTX // Description: // These methods enable an interactor observer to exclusively grab all // events invoked by its associated vtkRenderWindowInteractor. (This method @@ -167,7 +166,6 @@ class VTKRENDERINGCORE_EXPORT vtkInteractorObserver : public vtkObject // mouse events.) void GrabFocus(vtkCommand *mouseEvents, vtkCommand *keypressEvents=NULL); void ReleaseFocus(); - //ETX protected: vtkInteractorObserver(); diff --git a/Rendering/Core/vtkInteractorStyle.cxx b/Rendering/Core/vtkInteractorStyle.cxx index bb755b2011c..989654ee789 100644 --- a/Rendering/Core/vtkInteractorStyle.cxx +++ b/Rendering/Core/vtkInteractorStyle.cxx @@ -260,6 +260,25 @@ void vtkInteractorStyle::SetInteractor(vtkRenderWindowInteractor *i) i->AddObserver(vtkCommand::TDxButtonReleaseEvent, this->EventCallbackCommand, this->Priority); + + i->AddObserver(vtkCommand::PinchEvent, + this->EventCallbackCommand, + this->Priority); + i->AddObserver(vtkCommand::PanEvent, + this->EventCallbackCommand, + this->Priority); + i->AddObserver(vtkCommand::RotateEvent, + this->EventCallbackCommand, + this->Priority); + i->AddObserver(vtkCommand::TapEvent, + this->EventCallbackCommand, + this->Priority); + i->AddObserver(vtkCommand::LongTapEvent, + this->EventCallbackCommand, + this->Priority); + i->AddObserver(vtkCommand::SwipeEvent, + this->EventCallbackCommand, + this->Priority); } this->EventForwarder->SetTarget(this->Interactor); @@ -1185,5 +1204,77 @@ void vtkInteractorStyle::ProcessEvents(vtkObject* vtkNotUsed(object), case vtkCommand::TDxButtonReleaseEvent: self->DelegateTDxEvent(event,calldata); break; + + case vtkCommand::PinchEvent: + if (self->HandleObservers && + self->HasObserver(vtkCommand::PinchEvent)) + { + self->InvokeEvent(vtkCommand::PinchEvent,NULL); + } + else + { + self->OnPinch(); + } + break; + case vtkCommand::PanEvent: + if (self->HandleObservers && + self->HasObserver(vtkCommand::PanEvent)) + { + self->InvokeEvent(vtkCommand::PanEvent,NULL); + } + else + { + self->OnPan(); + } + break; + + case vtkCommand::RotateEvent: + if (self->HandleObservers && + self->HasObserver(vtkCommand::RotateEvent)) + { + self->InvokeEvent(vtkCommand::RotateEvent,NULL); + } + else + { + self->OnRotate(); + } + break; + + case vtkCommand::TapEvent: + if (self->HandleObservers && + self->HasObserver(vtkCommand::TapEvent)) + { + self->InvokeEvent(vtkCommand::TapEvent,NULL); + } + else + { + self->OnTap(); + } + break; + + case vtkCommand::LongTapEvent: + if (self->HandleObservers && + self->HasObserver(vtkCommand::LongTapEvent)) + { + self->InvokeEvent(vtkCommand::LongTapEvent,NULL); + } + else + { + self->OnLongTap(); + } + break; + + case vtkCommand::SwipeEvent: + if (self->HandleObservers && + self->HasObserver(vtkCommand::SwipeEvent)) + { + self->InvokeEvent(vtkCommand::SwipeEvent,NULL); + } + else + { + self->OnSwipe(); + } + break; + } } diff --git a/Rendering/Core/vtkInteractorStyle.h b/Rendering/Core/vtkInteractorStyle.h index a43ee0ee289..d837e736a6b 100644 --- a/Rendering/Core/vtkInteractorStyle.h +++ b/Rendering/Core/vtkInteractorStyle.h @@ -249,6 +249,15 @@ class VTKRENDERINGCORE_EXPORT vtkInteractorStyle : public vtkInteractorObserver virtual void Zoom() {} virtual void UniformScale() {} + // Description: + // gesture based events + virtual void OnPinch() {} + virtual void OnRotate() {} + virtual void OnPan() {} + virtual void OnTap() {} + virtual void OnLongTap() {} + virtual void OnSwipe() {} + // Description: // utility routines used by state changes virtual void StartState(int newstate); diff --git a/Rendering/Core/vtkLODProp3D.h b/Rendering/Core/vtkLODProp3D.h index ac7a75ba502..e138b2b2ced 100644 --- a/Rendering/Core/vtkLODProp3D.h +++ b/Rendering/Core/vtkLODProp3D.h @@ -217,8 +217,6 @@ class VTKRENDERINGCORE_EXPORT vtkLODProp3D : public vtkProp3D // Shallow copy of this vtkLODProp3D. void ShallowCopy(vtkProp *prop); -//BTX - // Description: // Support the standard render methods. int RenderOpaqueGeometry(vtkViewport *viewport); @@ -253,8 +251,6 @@ class VTKRENDERINGCORE_EXPORT vtkLODProp3D : public vtkProp3D // selected LOD as well. virtual void AddEstimatedRenderTime( double t, vtkViewport *vp ); -//ETX - protected: vtkLODProp3D(); ~vtkLODProp3D(); diff --git a/Rendering/Core/vtkLabeledContourMapper.cxx b/Rendering/Core/vtkLabeledContourMapper.cxx index ae7e3e22faf..5a74ec39c7f 100644 --- a/Rendering/Core/vtkLabeledContourMapper.cxx +++ b/Rendering/Core/vtkLabeledContourMapper.cxx @@ -295,7 +295,7 @@ void vtkLabeledContourMapper::Render(vtkRenderer *ren, vtkActor *act) } this->Internal->PrepareTime = vtkTimerLog::GetUniversalTime() - startPrep; - this->BuildTime.Modified(); + this->LabelBuildTime.Modified(); } double startRender = vtkTimerLog::GetUniversalTime(); @@ -431,7 +431,7 @@ void vtkLabeledContourMapper::PrintSelf(ostream& os, vtkIndent indent) << indent << "StencilQuadsSize: " << this->StencilQuadsSize << "\n" << indent << "StencilQuadIndicesSize: " << this->StencilQuadIndicesSize << "\n" - << indent << "BuildTime: " << this->BuildTime.GetMTime() << "\n" + << indent << "BuildTime: " << this->LabelBuildTime.GetMTime() << "\n" << indent << "PolyDataMapper:\n"; this->PolyDataMapper->PrintSelf(os, indent.GetNextIndent()); os << indent << "TextProperties:\n"; @@ -548,8 +548,8 @@ bool vtkLabeledContourMapper::CheckRebuild(vtkRenderer *, vtkActor *act) } // Are we out of date? - if (this->BuildTime.GetMTime() < this->GetInput()->GetMTime() || - this->BuildTime.GetMTime() < tPropMTime) + if (this->LabelBuildTime.GetMTime() < this->GetInput()->GetMTime() || + this->LabelBuildTime.GetMTime() < tPropMTime) { return true; } diff --git a/Rendering/Core/vtkLabeledContourMapper.h b/Rendering/Core/vtkLabeledContourMapper.h index 190aaf0eeb1..b75ab4ce904 100644 --- a/Rendering/Core/vtkLabeledContourMapper.h +++ b/Rendering/Core/vtkLabeledContourMapper.h @@ -156,7 +156,7 @@ class VTKRENDERINGCORE_EXPORT vtkLabeledContourMapper : public vtkMapper vtkIdType StencilQuadIndicesSize; void FreeStencilQuads(); - vtkTimeStamp BuildTime; + vtkTimeStamp LabelBuildTime; private: vtkLabeledContourMapper(const vtkLabeledContourMapper&); // Not implemented. diff --git a/Rendering/Core/vtkLightCollection.h b/Rendering/Core/vtkLightCollection.h index 634ec388a9c..322a5936fe4 100644 --- a/Rendering/Core/vtkLightCollection.h +++ b/Rendering/Core/vtkLightCollection.h @@ -45,12 +45,10 @@ class VTKRENDERINGCORE_EXPORT vtkLightCollection : public vtkCollection // exhausted. vtkLight *GetNextItem(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkLight *GetNextLight(vtkCollectionSimpleIterator &cookie); - //ETX protected: vtkLightCollection() {} diff --git a/Rendering/Core/vtkLightKit.h b/Rendering/Core/vtkLightKit.h index 62c996dc9ec..ebe90102421 100644 --- a/Rendering/Core/vtkLightKit.h +++ b/Rendering/Core/vtkLightKit.h @@ -103,7 +103,6 @@ class VTKRENDERINGCORE_EXPORT vtkLightKit : public vtkObject vtkTypeMacro(vtkLightKit, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); - //BTX enum LightKitType { TKeyLight, TFillLight, @@ -121,8 +120,6 @@ class VTKRENDERINGCORE_EXPORT vtkLightKit : public vtkObject KHRatio }; - //ETX - // Description: // Set/Get the intensity of the key light. The key light is the // brightest light in the scene. The intensities of the other two diff --git a/Rendering/Core/vtkMapArrayValues.cxx b/Rendering/Core/vtkMapArrayValues.cxx index e7b9c985569..4ca414ba6b1 100644 --- a/Rendering/Core/vtkMapArrayValues.cxx +++ b/Rendering/Core/vtkMapArrayValues.cxx @@ -199,9 +199,9 @@ int vtkMapArrayValues::RequestData( } vtkAbstractArray *outputArray = vtkAbstractArray::CreateArray(this->OutputArrayType); - vtkDataArray *outputDataArray = vtkDataArray::SafeDownCast(outputArray); + vtkDataArray *outputDataArray = vtkArrayDownCast(outputArray); vtkStringArray *outputStringArray = - vtkStringArray::SafeDownCast(outputArray); + vtkArrayDownCast(outputArray); outputArray->SetName(this->OutputArrayName); // Are we copying the input array values to the output array before diff --git a/Rendering/Core/vtkMapArrayValues.h b/Rendering/Core/vtkMapArrayValues.h index 13170249654..b07f6c7f94f 100644 --- a/Rendering/Core/vtkMapArrayValues.h +++ b/Rendering/Core/vtkMapArrayValues.h @@ -105,7 +105,6 @@ class VTKRENDERINGCORE_EXPORT vtkMapArrayValues : public vtkPassInputTypeAlgorit // Get the size of the internal map. int GetMapSize(); -//BTX // Always keep NUM_ATTRIBUTE_LOCS as the last entry enum FieldType { @@ -116,7 +115,6 @@ class VTKRENDERINGCORE_EXPORT vtkMapArrayValues : public vtkPassInputTypeAlgorit ROW_DATA=4, NUM_ATTRIBUTE_LOCS }; -//ETX protected: diff --git a/Rendering/Core/vtkMapper.cxx b/Rendering/Core/vtkMapper.cxx index d58b0eb20c7..86b435b351c 100644 --- a/Rendering/Core/vtkMapper.cxx +++ b/Rendering/Core/vtkMapper.cxx @@ -410,7 +410,16 @@ void vtkMapper::ShallowCopy(vtkAbstractMapper *mapper) vtkUnsignedCharArray *vtkMapper::MapScalars(double alpha) { vtkDataSet *input = this->GetInput(); - return this->MapScalars(input,alpha); + int cellFlag; //not used + return this->MapScalars(input,alpha,cellFlag); +} + +// a side effect of this is that this->Colors is also set +// to the return value +vtkUnsignedCharArray *vtkMapper::MapScalars(double alpha, int &cellFlag) +{ + vtkDataSet *input = this->GetInput(); + return this->MapScalars(input,alpha,cellFlag); } //----------------------------------------------------------------------------- @@ -454,7 +463,7 @@ int vtkMapper::CanUseTextureMapForColoring(vtkDataObject* input) } if ((this->ColorMode == VTK_COLOR_MODE_DEFAULT && - vtkUnsignedCharArray::SafeDownCast(scalars)) || + vtkArrayDownCast(scalars)) || this->ColorMode == VTK_COLOR_MODE_DIRECT_SCALARS) { // Don't use texture is direct coloring using RGB unsigned chars is @@ -466,13 +475,19 @@ int vtkMapper::CanUseTextureMapForColoring(vtkDataObject* input) return 1; } -// a side effect of this is that this->Colors is also set -// to the return value vtkUnsignedCharArray *vtkMapper::MapScalars(vtkDataSet *input, double alpha) { int cellFlag = 0; + return this->MapScalars(input, alpha, cellFlag); +} +// a side effect of this is that this->Colors is also set +// to the return value +vtkUnsignedCharArray *vtkMapper::MapScalars(vtkDataSet *input, + double alpha, + int &cellFlag) +{ vtkAbstractArray *scalars = NULL; if (!this->UseInvertibleColors) { @@ -509,7 +524,7 @@ vtkUnsignedCharArray *vtkMapper::MapScalars(vtkDataSet *input, } // Get the lookup table. - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(scalars); + vtkDataArray *dataArray = vtkArrayDownCast(scalars); if (dataArray && dataArray->GetLookupTable()) { this->SetLookupTable(dataArray->GetLookupTable()); @@ -679,7 +694,7 @@ void vtkMapper::CreateDefaultLookupTable() GetAbstractScalars(this->GetInput(), this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, cellFlag); - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstractArray); + vtkDataArray *dataArray = vtkArrayDownCast(abstractArray); if (abstractArray && !dataArray) { // Use indexed lookup for non-numeric arrays @@ -819,6 +834,13 @@ void vtkMapper::UseInvertibleColorFor(int scalarMode, this->Modified(); + // Ensure the scalar range is initialized + vtkDataArray *dataArray = vtkArrayDownCast(abstractArray); + if (dataArray && scalarRange[0] > scalarRange[1]) + { + scalarRange = dataArray->GetRange(); + } + this->ScalarMode = scalarMode; this->ArrayComponent = arrayComponent; this->SetScalarRange(scalarRange); @@ -848,7 +870,6 @@ void vtkMapper::UseInvertibleColorFor(int scalarMode, this->LookupTable = NULL; } - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstractArray); if (!dataArray) { vtkLookupTable* table = vtkLookupTable::New(); @@ -864,6 +885,9 @@ void vtkMapper::UseInvertibleColorFor(int scalarMode, this->LookupTable = vtkMapper::InvertibleLookupTable; this->LookupTable->Register(this); } + + // Update the component in either case. + this->LookupTable->SetVectorComponent(arrayComponent); } //------------------------------------------------------------------- @@ -882,6 +906,7 @@ void vtkMapper::ClearInvertibleColor() } } +//------------------------------------------------------------------- // Return the method of coloring scalar data. const char *vtkMapper::GetColorModeAsString(void) { @@ -1272,3 +1297,41 @@ void vtkMapper::PrintSelf(ostream& os, vtkIndent indent) os << indent << "CoincidentPolygonFactor: " << this->CoincidentPolygonFactor << "\n"; } + +//------------------------------------------------------------------- +void vtkMapper::ClearColorArrays() +{ + if (this->Colors) + { + this->Colors->Delete(); + this->Colors = NULL; + } + if (this->ColorCoordinates) + { + this->ColorCoordinates->Delete(); + this->ColorCoordinates = NULL; + } + if (this->ColorTextureMap) + { + this->ColorTextureMap->Delete(); + this->ColorTextureMap = NULL; + } +} + +//------------------------------------------------------------------- +vtkUnsignedCharArray *vtkMapper::GetColorMapColors() +{ + return this->Colors; +} + +//------------------------------------------------------------------- +vtkFloatArray *vtkMapper::GetColorCoordinates() +{ + return this->ColorCoordinates; +} + +//------------------------------------------------------------------- +vtkImageData* vtkMapper::GetColorTextureMap() +{ + return this->ColorTextureMap; +} diff --git a/Rendering/Core/vtkMapper.h b/Rendering/Core/vtkMapper.h index d0a2cc97571..24638aa99c8 100644 --- a/Rendering/Core/vtkMapper.h +++ b/Rendering/Core/vtkMapper.h @@ -205,7 +205,6 @@ class VTKRENDERINGCORE_EXPORT vtkMapper : public vtkAbstractMapper3D { vtkMapper::SetGlobalImmediateModeRendering(0); } static int GetGlobalImmediateModeRendering(); - //BTX // Description: // Force compile only mode in case display lists are used // (ImmediateModeRendering is false). If ImmediateModeRendering is true, @@ -216,7 +215,6 @@ class VTKRENDERINGCORE_EXPORT vtkMapper : public vtkAbstractMapper3D // There is no good reason to expose it to wrappers. vtkGetMacro(ForceCompileOnly, int); void SetForceCompileOnly(int value); - //ETX // Description: // Control how the filter works with scalar point data and cell attribute @@ -401,12 +399,10 @@ class VTKRENDERINGCORE_EXPORT vtkMapper : public vtkAbstractMapper3D void SetRenderTime(double time) {this->RenderTime = time;} vtkGetMacro(RenderTime, double); - //BTX // Description: // Get the input as a vtkDataSet. This method is overridden in // the specialized mapper classes to return more specific data types. vtkDataSet *GetInput(); - //ETX // Description: // Get the input to this mapper as a vtkDataSet, instead of as a @@ -423,8 +419,13 @@ class VTKRENDERINGCORE_EXPORT vtkMapper : public vtkAbstractMapper3D // allows the blending of the scalars with an additional alpha (typically // which comes from a vtkActor, etc.) virtual vtkUnsignedCharArray *MapScalars(double alpha); + virtual vtkUnsignedCharArray *MapScalars(double alpha, + int &cellFlag); virtual vtkUnsignedCharArray *MapScalars(vtkDataSet *input, double alpha); + virtual vtkUnsignedCharArray *MapScalars(vtkDataSet *input, + double alpha, + int &cellFlag); // Description: // Set/Get the light-model color mode. @@ -492,10 +493,28 @@ class VTKRENDERINGCORE_EXPORT vtkMapper : public vtkAbstractMapper3D static void ColorToValue(unsigned char *color, double min, double scale, double &value); + // Description: + // Call to force a rebuild of color result arrays on next MapScalars. + // Necessary when using arrays in the case of multiblock data. + void ClearColorArrays(); + + // Description: + // Provide read access to the color array + vtkUnsignedCharArray *GetColorMapColors(); + + // Description: + // Provide read access to the color texture coordinate array + vtkFloatArray *GetColorCoordinates(); + + // Description: + // Provide read access to the color texture array + vtkImageData* GetColorTextureMap(); + protected: vtkMapper(); ~vtkMapper(); + // color mapped colors vtkUnsignedCharArray *Colors; // Use texture coordinates for coloring. diff --git a/Rendering/Core/vtkMapperCollection.h b/Rendering/Core/vtkMapperCollection.h index 4f8aebdef29..76fc9c0ebb4 100644 --- a/Rendering/Core/vtkMapperCollection.h +++ b/Rendering/Core/vtkMapperCollection.h @@ -51,13 +51,11 @@ class VTKRENDERINGCORE_EXPORT vtkMapperCollection : public vtkCollection vtkMapper *GetLastItem() { return this->Bottom ? static_cast(this->Bottom->Item) : 0; } - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkMapper *GetNextMapper(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie)); } - //ETX protected: vtkMapperCollection() {} diff --git a/Rendering/Core/vtkPickingManager.cxx b/Rendering/Core/vtkPickingManager.cxx index 6a65b4a949d..30c516f673b 100644 --- a/Rendering/Core/vtkPickingManager.cxx +++ b/Rendering/Core/vtkPickingManager.cxx @@ -88,14 +88,14 @@ class vtkPickingManager::vtkInternal // Create a new list of associated observers void CreateDefaultCollection(vtkAbstractPicker* picker, vtkObject* object); - // Instead of a vtkCollection we are using a vector of a vtkSmartPointer + // vtkCollection doesn't allow NULL values. Instead we use a vector // containing vtkObject to allow using 0 as a valid value because it is // allowed the return a picker event if he is not associated to a specific // object. // This is related with the capacity when a picker associated with a given // object does not manage others object, // it will automatically be removed from the list as well. - typedef std::vector > CollectionType; + typedef std::vector CollectionType; // For code clearance and performances during the computation std::map is // used instead of a vector of pair. Nevertheless, it makes internally use of @@ -138,23 +138,6 @@ class vtkPickingManager::vtkInternal vtkAbstractPicker* Picker; }; - // Predicate comparing a vtkObject* - // and a vtkSmartPointer using the PickerObjectsType. - // As we use a vtkSmartPointer, this predicate allows to compare the equality - // of a pointer on a vtkObject with the adress contained in - // a corresponding vtkSmartPointer. - struct equal_smartPtrObject - { - equal_smartPtrObject(vtkObject* object) : Object(object) {} - - bool operator () (const vtkSmartPointer& smartObj) const - { - return this->Object == smartObj.GetPointer(); - } - - vtkObject* Object; - }; - PickerObjectsType Pickers; // Map the picker with the objects vtkTimeStamp CurrentInteractionTime; // Time of the last interaction event vtkTimeStamp LastPickingTime; // Time of the last picking process @@ -202,9 +185,9 @@ CreateDefaultCollection(vtkAbstractPicker* picker, vtkObject* object) void vtkPickingManager::vtkInternal:: LinkPickerObject(const PickerObjectsType::iterator& it, vtkObject* object) { - CollectionType::iterator itObj = std::find_if(it->second.begin(), - it->second.end(), - equal_smartPtrObject(object)); + CollectionType::iterator itObj = std::find(it->second.begin(), + it->second.end(), + object); if (itObj != it->second.end() && object) { @@ -234,9 +217,9 @@ IsObjectLinked(vtkAbstractPicker* picker, vtkObject* obj) return false; } - CollectionType::iterator itObj = std::find_if(itPick->second.begin(), - itPick->second.end(), - equal_smartPtrObject(obj)); + CollectionType::iterator itObj = std::find(itPick->second.begin(), + itPick->second.end(), + obj); return (itObj != itPick->second.end()); } @@ -418,9 +401,9 @@ void vtkPickingManager::RemovePicker(vtkAbstractPicker* picker, } vtkPickingManager::vtkInternal::CollectionType::iterator itObj = - std::find_if(it->second.begin(), - it->second.end(), - vtkPickingManager::vtkInternal::equal_smartPtrObject(object)); + std::find(it->second.begin(), + it->second.end(), + object); // The object is not associated with the given picker. if (itObj == it->second.end()) @@ -446,9 +429,9 @@ void vtkPickingManager::RemoveObject(vtkObject* object) for(; it != this->Internal->Pickers.end();) { vtkPickingManager::vtkInternal::CollectionType::iterator itObj = - std::find_if(it->second.begin(), - it->second.end(), - vtkPickingManager::vtkInternal::equal_smartPtrObject(object)); + std::find(it->second.begin(), + it->second.end(), + object); if (itObj != it->second.end()) { diff --git a/Rendering/Core/vtkPolyDataMapper2D.cxx b/Rendering/Core/vtkPolyDataMapper2D.cxx index aee25493442..7fba8a85d47 100644 --- a/Rendering/Core/vtkPolyDataMapper2D.cxx +++ b/Rendering/Core/vtkPolyDataMapper2D.cxx @@ -160,7 +160,7 @@ vtkUnsignedCharArray *vtkPolyDataMapper2D::MapScalars(double alpha) if (scalars) { - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(scalars); + vtkDataArray *dataArray = vtkArrayDownCast(scalars); if (dataArray && dataArray->GetLookupTable()) { this->SetLookupTable(dataArray->GetLookupTable()); @@ -268,7 +268,7 @@ void vtkPolyDataMapper2D::CreateDefaultLookupTable() GetAbstractScalars(this->GetInput(), this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, cellFlag); - vtkDataArray *dataArray = vtkDataArray::SafeDownCast(abstractArray); + vtkDataArray *dataArray = vtkArrayDownCast(abstractArray); if (abstractArray && !dataArray) { // Use indexed lookup for non-numeric arrays diff --git a/Rendering/Core/vtkProp.h b/Rendering/Core/vtkProp.h index 3a29cea1c3b..3e99fc4ddcc 100644 --- a/Rendering/Core/vtkProp.h +++ b/Rendering/Core/vtkProp.h @@ -167,7 +167,6 @@ class VTKRENDERINGCORE_EXPORT vtkProp : public vtkObject // down to a mapper. static vtkInformationDoubleVectorKey *GeneralTextureTransform(); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THESE METHODS OUTSIDE OF THE RENDERING PROCESS @@ -367,8 +366,6 @@ class VTKRENDERINGCORE_EXPORT vtkProp : public vtkObject vtkObject *GetConsumer(int i); int IsConsumer(vtkObject *c); -//ETX - protected: vtkProp(); ~vtkProp(); diff --git a/Rendering/Core/vtkProp3DCollection.h b/Rendering/Core/vtkProp3DCollection.h index 9c0fff42a6f..34a141034c9 100644 --- a/Rendering/Core/vtkProp3DCollection.h +++ b/Rendering/Core/vtkProp3DCollection.h @@ -47,7 +47,6 @@ class VTKRENDERINGCORE_EXPORT vtkProp3DCollection : public vtkPropCollection // Get the last actor in the list. vtkProp3D *GetLastProp3D(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. @@ -55,7 +54,6 @@ class VTKRENDERINGCORE_EXPORT vtkProp3DCollection : public vtkPropCollection { return static_cast(this->GetNextItemAsObject(cookie)); } - //ETX protected: vtkProp3DCollection() {} diff --git a/Rendering/Core/vtkPropAssembly.h b/Rendering/Core/vtkPropAssembly.h index ee75cbde6ed..3e9f2c5c7ce 100644 --- a/Rendering/Core/vtkPropAssembly.h +++ b/Rendering/Core/vtkPropAssembly.h @@ -112,13 +112,11 @@ class VTKRENDERINGCORE_EXPORT vtkPropAssembly : public vtkProp vtkAssemblyPath *GetNextPath(); int GetNumberOfPaths(); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS // Overload the superclass' vtkProp BuildPaths() method. void BuildPaths(vtkAssemblyPaths *paths, vtkAssemblyPath *path); -//ETX protected: vtkPropAssembly(); diff --git a/Rendering/Core/vtkPropCollection.h b/Rendering/Core/vtkPropCollection.h index 877b47272d4..dbc9c758ead 100644 --- a/Rendering/Core/vtkPropCollection.h +++ b/Rendering/Core/vtkPropCollection.h @@ -54,13 +54,11 @@ class VTKRENDERINGCORE_EXPORT vtkPropCollection : public vtkCollection // or vtkPropAssembly. int GetNumberOfPaths(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkProp *GetNextProp(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie));}; - //ETX protected: vtkPropCollection() {} diff --git a/Rendering/Core/vtkProperty.h b/Rendering/Core/vtkProperty.h index afae38cb078..93b6ed9dc86 100644 --- a/Rendering/Core/vtkProperty.h +++ b/Rendering/Core/vtkProperty.h @@ -84,13 +84,11 @@ class VTKRENDERINGCORE_EXPORT vtkProperty : public vtkObject // such as Representation, Culling are specified by the Property. virtual void BackfaceRender(vtkActor *, vtkRenderer *) {} - //BTX // Description: // This method is called after the actor has been rendered. // Don't call this directly. This method cleans up // any shaders allocated. virtual void PostRender(vtkActor*, vtkRenderer*); - //ETX // Description: // Set/Get lighting flag for an object. Initial value is true. @@ -333,7 +331,6 @@ class VTKRENDERINGCORE_EXPORT vtkProperty : public vtkObject // resources to release. virtual void ReleaseGraphicsResources(vtkWindow *win); -//BTX // Description: // Used to specify which texture unit a texture will use. // Only relevant when multitexturing. @@ -348,7 +345,6 @@ class VTKRENDERINGCORE_EXPORT vtkProperty : public vtkObject VTK_TEXTURE_UNIT_6, VTK_TEXTURE_UNIT_7 }; -//ETX protected: vtkProperty(); @@ -387,14 +383,12 @@ class VTKRENDERINGCORE_EXPORT vtkProperty : public vtkObject char* MaterialName; vtkSetStringMacro(MaterialName); -//BTX // FIXME: // Don't use these methods. They will be removed. They are provided only // for the time-being. vtkTexture* GetTextureAtIndex(int index); int GetTextureUnitAtIndex(int index); int GetTextureUnit(const char* name); -//ETX private: vtkProperty(const vtkProperty&); // Not implemented. diff --git a/Rendering/Core/vtkProperty2D.h b/Rendering/Core/vtkProperty2D.h index e64159294e0..4444706a23d 100644 --- a/Rendering/Core/vtkProperty2D.h +++ b/Rendering/Core/vtkProperty2D.h @@ -98,11 +98,9 @@ class VTKRENDERINGCORE_EXPORT vtkProperty2D : public vtkObject void SetDisplayLocationToForeground() {this->DisplayLocation = VTK_FOREGROUND_LOCATION;}; -//BTX // Description: // Have the device specific subclass render this property. virtual void Render (vtkViewport* vtkNotUsed(viewport)) {} -//ETX protected: vtkProperty2D(); diff --git a/Rendering/OpenGL/vtkRenderPass.cxx b/Rendering/Core/vtkRenderPass.cxx similarity index 91% rename from Rendering/OpenGL/vtkRenderPass.cxx rename to Rendering/Core/vtkRenderPass.cxx index 8f75ca6d772..3a018651e43 100644 --- a/Rendering/OpenGL/vtkRenderPass.cxx +++ b/Rendering/Core/vtkRenderPass.cxx @@ -16,8 +16,6 @@ #include "vtkRenderPass.h" #include #include "vtkRenderer.h" -#include "vtkOpenGLRenderer.h" - // ---------------------------------------------------------------------------- // Description: @@ -63,9 +61,8 @@ void vtkRenderPass::UpdateCamera(vtkRenderer *renderer) // \pre renderer_exists: renderer!=0 void vtkRenderPass::ClearLights(vtkRenderer *renderer) { - assert("pre: renderer_exists" && renderer != 0); - vtkOpenGLRenderer *oRenderer = static_cast(renderer); - oRenderer->ClearLights(); + // assert("pre: renderer_exists" && renderer != 0); + renderer->ClearLights(); } // ---------------------------------------------------------------------------- @@ -99,10 +96,6 @@ void vtkRenderPass::UpdateGeometry(vtkRenderer *renderer) } // ---------------------------------------------------------------------------- -// Description: -// Modify protected member LastRenderingUsedDepthPeeling on Renderer. -// See note about UpdateCamera(). -// \pre renderer_exists: renderer!=0 void vtkRenderPass::SetLastRenderingUsedDepthPeeling(vtkRenderer *renderer, bool value) { diff --git a/Rendering/OpenGL/vtkRenderPass.h b/Rendering/Core/vtkRenderPass.h similarity index 95% rename from Rendering/OpenGL/vtkRenderPass.h rename to Rendering/Core/vtkRenderPass.h index 42cbd5c55c5..24da9817bd8 100644 --- a/Rendering/OpenGL/vtkRenderPass.h +++ b/Rendering/Core/vtkRenderPass.h @@ -42,26 +42,24 @@ #ifndef vtkRenderPass_h #define vtkRenderPass_h -#include "vtkRenderingOpenGLModule.h" // For export macro +#include "vtkRenderingCoreModule.h" // For export macro #include "vtkObject.h" class vtkRenderState; class vtkWindow; class vtkRenderer; -class VTKRENDERINGOPENGL_EXPORT vtkRenderPass : public vtkObject +class VTKRENDERINGCORE_EXPORT vtkRenderPass : public vtkObject { public: vtkTypeMacro(vtkRenderPass,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // It modifies NumberOfRenderedProps. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s)=0; - //ETX // Description: // Number of props rendered at the last Render call. @@ -112,6 +110,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkRenderPass : public vtkObject // Modify protected member LastRenderingUsedDepthPeeling on Renderer. // See note about UpdateCamera(). // \pre renderer_exists: renderer!=0 + // Note - OpenGL1 specific, remove when completely switched to OpenGL2 void SetLastRenderingUsedDepthPeeling(vtkRenderer *renderer, bool value); diff --git a/Rendering/OpenGL2/vtkRenderState.cxx b/Rendering/Core/vtkRenderState.cxx similarity index 96% rename from Rendering/OpenGL2/vtkRenderState.cxx rename to Rendering/Core/vtkRenderState.cxx index d0e1788c745..cf0d461f609 100644 --- a/Rendering/OpenGL2/vtkRenderState.cxx +++ b/Rendering/Core/vtkRenderState.cxx @@ -15,7 +15,7 @@ #include "vtkRenderState.h" #include #include "vtkRenderer.h" -#include "vtkFrameBufferObject.h" +#include "vtkFrameBufferObjectBase.h" // ---------------------------------------------------------------------------- // Description: @@ -65,7 +65,7 @@ vtkRenderer *vtkRenderState::GetRenderer() const // ---------------------------------------------------------------------------- // Description: // Return the FrameBuffer. -vtkFrameBufferObject *vtkRenderState::GetFrameBuffer() const +vtkFrameBufferObjectBase *vtkRenderState::GetFrameBuffer() const { return this->FrameBuffer; } @@ -74,7 +74,7 @@ vtkFrameBufferObject *vtkRenderState::GetFrameBuffer() const // Description: // Set the FrameBuffer. // \post is_set: GetFrameBuffer()==fbo -void vtkRenderState::SetFrameBuffer(vtkFrameBufferObject *fbo) +void vtkRenderState::SetFrameBuffer(vtkFrameBufferObjectBase *fbo) { this->FrameBuffer = fbo; assert("post: is_set" && this->GetFrameBuffer() == fbo); diff --git a/Rendering/OpenGL/vtkRenderState.h b/Rendering/Core/vtkRenderState.h similarity index 94% rename from Rendering/OpenGL/vtkRenderState.h rename to Rendering/Core/vtkRenderState.h index 51b4f6301ca..5ec9acffe0c 100644 --- a/Rendering/OpenGL/vtkRenderState.h +++ b/Rendering/Core/vtkRenderState.h @@ -26,15 +26,15 @@ #ifndef vtkRenderState_h #define vtkRenderState_h -#include "vtkRenderingOpenGLModule.h" // For export macro +#include "vtkRenderingCoreModule.h" // For export macro #include "vtkObject.h" class vtkRenderer; class vtkProp; -class vtkFrameBufferObject; +class vtkFrameBufferObjectBase; class vtkInformation; -class VTKRENDERINGOPENGL_EXPORT vtkRenderState +class VTKRENDERINGCORE_EXPORT vtkRenderState { public: // Description: @@ -63,12 +63,12 @@ class VTKRENDERINGOPENGL_EXPORT vtkRenderState // Return the FrameBuffer. This is the framebuffer in use. NULL means it is // the FrameBuffer provided by the RenderWindow (it can actually be an FBO // in case the RenderWindow is in off screen mode). - vtkFrameBufferObject *GetFrameBuffer() const; + vtkFrameBufferObjectBase *GetFrameBuffer() const; // Description: // Set the FrameBuffer. See GetFrameBuffer(). // \post is_set: GetFrameBuffer()==fbo - void SetFrameBuffer(vtkFrameBufferObject *fbo); + void SetFrameBuffer(vtkFrameBufferObjectBase *fbo); // Description: // Get the window size of the state. @@ -118,7 +118,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkRenderState // The framebuffer in use. NULL means the FrameBuffer provided by // the RenderWindow (it can actually be an FBO in case the RenderWindow // is in off screen mode). - vtkFrameBufferObject *FrameBuffer; + vtkFrameBufferObjectBase *FrameBuffer; // Description: // Subset of props to render. A renderpass might ignore this filtered list diff --git a/Rendering/Core/vtkRenderWindow.cxx b/Rendering/Core/vtkRenderWindow.cxx index 75e9f9a391d..0da755d5d4f 100644 --- a/Rendering/Core/vtkRenderWindow.cxx +++ b/Rendering/Core/vtkRenderWindow.cxx @@ -828,6 +828,7 @@ void vtkRenderWindow::RemoveRenderer(vtkRenderer *ren) // we are its parent if (ren->GetRenderWindow() == this) { + ren->ReleaseGraphicsResources(this); ren->SetRenderWindow(NULL); } this->Renderers->RemoveItem(ren); diff --git a/Rendering/Core/vtkRenderWindowCollection.h b/Rendering/Core/vtkRenderWindowCollection.h index 813f90f8fd1..412de501b76 100644 --- a/Rendering/Core/vtkRenderWindowCollection.h +++ b/Rendering/Core/vtkRenderWindowCollection.h @@ -50,7 +50,6 @@ class VTKRENDERINGCORE_EXPORT vtkRenderWindowCollection : public vtkCollection return static_cast(this->GetNextItemAsObject()); } - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. @@ -58,7 +57,6 @@ class VTKRENDERINGCORE_EXPORT vtkRenderWindowCollection : public vtkCollection { return static_cast(this->GetNextItemAsObject(cookie)); } - //ETX protected: vtkRenderWindowCollection() {} diff --git a/Rendering/Core/vtkRenderWindowInteractor.cxx b/Rendering/Core/vtkRenderWindowInteractor.cxx index 00030105da7..df1d4bfc911 100644 --- a/Rendering/Core/vtkRenderWindowInteractor.cxx +++ b/Rendering/Core/vtkRenderWindowInteractor.cxx @@ -110,6 +110,10 @@ vtkRenderWindowInteractor::vtkRenderWindowInteractor() this->ControlKey = 0; this->ShiftKey = 0; this->KeyCode = 0; + this->Rotation = 0; + this->LastRotation = 0; + this->Scale = 0; + this->LastScale = 0; this->RepeatCount = 0; this->KeySym = 0; this->TimerEventId = 0; @@ -127,8 +131,12 @@ vtkRenderWindowInteractor::vtkRenderWindowInteractor() for (int i=0; i < VTKI_MAX_POINTERS; i++) { this->PointerIndexLookup[i] = 0; + this->PointersDown[i] = 0; } + this->RecognizeGestures = true; + this->PointersDownCount = 0; + this->CurrentGesture = vtkCommand::StartEvent; } //---------------------------------------------------------------------- @@ -545,6 +553,213 @@ vtkRenderer* vtkRenderWindowInteractor::FindPokedRenderer(int x,int y) return currentRenderer; } +//---------------------------------------------------------------------------- +void vtkRenderWindowInteractor::SetScale(double scale) +{ + this->LastScale = this->Scale; + if (this->Scale != scale) + { + this->Scale = scale; + this->Modified(); + } +} + +//---------------------------------------------------------------------------- +void vtkRenderWindowInteractor::SetRotation(double rot) +{ + this->LastRotation = this->Rotation; + if (this->Rotation != rot) + { + this->Rotation = rot; + this->Modified(); + } +} + +//---------------------------------------------------------------------------- +void vtkRenderWindowInteractor::SetTranslation(double val[2]) +{ + this->LastTranslation[0] = this->Translation[0]; + this->LastTranslation[1] = this->Translation[1]; + if (this->Translation[0] != val[0] || + this->Translation[1] != val[1]) + { + this->Translation[0] = val[0]; + this->Translation[1] = val[1]; + this->Modified(); + } +} + +//---------------------------------------------------------------------------- +void vtkRenderWindowInteractor::RecognizeGesture(vtkCommand::EventIds event) +{ + // we know we are in multitouch now, so start recognizing + + // more than two pointers we ignore + if (this->PointersDownCount > 2) + { + return; + } + + // store the initial positions + if (event == vtkCommand::LeftButtonPressEvent) + { + for (int i = 0; i < VTKI_MAX_POINTERS; i++) + { + if (this->PointersDown[i]) + { + this->StartingEventPositions[i][0] = + this->EventPositions[i][0]; + this->StartingEventPositions[i][1] = + this->EventPositions[i][1]; + } + } + // we do not know what the gesture is yet + this->CurrentGesture = vtkCommand::StartEvent; + return; + } + + // end the gesture if needed + if (event == vtkCommand::LeftButtonReleaseEvent) + { + if (this->CurrentGesture == vtkCommand::PinchEvent) + { + this->EndPinchEvent(); + } + if (this->CurrentGesture == vtkCommand::RotateEvent) + { + this->EndRotateEvent(); + } + if (this->CurrentGesture == vtkCommand::PanEvent) + { + this->EndPanEvent(); + } + this->CurrentGesture = vtkCommand::StartEvent; + return; + } + + // what are the two pointers we are working with + int count = 0; + int *posVals[2]; + int *startVals[2]; + for (int i = 0; i < VTKI_MAX_POINTERS; i++) + { + if (this->PointersDown[i]) + { + posVals[count] = this->EventPositions[i]; + startVals[count] = this->StartingEventPositions[i]; + count++; + } + } + + // The meat of the algorithm + // on move events we analyze them to determine what type + // of movement it is and then deal with it. + if (event == vtkCommand::MouseMoveEvent) + { + // calculate the distances + double originalDistance = sqrt( + static_cast( + (startVals[0][0] - startVals[1][0])*(startVals[0][0] - startVals[1][0]) + + (startVals[0][1] - startVals[1][1])*(startVals[0][1] - startVals[1][1]))); + double newDistance = sqrt( + static_cast( + (posVals[0][0] - posVals[1][0])*(posVals[0][0] - posVals[1][0]) + + (posVals[0][1] - posVals[1][1])*(posVals[0][1] - posVals[1][1]))); + + // calculate rotations + double originalAngle = + vtkMath::DegreesFromRadians( atan2((double)startVals[1][1] - startVals[0][1], + (double)startVals[1][0] - startVals[0][0])); + double newAngle = + vtkMath::DegreesFromRadians( atan2( (double)posVals[1][1] - posVals[0][1], + (double)posVals[1][0] - posVals[0][0])); + + // angles are cyclic so watch for that, 1 and 359 are only 2 apart :) + double angleDeviation = newAngle - originalAngle; + newAngle = (newAngle+180.0 >= 360.0 ? newAngle - 180.0 : newAngle + 180.0); + originalAngle = (originalAngle+180.0 >= 360.0 ? originalAngle - 180.0 : originalAngle + 180.0); + if (fabs(newAngle - originalAngle) < fabs(angleDeviation)) + { + angleDeviation = newAngle - originalAngle; + } + + // calculate the translations + double trans[2]; + trans[0] = (posVals[0][0] - startVals[0][0] + posVals[1][0] - startVals[1][0])/2.0; + trans[1] = (posVals[0][1] - startVals[0][1] + posVals[1][1] - startVals[1][1])/2.0; + + // OK we want to + // - immediately respond to the user + // - allow the user to zoom without panning (saves focal point) + // - allow the user to rotate without panning (saves focal point) + + // do we know what gesture we are doing yet? If not + // see if we can figure it out + if (this->CurrentGesture == vtkCommand::StartEvent) + { + // pinch is a move to/from the center point + // rotate is a move along the circumference + // pan is a move of the center point + // compute the distance along each of these axes in pixels + // the first to break thresh wins + double thresh = 0.01*sqrt( + static_cast(this->Size[0]*this->Size[0] + this->Size[1]*this->Size[1])); + if (thresh < 15.0) + { + thresh = 15.0; + } + double pinchDistance = fabs(newDistance - originalDistance); + double rotateDistance = newDistance*3.1415926*fabs(angleDeviation)/360.0; + double panDistance = sqrt(trans[0]*trans[0] + trans[1]*trans[1]); + if (pinchDistance > thresh + && pinchDistance > rotateDistance + && pinchDistance > panDistance) + { + this->CurrentGesture = vtkCommand::PinchEvent; + this->Scale = 1.0; + this->StartPinchEvent(); + } + else if (rotateDistance > thresh + && rotateDistance > panDistance) + { + this->CurrentGesture = vtkCommand::RotateEvent; + this->Rotation = 0.0; + this->StartRotateEvent(); + } + else if (panDistance > thresh) + { + this->CurrentGesture = vtkCommand::PanEvent; + this->Translation[0] = 0.0; + this->Translation[1] = 0.0; + this->StartPanEvent(); + } + } + + // if we have found a specific type of movement then + // handle it + if (this->CurrentGesture == vtkCommand::RotateEvent) + { + this->SetRotation(angleDeviation); + this->RotateEvent(); + } + + if (this->CurrentGesture == vtkCommand::PinchEvent) + { + vtkErrorMacro("See pinch"); + this->SetScale(newDistance/originalDistance); + this->PinchEvent(); + } + + if (this->CurrentGesture == vtkCommand::PanEvent) + { + this->SetTranslation(trans); + this->PanEvent(); + } + + } + +} + // Timer methods. There are two basic groups of methods, those for backward // compatibility (group #1) and those that operate on specific timers (i.e., @@ -767,6 +982,7 @@ void vtkRenderWindowInteractor::PrintSelf(ostream& os, vtkIndent indent) os << indent << "TimerEventDuration: " << this->TimerEventDuration << "\n"; os << indent << "TimerEventPlatformId: " << this->TimerEventPlatformId << "\n"; os << indent << "UseTDx: " << this->UseTDx << endl; + os << indent << "Recognize Gestures: " << this->RecognizeGestures << endl; } //---------------------------------------------------------------------------- @@ -808,7 +1024,17 @@ void vtkRenderWindowInteractor::MouseMoveEvent() { return; } - this->InvokeEvent(vtkCommand::MouseMoveEvent, NULL); + + // handle gestures or not? + if (this->RecognizeGestures && this->PointersDownCount > 1) + { + // handle the gesture + this->RecognizeGesture(vtkCommand::MouseMoveEvent); + } + else + { + this->InvokeEvent(vtkCommand::MouseMoveEvent, NULL); + } } //------------------------------------------------------------------ @@ -838,6 +1064,29 @@ void vtkRenderWindowInteractor::LeftButtonPressEvent() { return; } + + // are we translating multitouch into gestures? + if (this->RecognizeGestures) + { + if (!this->PointersDown[this->PointerIndex]) + { + this->PointersDown[this->PointerIndex] = 1; + this->PointersDownCount++; + } + // do we have multitouch + if (this->PointersDownCount > 1) + { + // did we just transition to multitouch? + if (this->PointersDownCount == 2) + { + this->InvokeEvent(vtkCommand::LeftButtonReleaseEvent, NULL); + } + // handle the gesture + this->RecognizeGesture(vtkCommand::LeftButtonPressEvent); + return; + } + } + this->InvokeEvent(vtkCommand::LeftButtonPressEvent, NULL); } @@ -848,6 +1097,22 @@ void vtkRenderWindowInteractor::LeftButtonReleaseEvent() { return; } + + if (this->RecognizeGestures) + { + if (this->PointersDown[this->PointerIndex]) + { + this->PointersDown[this->PointerIndex] = 0; + this->PointersDownCount--; + } + // do we have multitouch + if (this->PointersDownCount > 1) + { + // handle the gesture + this->RecognizeGesture(vtkCommand::LeftButtonReleaseEvent); + return; + } + } this->InvokeEvent(vtkCommand::LeftButtonReleaseEvent, NULL); } @@ -971,4 +1236,115 @@ void vtkRenderWindowInteractor::ExitEvent() this->InvokeEvent(vtkCommand::ExitEvent, NULL); } +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::StartPinchEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::StartPinchEvent, NULL); +} +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::PinchEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::PinchEvent, NULL); +} +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::EndPinchEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::EndPinchEvent, NULL); +} + +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::StartRotateEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::StartRotateEvent, NULL); +} +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::RotateEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::RotateEvent, NULL); +} +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::EndRotateEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::EndRotateEvent, NULL); +} + +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::StartPanEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::StartPanEvent, NULL); +} +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::PanEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::PanEvent, NULL); +} +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::EndPanEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::EndPanEvent, NULL); +} +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::TapEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::TapEvent, NULL); +} +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::LongTapEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::LongTapEvent, NULL); +} + +//------------------------------------------------------------------ +void vtkRenderWindowInteractor::SwipeEvent() +{ + if (!this->Enabled) + { + return; + } + this->InvokeEvent(vtkCommand::SwipeEvent, NULL); +} diff --git a/Rendering/Core/vtkRenderWindowInteractor.h b/Rendering/Core/vtkRenderWindowInteractor.h index c796c3f8a71..a311ac71128 100644 --- a/Rendering/Core/vtkRenderWindowInteractor.h +++ b/Rendering/Core/vtkRenderWindowInteractor.h @@ -44,6 +44,7 @@ #include "vtkRenderingCoreModule.h" // For export macro #include "vtkObject.h" +#include "vtkCommand.h" // for method sig class vtkTimerIdMap; @@ -67,9 +68,9 @@ class vtkPickingManager; class VTKRENDERINGCORE_EXPORT vtkRenderWindowInteractor : public vtkObject { -//BTX + friend class vtkInteractorEventRecorder; -//ETX + public: static vtkRenderWindowInteractor *New(); vtkTypeMacro(vtkRenderWindowInteractor,vtkObject); @@ -175,11 +176,9 @@ class VTKRENDERINGCORE_EXPORT vtkRenderWindowInteractor : public vtkObject // Get the VTK timer ID that corresponds to the supplied platform ID. virtual int GetVTKTimerId(int platformTimerId); - //BTX // Moved into the public section of the class so that classless timer procs // can access these enum members without being "friends"... enum {OneShotTimer=1,RepeatingTimer}; - //ETX // Description: // Specify the default timer interval (in milliseconds). (This is used in @@ -447,6 +446,24 @@ class VTKRENDERINGCORE_EXPORT vtkRenderWindowInteractor : public vtkObject vtkSetMacro(PointerIndex, int); vtkGetMacro(PointerIndex, int); + // Description: + // Set/get the rotation for the gesture in degrees, update LastRotation + void SetRotation(double val); + vtkGetMacro(Rotation, double); + vtkGetMacro(LastRotation, double); + + // Description: + // Set/get the scale for the gesture, updates LastScale + void SetScale(double val); + vtkGetMacro(Scale, double); + vtkGetMacro(LastScale, double); + + // Description: + // Set/get the tranlation for pan/swipe gestures, update LastTranslation + void SetTranslation(double val[2]); + vtkGetVector2Macro(Translation, double); + vtkGetVector2Macro(LastTranslation, double); + // Description: // Set all the event information in one call. void SetEventInformation(int x, @@ -587,6 +604,36 @@ class VTKRENDERINGCORE_EXPORT vtkRenderWindowInteractor : public vtkObject virtual void CharEvent(); virtual void ExitEvent(); + // Description: + // Fire various gesture based events. These methods will Invoke the + // corresponding vtk event. + virtual void StartPinchEvent(); + virtual void PinchEvent(); + virtual void EndPinchEvent(); + virtual void StartRotateEvent(); + virtual void RotateEvent(); + virtual void EndRotateEvent(); + virtual void StartPanEvent(); + virtual void PanEvent(); + virtual void EndPanEvent(); + virtual void TapEvent(); + virtual void LongTapEvent(); + virtual void SwipeEvent(); + + // Description: + // Convert multitouch events into gestures. When this is on + // (its default) multitouch events received by this interactor + // will be converted into gestures by VTK. If turned off the + // raw multitouch events will be passed down. + vtkSetMacro(RecognizeGestures,bool); + vtkGetMacro(RecognizeGestures,bool); + + // Description: + // When handling gestures you can query this value to + // determine how many pointers are down for the gesture + // this is useful for pan gestures for example + vtkGetMacro(PointersDownCount,int); + // Description: // Most multitouch systems use persistent contact/pointer ids to // track events/motion during multitouch events. We keep an array @@ -629,6 +676,12 @@ class VTKRENDERINGCORE_EXPORT vtkRenderWindowInteractor : public vtkObject int ControlKey; int ShiftKey; char KeyCode; + double Rotation; + double LastRotation; + double Scale; + double LastScale; + double Translation[2]; + double LastTranslation[2]; int RepeatCount; char* KeySym; int EventPosition[2]; @@ -650,7 +703,6 @@ class VTKRENDERINGCORE_EXPORT vtkRenderWindowInteractor : public vtkObject int NumberOfFlyFrames; double Dolly; -//BTX // Description: // These methods allow the interactor to control which events are // processed. When the GrabFocus() method is called, then only events that @@ -663,13 +715,11 @@ class VTKRENDERINGCORE_EXPORT vtkRenderWindowInteractor : public vtkObject {this->Superclass::InternalGrabFocus(mouseEvents,keypressEvents);} void ReleaseFocus() {this->Superclass::InternalReleaseFocus();} -//ETX // Description: // Widget mediators are used to resolve contention for cursors and other resources. vtkObserverMediator *ObserverMediator; -//BTX // Timer related members friend struct vtkTimerStruct; vtkTimerIdMap *TimerMap; // An internal, PIMPLd map of timers and associated attributes @@ -682,7 +732,6 @@ class VTKRENDERINGCORE_EXPORT vtkRenderWindowInteractor : public vtkObject virtual int InternalCreateTimer(int timerId, int timerType, unsigned long duration); virtual int InternalDestroyTimer(int platformTimerId); int GetCurrentTimerId(); -//ETX // Force the interactor to handle the Start() event loop, ignoring any // overrides. (Overrides are registered by observing StartEvent on the @@ -695,6 +744,15 @@ class VTKRENDERINGCORE_EXPORT vtkRenderWindowInteractor : public vtkObject bool UseTDx; // 3DConnexion device. + // when recognizing gestures VTK will take multitouch events + // if it receives them and convert them to gestures + bool RecognizeGestures; + int PointersDownCount; + int PointersDown[VTKI_MAX_POINTERS]; + virtual void RecognizeGesture(vtkCommand::EventIds); + int StartingEventPositions[VTKI_MAX_POINTERS][2]; + vtkCommand::EventIds CurrentGesture; + private: vtkRenderWindowInteractor(const vtkRenderWindowInteractor&); // Not implemented. void operator=(const vtkRenderWindowInteractor&); // Not implemented. diff --git a/Rendering/Core/vtkRenderer.cxx b/Rendering/Core/vtkRenderer.cxx index 20b2beab305..2b12bc42d2a 100644 --- a/Rendering/Core/vtkRenderer.cxx +++ b/Rendering/Core/vtkRenderer.cxx @@ -24,6 +24,7 @@ #include "vtkFrustumCoverageCuller.h" #include "vtkObjectFactory.h" #include "vtkHardwareSelector.h" +#include "vtkInformation.h" #include "vtkLightCollection.h" #include "vtkLight.h" #include "vtkMath.h" @@ -33,13 +34,16 @@ #include "vtkProp3DCollection.h" #include "vtkPropCollection.h" #include "vtkRendererDelegate.h" +#include "vtkRenderPass.h" #include "vtkRenderWindow.h" #include "vtkTimerLog.h" #include "vtkVolume.h" #include "vtkTexture.h" +vtkCxxSetObjectMacro(vtkRenderer, Information, vtkInformation); vtkCxxSetObjectMacro(vtkRenderer, Delegate, vtkRendererDelegate); vtkCxxSetObjectMacro(vtkRenderer, BackgroundTexture, vtkTexture); +vtkCxxSetObjectMacro(vtkRenderer, Pass, vtkRenderPass); //---------------------------------------------------------------------------- // Return NULL if no override is supplied. @@ -125,6 +129,12 @@ vtkRenderer::vtkRenderer() this->TexturedBackground = false; this->BackgroundTexture = NULL; + + this->Pass = 0; + + this->Information = vtkInformation::New(); + this->Information->Register(this); + this->Information->Delete(); } vtkRenderer::~vtkRenderer() @@ -163,6 +173,8 @@ vtkRenderer::~vtkRenderer() { this->BackgroundTexture->Delete(); } + + this->SetInformation(0); } void vtkRenderer::ReleaseGraphicsResources(vtkWindow *renWin) @@ -834,6 +846,7 @@ void vtkRenderer::CreateLight(void) if (this->CreatedLight) { + this->RemoveLight(this->CreatedLight); this->CreatedLight->UnRegister(this); this->CreatedLight = NULL; } @@ -1232,32 +1245,9 @@ void vtkRenderer::ResetCameraClippingRange(double xmin, double xmax, // no reference counting! void vtkRenderer::SetRenderWindow(vtkRenderWindow *renwin) { - vtkProp *aProp; - if (renwin != this->RenderWindow) { - // This renderer is be dis-associated with its previous render window. - // this information needs to be passed to the renderer's actors and - // volumes so they can release and render window specific (or graphics - // context specific) information (such as display lists and texture ids) - vtkCollectionSimpleIterator pit; - this->Props->InitTraversal(pit); - for ( aProp = this->Props->GetNextProp(pit); - aProp != NULL; - aProp = this->Props->GetNextProp(pit) ) - { - aProp->ReleaseGraphicsResources(this->RenderWindow); - } - // what about lights? - // what about cullers? - this->ReleaseGraphicsResources(this->RenderWindow); - - if(this->BackgroundTexture != 0 && this->RenderWindow!=0) - { - this->BackgroundTexture->ReleaseGraphicsResources(this->RenderWindow); - } - this->VTKWindow = renwin; this->RenderWindow = renwin; } @@ -1464,6 +1454,17 @@ void vtkRenderer::PrintSelf(ostream& os, vtkIndent indent) { os << "null" << endl; } + + os << indent << "Pass:"; + if(this->Pass!=0) + { + os << "exists" << endl; + } + else + { + os << "null" << endl; + } + } int vtkRenderer::VisibleActorCount() diff --git a/Rendering/Core/vtkRenderer.h b/Rendering/Core/vtkRenderer.h index 7684c65b951..9a11dfbc393 100644 --- a/Rendering/Core/vtkRenderer.h +++ b/Rendering/Core/vtkRenderer.h @@ -41,11 +41,13 @@ class vtkCuller; class vtkActor; class vtkActor2D; class vtkCamera; +class vtkInformation; class vtkLightCollection; class vtkCullerCollection; class vtkLight; class vtkHardwareSelector; class vtkRendererDelegate; +class vtkRenderPass; class vtkTexture; class VTKRENDERINGCORE_EXPORT vtkRenderer : public vtkViewport @@ -245,6 +247,11 @@ class VTKRENDERINGCORE_EXPORT vtkRenderer : public vtkViewport // It updates boolean ivar LastRenderingUsedDepthPeeling. virtual void DeviceRenderTranslucentPolygonalGeometry(); + // Description: + // Internal method temporarily removes lights before reloading them + // into graphics pipeline. + virtual void ClearLights(void) {}; + // Description: // Clear the image to the background color. virtual void Clear() {} @@ -300,7 +307,7 @@ class VTKRENDERINGCORE_EXPORT vtkRenderer : public vtkViewport // The camera will reposition itself to view the center point of the actors, // and move along its initial view plane normal (i.e., vector defined from // camera position to focal point) so that all of the actors can be seen. - void ResetCamera(); + virtual void ResetCamera(); // Description: // Automatically set up the camera based on a specified bounding box @@ -310,11 +317,11 @@ class VTKRENDERINGCORE_EXPORT vtkRenderer : public vtkViewport // (i.e., vector defined from camera position to focal point). Note: is // the view plane is parallel to the view up axis, the view up axis will // be reset to one of the three coordinate axes. - void ResetCamera(double bounds[6]); + virtual void ResetCamera(double bounds[6]); // Description: // Alternative version of ResetCamera(bounds[6]); - void ResetCamera(double xmin, double xmax, double ymin, double ymax, + virtual void ResetCamera(double xmin, double xmax, double ymin, double ymax, double zmin, double zmax); // Description: @@ -521,7 +528,16 @@ class VTKRENDERINGCORE_EXPORT vtkRenderer : public vtkViewport vtkGetMacro(UseShadows,int); vtkBooleanMacro(UseShadows,int); -//BTX + // Set/Get a custom render pass. + // Initial value is NULL. + void SetPass(vtkRenderPass *p); + vtkGetObjectMacro(Pass, vtkRenderPass); + + // Description: + // Set/Get the information object associated with this algorithm. + vtkGetObjectMacro(Information, vtkInformation); + virtual void SetInformation(vtkInformation*); + protected: vtkRenderer(); ~vtkRenderer(); @@ -619,9 +635,6 @@ class VTKRENDERINGCORE_EXPORT vtkRenderer : public vtkViewport // Temporary collection used by vtkRenderWindow::CaptureGL2PSSpecialProps. vtkPropCollection *GL2PSSpecialPropCollection; - // Friend class to allow render passes to access functions. - friend class vtkRenderPass; - // Description: // Ask all props to update and draw any opaque and translucent // geometry. This includes both vtkActors and vtkVolumes @@ -710,10 +723,16 @@ class VTKRENDERINGCORE_EXPORT vtkRenderer : public vtkViewport bool TexturedBackground; vtkTexture* BackgroundTexture; + friend class vtkRenderPass; + vtkRenderPass *Pass; + + // Arbitrary extra information associated with this renderer + vtkInformation* Information; + private: vtkRenderer(const vtkRenderer&); // Not implemented. void operator=(const vtkRenderer&); // Not implemented. -//ETX + }; inline vtkLightCollection *vtkRenderer::GetLights() { diff --git a/Rendering/Core/vtkRendererCollection.h b/Rendering/Core/vtkRendererCollection.h index ba4e1384705..41a3bc87a31 100644 --- a/Rendering/Core/vtkRendererCollection.h +++ b/Rendering/Core/vtkRendererCollection.h @@ -56,13 +56,11 @@ class VTKRENDERINGCORE_EXPORT vtkRendererCollection : public vtkCollection // Return NULL when at the end of the list. vtkRenderer *GetFirstRenderer(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkRenderer *GetNextRenderer(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie)); } - //ETX protected: vtkRendererCollection() {} diff --git a/Rendering/Core/vtkRendererSource.cxx b/Rendering/Core/vtkRendererSource.cxx index 91f9ef6f2b2..89c56a6ef0f 100644 --- a/Rendering/Core/vtkRendererSource.cxx +++ b/Rendering/Core/vtkRendererSource.cxx @@ -71,7 +71,7 @@ void vtkRendererSource::RequestData(vtkInformation*, output->AllocateScalars(info); vtkUnsignedCharArray *outScalars = - vtkUnsignedCharArray::SafeDownCast(output->GetPointData()->GetScalars()); + vtkArrayDownCast(output->GetPointData()->GetScalars()); if (this->Input == NULL) { diff --git a/Rendering/Core/vtkScenePicker.h b/Rendering/Core/vtkScenePicker.h index 18ccf6642e0..63f90bd1685 100644 --- a/Rendering/Core/vtkScenePicker.h +++ b/Rendering/Core/vtkScenePicker.h @@ -51,10 +51,10 @@ class vtkScenePickerSelectionRenderCommand; class VTKRENDERINGCORE_EXPORT vtkScenePicker : public vtkObject { - //BTX + friend class vtkRenderer; friend class vtkScenePickerSelectionRenderCommand; - //ETX + public: static vtkScenePicker* New(); vtkTypeMacro(vtkScenePicker, vtkObject); diff --git a/Rendering/Core/vtkShaderDeviceAdapter2.h b/Rendering/Core/vtkShaderDeviceAdapter2.h index 198c69ff57f..9244d1653e9 100644 --- a/Rendering/Core/vtkShaderDeviceAdapter2.h +++ b/Rendering/Core/vtkShaderDeviceAdapter2.h @@ -50,7 +50,6 @@ class VTKRENDERINGCORE_EXPORT vtkShaderDeviceAdapter2 : public vtkObject const void* attribute, unsigned long offset = 0) = 0; -//BTX // Description: // Set the shader program which is being updated by this device adapter. // The shader program is not reference counted to avoid reference loops. @@ -73,7 +72,7 @@ class VTKRENDERINGCORE_EXPORT vtkShaderDeviceAdapter2 : public vtkObject private: vtkShaderDeviceAdapter2(const vtkShaderDeviceAdapter2&); // Not implemented void operator=(const vtkShaderDeviceAdapter2&); // Not implemented -//ETX + }; #endif diff --git a/Rendering/Core/vtkTDxInteractorStyle.h b/Rendering/Core/vtkTDxInteractorStyle.h index 4aceabf0237..701a2d56530 100644 --- a/Rendering/Core/vtkTDxInteractorStyle.h +++ b/Rendering/Core/vtkTDxInteractorStyle.h @@ -42,7 +42,6 @@ class VTKRENDERINGCORE_EXPORT vtkTDxInteractorStyle : public vtkObject vtkTypeMacro(vtkTDxInteractorStyle,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Action on motion event. Default implementation is empty. // \pre: motionInfo_exist: motionInfo!=0 @@ -55,7 +54,6 @@ class VTKRENDERINGCORE_EXPORT vtkTDxInteractorStyle : public vtkObject // Description: // Action on button released event. Default implementation is empty. virtual void OnButtonReleasedEvent(int button); - //ETX // Description: // Dispatch the events TDxMotionEvent, TDxButtonPressEvent and diff --git a/Rendering/Core/vtkTDxInteractorStyleCamera.h b/Rendering/Core/vtkTDxInteractorStyleCamera.h index 0255ed8d83c..7f6e4d48341 100644 --- a/Rendering/Core/vtkTDxInteractorStyleCamera.h +++ b/Rendering/Core/vtkTDxInteractorStyleCamera.h @@ -37,12 +37,10 @@ class VTKRENDERINGCORE_EXPORT vtkTDxInteractorStyleCamera : public vtkTDxInterac vtkTypeMacro(vtkTDxInteractorStyleCamera,vtkTDxInteractorStyle); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Action on motion event. // \pre: motionInfo_exist: motionInfo!=0 virtual void OnMotionEvent(vtkTDxMotionEventInfo *motionInfo); - //ETX protected: vtkTDxInteractorStyleCamera(); diff --git a/Rendering/Core/vtkTextActor.cxx b/Rendering/Core/vtkTextActor.cxx index 0bf3d2447ec..fd76187a913 100644 --- a/Rendering/Core/vtkTextActor.cxx +++ b/Rendering/Core/vtkTextActor.cxx @@ -13,23 +13,26 @@ =========================================================================*/ #include "vtkTextActor.h" -#include "vtkObjectFactory.h" -#include "vtkPolyDataMapper2D.h" -#include "vtkTextProperty.h" -#include "vtkViewport.h" -#include "vtkWindow.h" -#include "vtkTransform.h" -#include "vtkImageData.h" -#include "vtkPoints.h" -#include "vtkPointData.h" -#include "vtkPolyData.h" + #include "vtkCellArray.h" #include "vtkFloatArray.h" -#include "vtkTexture.h" +#include "vtkImageData.h" #include "vtkMath.h" -#include "vtkTextRenderer.h" +#include "vtkNew.h" +#include "vtkObjectFactory.h" +#include "vtkPointData.h" +#include "vtkPoints.h" +#include "vtkPolyData.h" +#include "vtkPolyDataMapper2D.h" +#include "vtkProperty2D.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" +#include "vtkTextProperty.h" +#include "vtkTextRenderer.h" +#include "vtkTexture.h" +#include "vtkTransform.h" +#include "vtkViewport.h" +#include "vtkWindow.h" #include @@ -109,6 +112,28 @@ vtkTextActor::vtkTextActor() { vtkErrorMacro(<<"Failed getting the TextRenderer instance!"); } + + this->DrawFrame = false; + this->FrameProperty = vtkProperty2D::New(); + + this->FramePoints = vtkPoints::New(); + this->FramePoints->SetNumberOfPoints(4); + vtkNew frame; + frame->SetPoints(this->FramePoints); + + vtkNew lines; + lines->Allocate(lines->EstimateSize(1, 5)); + frame->SetLines(lines.Get()); + vtkIdType frameIds[5] = { 0, 1, 2, 3, 0 }; + lines->InsertNextCell(5, frameIds); + + this->FrameMapper = vtkPolyDataMapper2D::New(); + this->FrameMapper->SetInputData(frame.Get()); + this->FrameActor = vtkActor2D::New(); + this->FrameActor->SetMapper(this->FrameMapper); + this->FrameActor-> + GetPositionCoordinate()->SetReferenceCoordinate(this->PositionCoordinate); + this->FrameActor->SetProperty(this->FrameProperty); } // ---------------------------------------------------------------------------- @@ -125,6 +150,12 @@ vtkTextActor::~vtkTextActor() this->RectanglePoints->Delete(); this->RectanglePoints = 0; this->SetTexture(0); + + this->FrameMapper->Delete(); + this->FrameActor->Delete(); + this->FrameProperty->Delete(); + this->FrameProperty = 0; + this->FramePoints->Delete(); } // ---------------------------------------------------------------------------- @@ -369,7 +400,41 @@ bool vtkTextActor::GetImageBoundingBox(vtkTextProperty *tprop, vtkViewport *vp, return false; } - return this->TextRenderer->GetBoundingBox(tprop, text, bbox, win->GetDPI()); + vtkTextRenderer::Metrics metrics; + bool ret = this->TextRenderer->GetMetrics(tprop, text, metrics, win->GetDPI()); + + bbox[0] = metrics.BoundingBox[0]; + bbox[1] = metrics.BoundingBox[1]; + bbox[2] = metrics.BoundingBox[2]; + bbox[3] = metrics.BoundingBox[3]; + + // The rectangle returned by the GetMetrics function is one pixel less larger + // than the background drawn so we need to move right points in the direction + // of the width vector. Those points are the geometry of the frame. + vtkVector2 v( + metrics.TopRight.GetX() - metrics.TopLeft.GetX(), + metrics.TopRight.GetY() - metrics.TopLeft.GetY()); + v.Normalize(); + + this->FramePoints->SetNumberOfPoints(4); + + this->FramePoints->SetPoint(0, + metrics.TopLeft.GetX(), + metrics.TopLeft.GetY(), 0.0); + + this->FramePoints->SetPoint(1, + metrics.TopRight.GetX() + vtkMath::Round(v.GetX()), + metrics.TopRight.GetY() + vtkMath::Round(v.GetY()), 0.0); + + this->FramePoints->SetPoint(2, + metrics.BottomRight.GetX() + vtkMath::Round(v.GetX()), + metrics.BottomRight.GetY() + vtkMath::Round(v.GetY()), 0.0); + + this->FramePoints->SetPoint(3, + metrics.BottomLeft.GetX(), + metrics.BottomLeft.GetY(), 0.0); + + return ret; } // ---------------------------------------------------------------------------- @@ -420,6 +485,28 @@ void vtkTextActor::SetTextProperty(vtkTextProperty *p) this->Modified(); } +// ---------------------------------------------------------------------------- +void vtkTextActor::SetFrameProperty(vtkProperty2D *p) +{ + if (this->FrameProperty == p) + { + return; + } + if (this->FrameProperty) + { + this->FrameActor->SetProperty(NULL); + this->FrameProperty->UnRegister(this); + this->FrameProperty = NULL; + } + this->FrameProperty = p; + if (this->FrameProperty) + { + this->FrameProperty->Register(this); + this->FrameActor->SetProperty(this->FrameProperty); + } + this->Modified(); +} + // ---------------------------------------------------------------------------- void vtkTextActor::ShallowCopy(vtkProp *prop) { @@ -432,6 +519,8 @@ void vtkTextActor::ShallowCopy(vtkProp *prop) this->SetTextScaleMode(a->GetTextScaleMode()); this->SetTextProperty(a->GetTextProperty()); this->SetInput(a->GetInput()); + this->SetDrawFrame(a->GetDrawFrame()); + this->SetFrameProperty(a->GetFrameProperty()); } // Now do superclass (mapper is handled by it as well). this->Superclass::ShallowCopy(prop); @@ -443,6 +532,8 @@ void vtkTextActor::ShallowCopy(vtkProp *prop) // resources to release. void vtkTextActor::ReleaseGraphicsResources(vtkWindow *win) { + this->FrameActor->ReleaseGraphicsResources(win); + this->Superclass::ReleaseGraphicsResources(win); } @@ -455,7 +546,14 @@ int vtkTextActor::RenderOverlay(vtkViewport *viewport) } // Everything is built in RenderOpaqueGeometry, just have to render - return this->Superclass::RenderOverlay(viewport); + int renderedSomething = this->Superclass::RenderOverlay(viewport); + + if (this->DrawFrame) + { + renderedSomething += this->FrameActor->RenderOverlay(viewport); + } + + return renderedSomething; } // ---------------------------------------------------------------------------- @@ -795,7 +893,7 @@ void vtkTextActor::ComputeRectangle(vtkViewport *viewport) anchorOffset[1] = text_bbox[2]; // compute TCoords. - vtkFloatArray* tc = vtkFloatArray::SafeDownCast + vtkFloatArray* tc = vtkArrayDownCast ( this->Rectangle->GetPointData()->GetTCoords() ); float tcXMax, tcYMax; // Add a fudge factor to the texture coordinates to prevent the top @@ -873,10 +971,11 @@ void vtkTextActor::ComputeRectangle(vtkViewport *viewport) yo = anchorOffset[1]; } //end unscaled text case - this->RectanglePoints->InsertNextPoint(xo, yo, 0.0 ); - this->RectanglePoints->InsertNextPoint(xo, yo + dims[1], 0.0 ); - this->RectanglePoints->InsertNextPoint(xo + dims[0], yo + dims[1], 0.0 ); - this->RectanglePoints->InsertNextPoint(xo + dims[0], yo, 0.0 ); + this->RectanglePoints->SetNumberOfPoints(4); + this->RectanglePoints->SetPoint(0, xo, yo, 0.0); + this->RectanglePoints->SetPoint(1, xo, yo + dims[1], 0.0); + this->RectanglePoints->SetPoint(2, xo + dims[0], yo + dims[1], 0.0); + this->RectanglePoints->SetPoint(3, xo + dims[0], yo, 0.0); } // ---------------------------------------------------------------------------- @@ -1021,4 +1120,8 @@ void vtkTextActor::PrintSelf(ostream& os, vtkIndent indent) os << indent << "Orientation: " << this->Orientation << endl; os << indent << "FontScaleExponent: " << this->FontScaleExponent << endl; os << indent << "UseBorderAlign: " << this->UseBorderAlign << "\n"; + + os << indent << "DrawFrame: " << this->DrawFrame << "\n"; + os << indent << "Frame Property:\n"; + this->FrameProperty->PrintSelf(os, indent.GetNextIndent()); } diff --git a/Rendering/Core/vtkTextActor.h b/Rendering/Core/vtkTextActor.h index 4eff5b5ea84..ca9431ad26b 100644 --- a/Rendering/Core/vtkTextActor.h +++ b/Rendering/Core/vtkTextActor.h @@ -35,13 +35,14 @@ #include "vtkRenderingCoreModule.h" // For export macro #include "vtkTexturedActor2D.h" -class vtkTextProperty; -class vtkPolyDataMapper2D; class vtkImageData; +class vtkPoints; +class vtkPolyData; +class vtkPolyDataMapper2D; +class vtkProperty2D; +class vtkTextProperty; class vtkTextRenderer; class vtkTransform; -class vtkPolyData; -class vtkPoints; class VTKRENDERINGCORE_EXPORT vtkTextActor : public vtkTexturedActor2D { @@ -100,13 +101,11 @@ class VTKRENDERINGCORE_EXPORT vtkTextActor : public vtkTexturedActor2D void SetTextScaleModeToViewport() { this->SetTextScaleMode(TEXT_SCALE_MODE_VIEWPORT); } -//BTX enum { TEXT_SCALE_MODE_NONE = 0, TEXT_SCALE_MODE_PROP, TEXT_SCALE_MODE_VIEWPORT }; -//ETX // Description: // Turn on or off the UseBorderAlign option. @@ -147,6 +146,17 @@ class VTKRENDERINGCORE_EXPORT vtkTextActor : public vtkTexturedActor2D virtual void SetTextProperty(vtkTextProperty *p); vtkGetObjectMacro(TextProperty,vtkTextProperty); + // Description: + // Draw a frame around the text. Default is FALSE. + vtkSetMacro(DrawFrame, bool); + vtkGetMacro(DrawFrame, bool); + vtkBooleanMacro(DrawFrame, bool); + + // Description: + // Set/Get the frame property + virtual void SetFrameProperty(vtkProperty2D* p); + vtkGetObjectMacro(FrameProperty, vtkProperty2D); + // Description: // Return the bounding box coordinates of the text in viewport coordinates. // The bbox array is populated with [ xmin, xmax, ymin, ymax ] @@ -213,7 +223,6 @@ class VTKRENDERINGCORE_EXPORT vtkTextActor : public vtkTexturedActor2D // and then resizes based on if that long dimension was 72 DPI. static float GetFontScale(vtkViewport *viewport); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS. @@ -233,7 +242,6 @@ class VTKRENDERINGCORE_EXPORT vtkTextActor : public vtkTexturedActor2D // Description: // Does this prop have some translucent polygonal geometry? virtual int HasTranslucentPolygonalGeometry(); -//ETX protected: // Description: @@ -267,6 +275,13 @@ class VTKRENDERINGCORE_EXPORT vtkTextActor : public vtkTexturedActor2D double FormerOrientation; int RenderedDPI; + bool DrawFrame; + + vtkProperty2D* FrameProperty; + vtkPolyDataMapper2D* FrameMapper; + vtkActor2D* FrameActor; + vtkPoints* FramePoints; + vtkTextProperty *ScaledTextProperty; // Stuff needed to display the image text as a texture map. diff --git a/Rendering/Core/vtkTextActor3D.h b/Rendering/Core/vtkTextActor3D.h index 2f134235762..950fa3f7e04 100644 --- a/Rendering/Core/vtkTextActor3D.h +++ b/Rendering/Core/vtkTextActor3D.h @@ -77,7 +77,6 @@ class VTKRENDERINGCORE_EXPORT vtkTextActor3D : public vtkProp3D // array. This call can be used for sizing other elements. int GetBoundingBox(int bbox[4]); - //BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS. @@ -97,7 +96,6 @@ class VTKRENDERINGCORE_EXPORT vtkTextActor3D : public vtkProp3D // Description: // Does this prop have some translucent polygonal geometry? virtual int HasTranslucentPolygonalGeometry(); - //ETX protected: vtkTextActor3D(); diff --git a/Rendering/Core/vtkTextMapper.cxx b/Rendering/Core/vtkTextMapper.cxx index da885b6a0e4..78b9562930f 100644 --- a/Rendering/Core/vtkTextMapper.cxx +++ b/Rendering/Core/vtkTextMapper.cxx @@ -367,7 +367,7 @@ void vtkTextMapper::RenderOverlay(vtkViewport *viewport, vtkActor2D *actor) vtkDebugMacro(<<"RenderOverlay called"); vtkRenderer *ren = NULL; - if (this->Input) + if (this->Input && this->Input[0]) { vtkWindow *win = viewport->GetVTKWindow(); if (!win) @@ -394,15 +394,15 @@ void vtkTextMapper::RenderOverlay(vtkViewport *viewport, vtkActor2D *actor) info->Set(vtkProp::GeneralTextureUnit(), this->Texture->GetTextureUnit()); } - } - vtkDebugMacro(<<"PolyData::RenderOverlay called"); - this->Mapper->RenderOverlay(viewport, actor); + vtkDebugMacro(<<"PolyData::RenderOverlay called"); + this->Mapper->RenderOverlay(viewport, actor); - // clean up - if (ren) - { - this->Texture->PostRender(ren); + // clean up + if (ren) + { + this->Texture->PostRender(ren); + } } vtkDebugMacro(<<"Superclass::RenderOverlay called"); @@ -457,7 +457,7 @@ void vtkTextMapper::UpdateQuad(vtkActor2D *actor, int dpi) float tcYMax = std::min(1.0f, (((2.f * th - 1.f) / (2.f)) + 0.000001f) / ih); if (vtkFloatArray *tc = - vtkFloatArray::SafeDownCast( + vtkArrayDownCast( this->PolyData->GetPointData()->GetTCoords())) { vtkDebugMacro(<<"Setting tcoords: xmin, xmax, ymin, ymax: " diff --git a/Rendering/Core/vtkTexture.h b/Rendering/Core/vtkTexture.h index e8fb979c3a2..86e17aaefcc 100644 --- a/Rendering/Core/vtkTexture.h +++ b/Rendering/Core/vtkTexture.h @@ -132,12 +132,10 @@ class VTKRENDERINGCORE_EXPORT vtkTexture : public vtkImageAlgorithm vtkSetMacro(MapColorScalarsThroughLookupTable, int); vtkBooleanMacro(MapColorScalarsThroughLookupTable, int); -//BTX // Description: // Get the input as a vtkImageData object. This method is for // backwards compatibility. vtkImageData* GetInput(); -//ETX // Description: // Specify the lookup table to convert scalars if necessary @@ -158,7 +156,6 @@ class VTKRENDERINGCORE_EXPORT vtkTexture : public vtkImageAlgorithm void SetTransform(vtkTransform *transform); vtkGetObjectMacro(Transform, vtkTransform); -//BTX // Description: // Used to specify how the texture will blend its RGB and Alpha values // with other textures and the fragment the texture is rendered upon. @@ -172,7 +169,6 @@ class VTKRENDERINGCORE_EXPORT vtkTexture : public vtkImageAlgorithm VTK_TEXTURE_BLENDING_MODE_INTERPOLATE, VTK_TEXTURE_BLENDING_MODE_SUBTRACT }; -//ETX // Description: // Used to specify how the texture will blend its RGB and Alpha values diff --git a/Rendering/Core/vtkTransformInterpolator.h b/Rendering/Core/vtkTransformInterpolator.h index 5fd03e40d60..8401a37ecad 100644 --- a/Rendering/Core/vtkTransformInterpolator.h +++ b/Rendering/Core/vtkTransformInterpolator.h @@ -106,14 +106,12 @@ class VTKRENDERINGCORE_EXPORT vtkTransformInterpolator : public vtkObject // (min,max) values, then t is clamped. void InterpolateTransform(double t, vtkTransform *xform); -//BTX // Description: // Enums to control the type of interpolation to use. enum {INTERPOLATION_TYPE_LINEAR=0, INTERPOLATION_TYPE_SPLINE, INTERPOLATION_TYPE_MANUAL }; -//ETX // Description: // These are convenience methods to switch between linear and spline diff --git a/Rendering/Core/vtkTupleInterpolator.h b/Rendering/Core/vtkTupleInterpolator.h index 9d683ed0d44..13c2520d79e 100644 --- a/Rendering/Core/vtkTupleInterpolator.h +++ b/Rendering/Core/vtkTupleInterpolator.h @@ -100,13 +100,11 @@ class VTKRENDERINGCORE_EXPORT vtkTupleInterpolator : public vtkObject // of tuple[] is interpolated independently. void InterpolateTuple(double t, double tuple[]); -//BTX // Description: // Enums to control the type of interpolation to use. enum {INTERPOLATION_TYPE_LINEAR=0, INTERPOLATION_TYPE_SPLINE }; -//ETX // Description: // Specify which type of function to use for interpolation. By default diff --git a/Rendering/Core/vtkViewport.h b/Rendering/Core/vtkViewport.h index d5dac5b98ba..78d6691b59b 100644 --- a/Rendering/Core/vtkViewport.h +++ b/Rendering/Core/vtkViewport.h @@ -262,7 +262,6 @@ class VTKRENDERINGCORE_EXPORT vtkViewport : public vtkObject vtkViewport(); ~vtkViewport(); - //BTX // Picking functions to be implemented by sub-classes // Perform the main picking loop virtual void DevicePickRender() = 0; @@ -279,7 +278,6 @@ class VTKRENDERINGCORE_EXPORT vtkViewport : public vtkObject // Put no more than atMost picked object ids into the callerBuffer and // return the number of picked objects returned. virtual int GetPickedIds(unsigned int atMost, unsigned int *callerBuffer) = 0; - //ETX // Ivars for picking // Store a picked Prop (contained in an assembly path) diff --git a/Rendering/Core/vtkVisibilitySort.h b/Rendering/Core/vtkVisibilitySort.h index d6f150f3e1a..59680608849 100644 --- a/Rendering/Core/vtkVisibilitySort.h +++ b/Rendering/Core/vtkVisibilitySort.h @@ -103,9 +103,7 @@ class VTKRENDERINGCORE_EXPORT vtkVisibilitySort : public vtkObject void SetDirectionToBackToFront() { this->SetDirection(BACK_TO_FRONT); } void SetDirectionToFrontToBack() { this->SetDirection(FRONT_TO_BACK); } -//BTX enum { BACK_TO_FRONT, FRONT_TO_BACK }; -//ETX // Description: // Overwritten to enable garbage collection. diff --git a/Rendering/Core/vtkVolume.h b/Rendering/Core/vtkVolume.h index 58e0cf1fdec..b43a5082a95 100644 --- a/Rendering/Core/vtkVolume.h +++ b/Rendering/Core/vtkVolume.h @@ -98,7 +98,6 @@ class VTKRENDERINGCORE_EXPORT vtkVolume : public vtkProp3D // Shallow copy of this vtkVolume. Overloads the virtual vtkProp method. void ShallowCopy(vtkProp *prop); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS @@ -174,7 +173,12 @@ class VTKRENDERINGCORE_EXPORT vtkVolume : public vtkProp3D void UpdateScalarOpacityforSampleSize(vtkRenderer *ren, float sample_distance); -//ETX + /// Used by vtkHardwareSelector to determine if the prop supports hardware + /// selection. + /// @warning INTERNAL METHOD - NOT INTENDED FOR GENERAL USE + /// DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS + virtual bool GetSupportsSelection() + { return true; } protected: vtkVolume(); diff --git a/Rendering/Core/vtkVolumeCollection.h b/Rendering/Core/vtkVolumeCollection.h index 8a1bf4d290e..e40ad1aeb94 100644 --- a/Rendering/Core/vtkVolumeCollection.h +++ b/Rendering/Core/vtkVolumeCollection.h @@ -55,13 +55,11 @@ class VTKRENDERINGCORE_EXPORT vtkVolumeCollection : public vtkPropCollection vtkVolume *GetNextItem() { return this->GetNextVolume(); } - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkVolume *GetNextVolume(vtkCollectionSimpleIterator &cookie) { return static_cast(this->GetNextItemAsObject(cookie)); } - //ETX protected: vtkVolumeCollection() {} diff --git a/Rendering/Core/vtkVolumeProperty.h b/Rendering/Core/vtkVolumeProperty.h index bbe6b6af67c..6970b0df56d 100644 --- a/Rendering/Core/vtkVolumeProperty.h +++ b/Rendering/Core/vtkVolumeProperty.h @@ -280,7 +280,6 @@ class VTKRENDERINGCORE_EXPORT vtkVolumeProperty : public vtkObject double GetSpecularPower() { return this->GetSpecularPower(0); } - //BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // UpdateMTimes performs a Modified() on all TimeStamps. @@ -316,7 +315,6 @@ class VTKRENDERINGCORE_EXPORT vtkVolumeProperty : public vtkObject vtkTimeStamp GetGrayTransferFunctionMTime(int index); vtkTimeStamp GetGrayTransferFunctionMTime() { return this->GetGrayTransferFunctionMTime(0); } - //ETX protected: vtkVolumeProperty(); diff --git a/Rendering/FreeType/Testing/Cxx/TestFreeTypeTextMapperNoMath.cxx b/Rendering/FreeType/Testing/Cxx/TestFreeTypeTextMapperNoMath.cxx index ad66e496301..03f6d00c115 100644 --- a/Rendering/FreeType/Testing/Cxx/TestFreeTypeTextMapperNoMath.cxx +++ b/Rendering/FreeType/Testing/Cxx/TestFreeTypeTextMapperNoMath.cxx @@ -172,6 +172,19 @@ int TestFreeTypeTextMapperNoMath(int argc, char *argv[]) mapper11->SetInput("oTeVaVoVAW"); actor11->SetPosition(300, 200); + // Empty string, solid background: should not render + vtkNew mapper12; + vtkNew actor12; + actor12->SetMapper(mapper12.GetPointer()); + mapper12->GetTextProperty()->SetFontSize(16); + mapper12->GetTextProperty()->SetColor(1.0, 0.0, 0.0); + mapper12->GetTextProperty()->SetBackgroundColor(1.0, 0.5, 1.0); + mapper12->GetTextProperty()->SetBackgroundOpacity(1.0); + mapper12->GetTextProperty()->SetJustificationToRight(); + mapper12->GetTextProperty()->SetVerticalJustificationToCentered(); + mapper12->SetInput(""); + actor12->SetPosition(0, 0); + // Boring rendering setup.... vtkNew ren; @@ -193,6 +206,7 @@ int TestFreeTypeTextMapperNoMath(int argc, char *argv[]) ren->AddActor(actor9.GetPointer()); ren->AddActor(actor10.GetPointer()); ren->AddActor(actor11.GetPointer()); + ren->AddActor(actor12.GetPointer()); win->SetMultiSamples(0); win->Render(); diff --git a/Rendering/FreeType/Testing/Cxx/TestTextActor.cxx b/Rendering/FreeType/Testing/Cxx/TestTextActor.cxx index bb18e9e9514..5a8490261ce 100644 --- a/Rendering/FreeType/Testing/Cxx/TestTextActor.cxx +++ b/Rendering/FreeType/Testing/Cxx/TestTextActor.cxx @@ -117,6 +117,12 @@ int TestTextActor(int, char *[]) actor->GetTextProperty()->SetBackgroundOpacity(1.0); actor->SetPosition(x[col], y[row]); + + actor->SetDrawFrame((row + col) % 2 == 0); + actor->GetFrameProperty()->SetColor( + col > 0 ? 1. : 0., col == 1 ? 1. : 0., col < 2 ? 1. : 0.); + actor->GetFrameProperty()->SetLineWidth((row) % 3 + 1); + setupTextActor(actor.GetPointer(), anchors.GetPointer()); ren->AddActor2D(actor.GetPointer()); } @@ -164,8 +170,8 @@ int TestTextActor(int, char *[]) // Finally render the scene and compare the image to a reference image win->SetMultiSamples(0); - win->GetInteractor()->Initialize(); - win->GetInteractor()->Start(); + iren->Initialize(); + iren->Start(); return EXIT_SUCCESS; } diff --git a/Rendering/FreeType/Testing/Cxx/TestTextActor3DDepthPeeling.cxx b/Rendering/FreeType/Testing/Cxx/TestTextActor3DDepthPeeling.cxx index 9597a58484a..28036dc3ba2 100644 --- a/Rendering/FreeType/Testing/Cxx/TestTextActor3DDepthPeeling.cxx +++ b/Rendering/FreeType/Testing/Cxx/TestTextActor3DDepthPeeling.cxx @@ -37,7 +37,7 @@ int TestTextActor3DDepthPeeling(int argc, char* argv[]) iren->SetRenderWindow(renWin); renWin->Delete(); - renWin->SetMultiSamples(1); + renWin->SetMultiSamples(0); renWin->SetAlphaBitPlanes(1); vtkRenderer *renderer = vtkRenderer::New(); diff --git a/Rendering/FreeType/Testing/Data/Baseline/TestTextActor.png.md5 b/Rendering/FreeType/Testing/Data/Baseline/TestTextActor.png.md5 index de4de7932ba..c0065082682 100644 --- a/Rendering/FreeType/Testing/Data/Baseline/TestTextActor.png.md5 +++ b/Rendering/FreeType/Testing/Data/Baseline/TestTextActor.png.md5 @@ -1 +1 @@ -092c060b28c4e98d89f56f4060aad451 +97b2d39dc73d76ea381920eb35d529bb diff --git a/Rendering/FreeType/vtkFreeTypeTools.cxx b/Rendering/FreeType/vtkFreeTypeTools.cxx index 114f5f85c37..a860d13c7c0 100644 --- a/Rendering/FreeType/vtkFreeTypeTools.cxx +++ b/Rendering/FreeType/vtkFreeTypeTools.cxx @@ -1239,6 +1239,17 @@ bool vtkFreeTypeTools::RenderStringInternal(vtkTextProperty *tprop, return false; } + if (str.empty()) + { + data->Initialize(); + if (textDims) + { + textDims[0] = 0; + textDims[1] = 0; + } + return true; + } + ImageMetaData metaData; // Setup the metadata cache diff --git a/Rendering/GL2PS/vtkGL2PSUtilities.cxx b/Rendering/GL2PS/vtkGL2PSUtilities.cxx index 6b49e9c19ed..87befeec27f 100644 --- a/Rendering/GL2PS/vtkGL2PSUtilities.cxx +++ b/Rendering/GL2PS/vtkGL2PSUtilities.cxx @@ -362,7 +362,7 @@ void vtkGL2PSUtilities::DrawPathPS(vtkPath *path, double rasterPos[3], float strokeWidth, const char *label) { vtkFloatArray *points = - vtkFloatArray::SafeDownCast(path->GetPoints()->GetData()); + vtkArrayDownCast(path->GetPoints()->GetData()); vtkIntArray *codes = path->GetCodes(); if (points->GetNumberOfTuples() != codes->GetNumberOfTuples()) @@ -500,7 +500,7 @@ void vtkGL2PSUtilities::DrawPathPDF(vtkPath *path, double rasterPos[3], const char *) { vtkFloatArray *points = - vtkFloatArray::SafeDownCast(path->GetPoints()->GetData()); + vtkArrayDownCast(path->GetPoints()->GetData()); vtkIntArray *codes = path->GetCodes(); if (points->GetNumberOfTuples() != codes->GetNumberOfTuples()) @@ -648,7 +648,7 @@ void vtkGL2PSUtilities::DrawPathSVG(vtkPath *path, double rasterPos[3], float strokeWidth, const char *label) { vtkFloatArray *points = - vtkFloatArray::SafeDownCast(path->GetPoints()->GetData()); + vtkArrayDownCast(path->GetPoints()->GetData()); vtkIntArray *codes = path->GetCodes(); if (points->GetNumberOfTuples() != codes->GetNumberOfTuples()) diff --git a/Rendering/GL2PSOpenGL2/vtkOpenGLGL2PSHelperImpl.cxx b/Rendering/GL2PSOpenGL2/vtkOpenGLGL2PSHelperImpl.cxx index ad086b03f89..9ab02127ed0 100644 --- a/Rendering/GL2PSOpenGL2/vtkOpenGLGL2PSHelperImpl.cxx +++ b/Rendering/GL2PSOpenGL2/vtkOpenGLGL2PSHelperImpl.cxx @@ -730,7 +730,7 @@ void vtkOpenGLGL2PSHelperImpl::DrawPathPS( float strokeWidth, const std::string &label) { vtkFloatArray *points = - vtkFloatArray::SafeDownCast(path->GetPoints()->GetData()); + vtkArrayDownCast(path->GetPoints()->GetData()); vtkIntArray *codes = path->GetCodes(); if (points->GetNumberOfTuples() != codes->GetNumberOfTuples()) @@ -876,7 +876,7 @@ void vtkOpenGLGL2PSHelperImpl::DrawPathPDF( float strokeWidth, const std::string &/*label*/) { vtkFloatArray *points = - vtkFloatArray::SafeDownCast(path->GetPoints()->GetData()); + vtkArrayDownCast(path->GetPoints()->GetData()); vtkIntArray *codes = path->GetCodes(); if (points->GetNumberOfTuples() != codes->GetNumberOfTuples()) @@ -1033,7 +1033,7 @@ void vtkOpenGLGL2PSHelperImpl::DrawPathSVG( float strokeWidth, const std::string &label) { vtkFloatArray *points = - vtkFloatArray::SafeDownCast(path->GetPoints()->GetData()); + vtkArrayDownCast(path->GetPoints()->GetData()); vtkIntArray *codes = path->GetCodes(); if (points->GetNumberOfTuples() != codes->GetNumberOfTuples()) diff --git a/Rendering/Image/Testing/Cxx/TestImageSliceMapperBackground.cxx b/Rendering/Image/Testing/Cxx/TestImageSliceMapperBackground.cxx index ab8ef201884..e9f60c940d0 100644 --- a/Rendering/Image/Testing/Cxx/TestImageSliceMapperBackground.cxx +++ b/Rendering/Image/Testing/Cxx/TestImageSliceMapperBackground.cxx @@ -20,15 +20,17 @@ #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" -#include "vtkRenderWindowInteractor.h" -#include "vtkInteractorStyleImage.h" -#include "vtkRenderWindow.h" -#include "vtkRenderer.h" #include "vtkCamera.h" #include "vtkImageData.h" -#include "vtkImageSliceMapper.h" #include "vtkImageProperty.h" #include "vtkImageSlice.h" +#include "vtkImageSliceMapper.h" +#include "vtkInteractorStyleImage.h" +#include "vtkNew.h" +#include "vtkPlane.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkRenderer.h" #include "vtkTIFFReader.h" int TestImageSliceMapperBackground(int argc, char* argv[]) @@ -63,6 +65,10 @@ int TestImageSliceMapperBackground(int argc, char* argv[]) imageMapper->SetInputConnection(reader->GetOutputPort()); imageMapper->CroppingOn(); imageMapper->SetCroppingRegion(100, 107, 100, 107, 0, 0); + vtkNew cplane; + cplane->SetNormal(-0.5,0.5,0); + cplane->SetOrigin(105,105,0); + imageMapper->AddClippingPlane(cplane.Get()); double *bounds = imageMapper->GetBounds(); double point[3]; diff --git a/Rendering/Image/Testing/Data/Baseline/TestImageSliceMapperBackground.png.md5 b/Rendering/Image/Testing/Data/Baseline/TestImageSliceMapperBackground.png.md5 index 9784937bcd5..f62e13124ef 100644 --- a/Rendering/Image/Testing/Data/Baseline/TestImageSliceMapperBackground.png.md5 +++ b/Rendering/Image/Testing/Data/Baseline/TestImageSliceMapperBackground.png.md5 @@ -1 +1 @@ -5b7cf00ecf5acf17279a095b930c38eb +93c18b08789ca38ea806d7288e2d9ba1 diff --git a/Rendering/Image/Testing/Data/Baseline/TestImageSliceMapperBackground_1.png.md5 b/Rendering/Image/Testing/Data/Baseline/TestImageSliceMapperBackground_1.png.md5 index 003ebdd1c0f..8371b19a139 100644 --- a/Rendering/Image/Testing/Data/Baseline/TestImageSliceMapperBackground_1.png.md5 +++ b/Rendering/Image/Testing/Data/Baseline/TestImageSliceMapperBackground_1.png.md5 @@ -1 +1 @@ -ea2159a9fc663a222c8a75dc691b82e3 +1fcd489d2f089cb593ea54dada2867f2 diff --git a/Rendering/Image/vtkImageResliceMapper.h b/Rendering/Image/vtkImageResliceMapper.h index ed19e1f3d5e..7cbe0d4c11e 100644 --- a/Rendering/Image/vtkImageResliceMapper.h +++ b/Rendering/Image/vtkImageResliceMapper.h @@ -209,7 +209,7 @@ class VTKRENDERINGIMAGE_EXPORT vtkImageResliceMapper : public vtkImageMapper3D // Description: // Garbage collection for reference loops. - void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; vtkImageSliceMapper *SliceMapper; // Does the OpenGL rendering diff --git a/Rendering/Image/vtkImageSliceCollection.cxx b/Rendering/Image/vtkImageSliceCollection.cxx index e33f93ca1e3..6253cb28709 100644 --- a/Rendering/Image/vtkImageSliceCollection.cxx +++ b/Rendering/Image/vtkImageSliceCollection.cxx @@ -41,20 +41,10 @@ vtkImageSliceCollection::~vtkImageSliceCollection() void vtkImageSliceCollection::AddItem(vtkImageSlice *a) { vtkCollectionElement* elem = new vtkCollectionElement; + elem->Item = a; - // Check if the top item is NULL - if (this->Top == NULL) - { - this->Top = elem; - elem->Item = a; - elem->Next = NULL; - this->Bottom = elem; - this->NumberOfItems++; - a->Register(this); - return; - } - - // Insert according to the layer number + // Find insertion location according to the layer number + vtkCollectionElement *prevElem = 0; int layerNumber = a->GetProperty()->GetLayerNumber(); for (vtkCollectionElement *indexElem = this->Top; indexElem != 0; @@ -63,23 +53,29 @@ void vtkImageSliceCollection::AddItem(vtkImageSlice *a) vtkImageSlice* tempImage = static_cast(indexElem->Item); if (layerNumber < tempImage->GetProperty()->GetLayerNumber()) { - // The indexElem item's layer number is larger, so swap - // the new item and the indexElem item. - elem->Item = indexElem->Item; - elem->Next = indexElem->Next; - indexElem->Item = a; - indexElem->Next = elem; - this->NumberOfItems++; - a->Register(this); - return; + break; } + prevElem = indexElem; + } + + // Insert the new element into the linked list + if (prevElem == 0) + { + elem->Next = this->Top; + this->Top = elem; + } + else + { + elem->Next = prevElem->Next; + prevElem->Next = elem; + } + + // Check if this is the new bottom + if (elem->Next == 0) + { + this->Bottom = elem; } - //End of list found before a larger layer number - elem->Item = a; - elem->Next = NULL; - this->Bottom->Next = elem; - this->Bottom = elem; this->NumberOfItems++; a->Register(this); } diff --git a/Rendering/Image/vtkImageSliceCollection.h b/Rendering/Image/vtkImageSliceCollection.h index 6e567e63133..673d3e6bee5 100644 --- a/Rendering/Image/vtkImageSliceCollection.h +++ b/Rendering/Image/vtkImageSliceCollection.h @@ -51,11 +51,9 @@ class VTKRENDERINGIMAGE_EXPORT vtkImageSliceCollection : public vtkPropCollectio // GetNextImage method that takes a collection iterator instead. vtkImageSlice *GetNextImage(); - //BTX // Description: // Reentrant safe way to get an object in a collection. vtkImageSlice *GetNextImage(vtkCollectionSimpleIterator &cookie); - //ETX // Description: // Access routine provided for compatibility with previous diff --git a/Rendering/LIC/Testing/Cxx/TestImageDataLIC2D.cxx b/Rendering/LIC/Testing/Cxx/TestImageDataLIC2D.cxx index cf0cab8c337..f4eab895d59 100644 --- a/Rendering/LIC/Testing/Cxx/TestImageDataLIC2D.cxx +++ b/Rendering/LIC/Testing/Cxx/TestImageDataLIC2D.cxx @@ -159,7 +159,7 @@ int ImageDataLIC2D(int argc, char* argv[]) noise = pngReader->GetOutput(); vtkUnsignedCharArray *cVals - = vtkUnsignedCharArray::SafeDownCast(noise->GetPointData()->GetScalars()); + = vtkArrayDownCast(noise->GetPointData()->GetScalars()); if (!cVals) { cerr << "Error: expected unsigned chars, test fails" << endl; diff --git a/Rendering/LIC/vtkImageDataLIC2D.h b/Rendering/LIC/vtkImageDataLIC2D.h index ff8701c8fbd..32fab25898d 100644 --- a/Rendering/LIC/vtkImageDataLIC2D.h +++ b/Rendering/LIC/vtkImageDataLIC2D.h @@ -92,7 +92,6 @@ class VTKRENDERINGLIC_EXPORT vtkImageDataLIC2D : public vtkImageAlgorithm const int* inWholeExtent, int *outExt); -//BTX protected: vtkImageDataLIC2D(); ~vtkImageDataLIC2D(); @@ -137,7 +136,7 @@ class VTKRENDERINGLIC_EXPORT vtkImageDataLIC2D : public vtkImageAlgorithm private: vtkImageDataLIC2D(const vtkImageDataLIC2D&); // Not implemented. void operator=(const vtkImageDataLIC2D&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/LIC/vtkLineIntegralConvolution2D.cxx b/Rendering/LIC/vtkLineIntegralConvolution2D.cxx index d8a16cab075..ba636585777 100644 --- a/Rendering/LIC/vtkLineIntegralConvolution2D.cxx +++ b/Rendering/LIC/vtkLineIntegralConvolution2D.cxx @@ -1056,7 +1056,7 @@ bool vtkLineIntegralConvolution2D::IsSupported(vtkRenderWindow *renWin) #if defined(__APPLE__) if (manager->DriverIsNvidia() && manager->DriverVersionIs(1,6)) { - // Mac OSX 10.6 GLSL doesn't support array initializer + // Mac OS X 10.6 GLSL doesn't support array initializer return false; } #endif diff --git a/Rendering/LIC/vtkLineIntegralConvolution2D.h b/Rendering/LIC/vtkLineIntegralConvolution2D.h index dc942a82a38..694f7370977 100644 --- a/Rendering/LIC/vtkLineIntegralConvolution2D.h +++ b/Rendering/LIC/vtkLineIntegralConvolution2D.h @@ -268,7 +268,6 @@ class VTKRENDERINGLIC_EXPORT vtkLineIntegralConvolution2D : public vtkObject vtkTextureObject *vectorTex, vtkTextureObject *noiseTex); - //BTX // Description: // Compute LIC over the desired subset of the input texture. The // result is copied into the desired subset of the provided output @@ -287,7 +286,6 @@ class VTKRENDERINGLIC_EXPORT vtkLineIntegralConvolution2D : public vtkObject vtkTextureObject *vectorTex, vtkTextureObject *maskVectorTex, vtkTextureObject *noiseTex); - //ETX // Description: // Convenience functions to ensure that the input textures are @@ -298,7 +296,6 @@ class VTKRENDERINGLIC_EXPORT vtkLineIntegralConvolution2D : public vtkObject static void SetNoiseTexParameters(vtkTextureObject *noise); - //BTX // Description: // Set the communicator to use during parallel operation // The communicator will not be duplicated or reference @@ -315,7 +312,6 @@ class VTKRENDERINGLIC_EXPORT vtkLineIntegralConvolution2D : public vtkObject vtkPainterCommunicator*, float&, float&) {} - //ETX // Description: // Methods used for parallel benchmarks. Use cmake to define diff --git a/Rendering/LIC/vtkStructuredGridLIC2D.h b/Rendering/LIC/vtkStructuredGridLIC2D.h index d1f1156fd35..bb7daca6f44 100644 --- a/Rendering/LIC/vtkStructuredGridLIC2D.h +++ b/Rendering/LIC/vtkStructuredGridLIC2D.h @@ -101,7 +101,6 @@ class VTKRENDERINGLIC_EXPORT vtkStructuredGridLIC2D // Check if LIC runs properly. int GetLICSuccess() { return this->LICSuccess; } -//BTX protected: vtkStructuredGridLIC2D(); ~vtkStructuredGridLIC2D(); @@ -160,7 +159,7 @@ class VTKRENDERINGLIC_EXPORT vtkStructuredGridLIC2D private: vtkStructuredGridLIC2D(const vtkStructuredGridLIC2D&); // Not implemented. void operator=(const vtkStructuredGridLIC2D&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/LIC/vtkSurfaceLICDefaultPainter.h b/Rendering/LIC/vtkSurfaceLICDefaultPainter.h index 9f475e92b47..193d7527aa6 100644 --- a/Rendering/LIC/vtkSurfaceLICDefaultPainter.h +++ b/Rendering/LIC/vtkSurfaceLICDefaultPainter.h @@ -45,7 +45,6 @@ class VTKRENDERINGLIC_EXPORT vtkSurfaceLICDefaultPainter void SetSurfaceLICPainter(vtkSurfaceLICPainter*); vtkGetObjectMacro(SurfaceLICPainter, vtkSurfaceLICPainter); -//BTX protected: vtkSurfaceLICDefaultPainter(); ~vtkSurfaceLICDefaultPainter(); @@ -68,7 +67,7 @@ class VTKRENDERINGLIC_EXPORT vtkSurfaceLICDefaultPainter private: vtkSurfaceLICDefaultPainter(const vtkSurfaceLICDefaultPainter&); // Not implemented. void operator=(const vtkSurfaceLICDefaultPainter&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/LIC/vtkSurfaceLICPainter.cxx b/Rendering/LIC/vtkSurfaceLICPainter.cxx index 4c568a4b84e..3af6db12538 100644 --- a/Rendering/LIC/vtkSurfaceLICPainter.cxx +++ b/Rendering/LIC/vtkSurfaceLICPainter.cxx @@ -3296,7 +3296,7 @@ bool vtkSurfaceLICPainter::VectorsToTCoords(vtkDataSet *data) if (this->Internals->FieldNameSet) { vectors - = vtkDataArray::SafeDownCast( + = vtkArrayDownCast( this->GetInputArrayToProcess( this->Internals->FieldAssociation, this->Internals->FieldName.c_str(), @@ -3306,7 +3306,7 @@ bool vtkSurfaceLICPainter::VectorsToTCoords(vtkDataSet *data) else { vectors - = vtkDataArray::SafeDownCast( + = vtkArrayDownCast( this->GetInputArrayToProcess( this->Internals->FieldAssociation, this->Internals->FieldAttributeType, diff --git a/Rendering/LICOpenGL2/CMakeLists.txt b/Rendering/LICOpenGL2/CMakeLists.txt index b3e5c2c3494..ebaa9febc63 100644 --- a/Rendering/LICOpenGL2/CMakeLists.txt +++ b/Rendering/LICOpenGL2/CMakeLists.txt @@ -1,18 +1,25 @@ set(Module_SRCS vtkImageDataLIC2D.cxx + vtkLICNoiseHelper.cxx vtkLineIntegralConvolution2D.cxx vtkStructuredGridLIC2D.cxx vtkSurfaceLICComposite.cxx + vtkSurfaceLICHelper.cxx + vtkSurfaceLICInterface.cxx vtkSurfaceLICMapper.cxx vtkCompositeSurfaceLICMapper.cxx vtkTextureIO.cxx ) set_source_files_properties( + vtkLICNoiseHelper.cxx + vtkSurfaceLICHelper.cxx vtkLineIntegralConvolution2D.cxx vtkSurfaceLICComposite.cxx vtkTextureIO.cxx - WRAP_EXCLUDE + PROPERTIES + WRAP_EXCLUDE 1 + WRAP_EXCLUDE_PYTHON 1 ) if (VTK_RENDERINGPARALLELLIC_SURFACELICPAINTER_TIMER) @@ -32,9 +39,9 @@ set(shader_files vtkLineIntegralConvolution2D_AAH.glsl vtkLineIntegralConvolution2D_AAV.glsl vtkStructuredGridLIC2D_fs.glsl - vtkSurfaceLICMapper_SC.glsl - vtkSurfaceLICMapper_CE.glsl - vtkSurfaceLICMapper_DCpy.glsl + vtkSurfaceLICInterface_SC.glsl + vtkSurfaceLICInterface_CE.glsl + vtkSurfaceLICInterface_DCpy.glsl ) unset(shader_h_files) foreach(file ${shader_files}) diff --git a/Rendering/LICOpenGL2/Testing/Cxx/TestImageDataLIC2D.cxx b/Rendering/LICOpenGL2/Testing/Cxx/TestImageDataLIC2D.cxx index 4f568b318af..6838a6676d5 100644 --- a/Rendering/LICOpenGL2/Testing/Cxx/TestImageDataLIC2D.cxx +++ b/Rendering/LICOpenGL2/Testing/Cxx/TestImageDataLIC2D.cxx @@ -158,7 +158,7 @@ int ImageDataLIC2D(int argc, char* argv[]) noise = pngReader->GetOutput(); vtkUnsignedCharArray *cVals - = vtkUnsignedCharArray::SafeDownCast(noise->GetPointData()->GetScalars()); + = vtkArrayDownCast(noise->GetPointData()->GetScalars()); if (!cVals) { cerr << "Error: expected unsigned chars, test fails" << endl; diff --git a/Rendering/LICOpenGL2/Testing/Cxx/vtkStructuredGridLIC2DTestDriver.cxx b/Rendering/LICOpenGL2/Testing/Cxx/vtkStructuredGridLIC2DTestDriver.cxx index c4984535588..f0c21afe8e8 100644 --- a/Rendering/LICOpenGL2/Testing/Cxx/vtkStructuredGridLIC2DTestDriver.cxx +++ b/Rendering/LICOpenGL2/Testing/Cxx/vtkStructuredGridLIC2DTestDriver.cxx @@ -310,6 +310,7 @@ int vtkStructuredGridLIC2DTestDriver(int argc, char* argv[]) break; case VTK_XZ_PLANE: renderer->GetActiveCamera()->Elevation(90); + renderer->GetActiveCamera()->SetViewUp(0,0,-1); break; } } diff --git a/Rendering/LICOpenGL2/Testing/Cxx/vtkSurfaceLICTestDriver.cxx b/Rendering/LICOpenGL2/Testing/Cxx/vtkSurfaceLICTestDriver.cxx index 65930832f27..af6f2df9b85 100644 --- a/Rendering/LICOpenGL2/Testing/Cxx/vtkSurfaceLICTestDriver.cxx +++ b/Rendering/LICOpenGL2/Testing/Cxx/vtkSurfaceLICTestDriver.cxx @@ -33,6 +33,7 @@ #include "vtkCompositePolyDataMapper2.h" #include "vtkCompositeSurfaceLICMapper.h" +#include "vtkSurfaceLICInterface.h" #include "vtk_glew.h" @@ -175,7 +176,7 @@ int vtkSurfaceLICTestDriver( } renWin->Render(); - if (!vtkSurfaceLICMapper::IsSupported(renWin)) + if (!vtkSurfaceLICInterface::IsSupported(renWin)) { cerr << "WARNING: The rendering context does not support required extensions." @@ -289,33 +290,34 @@ int vtkSurfaceLICTestDriver( } // Pass parameters. - mapper->SetNumberOfSteps(num_steps); - mapper->SetStepSize(step_size); - mapper->SetEnhancedLIC(enhanced_lic); - mapper->SetGenerateNoiseTexture(generate_noise_texture); - mapper->SetNoiseType(noise_type); - mapper->SetNormalizeVectors(normalize_vectors); - mapper->SetNoiseTextureSize(noise_texture_size); - mapper->SetNoiseGrainSize(noise_grain_size); - mapper->SetMinNoiseValue(min_noise_value); - mapper->SetMaxNoiseValue(max_noise_value); - mapper->SetNumberOfNoiseLevels(number_of_noise_levels); - mapper->SetImpulseNoiseProbability(impulse_noise_prob); - mapper->SetImpulseNoiseBackgroundValue(impulse_noise_bg_value); - mapper->SetNoiseGeneratorSeed(noise_gen_seed); - mapper->SetEnhanceContrast(enhance_contrast); - mapper->SetLowLICContrastEnhancementFactor(low_lic_contrast_enhancement_factor); - mapper->SetHighLICContrastEnhancementFactor(high_lic_contrast_enhancement_factor); - mapper->SetLowColorContrastEnhancementFactor(low_color_contrast_enhancement_factor); - mapper->SetHighColorContrastEnhancementFactor(high_color_contrast_enhancement_factor); - mapper->SetAntiAlias(anti_alias); - mapper->SetColorMode(color_mode); - mapper->SetLICIntensity(lic_intensity); - mapper->SetMapModeBias(map_mode_bias); - mapper->SetMaskOnSurface(mask_on_surface); - mapper->SetMaskThreshold(mask_threshold); - mapper->SetMaskIntensity(mask_intensity); - mapper->SetMaskColor(&mask_color_rgb[0]); + vtkSurfaceLICInterface *li = mapper->GetLICInterface(); + li->SetNumberOfSteps(num_steps); + li->SetStepSize(step_size); + li->SetEnhancedLIC(enhanced_lic); + li->SetGenerateNoiseTexture(generate_noise_texture); + li->SetNoiseType(noise_type); + li->SetNormalizeVectors(normalize_vectors); + li->SetNoiseTextureSize(noise_texture_size); + li->SetNoiseGrainSize(noise_grain_size); + li->SetMinNoiseValue(min_noise_value); + li->SetMaxNoiseValue(max_noise_value); + li->SetNumberOfNoiseLevels(number_of_noise_levels); + li->SetImpulseNoiseProbability(impulse_noise_prob); + li->SetImpulseNoiseBackgroundValue(impulse_noise_bg_value); + li->SetNoiseGeneratorSeed(noise_gen_seed); + li->SetEnhanceContrast(enhance_contrast); + li->SetLowLICContrastEnhancementFactor(low_lic_contrast_enhancement_factor); + li->SetHighLICContrastEnhancementFactor(high_lic_contrast_enhancement_factor); + li->SetLowColorContrastEnhancementFactor(low_color_contrast_enhancement_factor); + li->SetHighColorContrastEnhancementFactor(high_color_contrast_enhancement_factor); + li->SetAntiAlias(anti_alias); + li->SetColorMode(color_mode); + li->SetLICIntensity(lic_intensity); + li->SetMapModeBias(map_mode_bias); + li->SetMaskOnSurface(mask_on_surface); + li->SetMaskThreshold(mask_threshold); + li->SetMaskIntensity(mask_intensity); + li->SetMaskColor(&mask_color_rgb[0]); vtkSmartPointer actor = vtkSmartPointer::New(); diff --git a/Rendering/LICOpenGL2/vtkCompositeSurfaceLICMapper.cxx b/Rendering/LICOpenGL2/vtkCompositeSurfaceLICMapper.cxx index ce9f462aa98..047eae2441c 100644 --- a/Rendering/LICOpenGL2/vtkCompositeSurfaceLICMapper.cxx +++ b/Rendering/LICOpenGL2/vtkCompositeSurfaceLICMapper.cxx @@ -475,7 +475,11 @@ void vtkCompositeSurfaceLICMapper::RenderBlock(vtkRenderer *renderer, helper = found->second; helper->SetInputData(ds); } - if (ds && ds->GetPoints()) + // the parallel LIC code must get called + // even if the data is empty to initialize the + // communicators. Normally we would only call on + // cases where we have data + // if (ds && ds->GetPoints()) { helper->RenderPiece(renderer,actor); } diff --git a/Rendering/LICOpenGL2/vtkImageDataLIC2D.h b/Rendering/LICOpenGL2/vtkImageDataLIC2D.h index c467bf24478..903842f3c39 100644 --- a/Rendering/LICOpenGL2/vtkImageDataLIC2D.h +++ b/Rendering/LICOpenGL2/vtkImageDataLIC2D.h @@ -92,7 +92,6 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkImageDataLIC2D : public vtkImageAlgorithm const int* inWholeExtent, int *outExt); -//BTX protected: vtkImageDataLIC2D(); ~vtkImageDataLIC2D(); @@ -134,7 +133,7 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkImageDataLIC2D : public vtkImageAlgorithm private: vtkImageDataLIC2D(const vtkImageDataLIC2D&); // Not implemented. void operator=(const vtkImageDataLIC2D&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/LICOpenGL2/vtkLICNoiseHelper.cxx b/Rendering/LICOpenGL2/vtkLICNoiseHelper.cxx new file mode 100644 index 00000000000..ec879a1e9c1 --- /dev/null +++ b/Rendering/LICOpenGL2/vtkLICNoiseHelper.cxx @@ -0,0 +1,468 @@ +/*========================================================================= + + Program: Visualization Toolkit + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkLICNoiseHelper.h" + +#include "vtkBase64Utilities.h" +#include "vtkGenericDataObjectReader.h" +#include "vtkImageData.h" +#include "vtkNoise200x200.h" + +#include + +namespace +{ + +/** +integer log base 2 +*/ +int ilog2(unsigned int n) +{ + if (n == 0) + { + return -1; + } + unsigned int r = 0; + while ((n >>= 1)) + { + r += 1; + } + return r; +} + +} // end anonymous namespace + + +//----------------------------------------------------------------------------- +void vtkLICRandomNoise2D::GetValidDimensionAndGrainSize(int type, int &sideLen, int &grainSize) +{ + // perlin noise both side len and grain size need to be powers of 2 + if (type == PERLIN) + { + sideLen = 1 << ilog2(sideLen); + grainSize = 1 << ilog2(grainSize); + } + + // grains can't be larger than the patch + if (sideLen < grainSize) + { + sideLen = grainSize; + } + + // generate noise with agiven grainSize size on the patch + if (sideLen % grainSize) + { + // grainSize is not an even divsior of sideLen, adjust sideLen to + // next larger even divisor + sideLen = grainSize * (sideLen/grainSize + 1); + } +} + +//----------------------------------------------------------------------------- +int vtkLICRandomNoise2D::ShouldGenerateValue(double prob) +{ + if (this->ProbGen.GetRandomNumber() > (1.0 - prob)) + { + return 1; + } + return 0; +} + +//----------------------------------------------------------------------------- +float *vtkLICRandomNoise2D::Generate( + int type, + int &sideLen, + int &grainSize, + float minNoiseVal, + float maxNoiseVal, + int nLevels, + double impulseProb, + float impulseBgNoiseVal, + int seed) +{ + this->GetValidDimensionAndGrainSize(type, sideLen, grainSize); + + switch (type) + { + case GAUSSIAN: + return this->GenerateGaussian( + sideLen, + grainSize, + minNoiseVal, + maxNoiseVal, + nLevels, + impulseProb, + impulseBgNoiseVal, + seed); + + case UNIFORM: + return this->GenerateUniform( + sideLen, + grainSize, + minNoiseVal, + maxNoiseVal, + nLevels, + impulseProb, + impulseBgNoiseVal, + seed); + + case PERLIN: + return this->GeneratePerlin( + sideLen, + grainSize, + minNoiseVal, + maxNoiseVal, + nLevels, + impulseProb, + impulseBgNoiseVal, + seed); + } + return NULL; +} + +//----------------------------------------------------------------------------- +float *vtkLICRandomNoise2D::GenerateUniform( + int sideLen, + int grainSize, + float minNoiseVal, + float maxNoiseVal, + int nLevels, + double impulseProb, + float impulseBgNoiseVal, + int seed) +{ + // generate a patch of single pixel random values + // with a uniform distribution and fixed number of levels + nLevels = nLevels < 1 ? 1 : nLevels; + int maxLevel = nLevels-1; + float delta = maxLevel != 0 ? 1.0f/maxLevel : 0.0f; + minNoiseVal = minNoiseVal < 0.0f ? 0.0f : minNoiseVal; + maxNoiseVal = maxNoiseVal > 1.0f ? 1.0f : maxNoiseVal; + float noiseRange = maxNoiseVal - minNoiseVal; + impulseProb = impulseProb < 0.0 ? 0.0 : impulseProb; + impulseProb = impulseProb > 1.0 ? 1.0 : impulseProb; + impulseBgNoiseVal = impulseBgNoiseVal < 0.0f ? 0.0f : impulseBgNoiseVal; + impulseBgNoiseVal = impulseBgNoiseVal > 1.0f ? 1.0f : impulseBgNoiseVal; + this->ValueGen.SetSeed(seed); + this->ProbGen.SetSeed(seed); + const int sdim = sideLen/grainSize; + const int sdim2 = sdim*sdim; + float *rvals=(float*)malloc(sdim2*sizeof(float)); + for (int i=0; iShouldGenerateValue(impulseProb)) + { + int l = static_cast(this->ValueGen.GetRandomNumber()*nLevels); + l = l > maxLevel ? maxLevel : l; // needed for 1.0 + rvals[idx] = nLevels == 1 ? maxNoiseVal : minNoiseVal + (l*delta) * noiseRange; + } + } + } + + // map single pixel random values onto a patch of values of + // the requested grain size + const int ncomp = 2; + const int dim2 = sideLen*sideLen; + const int ntup = ncomp*dim2; + float *noise = (float*)malloc(ntup*sizeof(float)); + for (int j=0; j 1.0 ? 1.0 : impulseProb; + impulseBgNoiseVal = impulseBgNoiseVal < 0.0f ? 0.0f : impulseBgNoiseVal; + impulseBgNoiseVal = impulseBgNoiseVal > 1.0f ? 1.0f : impulseBgNoiseVal; + this->ValueGen.SetSeed(seed); + this->ProbGen.SetSeed(seed); + const int sdim = sideLen/grainSize; + const int sdim2 = sdim*sdim; + float *rvals = (float*)malloc(sdim2*sizeof(float)); + for (int i=0; iShouldGenerateValue(impulseProb)) + { + double val = 0.0; + for (int q=0; qValueGen.GetRandomNumber(); + } + rvals[idx] = static_cast(val); + } + } + } + + // normalize noise field from eps to nLevels onto 0 to 1 + // and restrict to the requested number of levels + // min/max + float minVal = static_cast(N+1); + float maxVal = 0.0f; + for (int i=0; i 0.0f ? rvals[i] : minVal); + + maxVal = rvals[i]>maxVal ? rvals[i] : maxVal; + } + float maxMinDiff = maxVal-minVal; + // because we ignore zero when impulseProb<1 we have to be careful + // here so that we can support one noise level. + minVal = maxMinDiff == 0.0f ? 0.0f : minVal; + maxMinDiff = maxMinDiff == 0.0f ? (maxVal == 0.0f ? 1.0f : maxVal) : maxMinDiff; + + nLevels = nLevels < 1 ? 1 : nLevels; + int maxLevel = nLevels-1; + float delta = maxLevel != 0 ? 1.0f/maxLevel : 0.0f; + minNoiseVal = minNoiseVal < 0.0f ? 0.0f : minNoiseVal; + maxNoiseVal = maxNoiseVal > 1.0f ? 1.0f : maxNoiseVal; + float noiseRange = maxNoiseVal - minNoiseVal; + for (int i=0; i(val*nLevels); + l = l > maxLevel ? maxLevel : l; + rvals[i] + = rvals[i] < minVal ? impulseBgNoiseVal + : nLevels == 1 ? maxNoiseVal : minNoiseVal + (l*delta) * noiseRange; + } + + // map single pixel random values onto a patch of values of + // the requested grain size + const int ncomp = 2; + const int dim2 = sideLen*sideLen; + const int ntup = ncomp*dim2; + float *noise = (float*)malloc(ntup*sizeof(float)); + for (int j=0; j grainSize + const int ncomp = 2; + const int dim2 = sideLen*sideLen; + const int ntup = ncomp*dim2; + float *noise = static_cast(malloc(ntup*sizeof(float))); + for (int i=0; i 1.0 ? 1.0 : impulseProb; + impulseBgNoiseVal = impulseBgNoiseVal < 0.0f ? 0.0f : impulseBgNoiseVal; + impulseBgNoiseVal = impulseBgNoiseVal > 1.0f ? 1.0f : impulseBgNoiseVal; + minNoiseVal = minNoiseVal < 0.0f ? 0.0f : minNoiseVal; + maxNoiseVal = maxNoiseVal > 1.0f ? 1.0f : maxNoiseVal; + + //int nIter = ilog2(static_cast(sideLen-1(grainSize)); + for (int w=0; w(1<<(nIter-1-w)); + //float levelNoiseMax = 1.0f - levelNoiseMin; + // generate a level of noise + int levelGrainSize = 1<= sideLen ? i : ii; + int jj = j+q-1; + jj = jj < 0 ? j : jj; + jj = jj >= sideLen ? j : jj; + int idx = 2*(sideLen*jj+ii); + val += levelNoise[idx]*K[q*3+p]; + } + } + levelNoise[2*(sideLen*j+i)] = val; + } + } + }*/ + // accumulate + for (int i=0; i(nIter+1); + float maxVal = 0.0f; + for (int i=0; imaxVal ? val : maxVal; + } + float maxMinDiff = maxVal - minVal; + if ( maxMinDiff <= 0.0f ) + { + maxMinDiff = 1.0f; + minVal = 0.0f; + } + for (int i=0; i(file_noise200x200_vtk_sections[cc]); + } + + unsigned char* binaryInput + = new unsigned char[file_noise200x200_vtk_decoded_length + 10]; + + unsigned long binarylength = static_cast( + vtkBase64Utilities::DecodeSafely( + reinterpret_cast(base64string.c_str()), + base64string.length(), + binaryInput, + file_noise200x200_vtk_decoded_length + 10)); + + assert("check valid_length" + && (binarylength == file_noise200x200_vtk_decoded_length)); + + vtkGenericDataObjectReader* reader = vtkGenericDataObjectReader::New(); + reader->ReadFromInputStringOn(); + + reader->SetBinaryInputString( + reinterpret_cast(binaryInput), + static_cast(binarylength)); + + reader->Update(); + vtkImageData* data = vtkImageData::New(); + data->ShallowCopy(reader->GetOutput()); + + delete [] binaryInput; + reader->Delete(); + return data; +} diff --git a/Rendering/LICOpenGL2/vtkLICNoiseHelper.h b/Rendering/LICOpenGL2/vtkLICNoiseHelper.h new file mode 100644 index 00000000000..682cfd17e3a --- /dev/null +++ b/Rendering/LICOpenGL2/vtkLICNoiseHelper.h @@ -0,0 +1,176 @@ +/*========================================================================= + + Program: Visualization Toolkit + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkLICNoiseHelper -- Support code for surface LIC +// .SECTION Description +// A small collection of noise routines for LIC +#ifndef vtkLICNoiseHelper_h +#define vtkLICNoiseHelper_h + +#include "vtkRenderingLICOpenGL2Module.h" // for export + +#include "vtkMinimalStandardRandomSequence.h" + +class vtkImageData; + +/** +An interface to a random number generator. We can't use +c stdlib since we're not gauranteed to get consistent. +sequences across platform or library version and that +would prevent consistent output during regression tests. +*/ +class vtkLICRandomNumberGeneratorInterface +{ +public: + vtkLICRandomNumberGeneratorInterface() + { + this->RNG = vtkMinimalStandardRandomSequence::New(); + } + + ~vtkLICRandomNumberGeneratorInterface() + { + this->RNG->Delete(); + } + + /** + Seed the random number generator + */ + void SetSeed(int seedVal) + { + this->RNG->SetSeed(seedVal); + } + + /** + Get a random number in the range of 0 to 1. + */ + double GetRandomNumber() + { + double val = this->RNG->GetValue(); + this->RNG->Next(); + return val; + } + +private: + void operator=(const vtkLICRandomNumberGeneratorInterface &); // not implemented + vtkLICRandomNumberGeneratorInterface(const vtkLICRandomNumberGeneratorInterface &); // not implemented + +private: + vtkMinimalStandardRandomSequence *RNG; +}; + +/** +2D Noise Generator. Generate arrays for use as noise texture +in the LIC algorithm. Can generate noise with uniform or Gaussian +distributions, with a desired number of noise levels, and a +desired frequency (f < 1 is impulse noise). +*/ +class vtkLICRandomNoise2D +{ +public: + vtkLICRandomNoise2D(){} + + // Description: + // Generate a patch of random gray scale values along with an + // alpha channel (in vtk array format). The data should be + // deleted by later calling DeleteValues. Grain size and sideLen + // may be modified to match the noise generator requirements, + // returned arrays will be sized accordingly. + // + // type - UNIFORM=0, GAUSSIAN=1, PERLIN=2 + // sideLen - side length of square patch in pixels (in/out) + // grainSize - grain size of noise values in pixels (in/out) + // nLevels - number of noise intesity levels + // minNoiseVal - set the min for noise pixels (position distribution) + // maxNoiseVal - set the max for noise pixels (position distribution) + // impulseProb - probability of impulse noise,1 touches every pixel + // impulseBgNoiseVal - set the background color for impulse noise + // seed - seed for random number generator + enum { + UNIFORM = 0, + GAUSSIAN = 1, + PERLIN = 2 + }; + float *Generate( + int type, + int &sideLen, + int &grainLize, + float minNoiseVal, + float maxNoiseVal, + int nLevels, + double impulseProb, + float impulseBgNoiseVal, + int seed); + + // Description + // Delete the passed in array of values. + void DeleteValues(unsigned char *vals){ free(vals); } + + static vtkImageData *GetNoiseResource(); + +private: + // Description: + // Generate noise with a uniform distribution. + float *GenerateUniform( + int sideLen, + int grainLize, + float minNoiseVal, + float maxNoiseVal, + int nLevels, + double impulseProb, + float impulseBgNoiseVal, + int seed); + + // Description: + // Generate noise with a Gaussian distribution. + float *GenerateGaussian( + int sideLen, + int grainLize, + float minNoiseVal, + float maxNoiseVal, + int nLevels, + double impulseProb, + float impulseBgNoiseVal, + int seed); + + // Description: + // Generate Perlin noise with a Gaussian distribution. + float *GeneratePerlin( + int sideLen, + int grainLize, + float minNoiseVal, + float maxNoiseVal, + int nLevels, + double impulseProb, + float impulseBgNoiseVal, + int seed); + + // Description: + // A way of controling the probability (from 0.0 to 1.0) that you + // generate values. returns 1 if you should generate a value. + // for example this is used to control the frequency of impulse + // noise. + int ShouldGenerateValue(double prob); + + // Description: + // Get a valid the length of the side of the patch and grains size in pixels + // given a desired patch side length and a grain size. This ensures that all + // grains are the same size. + void GetValidDimensionAndGrainSize(int type, int &dim, int &grainSize); + +private: + vtkLICRandomNumberGeneratorInterface ValueGen; + vtkLICRandomNumberGeneratorInterface ProbGen; +}; + +#endif +// VTK-HeaderTest-Exclude: vtkLICNoiseHelper.h diff --git a/Rendering/LICOpenGL2/vtkLineIntegralConvolution2D.h b/Rendering/LICOpenGL2/vtkLineIntegralConvolution2D.h index ebf6aa8ce3f..cc8c7715293 100644 --- a/Rendering/LICOpenGL2/vtkLineIntegralConvolution2D.h +++ b/Rendering/LICOpenGL2/vtkLineIntegralConvolution2D.h @@ -270,7 +270,6 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkLineIntegralConvolution2D : public vtkObj vtkTextureObject *vectorTex, vtkTextureObject *noiseTex); - //BTX // Description: // Compute LIC over the desired subset of the input texture. The // result is copied into the desired subset of the provided output @@ -289,7 +288,6 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkLineIntegralConvolution2D : public vtkObj vtkTextureObject *vectorTex, vtkTextureObject *maskVectorTex, vtkTextureObject *noiseTex); - //ETX // Description: // Convenience functions to ensure that the input textures are @@ -300,7 +298,6 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkLineIntegralConvolution2D : public vtkObj static void SetNoiseTexParameters(vtkTextureObject *noise); - //BTX // Description: // Set the communicator to use during parallel operation // The communicator will not be duplicated or reference @@ -317,7 +314,6 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkLineIntegralConvolution2D : public vtkObj vtkPainterCommunicator*, float&, float&) {} - //ETX // Description: // Methods used for parallel benchmarks. Use cmake to define diff --git a/Rendering/LICOpenGL2/vtkStructuredGridLIC2D.h b/Rendering/LICOpenGL2/vtkStructuredGridLIC2D.h index 56200bd180e..7b58036eba0 100644 --- a/Rendering/LICOpenGL2/vtkStructuredGridLIC2D.h +++ b/Rendering/LICOpenGL2/vtkStructuredGridLIC2D.h @@ -98,7 +98,6 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkStructuredGridLIC2D // Check if LIC runs properly. int GetLICSuccess() { return this->LICSuccess; } -//BTX protected: vtkStructuredGridLIC2D(); ~vtkStructuredGridLIC2D(); @@ -157,7 +156,7 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkStructuredGridLIC2D private: vtkStructuredGridLIC2D(const vtkStructuredGridLIC2D&); // Not implemented. void operator=(const vtkStructuredGridLIC2D&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/LICOpenGL2/vtkSurfaceLICHelper.cxx b/Rendering/LICOpenGL2/vtkSurfaceLICHelper.cxx new file mode 100644 index 00000000000..adb9f94ce27 --- /dev/null +++ b/Rendering/LICOpenGL2/vtkSurfaceLICHelper.cxx @@ -0,0 +1,600 @@ +/*========================================================================= + + Program: Visualization Toolkit + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkSurfaceLICHelper.h" + +#include "vtk_glew.h" +#include "vtkFrameBufferObject2.h" +#include "vtkPixelBufferObject.h" +#include "vtkPainterCommunicator.h" +#include "vtkLineIntegralConvolution2D.h" +#include "vtkOpenGLRenderWindow.h" +#include "vtkOpenGLRenderUtilities.h" +#include "vtkBoundingBox.h" +#include "vtkMath.h" +#include "vtkNew.h" +#include "vtkMatrix4x4.h" +#include "vtkOpenGLCamera.h" +#include "vtkRenderer.h" +#include "vtkOpenGLActor.h" +#include "vtkOpenGLError.h" +#include "vtkDataSet.h" +#include "vtkCompositeDataSet.h" +#include "vtkCompositeDataIterator.h" +#include "vtkSurfaceLICComposite.h" + +#include + +// Description +// find min/max of unmasked fragments across all regions +// download each search each region individually +void vtkSurfaceLICHelper::StreamingFindMinMax( + vtkFrameBufferObject2 *fbo, + std::deque &blockExts, + float &min, + float &max) +{ + size_t nBlocks = blockExts.size(); + // initiate download + fbo->ActivateReadBuffer(1U); + vtkStaticCheckFrameBufferStatusMacro(GL_FRAMEBUFFER); + std::vector pbos(nBlocks, NULL); + for (size_t e=0; eDownload( + blockExts[e].GetData(), + VTK_FLOAT, + 4, + GL_FLOAT, + GL_RGBA); + } + fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 0U); + fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 1U); + fbo->DeactivateDrawBuffers(); + fbo->DeactivateReadBuffer(); + // map search and release each region + for (size_t e=0; eMapPackedBuffer(); + + size_t n = blockExts[e].Size(); + for (size_t i = 0; i L ? L : min; + max = max < L ? L : max; + } + } + pbo->UnmapPackedBuffer(); + pbo->Delete(); + pbo = NULL; + } + #if vtkSurfaceLICMapperDEBUG >= 1 + cerr << "min=" << min << " max=" << max << endl; + #endif +} + +// Description: +// Constructor +vtkSurfaceLICHelper::vtkSurfaceLICHelper() +{ + this->Viewsize[0] = this->Viewsize[1] = 0; + + this->ContextNeedsUpdate = true; + this->CommunicatorNeedsUpdate = true; + + this->Communicator = new vtkPainterCommunicator; + + this->HasVectors = false; + + this->ColorPass = NULL; + this->ColorEnhancePass = NULL; + this->CopyPass = NULL; +} + +// Description: +// Destructor +vtkSurfaceLICHelper::~vtkSurfaceLICHelper() +{ + this->ReleaseGraphicsResources(NULL); + + if (this->ColorPass) + { + delete this->ColorPass; + } + if (this->ColorEnhancePass) + { + delete this->ColorEnhancePass; + } + if (this->CopyPass) + { + delete this->CopyPass; + } + this->ColorPass = NULL; + this->ColorEnhancePass = NULL; + this->CopyPass = NULL; + + delete this->Communicator; +} + +// Description: +// Check for OpenGL support +bool vtkSurfaceLICHelper::IsSupported(vtkOpenGLRenderWindow *context) +{ + if (context == NULL) + { + vtkGenericWarningMacro("OpenGL render window required"); + return false; + } + + bool lic2d = vtkLineIntegralConvolution2D::IsSupported(context); + + bool floatFormats + = vtkTextureObject::IsSupported(context, true, true, false); + + bool support = lic2d && floatFormats; + + if (!support) + { + vtkGenericWarningMacro( + << "SurfaceLIC is not supported" << endl + << context->GetClassName() << endl + << "LIC support = " << lic2d << endl + << "floating point texture formats = " << floatFormats); + return false; + } + return true; +} + +// Description: +// Free textures and shader programs we're holding a reference to. +void vtkSurfaceLICHelper::ReleaseGraphicsResources(vtkWindow *) +{ + this->ClearTextures(); + + this->Compositor = NULL; + this->LICer = NULL; + this->FBO = NULL; +} + +// Description: +// Free textures we're holding a reference to. +void vtkSurfaceLICHelper::ClearTextures() +{ + this->DepthImage = NULL; + this->GeometryImage = NULL; + this->VectorImage = NULL; + this->MaskVectorImage = NULL; + this->CompositeVectorImage = NULL; + this->CompositeMaskVectorImage = NULL; + this->NoiseImage = NULL; + this->LICImage = NULL; + this->RGBColorImage = NULL; + this->HSLColorImage = NULL; +} + +// Description: +// Allocate textures. +void vtkSurfaceLICHelper::AllocateTextures( + vtkOpenGLRenderWindow *context, + int *viewsize) +{ + this->AllocateDepthTexture(context, viewsize, this->DepthImage); + this->AllocateTexture(context, viewsize, this->GeometryImage, vtkTextureObject::Nearest); + this->AllocateTexture(context, viewsize, this->VectorImage, vtkTextureObject::Linear); + this->AllocateTexture(context, viewsize, this->MaskVectorImage, vtkTextureObject::Linear); + this->AllocateTexture(context, viewsize, this->CompositeVectorImage, vtkTextureObject::Linear); + this->AllocateTexture(context, viewsize, this->CompositeMaskVectorImage, vtkTextureObject::Linear); + this->AllocateTexture(context, viewsize, this->LICImage, vtkTextureObject::Nearest); + this->AllocateTexture(context, viewsize, this->RGBColorImage, vtkTextureObject::Nearest); + this->AllocateTexture(context, viewsize, this->HSLColorImage, vtkTextureObject::Nearest); +} + +// Description: +// Allocate a size texture, store in the given smart pointer. +void vtkSurfaceLICHelper::AllocateTexture( + vtkOpenGLRenderWindow *context, + int *viewsize, + vtkSmartPointer &tex, + int filter) +{ + if ( !tex ) + { + vtkTextureObject * newTex = vtkTextureObject::New(); + newTex->SetContext(context); + newTex->SetBaseLevel(0); + newTex->SetMaxLevel(0); + newTex->SetWrapS(vtkTextureObject::ClampToEdge); + newTex->SetWrapT(vtkTextureObject::ClampToEdge); + newTex->SetMinificationFilter(filter); + newTex->SetMagnificationFilter(filter); + newTex->SetBorderColor(0.0f, 0.0f, 0.0f, 0.0f); + newTex->Create2D(viewsize[0], viewsize[1], 4, VTK_FLOAT, false); + newTex->SetAutoParameters(0); + tex = newTex; + newTex->Delete(); + } +} + +// Description: +// Allocate a size texture, store in the given smart pointer. +void vtkSurfaceLICHelper::AllocateDepthTexture( + vtkOpenGLRenderWindow *context, + int *viewsize, + vtkSmartPointer &tex) +{ + if ( !tex ) + { + vtkTextureObject * newTex = vtkTextureObject::New(); + newTex->SetContext(context); + newTex->AllocateDepth(viewsize[0], viewsize[1], vtkTextureObject::Float32); + newTex->SetAutoParameters(0); + tex = newTex; + newTex->Delete(); + } +} + +// Description: +// After LIC has been computed reset/clean internal state +void vtkSurfaceLICHelper::Updated() +{ + this->ContextNeedsUpdate = false; + this->CommunicatorNeedsUpdate = false; +} + +// Description: +// Force all stages to re-execute. Necessary if the +// context or communicator changes. +void vtkSurfaceLICHelper::UpdateAll() +{ + this->ContextNeedsUpdate = true; + this->CommunicatorNeedsUpdate= true; +} + +// Description: +// Convert a viewport to a bounding box and it's texture coordinates for a +// screen size texture. +void vtkSurfaceLICHelper::ViewportQuadTextureCoords( + const vtkPixelExtent &viewExt, + const vtkPixelExtent &viewportExt, + GLfloat *tcoords) +{ + GLfloat viewsize[2]; + viewExt.Size(viewsize); + + // cell to node + vtkPixelExtent next(viewportExt); + next.CellToNode(); + next.GetData(tcoords); + + tcoords[0] = tcoords[0]/viewsize[0]; + tcoords[1] = tcoords[1]/viewsize[0]; + tcoords[2] = tcoords[2]/viewsize[1]; + tcoords[3] = tcoords[3]/viewsize[1]; +} + +// Description: +// Render a quad (to trigger a shader to run) +void vtkSurfaceLICHelper::RenderQuad( + const vtkPixelExtent &viewExt, + const vtkPixelExtent &viewportExt, + vtkOpenGLHelper *cbo) +{ + // cell to node + vtkPixelExtent next(viewportExt); + next.CellToNode(); + + GLfloat quadPts[4]; + next.GetData(quadPts); + + GLfloat quadTCoords[4]; + this->ViewportQuadTextureCoords(viewExt, viewportExt, quadTCoords); + + float tcoords[] = { + quadTCoords[0], quadTCoords[2], + quadTCoords[1], quadTCoords[2], + quadTCoords[1], quadTCoords[3], + quadTCoords[0], quadTCoords[3]}; + + float verts[] = { + quadTCoords[0]*2.0f-1.0f, quadTCoords[2]*2.0f-1.0f, 0.0f, + quadTCoords[1]*2.0f-1.0f, quadTCoords[2]*2.0f-1.0f, 0.0f, + quadTCoords[1]*2.0f-1.0f, quadTCoords[3]*2.0f-1.0f, 0.0f, + quadTCoords[0]*2.0f-1.0f, quadTCoords[3]*2.0f-1.0f, 0.0f}; + + vtkOpenGLRenderUtilities::RenderQuad(verts, tcoords, + cbo->Program, cbo->VAO); + vtkOpenGLStaticCheckErrorMacro("failed at RenderQuad"); +} + +// Description: +// given a axes aligned bounding box in +// normalized device coordinates test for +// view frustum visibility. +// if all points are outside one of the +// view frustum planes then this box +// is not visible. we might have false +// positive where more than one clip +// plane intersects the box. +bool vtkSurfaceLICHelper::VisibilityTest(double ndcBBox[24]) +{ + // check all points in the direction d + // at the same time. + for (int d=0; d<3; ++d) + { + if (((ndcBBox[ d] < -1.0) + && (ndcBBox[3 + d] < -1.0) + && (ndcBBox[6 + d] < -1.0) + && (ndcBBox[9 + d] < -1.0) + && (ndcBBox[12 + d] < -1.0) + && (ndcBBox[15 + d] < -1.0) + && (ndcBBox[18 + d] < -1.0) + && (ndcBBox[21 + d] < -1.0)) + ||((ndcBBox[ d] > 1.0) + && (ndcBBox[3 + d] > 1.0) + && (ndcBBox[6 + d] > 1.0) + && (ndcBBox[9 + d] > 1.0) + && (ndcBBox[12 + d] > 1.0) + && (ndcBBox[15 + d] > 1.0) + && (ndcBBox[18 + d] > 1.0) + && (ndcBBox[21 + d] > 1.0)) ) + { + return false; + } + } + return true; +} + +// Description: +// Given world space bounds, +// compute bounding boxes in clip and normalized device +// coordinates and perform view frustum visiblity test. +// return true if the bounds are visible. If so the passed +// in extent object is initialized with the corresponding +//screen space extents. +bool vtkSurfaceLICHelper::ProjectBounds( + double PMV[16], + int viewsize[2], + double bounds[6], + vtkPixelExtent &screenExt) +{ + // this is how to get the 8 corners of a bounding + // box from the VTK bounds + int bbIds[24] = { + 0,2,4, + 1,2,4, + 1,3,4, + 0,3,4, + 0,2,5, + 1,2,5, + 1,3,5, + 0,3,5 + }; + + // normalized device coordinate bounding box + double ndcBBox[24]; + for (int q = 0; q<8; ++q) + { + int qq = 3*q; + // bounding box corner + double wx = bounds[bbIds[qq ]]; + double wy = bounds[bbIds[qq+1]]; + double wz = bounds[bbIds[qq+2]]; + // to clip coordinates + ndcBBox[qq ] = wx * PMV[idx(0,0)] + wy * PMV[idx(0,1)] + wz * PMV[idx(0,2)] + PMV[idx(0,3)]; + ndcBBox[qq+1] = wx * PMV[idx(1,0)] + wy * PMV[idx(1,1)] + wz * PMV[idx(1,2)] + PMV[idx(1,3)]; + ndcBBox[qq+2] = wx * PMV[idx(2,0)] + wy * PMV[idx(2,1)] + wz * PMV[idx(2,2)] + PMV[idx(2,3)]; + double ndcw = wx * PMV[idx(3,0)] + wy * PMV[idx(3,1)] + wz * PMV[idx(3,2)] + PMV[idx(3,3)]; + + // TODO + // if the point is past the near clipping plane + // we need to do something more robust. this ensures + // the correct result but its inefficient + if (ndcw < 0.0) + { + screenExt = vtkPixelExtent(viewsize[0], viewsize[1]); + //cerr << "W<0!!!!!!!!!!!!!" << endl; + return true; + } + + // to normalized device coordinates + ndcw = (ndcw == 0.0 ? 1.0 : 1.0/ndcw); + ndcBBox[qq ] *= ndcw; + ndcBBox[qq+1] *= ndcw; + ndcBBox[qq+2] *= ndcw; + } + + // compute screen extent only if the object + // is inside the view frustum. + if (VisibilityTest(ndcBBox)) + { + // these bounds are visible. compute screen + // space exents + double vx = viewsize[0] - 1.0; + double vy = viewsize[1] - 1.0; + double vx2 = viewsize[0] * 0.5; + double vy2 = viewsize[1] * 0.5; + vtkBoundingBox box; + for (int q=0; q<8; ++q) + { + int qq = 3*q; + double sx = (ndcBBox[qq ] + 1.0) * vx2; + double sy = (ndcBBox[qq+1] + 1.0) * vy2; + box.AddPoint( + vtkMath::ClampValue(sx, 0.0, vx), + vtkMath::ClampValue(sy, 0.0, vy), + 0.0); + } + // to screen extent + const double *s0 = box.GetMinPoint(); + const double *s1 = box.GetMaxPoint(); + screenExt[0] = static_cast(s0[0]); + screenExt[1] = static_cast(s1[0]); + screenExt[2] = static_cast(s0[1]); + screenExt[3] = static_cast(s1[1]); + return true; + } + + // these bounds aren't visible + return false; +} + +// Description: +// Compute screen space extents for each block in the input +// dataset and for the entire dataset. Only visible blocks +// are used in the computations. +int vtkSurfaceLICHelper::ProjectBounds( + vtkRenderer *ren, + vtkActor *actor, + vtkDataObject *dobj, + int viewsize[2], + vtkPixelExtent &dataExt, + std::deque &blockExts) +{ + // get the modelview projection matrix + vtkNew tmpMatrix; + + vtkOpenGLCamera *oglCam = + vtkOpenGLCamera::SafeDownCast(ren->GetActiveCamera()); + vtkMatrix4x4 *wcdc; + vtkMatrix4x4 *wcvc; + vtkMatrix3x3 *norms; + vtkMatrix4x4 *vcdc; + oglCam->GetKeyMatrices(ren,wcvc,norms,vcdc,wcdc); + + if (!actor->GetIsIdentity()) + { + vtkMatrix4x4 *mcwc; + vtkMatrix3x3 *anorms; + ((vtkOpenGLActor *)actor)->GetKeyMatrices(mcwc,anorms); + vtkMatrix4x4::Multiply4x4(mcwc, wcdc, tmpMatrix.GetPointer()); + } + else + { + tmpMatrix->DeepCopy(wcdc); + } +/* + for ( int c = 0; c < 4; c ++ ) + { + for ( int r = 0; r < 4; r ++ ) + { + PMV[c*4+r] + = P[idx(r,0)] * MV[idx(0,c)] + + P[idx(r,1)] * MV[idx(1,c)] + + P[idx(r,2)] * MV[idx(2,c)] + + P[idx(r,3)] * MV[idx(3,c)]; + } + } +*/ + // dataset case + vtkDataSet* ds = dynamic_cast(dobj); + if (ds && ds->GetNumberOfCells()) + { + double bounds[6]; + ds->GetBounds(bounds); + if ( vtkBoundingBox::IsValid(bounds) + && this->ProjectBounds(tmpMatrix->Element[0], viewsize, bounds, dataExt) ) + { + // the dataset is visible + // add its extent + blockExts.push_back(dataExt); + return 1; + } + //cerr << "ds " << ds << " not visible " << endl; + return 0; + } + // composite dataset case + vtkCompositeDataSet* cd = dynamic_cast(dobj); + if (cd) + { + // process each block's bounds + vtkBoundingBox bbox; + vtkCompositeDataIterator* iter = cd->NewIterator(); + for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) + { + ds = dynamic_cast(iter->GetCurrentDataObject()); + if (ds && ds->GetNumberOfCells()) + { + double bounds[6]; + ds->GetBounds(bounds); + vtkPixelExtent screenExt; + if ( vtkBoundingBox::IsValid(bounds) + && this->ProjectBounds(tmpMatrix->Element[0], viewsize, bounds, screenExt) ) + { + // this block is visible + // save it's screen extent + // and accumulate its bounds + blockExts.push_back(screenExt); + bbox.AddBounds(bounds); + } + //else { cerr << "leaf " << ds << " not visible " << endl << endl;} + } + } + iter->Delete(); + // process accumulated dataset bounds + double bounds[6]; + bbox.GetBounds(bounds); + if ( vtkBoundingBox::IsValid(bounds) + && this->ProjectBounds(tmpMatrix->Element[0], viewsize, bounds, dataExt) ) + { + return 1; + } + return 0; + } + //cerr << "ds " << ds << " no cells " << endl; + return 0; +} + +// Description: +// Shrink an extent to tightly bound non-zero values +void vtkSurfaceLICHelper::GetPixelBounds(float *rgba, int ni, vtkPixelExtent &ext) +{ + vtkPixelExtent text; + for (int j=ext[2]; j<=ext[3]; ++j) + { + for (int i=ext[0]; i<=ext[1]; ++i) + { + if (rgba[4*(j*ni+i)+3] > 0.0f) + { + text[0] = text[0] > i ? i : text[0]; + text[1] = text[1] < i ? i : text[1]; + text[2] = text[2] > j ? j : text[2]; + text[3] = text[3] < j ? j : text[3]; + } + } + } + ext = text; +} + +// Description: +// Shrink a set of extents to tightly bound non-zero values +// cull extent if it's empty +void vtkSurfaceLICHelper::GetPixelBounds(float *rgba, int ni, + std::deque &blockExts) +{ + std::vector tmpExts(blockExts.begin(),blockExts.end()); + blockExts.clear(); + size_t nBlocks = tmpExts.size(); + for (size_t b=0; b // for methods + +class vtkFrameBufferObject2; +class vtkOpenGLRenderWindow; +class vtkPainterCommunicator; +class vtkImageData; +class vtkSurfaceLICComposite; +class vtkLineIntegralConvolution2D; +class vtkRenderer; +class vtkActor; +class vtkDataObject; + +class vtkSurfaceLICHelper +{ +public: + vtkSurfaceLICHelper(); + ~vtkSurfaceLICHelper(); + + // Description: + // Check for OpenGL support + static bool IsSupported(vtkOpenGLRenderWindow *context); + + // Description: + // Free textures and shader programs we're holding a reference to. + void ReleaseGraphicsResources(vtkWindow *win); + + // Description: + // Free textures we're holding a reference to. + void ClearTextures(); + + // Description: + // Allocate textures. + void AllocateTextures( + vtkOpenGLRenderWindow *context, + int *viewsize); + + // Description: + // Allocate a size texture, store in the given smart pointer. + void AllocateTexture( + vtkOpenGLRenderWindow *context, + int *viewsize, + vtkSmartPointer &tex, + int filter = vtkTextureObject::Nearest); + + // Description: + // Allocate a size texture, store in the given smart pointer. + void AllocateDepthTexture( + vtkOpenGLRenderWindow *context, + int *viewsize, + vtkSmartPointer &tex); + + // Description: + // After LIC has been computed reset/clean internal state + void Updated(); + + // Description: + // Force all stages to re-execute. Necessary if the + // context or communicator changes. + void UpdateAll(); + + // Description: + // Convert viewport to texture coordinates + void ViewportQuadTextureCoords(GLfloat *tcoords) + { + tcoords[0] = tcoords[2] = 0.0f; + tcoords[1] = tcoords[3] = 1.0f; + } + + // Description: + // Convert a viewport to a bounding box and it's texture coordinates for a + // screen size texture. + void ViewportQuadPoints(const vtkPixelExtent &viewportExt, GLfloat *quadpts) + { + viewportExt.GetData(quadpts); + } + + // Description: + // Convert a viewport to a bounding box and it's texture coordinates for a + // screen size texture. + void ViewportQuadTextureCoords( + const vtkPixelExtent &viewExt, + const vtkPixelExtent &viewportExt, + GLfloat *tcoords); + + // Description: + // Convert the entire view to a bounding box and it's texture coordinates for + // a screen size texture. + void ViewQuadPoints(GLfloat *quadpts) + { + quadpts[0] = quadpts[2] = 0.0f; + quadpts[1] = quadpts[3] = 1.0f; + } + + // Description: + // Convert the entire view to a bounding box and it's texture coordinates for + // a screen size texture. + void ViewQuadTextureCoords(GLfloat *tcoords) + { + tcoords[0] = tcoords[2] = 0.0f; + tcoords[1] = tcoords[3] = 1.0f; + } + + // Description: + // Render a quad (to trigger a shader to run) + void RenderQuad( + const vtkPixelExtent &viewExt, + const vtkPixelExtent &viewportExt, + vtkOpenGLHelper *cbo); + + // Description: + // Compute the index into the 4x4 OpenGL ordered matrix. + inline int idx(int row, int col) { return 4*col+row; } + + // Description: + // given a axes aligned bounding box in + // normalized device coordinates test for + // view frustum visibility. + // if all points are outside one of the + // view frustum planes then this box + // is not visible. we might have false + // positive where more than one clip + // plane intersects the box. + bool VisibilityTest(double ndcBBox[24]); + + // Description: + // Given world space bounds, + // compute bounding boxes in clip and normalized device + // coordinates and perform view frustum visiblity test. + // return true if the bounds are visible. If so the passed + // in extent object is initialized with the corresponding + //screen space extents. + bool ProjectBounds( + double PMV[16], + int viewsize[2], + double bounds[6], + vtkPixelExtent &screenExt); + + // Description: + // Compute screen space extents for each block in the input + // dataset and for the entire dataset. Only visible blocks + // are used in the computations. + int ProjectBounds( + vtkRenderer *ren, + vtkActor *actor, + vtkDataObject *dobj, + int viewsize[2], + vtkPixelExtent &dataExt, + std::deque &blockExts); + + // Description: + // Shrink an extent to tightly bound non-zero values + void GetPixelBounds(float *rgba, int ni, vtkPixelExtent &ext); + + // Description: + // Shrink a set of extents to tightly bound non-zero values + // cull extent if it's empty + void GetPixelBounds(float *rgba, int ni, std::deque &blockExts); + + static void StreamingFindMinMax( + vtkFrameBufferObject2 *fbo, + std::deque &blockExts, + float &min, float &max); + + vtkSmartPointer Noise; + vtkSmartPointer NoiseImage; + vtkSmartPointer DepthImage; + vtkSmartPointer GeometryImage; + vtkSmartPointer VectorImage; + vtkSmartPointer CompositeVectorImage; + vtkSmartPointer MaskVectorImage; + vtkSmartPointer CompositeMaskVectorImage; + vtkSmartPointer LICImage; + vtkSmartPointer RGBColorImage; + vtkSmartPointer HSLColorImage; + + bool HasVectors; + std::deque BlockExts; + + vtkOpenGLHelper *ColorEnhancePass; + vtkOpenGLHelper *CopyPass; + vtkOpenGLHelper *ColorPass; + + int Viewsize[2]; + vtkSmartPointer Compositor; + vtkSmartPointer FBO; + + vtkSmartPointer LICer; + vtkPainterCommunicator *Communicator; + vtkPixelExtent DataSetExt; + + vtkWeakPointer Context; + + bool ContextNeedsUpdate; + bool CommunicatorNeedsUpdate; + + +protected: + +}; + +#endif +// VTK-HeaderTest-Exclude: vtkSurfaceLICHelper.h diff --git a/Rendering/LICOpenGL2/vtkSurfaceLICInterface.cxx b/Rendering/LICOpenGL2/vtkSurfaceLICInterface.cxx new file mode 100644 index 00000000000..f28f92efb36 --- /dev/null +++ b/Rendering/LICOpenGL2/vtkSurfaceLICInterface.cxx @@ -0,0 +1,1339 @@ +/*========================================================================= + + Program: Visualization Toolkit + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkSurfaceLICInterface.h" + +#include "vtkFloatArray.h" +#include "vtkFrameBufferObject2.h" +#include "vtkImageData.h" +#include "vtkLineIntegralConvolution2D.h" +#include "vtkObjectFactory.h" +#include "vtkOpenGLError.h" +#include "vtkOpenGLRenderWindow.h" +#include "vtkOpenGLShaderCache.h" +#include "vtkPainterCommunicator.h" +#include "vtkPixelBufferObject.h" +#include "vtkPointData.h" +#include "vtkPolyData.h" +#include "vtkProperty.h" +#include "vtkRenderer.h" +#include "vtkScalarsToColors.h" +#include "vtkShaderProgram.h" +#include "vtkSurfaceLICComposite.h" +#include "vtkTextureObjectVS.h" + +#include "vtkOpenGLVertexBufferObject.h" +#include "vtkOpenGLVertexArrayObject.h" +#include "vtkOpenGLIndexBufferObject.h" + +#include "vtkLICNoiseHelper.h" +#include "vtkSurfaceLICHelper.h" + +#include +#include +#include +#include +#include +#include + +#include "vtkSurfaceLICInterface_SC.h" +#include "vtkSurfaceLICInterface_CE.h" +#include "vtkSurfaceLICInterface_DCpy.h" +#include "vtkTextureObjectVS.h" + +typedef vtkLineIntegralConvolution2D vtkLIC2D; + +// write intermediate results to disk for debugging +#define vtkSurfaceLICInterfaceDEBUG 0 +#if vtkSurfaceLICInterfaceDEBUG >= 2 +#include "vtkTextureIO.h" +#include +using std::ostringstream; +//---------------------------------------------------------------------------- +static +std::string mpifn(vtkPainterCommunicator *comm, const char *fn) +{ + ostringstream oss; + oss << comm->GetRank() << "_" << fn; + return oss.str(); +} +#endif + +vtkObjectFactoryNewMacro(vtkSurfaceLICInterface); + +//---------------------------------------------------------------------------- +vtkSurfaceLICInterface::vtkSurfaceLICInterface() +{ + this->Internals = new vtkSurfaceLICHelper(); + + this->Enable = 1; + this->AlwaysUpdate = 0; + + this->StepSize = 1; + this->NumberOfSteps = 20; + this->NormalizeVectors = 1; + + this->EnhancedLIC = 1; + + this->EnhanceContrast = 0; + this->LowLICContrastEnhancementFactor = 0.0; + this->HighLICContrastEnhancementFactor = 0.0; + this->LowColorContrastEnhancementFactor = 0.0; + this->HighColorContrastEnhancementFactor = 0.0; + this->AntiAlias = 0; + this->ColorMode = COLOR_MODE_BLEND; + this->LICIntensity = 0.8; + this->MapModeBias = 0.0; + + this->GenerateNoiseTexture = 0; + this->NoiseType = NOISE_TYPE_GAUSSIAN; + this->NoiseTextureSize = 200; + this->MinNoiseValue = 0.0; + this->MaxNoiseValue = 0.8; + this->NoiseGrainSize = 1; + this->NumberOfNoiseLevels = 256; + this->ImpulseNoiseProbability = 1.0; + this->ImpulseNoiseBackgroundValue = 0.0; + this->NoiseGeneratorSeed = 1; + + this->MaskOnSurface = 0; + this->MaskThreshold = 0.0; + this->MaskIntensity = 0.0; + this->MaskColor[0] = 0.5; + this->MaskColor[1] = 0.5; + this->MaskColor[2] = 0.5; + + this->CompositeStrategy = COMPOSITE_AUTO; +} + +//---------------------------------------------------------------------------- +vtkSurfaceLICInterface::~vtkSurfaceLICInterface() +{ + #if vtkSurfaceLICInterfaceDEBUG >= 1 + cerr << "=====vtkSurfaceLICInterface::~vtkSurfaceLICInterface" << endl; + #endif + this->ReleaseGraphicsResources(this->Internals->Context); + delete this->Internals; +} + +void vtkSurfaceLICInterface::ShallowCopy(vtkSurfaceLICInterface *m) +{ + this->SetNumberOfSteps(m->GetNumberOfSteps()); + this->SetStepSize(m->GetStepSize()); + this->SetEnhancedLIC(m->GetEnhancedLIC()); + this->SetGenerateNoiseTexture(m->GetGenerateNoiseTexture()); + this->SetNoiseType(m->GetNoiseType()); + this->SetNormalizeVectors(m->GetNormalizeVectors()); + this->SetNoiseTextureSize(m->GetNoiseTextureSize()); + this->SetNoiseGrainSize(m->GetNoiseGrainSize()); + this->SetMinNoiseValue(m->GetMinNoiseValue()); + this->SetMaxNoiseValue(m->GetMaxNoiseValue()); + this->SetNumberOfNoiseLevels(m->GetNumberOfNoiseLevels()); + this->SetImpulseNoiseProbability(m->GetImpulseNoiseProbability()); + this->SetImpulseNoiseBackgroundValue(m->GetImpulseNoiseBackgroundValue()); + this->SetNoiseGeneratorSeed(m->GetNoiseGeneratorSeed()); + this->SetEnhanceContrast(m->GetEnhanceContrast()); + this->SetLowLICContrastEnhancementFactor( + m->GetLowLICContrastEnhancementFactor()); + this->SetHighLICContrastEnhancementFactor( + m->GetHighLICContrastEnhancementFactor()); + this->SetLowColorContrastEnhancementFactor( + m->GetLowColorContrastEnhancementFactor()); + this->SetHighColorContrastEnhancementFactor( + m->GetHighColorContrastEnhancementFactor()); + this->SetAntiAlias(m->GetAntiAlias()); + this->SetColorMode(m->GetColorMode()); + this->SetLICIntensity(m->GetLICIntensity()); + this->SetMapModeBias(m->GetMapModeBias()); + this->SetMaskOnSurface(m->GetMaskOnSurface()); + this->SetMaskThreshold(m->GetMaskThreshold()); + this->SetMaskIntensity(m->GetMaskIntensity()); + this->SetMaskColor(m->GetMaskColor()); +} + +void vtkSurfaceLICInterface::UpdateCommunicator( + vtkRenderer *renderer, vtkActor *actor, vtkDataObject *input) +{ + // commented out as camera and data changes also + // require a communicator update, currently the + // test does not include these +// if (this->NeedToUpdateCommunicator()) + { + // create a communicator that contains only ranks + // that have visible data. In parallel this is a + // collective operation accross all ranks. In + // serial this is a no-op. + this->CreateCommunicator(renderer,actor, input); + } +} + +void vtkSurfaceLICInterface::PrepareForGeometry() +{ + // save the active fbo and its draw buffer + this->PrevDrawBuf = 0; + glGetIntegerv(GL_DRAW_BUFFER, &this->PrevDrawBuf); + + this->PrevFbo = 0; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &this->PrevFbo); + + // ------------------------------------------- render geometry, project vectors onto screen, etc + // setup our fbo + vtkFrameBufferObject2 *fbo = this->Internals->FBO; + fbo->SaveCurrentBindings(); + fbo->Bind(GL_FRAMEBUFFER); + fbo->AddDepthAttachment(GL_DRAW_FRAMEBUFFER, this->Internals->DepthImage); + fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 0U, this->Internals->GeometryImage); + fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 1U, this->Internals->VectorImage); + fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 2U, this->Internals->MaskVectorImage); + fbo->ActivateDrawBuffers(3); + vtkCheckFrameBufferStatusMacro(GL_FRAMEBUFFER); + + // clear internal color and depth buffers + // the LIC'er requires *all* fragments in the vector + // texture to be initialized to 0 + glDisable(GL_BLEND); + glEnable(GL_DEPTH_TEST); + glDisable(GL_SCISSOR_TEST); + glClearColor(0.0, 0.0, 0.0, 0.0); + glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT); +} + +void vtkSurfaceLICInterface::CompletedGeometry() +{ + vtkFrameBufferObject2 *fbo = this->Internals->FBO; + fbo->RemoveRenDepthAttachment(GL_DRAW_FRAMEBUFFER); + fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 0U); + fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 1U); + fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 2U); + fbo->DeactivateDrawBuffers(); + fbo->UnBind(GL_FRAMEBUFFER); + + #if vtkSurfaceLICInterfaceDEBUG >= 2 + vtkPainterCommunicator *comm = this->GetCommunicator(); + + vtkTextureIO::Write( + mpifn(comm,"slicp_geometry_image.vtm"), + this->Internals->GeometryImage, + this->Internals->BlockExts); + vtkTextureIO::Write( + mpifn(comm,"slicp_vector_image.vtm"), + this->Internals->VectorImage, + this->Internals->BlockExts); + vtkTextureIO::Write( + mpifn(comm,"slicp_mask_vector_image.vtm"), + this->Internals->MaskVectorImage, + this->Internals->BlockExts); + vtkTextureIO::Write( + mpifn(comm,"slicp_depth_image.vtm"), + this->Internals->DepthImage, + this->Internals->BlockExts); + #endif +} + + +void vtkSurfaceLICInterface::GatherVectors() +{ + vtkPixelExtent viewExt( + this->Internals->Viewsize[0], + this->Internals->Viewsize[1]); + + vtkPainterCommunicator *comm = this->GetCommunicator(); + + // get tight screen space bounds to reduce communication/computation + vtkPixelBufferObject *vecPBO = this->Internals->VectorImage->Download(); + void *pVecPBO = vecPBO->MapPackedBuffer(); + + this->Internals->GetPixelBounds( + (float*)pVecPBO, + this->Internals->Viewsize[0], + this->Internals->BlockExts); + + // initialize compositor + this->Internals->Compositor->Initialize( + viewExt, + this->Internals->BlockExts, + this->CompositeStrategy, + this->StepSize, + this->NumberOfSteps, + this->NormalizeVectors, + this->EnhancedLIC, + this->AntiAlias); + + if (comm->GetMPIInitialized()) + { + // parallel run + // need to use the communicator provided by the rendering engine + this->Internals->Compositor->SetCommunicator(comm); + + // build compositing program and set up the screen space decomp + // with guard pixels + int iErr = 0; + iErr = this->Internals->Compositor->BuildProgram((float*)pVecPBO); + if (iErr) + { + vtkErrorMacro("Failed to construct program, reason " << iErr); + } + + // composite vectors + vtkTextureObject *compositeVectors = this->Internals->CompositeVectorImage; + iErr = this->Internals->Compositor->Gather( + pVecPBO, + VTK_FLOAT, + 4, + compositeVectors); + if (iErr) + { + vtkErrorMacro("Failed to composite vectors, reason " << iErr); + } + + // composite mask vectors + vtkTextureObject *compositeMaskVectors = this->Internals->CompositeMaskVectorImage; + vtkPixelBufferObject *maskVecPBO = this->Internals->MaskVectorImage->Download(); + void *pMaskVecPBO = maskVecPBO->MapPackedBuffer(); + iErr = this->Internals->Compositor->Gather( + pMaskVecPBO, + VTK_FLOAT, + 4, + compositeMaskVectors); + if (iErr) + { + vtkErrorMacro("Failed to composite mask vectors, reason " << iErr); + } + maskVecPBO->UnmapPackedBuffer(); + maskVecPBO->Delete(); + + // restore the default communicator + this->Internals->Compositor->RestoreDefaultCommunicator(); + + #if vtkSurfaceLICInterfaceDEBUG >= 2 + vtkTextureIO::Write( + mpifn(comm,"slicp_new_vector_image.vtm"), + this->Internals->CompositeVectorImage, + this->Internals->Compositor->GetDisjointGuardExtents()); + + vtkTextureIO::Write( + mpifn(comm,"slicp_new_mask_vector_image.vtm"), + this->Internals->CompositeMaskVectorImage, + this->Internals->Compositor->GetDisjointGuardExtents()); + #endif + } + else + { + // serial run + // make the decomposition disjoint and add guard pixels + this->Internals->Compositor->InitializeCompositeExtents((float*)pVecPBO); + + // use the lic decomp from here on out, in serial we have this + // flexibility because we don't need to worry about ordered compositing + // or IceT's scissor boxes + this->Internals->BlockExts + = this->Internals->Compositor->GetCompositeExtents(); + + // pass through without compositing + this->Internals->CompositeVectorImage = this->Internals->VectorImage; + this->Internals->CompositeMaskVectorImage = this->Internals->MaskVectorImage; + } + + vecPBO->UnmapPackedBuffer(); + vecPBO->Delete(); +} + +void vtkSurfaceLICInterface::ApplyLIC() +{ + vtkPainterCommunicator *comm = this->GetCommunicator(); + + vtkPixelExtent viewExt( + this->Internals->Viewsize[0], + this->Internals->Viewsize[1]); + + #if vtkSurfaceLICInterfaceDEBUG >= 2 + ostringstream oss; + if ( this->GenerateNoiseTexture ) + { + const char *noiseType[3]={"unif","gauss","perl"}; + oss + << "slicp_noise_" + << noiseType[this->NoiseType] + << "_size_" << this->NoiseTextureSize + << "_grain_" << this->NoiseGrainSize + << "_minval_" << this->MinNoiseValue + << "_maxval_" << this->MaxNoiseValue + << "_nlevels_" << this->NumberOfNoiseLevels + << "_impulseprob_" << this->ImpulseNoiseProbability + << "_impulseprob_" << this->ImpulseNoiseBackgroundValue + << ".vtk"; + } + else + { + oss << "slicp_noise_default.vtk"; + } + vtkTextureIO::Write( + mpifn(comm, oss.str().c_str()), + this->Internals->NoiseImage); + #endif + + // TODO -- this means that the steps size is a function + // of aspect ratio which is pretty insane... + // convert from window units to texture units + // this isn't correct since there's no way to account + // for anisotropy in the trasnform to texture space + double tcScale[2] = { + 1.0/this->Internals->Viewsize[0], + 1.0/this->Internals->Viewsize[1]}; + + double stepSize + = this->StepSize*sqrt(tcScale[0]*tcScale[0]+tcScale[1]*tcScale[1]); + + stepSize = stepSize <= 0.0 ? 1.0e-10 : stepSize; + + // configure image lic + vtkLineIntegralConvolution2D *LICer = this->Internals->LICer; + + LICer->SetStepSize(stepSize); + LICer->SetNumberOfSteps(this->NumberOfSteps); + LICer->SetEnhancedLIC(this->EnhancedLIC); + switch (this->EnhanceContrast) + { + case ENHANCE_CONTRAST_LIC: + case ENHANCE_CONTRAST_BOTH: + LICer->SetEnhanceContrast(vtkLIC2D::ENHANCE_CONTRAST_ON); + break; + default: + LICer->SetEnhanceContrast(vtkLIC2D::ENHANCE_CONTRAST_OFF); + } + LICer->SetLowContrastEnhancementFactor(this->LowLICContrastEnhancementFactor); + LICer->SetHighContrastEnhancementFactor(this->HighLICContrastEnhancementFactor); + LICer->SetAntiAlias(this->AntiAlias); + LICer->SetComponentIds(0, 1); + LICer->SetNormalizeVectors(this->NormalizeVectors); + LICer->SetMaskThreshold(this->MaskThreshold); + LICer->SetCommunicator(comm); + + // loop over composited extents + const std::deque &compositeExts + = this->Internals->Compositor->GetCompositeExtents(); + + const std::deque &disjointGuardExts + = this->Internals->Compositor->GetDisjointGuardExtents(); + + this->Internals->LICImage.TakeReference( + LICer->Execute( + viewExt, // screen extent + disjointGuardExts, // disjoint extent of valid vectors + compositeExts, // disjoint extent where lic is needed + this->Internals->CompositeVectorImage, + this->Internals->CompositeMaskVectorImage, + this->Internals->NoiseImage)); + + if (!this->Internals->LICImage) + { + vtkErrorMacro("Failed to compute image LIC"); + return; + } + + #if vtkSurfaceLICInterfaceDEBUG >= 2 + vtkTextureIO::Write( + mpifn(comm,"slicp_lic.vtm"), + this->Internals->LICImage, + compositeExts); + #endif + + // ------------------------------------------- move from LIC decomp back to geometry decomp + if ( comm->GetMPIInitialized() + && (this->Internals->Compositor->GetStrategy()!=COMPOSITE_INPLACE ) ) + { + #ifdef vtkSurfaceLICMapperTIME + this->StartTimerEvent("vtkSurfaceLICMapper::ScatterLIC"); + #endif + + // parallel run + // need to use the communicator provided by the rendering engine + this->Internals->Compositor->SetCommunicator(comm); + + vtkPixelBufferObject *licPBO = this->Internals->LICImage->Download(); + void *pLicPBO = licPBO->MapPackedBuffer(); + vtkTextureObject *newLicImage = NULL; + int iErr = this->Internals->Compositor->Scatter(pLicPBO, VTK_FLOAT, 4, newLicImage); + if (iErr) + { + vtkErrorMacro("Failed to scatter lic"); + } + licPBO->UnmapPackedBuffer(); + licPBO->Delete(); + this->Internals->LICImage = NULL; + this->Internals->LICImage = newLicImage; + newLicImage->Delete(); + + // restore the default communicator + this->Internals->Compositor->RestoreDefaultCommunicator(); + + #ifdef vtkSurfaceLICMapperTIME + this->EndTimerEvent("vtkSurfaceLICMapper::ScatterLIC"); + #endif + #if vtkSurfaceLICMapperDEBUG >= 2 + vtkTextureIO::Write( + mpifn(comm,"slicp_new_lic.vtm"), + this->Internals->LICImage, + this->Internals->BlockExts); + #endif + } +} + +void vtkSurfaceLICInterface::CombineColorsAndLIC() +{ + vtkOpenGLRenderWindow *renWin = this->Internals->Context; + + vtkPainterCommunicator *comm = this->GetCommunicator(); + + vtkPixelExtent viewExt( + this->Internals->Viewsize[0], + this->Internals->Viewsize[1]); + + vtkFrameBufferObject2 *fbo = this->Internals->FBO; + fbo->SaveCurrentBindings(); + fbo->Bind(GL_FRAMEBUFFER); + fbo->InitializeViewport(this->Internals->Viewsize[0], this->Internals->Viewsize[1]); + fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 0U, this->Internals->RGBColorImage); + fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 1U, this->Internals->HSLColorImage); + fbo->ActivateDrawBuffers(2U); + vtkCheckFrameBufferStatusMacro(GL_FRAMEBUFFER); + + // clear the parts of the screen which we will modify + glEnable(GL_SCISSOR_TEST); + glClearColor(0.0, 0.0, 0.0, 0.0); + size_t nBlocks = this->Internals->BlockExts.size(); + for (size_t e=0; eInternals->BlockExts[e]; + ext.Grow(2); // halo for linear filtering + ext &= viewExt; + + unsigned int extSize[2]; + ext.Size(extSize); + + glScissor(ext[0], ext[2], extSize[0], extSize[1]); + glClear(GL_COLOR_BUFFER_BIT); + } + glDisable(GL_SCISSOR_TEST); + + this->Internals->VectorImage->Activate(); + this->Internals->GeometryImage->Activate(); + this->Internals->LICImage->Activate(); + + vtkShaderProgram *colorPass = this->Internals->ColorPass->Program; + renWin->GetShaderCache()->ReadyShaderProgram(colorPass); + colorPass->SetUniformi("texVectors", + this->Internals->VectorImage->GetTextureUnit()); + colorPass->SetUniformi("texGeomColors", + this->Internals->GeometryImage->GetTextureUnit()); + colorPass->SetUniformi("texLIC", + this->Internals->LICImage->GetTextureUnit()); + colorPass->SetUniformi("uScalarColorMode", this->ColorMode); + colorPass->SetUniformf("uLICIntensity", this->LICIntensity); + colorPass->SetUniformf("uMapBias", this->MapModeBias); + colorPass->SetUniformf("uMaskIntensity", this->MaskIntensity); + float fMaskColor[3]; + fMaskColor[0] = this->MaskColor[0]; + fMaskColor[1] = this->MaskColor[1]; + fMaskColor[2] = this->MaskColor[2]; + colorPass->SetUniform3f("uMaskColor", fMaskColor); + + for (size_t e=0; eInternals->RenderQuad(viewExt, this->Internals->BlockExts[e], + this->Internals->ColorPass); + } + + this->Internals->VectorImage->Deactivate(); + this->Internals->GeometryImage->Deactivate(); + this->Internals->LICImage->Deactivate(); + + // --------------------------------------------- color contrast enhance + if ( ( this->EnhanceContrast == ENHANCE_CONTRAST_COLOR ) + || ( this->EnhanceContrast == ENHANCE_CONTRAST_BOTH ) ) + { + #if vtkSurfaceLICInterfaceDEBUG >= 2 + vtkTextureIO::Write( + mpifn(comm,"slic_color_rgb_in.vtm"), + this->Internals->RGBColorImage, + this->Internals->BlockExts); + vtkTextureIO::Write( + mpifn(comm,"slic_color_hsl_in.vtm"), + this->Internals->HSLColorImage, + this->Internals->BlockExts); + #endif + + // find min/max lighness value for color contrast enhancement. + float LMin = VTK_FLOAT_MAX; + float LMax = -VTK_FLOAT_MAX; + float LMaxMinDiff = VTK_FLOAT_MAX; + + vtkSurfaceLICHelper::StreamingFindMinMax(fbo, this->Internals->BlockExts, LMin, LMax); + + if ( this->Internals->BlockExts.size() + && ((LMax <= LMin) || (LMin < 0.0f) || (LMax > 1.0f)) ) + { + vtkErrorMacro( + << comm->GetRank() + << ": Invalid range " << LMin << ", " << LMax + << " for color contrast enhancement"); + LMin = 0.0; + LMax = 1.0; + LMaxMinDiff = 1.0; + } + + // global collective reduction for parallel operation + this->GetGlobalMinMax(comm, LMin, LMax); + + // set M and m as a fraction of the range. + LMaxMinDiff = LMax-LMin; + LMin += LMaxMinDiff*this->LowColorContrastEnhancementFactor; + LMax -= LMaxMinDiff*this->HighColorContrastEnhancementFactor; + LMaxMinDiff = LMax-LMin; + + // normalize shader + fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 0U, this->Internals->RGBColorImage); + fbo->ActivateDrawBuffer(0U); + vtkCheckFrameBufferStatusMacro(GL_DRAW_FRAMEBUFFER); + + this->Internals->GeometryImage->Activate(); + this->Internals->HSLColorImage->Activate(); + this->Internals->LICImage->Activate(); + + vtkShaderProgram *colorEnhancePass = + this->Internals->ColorEnhancePass->Program; + renWin->GetShaderCache()->ReadyShaderProgram(colorEnhancePass); + colorEnhancePass->SetUniformi("texGeomColors", + this->Internals->GeometryImage->GetTextureUnit()); + colorEnhancePass->SetUniformi("texHSLColors", + this->Internals->HSLColorImage->GetTextureUnit()); + colorEnhancePass->SetUniformi("texLIC", + this->Internals->LICImage->GetTextureUnit()); + colorEnhancePass->SetUniformf("uLMin", LMin); + colorEnhancePass->SetUniformf("uLMaxMinDiff", LMaxMinDiff); + + for (size_t e=0; eInternals->RenderQuad(viewExt, this->Internals->BlockExts[e], + this->Internals->ColorEnhancePass); + } + + this->Internals->GeometryImage->Deactivate(); + this->Internals->HSLColorImage->Deactivate(); + this->Internals->LICImage->Deactivate(); + + fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 0U); + fbo->DeactivateDrawBuffers(); + } + else + { + fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 0U); + fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 1U); + fbo->DeactivateDrawBuffers(); + } + + fbo->UnBind(GL_FRAMEBUFFER); + + #if vtkSurfaceLICInterfaceDEBUG >= 2 + vtkTextureIO::Write( + mpifn(comm,"slicp_new_rgb.vtm"), + this->Internals->RGBColorImage, + this->Internals->BlockExts); + #endif +} + +void vtkSurfaceLICInterface::CopyToScreen() +{ + vtkOpenGLRenderWindow *renWin = this->Internals->Context; + + vtkPixelExtent viewExt( + this->Internals->Viewsize[0], + this->Internals->Viewsize[1]); + + glBindFramebuffer(GL_FRAMEBUFFER, this->PrevFbo); + glDrawBuffer(this->PrevDrawBuf); + vtkFrameBufferObject2::InitializeViewport( + this->Internals->Viewsize[0], + this->Internals->Viewsize[1]); + glEnable(GL_DEPTH_TEST); + + this->Internals->DepthImage->Activate(); + this->Internals->RGBColorImage->Activate(); + + vtkShaderProgram *copyPass = + this->Internals->CopyPass->Program; + renWin->GetShaderCache()->ReadyShaderProgram(copyPass); + copyPass->SetUniformi("texDepth", + this->Internals->DepthImage->GetTextureUnit()); + copyPass->SetUniformi("texRGBColors", + this->Internals->RGBColorImage->GetTextureUnit()); + + size_t nBlocks = this->Internals->BlockExts.size(); + for (size_t e=0; eInternals->RenderQuad(viewExt, this->Internals->BlockExts[e], + this->Internals->CopyPass); + } + + this->Internals->DepthImage->Deactivate(); + this->Internals->RGBColorImage->Deactivate(); + + #ifdef vtkSurfaceLICMapperTIME + this->EndTimerEvent("vtkSurfaceLICMapper::DepthCopy"); + #endif + + // + this->Internals->Updated(); +} + +//---------------------------------------------------------------------------- +void vtkSurfaceLICInterface::ReleaseGraphicsResources(vtkWindow* win) +{ + this->Internals->ReleaseGraphicsResources(win); + this->Internals->Context = NULL; +} + +//---------------------------------------------------------------------------- +#define vtkSetMonitoredParameterMacro(_name, _type, _code) \ +void vtkSurfaceLICInterface::Set##_name (_type val) \ +{ \ + if (val == this->_name) \ + { \ + return; \ + } \ + _code \ + this->_name = val; \ + this->Modified(); \ +} +// lic +vtkSetMonitoredParameterMacro( + GenerateNoiseTexture, + int, + this->Internals->Noise = NULL; + this->Internals->NoiseImage = NULL;) + +vtkSetMonitoredParameterMacro( + NoiseType, + int, + this->Internals->Noise = NULL; + this->Internals->NoiseImage = NULL;) + +vtkSetMonitoredParameterMacro( + NoiseTextureSize, + int, + this->Internals->Noise = NULL; + this->Internals->NoiseImage = NULL;) + +vtkSetMonitoredParameterMacro( + NoiseGrainSize, + int, + this->Internals->Noise = NULL; + this->Internals->NoiseImage = NULL;) + +vtkSetMonitoredParameterMacro( + MinNoiseValue, + double, + val = val < 0.0 ? 0.0 : val; + val = val > 1.0 ? 1.0 : val; + this->Internals->Noise = NULL; + this->Internals->NoiseImage = NULL;) + +vtkSetMonitoredParameterMacro( + MaxNoiseValue, + double, + val = val < 0.0 ? 0.0 : val; + val = val > 1.0 ? 1.0 : val; + this->Internals->Noise = NULL; + this->Internals->NoiseImage = NULL;) + +vtkSetMonitoredParameterMacro( + NumberOfNoiseLevels, + int, + this->Internals->Noise = NULL; + this->Internals->NoiseImage = NULL;) + +vtkSetMonitoredParameterMacro( + ImpulseNoiseProbability, + double, + val = val < 0.0 ? 0.0 : val; + val = val > 1.0 ? 1.0 : val; + this->Internals->Noise = NULL; + this->Internals->NoiseImage = NULL;) + +vtkSetMonitoredParameterMacro( + ImpulseNoiseBackgroundValue, + double, + val = val < 0.0 ? 0.0 : val; + val = val > 1.0 ? 1.0 : val; + this->Internals->Noise = NULL; + this->Internals->NoiseImage = NULL;) + +vtkSetMonitoredParameterMacro( + NoiseGeneratorSeed, + int, + this->Internals->Noise = NULL; + this->Internals->NoiseImage = NULL;) + +// compositor +vtkSetMonitoredParameterMacro( + CompositeStrategy, + int,) + +// lic/compositor +vtkSetMonitoredParameterMacro( + NumberOfSteps, + int,) + +vtkSetMonitoredParameterMacro( + StepSize, + double,) + +vtkSetMonitoredParameterMacro( + NormalizeVectors, + int, + val = val < 0 ? 0 : val; + val = val > 1 ? 1 : val;) + +vtkSetMonitoredParameterMacro( + MaskThreshold, + double,) + +vtkSetMonitoredParameterMacro( + EnhancedLIC, + int,) + +// lic +vtkSetMonitoredParameterMacro( + LowLICContrastEnhancementFactor, + double, + val = val < 0.0 ? 0.0 : val; + val = val > 1.0 ? 1.0 : val;) + +vtkSetMonitoredParameterMacro( + HighLICContrastEnhancementFactor, + double, + val = val < 0.0 ? 0.0 : val; + val = val > 1.0 ? 1.0 : val;) + +vtkSetMonitoredParameterMacro( + AntiAlias, + int, + val = val < 0 ? 0 : val;) + +// geometry +vtkSetMonitoredParameterMacro( + MaskOnSurface, + int, + val = val < 0 ? 0 : val; + val = val > 1 ? 1 : val;) + +// colors +vtkSetMonitoredParameterMacro( + ColorMode, + int,) + +vtkSetMonitoredParameterMacro( + LICIntensity, + double, + val = val < 0.0 ? 0.0 : val; + val = val > 1.0 ? 1.0 : val;) + +vtkSetMonitoredParameterMacro( + MaskIntensity, + double, + val = val < 0.0 ? 0.0 : val; + val = val > 1.0 ? 1.0 : val;) + +vtkSetMonitoredParameterMacro( + MapModeBias, + double, + val = val <-1.0 ? -1.0 : val; + val = val > 1.0 ? 1.0 : val;) + +vtkSetMonitoredParameterMacro( + LowColorContrastEnhancementFactor, + double, + val = val < 0.0 ? 0.0 : val; + val = val > 1.0 ? 1.0 : val;) + +vtkSetMonitoredParameterMacro( + HighColorContrastEnhancementFactor, + double, + val = val < 0.0 ? 0.0 : val; + val = val > 1.0 ? 1.0 : val;) + +//---------------------------------------------------------------------------- +void vtkSurfaceLICInterface::SetMaskColor(double *val) +{ + double rgb[3]; + for (int q=0; q<3; ++q) + { + rgb[q] = val[q]; + rgb[q] = rgb[q] < 0.0 ? 0.0 : rgb[q]; + rgb[q] = rgb[q] > 1.0 ? 1.0 : rgb[q]; + } + if ( (rgb[0] == this->MaskColor[0]) + && (rgb[1] == this->MaskColor[1]) + && (rgb[2] == this->MaskColor[2]) ) + { + return; + } + for (int q=0; q<3; ++q) + { + this->MaskColor[q] = rgb[q]; + } + this->Modified(); +} + +//---------------------------------------------------------------------------- +void vtkSurfaceLICInterface::SetEnhanceContrast(int val) +{ + val = val < ENHANCE_CONTRAST_OFF ? ENHANCE_CONTRAST_OFF : val; + val = val > ENHANCE_CONTRAST_BOTH ? ENHANCE_CONTRAST_BOTH : val; + if (val == this->EnhanceContrast) + { + return; + } + + this->EnhanceContrast = val; + this->Modified(); +} + +//---------------------------------------------------------------------------- +void vtkSurfaceLICInterface::SetNoiseDataSet(vtkImageData *data) +{ + if (data == this->Internals->Noise) + { + return; + } + this->Internals->Noise = data; + this->Internals->NoiseImage = NULL; + this->Modified(); +} + +//---------------------------------------------------------------------------- +vtkImageData *vtkSurfaceLICInterface::GetNoiseDataSet() +{ + if (this->Internals->Noise == NULL) + { + vtkImageData *noise = NULL; + if ( this->GenerateNoiseTexture ) + { + // report potential issues + if ( this->NoiseGrainSize >= this->NoiseTextureSize ) + { + vtkErrorMacro( + "NoiseGrainSize must be smaller than NoiseTextureSize"); + } + if ( this->MinNoiseValue >= this->MaxNoiseValue ) + { + vtkErrorMacro( + "MinNoiseValue must be smaller than MaxNoiseValue"); + } + if ( (this->ImpulseNoiseProbability == 1.0) + && (this->NumberOfNoiseLevels < 2) ) + { + vtkErrorMacro( + "NumberOfNoiseLevels must be greater than 1 " + "when not generating impulse noise"); + } + + // generate a custom noise texture based on the + // current settings. + int noiseTextureSize = this->NoiseTextureSize; + int noiseGrainSize = this->NoiseGrainSize; + vtkLICRandomNoise2D noiseGen; + float *noiseValues = noiseGen.Generate( + this->NoiseType, + noiseTextureSize, + noiseGrainSize, + static_cast(this->MinNoiseValue), + static_cast(this->MaxNoiseValue), + this->NumberOfNoiseLevels, + this->ImpulseNoiseProbability, + static_cast(this->ImpulseNoiseBackgroundValue), + this->NoiseGeneratorSeed); + if ( noiseValues == NULL ) + { + vtkErrorMacro("Failed to generate noise."); + } + + vtkFloatArray *noiseArray = vtkFloatArray::New(); + noiseArray->SetNumberOfComponents(2); + noiseArray->SetName("noise"); + vtkIdType arraySize = 2*noiseTextureSize*noiseTextureSize; + noiseArray->SetArray(noiseValues, arraySize, 0); + + noise = vtkImageData::New(); + noise->SetSpacing(1.0, 1.0, 1.0); + noise->SetOrigin(0.0, 0.0, 0.0); + noise->SetDimensions(noiseTextureSize, noiseTextureSize, 1); + noise->GetPointData()->SetScalars(noiseArray); + + noiseArray->Delete(); + } + else + { + // load a predefined noise texture. + noise = vtkLICRandomNoise2D::GetNoiseResource(); + } + + this->Internals->Noise = noise; + this->Internals->NoiseImage = NULL; + noise->Delete(); + noise = NULL; + } + + return this->Internals->Noise; +} + +//---------------------------------------------------------------------------- +void vtkSurfaceLICInterface::UpdateNoiseImage(vtkRenderWindow *renWin) +{ + vtkOpenGLRenderWindow *rw = vtkOpenGLRenderWindow::SafeDownCast(renWin); + vtkImageData *noiseDataSet = this->GetNoiseDataSet(); + + int ext[6]; + noiseDataSet->GetExtent(ext); + unsigned int dataWidth = ext[1]-ext[0]+1; + unsigned int dataHeight = ext[3]-ext[2]+1; + + vtkDataArray *noiseArray = noiseDataSet->GetPointData()->GetScalars(); + int dataType = noiseArray->GetDataType(); + void *data = noiseArray->GetVoidPointer(0); + int dataComps = noiseArray->GetNumberOfComponents(); + unsigned int dataSize = noiseArray->GetNumberOfTuples()*dataComps; + + vtkPixelBufferObject *pbo = vtkPixelBufferObject::New(); + pbo->SetContext(renWin); + pbo->Upload1D(dataType, data, dataSize, 1, 0); + + vtkTextureObject *tex = vtkTextureObject::New(); + tex->SetContext(rw); + tex->SetBaseLevel(0); + tex->SetMaxLevel(0); + tex->SetWrapS(vtkTextureObject::Repeat); + tex->SetWrapT(vtkTextureObject::Repeat); + tex->SetMinificationFilter(vtkTextureObject::Nearest); + tex->SetMagnificationFilter(vtkTextureObject::Nearest); + tex->Create2D(dataWidth, dataHeight, dataComps, pbo, false); + tex->SetAutoParameters(0); + pbo->Delete(); + + this->Internals->NoiseImage = tex; + tex->Delete(); +} + + +//---------------------------------------------------------------------------- +bool vtkSurfaceLICInterface::IsSupported(vtkRenderWindow *renWin) +{ + vtkOpenGLRenderWindow *context + = vtkOpenGLRenderWindow::SafeDownCast(renWin); + + return vtkSurfaceLICHelper::IsSupported(context); +} + +//---------------------------------------------------------------------------- +bool vtkSurfaceLICInterface::CanRenderSurfaceLIC(vtkActor *actor) +{ + // check the render context for GL fetaure support + // note this also handles non-opengl render window + if ( this->Internals->ContextNeedsUpdate + && !vtkSurfaceLICInterface::IsSupported(this->Internals->Context) ) + { + vtkErrorMacro("SurfaceLIC is not supported"); + return false; + } + + bool canRender = false; + + int rep = actor->GetProperty()->GetRepresentation(); + + if (this->Enable && + this->Internals->HasVectors + && (rep == VTK_SURFACE)) + { + canRender = true; + } + + #if vtkSurfaceLICInterfaceDEBUG >= 1 + cerr + << this->Internals->Communicator->GetWorldRank() + << " CanRender " << canRender << endl; + #endif + + return canRender; +} + +namespace { + void BuildAShader(vtkOpenGLRenderWindow *renWin, + vtkOpenGLHelper **cbor, const char * vert, + const char *frag) + { + if (*cbor == NULL) + { + *cbor = new vtkOpenGLHelper; + std::string GSSource; + (*cbor)->Program = + renWin->GetShaderCache()->ReadyShaderProgram(vert, + frag, + GSSource.c_str()); + } + else + { + renWin->GetShaderCache()->ReadyShaderProgram((*cbor)->Program); + } + } +} + +//---------------------------------------------------------------------------- +void vtkSurfaceLICInterface::InitializeResources() +{ + bool initialized = true; + + // noise image + if (!this->Internals->NoiseImage) + { + initialized = false; + + this->UpdateNoiseImage(this->Internals->Context); + } + + // compositer for parallel operation + if (!this->Internals->Compositor) + { + this->Internals->UpdateAll(); + vtkSurfaceLICComposite *compositor = vtkSurfaceLICComposite::New(); + compositor->SetContext(this->Internals->Context); + this->Internals->Compositor = compositor; + compositor->Delete(); + } + + // image LIC + if (!this->Internals->LICer) + { + initialized = false; + + vtkLineIntegralConvolution2D *LICer = vtkLineIntegralConvolution2D::New(); + LICer->SetContext(this->Internals->Context); + this->Internals->LICer = LICer; + LICer->Delete(); + } + + // frame buffers + if (!this->Internals->FBO) + { + initialized = false; + + vtkFrameBufferObject2 * fbo = vtkFrameBufferObject2::New(); + fbo->SetContext(this->Internals->Context); + this->Internals->FBO = fbo; + fbo->Delete(); + } + + // load shader codes + vtkOpenGLRenderWindow *renWin = this->Internals->Context; + + if (!this->Internals->ColorPass) + { + initialized = false; + BuildAShader(renWin, &this->Internals->ColorPass, + vtkTextureObjectVS, vtkSurfaceLICInterface_SC); + } + + if (!this->Internals->ColorEnhancePass) + { + initialized = false; + BuildAShader(renWin, &this->Internals->ColorEnhancePass, + vtkTextureObjectVS, vtkSurfaceLICInterface_CE); + } + + if (!this->Internals->CopyPass) + { + initialized = false; + BuildAShader(renWin, &this->Internals->CopyPass, + vtkTextureObjectVS, vtkSurfaceLICInterface_DCpy); + } + + // if any of the above were not already initialized + // then execute all stages + if (!initialized) + { + this->Internals->UpdateAll(); + } +} + +//---------------------------------------------------------------------------- +bool vtkSurfaceLICInterface::NeedToUpdateCommunicator() +{ + // no comm or externally modfied paramters + if ( this->Internals->CommunicatorNeedsUpdate + || this->Internals->ContextNeedsUpdate + || !this->Internals->Communicator + || this->AlwaysUpdate ) + { + this->Internals->CommunicatorNeedsUpdate = true; + this->Internals->UpdateAll(); + } + + #if vtkSurfaceLICInterfaceDEBUG >= 1 + cerr + << this->Internals->Communicator->GetWorldRank() + << " NeedToUpdateCommunicator " + << this->Internals->CommunicatorNeedsUpdate << endl; + #endif + + return this->Internals->CommunicatorNeedsUpdate; +} + +//---------------------------------------------------------------------------- +void vtkSurfaceLICInterface::ValidateContext(vtkRenderer *renderer) +{ + bool modified = false; + + vtkOpenGLRenderWindow *context + = vtkOpenGLRenderWindow::SafeDownCast(renderer->GetRenderWindow()); + + // context changed + if (this->Internals->Context != context) + { + modified = true; + if (this->Internals->Context) + { + this->ReleaseGraphicsResources(this->Internals->Context); + } + this->Internals->Context = context; + } + + // viewport size changed + int viewsize[2]; + renderer->GetTiledSize(&viewsize[0], &viewsize[1]); + if ( this->Internals->Viewsize[0] != viewsize[0] + || this->Internals->Viewsize[1] != viewsize[1] ) + { + modified = true; + + // udpate view size + this->Internals->Viewsize[0] = viewsize[0]; + this->Internals->Viewsize[1] = viewsize[1]; + + // resize textures + this->Internals->ClearTextures(); + this->Internals->AllocateTextures(context, viewsize); + } + + // if anything changed execute all stages + if (modified) + { + this->Internals->UpdateAll(); + } + + #if vtkSurfaceLICInterfaceDEBUG >= 1 + cerr + << this->Internals->Communicator->GetWorldRank() + << " NeedToUpdatContext " << modified << endl; + #endif +} + +void vtkSurfaceLICInterface::SetHasVectors(bool v) +{ + this->Internals->HasVectors = v; +} + +bool vtkSurfaceLICInterface::GetHasVectors() +{ + return this->Internals->HasVectors; +} + +//---------------------------------------------------------------------------- +vtkPainterCommunicator *vtkSurfaceLICInterface::GetCommunicator() +{ + return this->Internals->Communicator; +} + +//---------------------------------------------------------------------------- +vtkPainterCommunicator *vtkSurfaceLICInterface::CreateCommunicator(int) +{ + return new vtkPainterCommunicator; +} + +//---------------------------------------------------------------------------- +void vtkSurfaceLICInterface::CreateCommunicator( + vtkRenderer *ren, + vtkActor *act, + vtkDataObject *input) +{ + // compute screen space pixel extent of local blocks and + // union of local blocks. only blocks that pass view frustum + // visibility test are used in the computation. + this->Internals->DataSetExt.Clear(); + this->Internals->BlockExts.clear(); + + int includeRank = this->Internals->ProjectBounds( + ren, act, input, + this->Internals->Viewsize, + this->Internals->DataSetExt, + this->Internals->BlockExts); + + delete this->Internals->Communicator; + this->Internals->Communicator = this->CreateCommunicator(includeRank); + + #if vtkSurfaceLICInterfaceDEBUG >= 1 + cerr + << this->Internals->Communicator->GetWorldRank() + << " is rendering " << includeRank << endl; + #endif +} + +//---------------------------------------------------------------------------- +void vtkSurfaceLICInterface::SetUpdateAll() +{ + this->Internals->UpdateAll(); +} + +//---------------------------------------------------------------------------- +void vtkSurfaceLICInterface::PrintSelf(ostream & os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); + os + << indent << "NumberOfSteps=" << this->NumberOfSteps << endl + << indent << "StepSize=" << this->StepSize << endl + << indent << "NormalizeVectors=" << this->NormalizeVectors << endl + << indent << "EnhancedLIC=" << this->EnhancedLIC << endl + << indent << "EnhanceContrast=" << this->EnhanceContrast << endl + << indent << "LowLICContrastEnhancementFactor=" << this->LowLICContrastEnhancementFactor << endl + << indent << "HighLICContrastEnhancementFactor=" << this->HighLICContrastEnhancementFactor << endl + << indent << "LowColorContrastEnhancementFactor=" << this->LowColorContrastEnhancementFactor << endl + << indent << "HighColorContrastEnhancementFactor=" << this->HighColorContrastEnhancementFactor << endl + << indent << "AntiAlias=" << this->AntiAlias << endl + << indent << "MaskOnSurface=" << this->MaskOnSurface << endl + << indent << "MaskThreshold=" << this->MaskThreshold << endl + << indent << "MaskIntensity=" << this->MaskIntensity << endl + << indent << "MaskColor=" << this->MaskColor[0] << ", " << this->MaskColor[1] << ", " << this->MaskColor[2] << endl + << indent << "ColorMode=" << this->ColorMode << endl + << indent << "LICIntensity=" << this->LICIntensity << endl + << indent << "MapModeBias=" << this->MapModeBias << endl + << indent << "GenerateNoiseTexture=" << this->GenerateNoiseTexture << endl + << indent << "NoiseType=" << this->NoiseType << endl + << indent << "NoiseTextureSize=" << this->NoiseTextureSize << endl + << indent << "NoiseGrainSize=" << this->NoiseGrainSize << endl + << indent << "MinNoiseValue=" << this->MinNoiseValue << endl + << indent << "MaxNoiseValue=" << this->MaxNoiseValue << endl + << indent << "NumberOfNoiseLevels=" << this->NumberOfNoiseLevels << endl + << indent << "ImpulseNoiseProbablity=" << this->ImpulseNoiseProbability << endl + << indent << "ImpulseNoiseBackgroundValue=" << this->ImpulseNoiseBackgroundValue << endl + << indent << "NoiseGeneratorSeed=" << this->NoiseGeneratorSeed << endl + << indent << "AlwaysUpdate=" << this->AlwaysUpdate << endl + << indent << "CompositeStrategy=" << this->CompositeStrategy << endl; +} diff --git a/Rendering/LICOpenGL2/vtkSurfaceLICInterface.h b/Rendering/LICOpenGL2/vtkSurfaceLICInterface.h new file mode 100644 index 00000000000..ab73087b22c --- /dev/null +++ b/Rendering/LICOpenGL2/vtkSurfaceLICInterface.h @@ -0,0 +1,500 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkSurfaceLICMapper.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkSurfaceLICInterface - public API for surface lic parameters +// arbitrary geometry. +// +// .SECTION Description +// vtkSurfaceLICInterface performs LIC on the surface of arbitrary +// geometry. Point vectors are used as the vector field for generating the LIC. +// The implementation was originallu based on "Image Space Based Visualization +// on Unsteady Flow on Surfaces" by Laramee, Jobard and Hauser appeared in +// proceedings of IEEE Visualization '03, pages 131-138. +// +// Internal pipeline: +//
+// noise
+//     |
+//     [ PROJ (GAT) (COMP) LIC2D (SCAT) SHADE (CCE) DEP]
+//     |                                               |
+// vectors                                         surface LIC
+// 
+// PROj - prject vectors onto surface +// GAT - gather data for compositing and guard pixel generation (parallel only) +// COMP - composite gathered data +// LIC2D - line intengral convolution, see vtkLineIntegralConvolution2D. +// SCAT - scatter result (parallel only, not all compositors use it) +// SHADE - combine LIC and scalar colors +// CCE - color contrast enhancement (optional) +// DEP - depth test and copy to back buffer +// +// The result of each stage is cached in a texture so that during interaction +// a stage may be skipped if the user has not modified its paramters or input +// data. +// +// The parallel parts of algorithm are implemented in vtkPSurfaceLICInterface. +// Note that for MPI enabled builds this class will be automatically created +// by the object factory. +// +// .SECTION See also +// vtkLineIntegralConvolution2D +#ifndef vtkSurfaceLICInterface_h +#define vtkSurfaceLICInterface_h + +#include "vtkRenderingLICOpenGL2Module.h" // For export macro +#include "vtkOpenGLPolyDataMapper.h" + +class vtkRenderWindow; +class vtkRenderer; +class vtkActor; +class vtkImageData; +class vtkDataObject; +class vtkDataArray; +class vtkPainterCommunicator; +class vtkSurfaceLICHelper; + +class VTKRENDERINGLICOPENGL2_EXPORT vtkSurfaceLICInterface : public vtkObject +{ +public: + static vtkSurfaceLICInterface* New(); + vtkTypeMacro(vtkSurfaceLICInterface, vtkObject); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Get/Set the number of integration steps in each direction. + void SetNumberOfSteps(int val); + vtkGetMacro(NumberOfSteps, int); + + // Description: + // Get/Set the step size (in pixels). + void SetStepSize(double val); + vtkGetMacro(StepSize, double); + + // Description: + // Normalize vectors during integration. When set(the default) the + // input vector field is normalized during integration, and each + // integration occurs over the same arclength. When not set each + // integration occurs over an arc length proportional to the field + // magnitude as is customary in traditional numerical methods. See, + // "Imaging Vector Fields Using Line Integral Convolution" for an + // axample where normalization is used. See, "Image Space Based + // Visualization of Unsteady Flow on Surfaces" for an example + // of where no normalization is used. + void SetNormalizeVectors(int val); + vtkBooleanMacro(NormalizeVectors, int); + vtkGetMacro(NormalizeVectors, int); + + // Description: + // When set MaskOnSurface computes |V| for use in the fragment masking + // tests on the surface. When not set the original un-projected + // un-transformed |V| is used. + void SetMaskOnSurface(int val); + vtkBooleanMacro(MaskOnSurface, int); + vtkGetMacro(MaskOnSurface, int); + + // Description: + // The MaskThreshold controls the rendering of fragments in stagnant + // regions of flow. // In these regions LIC noise texture will be masked, + // where |V| < MaskThreshold is satisifed. The masking process blends a + // the MaskColor with the scalar color of the surface proportional to + // MaskIntesnsity. See MaskIntensity for more information on the blending + // algorithm. This blending allows one control over the masking process + // so that masked fragments may be: highlighted (by setting a unique + // mask color and mask intensity > 0), made invisible with and without + // passing the un-convolved noise texture (by setting mask intensity 0), + // made to blend into the LIC. + // + // MaskThreshold units are in the original vector space. Note that the + // threshold can be applied to the original vector field or to the surface + // projected vector field. See MaskOnSurface. + void SetMaskThreshold(double val); + vtkGetMacro(MaskThreshold, double); + + // Description: + // The MaskColor is used on masked fragments. The default of (0.5, 0.5, 0.5) + // makes the masked fragments look similar to the LIC'd fragments. The mask + // color is applied only when MaskIntensity > 0. + void SetMaskColor(double *val); + void SetMaskColor(double r, double g, double b) + { double rgb[3]={r,g,b}; this->SetMaskColor(rgb); } + vtkGetVector3Macro(MaskColor, double); + + // Description: + // The MaskIntensity controls the blending of the mask color and the geometry + // color. The color of masked fragments is given by: + // + // c = maskColor * maskIntensity + geomColor * (1 - maskIntensity) + // + // The default value of 0.0 results in the geometry color being used. + void SetMaskIntensity(double val); + vtkGetMacro(MaskIntensity, double); + + // Description: + // EnhancedLIC mean compute the LIC twice with the second pass using + // the edge-enhanced result of the first pass as a noise texture. Edge + // enhancedment is made by a simple Laplace convolution. + void SetEnhancedLIC(int val); + vtkGetMacro(EnhancedLIC, int); + vtkBooleanMacro(EnhancedLIC, int); + + // Description: + // Enable/Disable contrast and dynamic range correction stages. Contrast + // enhancement can be enabled during LIC computations (See + // vtkLineINtegralComvolution2D) and after the scalar colors have been + // combined with the LIC. + // + // The best appraoch for using this feature is to enable LIC enhancement, + // and only if the image is to dark or dull enable COLOR enhancement. + // + // Both stages are implemented by a histogram stretching algorithm. During + // LIC stages the contrast enhancement is applied to gray scale LIC image. + // During the scalar coloring stage the contrast enhancement is applied to + // the lightness channel of the color image in HSL color space. The + // histogram stretching is implemented as follows: + // + // L = (L-m)/(M-m) + // + // where, L is the fragment intensity/lightness, m is the intensity/lightness + // to map to 0, M is the intensity/lightness to map to 1. The default values + // of m and M are the min and max taken over all fragments. + // + // This increase the dynamic range and contrast in the LIC'd image, both of + // which are natuarly attenuated by the convolution proccess. + // + // Values + // + // ENHANCE_CONTRAST_OFF -- don't enhance LIC or scalar colors + // ENHANCE_CONTRAST_LIC -- enhance in LIC high-pass input and output + // ENHANCE_CONTRAST_COLOR -- enhance after scalars are combined with LIC + // ENHANCE_CONTRAST_BOTH -- enhance in LIC stages and after scalar colors + // + // This feature is disabled by default. + enum { + ENHANCE_CONTRAST_OFF=0, + ENHANCE_CONTRAST_LIC=1, + ENHANCE_CONTRAST_COLOR=3, + ENHANCE_CONTRAST_BOTH=4 + }; + void SetEnhanceContrast(int val); + vtkGetMacro(EnhanceContrast, int); + + // Description: + // This feature is used to fine tune the contrast enhancement. There are two + // modes AUTOMATIC and MANUAL.In AUTOMATIC mode values are provided indicating + // the fraction of the range to adjust M and m by, during contrast enahncement + // histogram stretching. M and m are the intensity/lightness values that map + // to 1 and 0. (see EnhanceContrast for an explanation of the mapping + // procedure). m and M are computed using the factors as follows: + // + // m = min(C) + mFactor * (max(C) - min(C)) + // M = max(C) - MFactor * (max(C) - min(C)) + // + // the default values for mFactor and MFactor are 0 which result in + // m = min(C), M = max(C), taken over the entire image. Modifying mFactor and + // MFactor above or below zero provide control over the saturation/ + // de-saturation during contrast enhancement. + vtkGetMacro(LowLICContrastEnhancementFactor, double); + vtkGetMacro(HighLICContrastEnhancementFactor, double); + void SetLowLICContrastEnhancementFactor(double val); + void SetHighLICContrastEnhancementFactor(double val); + // + vtkGetMacro(LowColorContrastEnhancementFactor, double); + vtkGetMacro(HighColorContrastEnhancementFactor, double); + void SetLowColorContrastEnhancementFactor(double val); + void SetHighColorContrastEnhancementFactor(double val); + + // Description: + // Enable/Disable the anti-aliasing pass. This optional pass (disabled by + // default) can be enabled to reduce jagged patterns in the final LIC image. + // Values greater than 0 control the number of iterations, 1 is typically + // sufficient. + void SetAntiAlias(int val); + vtkBooleanMacro(AntiAlias, int); + vtkGetMacro(AntiAlias, int); + + // Description: + // Set/Get the color mode. The color mode controls how scalar colors are + // combined with the LIC in the final image. The BLEND mode combines scalar + // colors with LIC intensities with proportional blending controled by the + // LICIntensity parameter. The MAP mode combines scalar colors with LIC, + // by multiplication the HSL represntation of color's lightness. + // + // The default is COLOR_MODE_BLEND. + enum { + COLOR_MODE_BLEND=0, + COLOR_MODE_MAP + }; + void SetColorMode(int val); + vtkGetMacro(ColorMode, int); + + // Description: + // Factor used when blend mode is set to COLOR_MODE_BLEND. This controls the + // contribution of the LIC in the final output image as follows: + // + // c = LIC * LICIntensity + scalar * (1 - LICIntensity); + // + // 0.0 produces same result as disabling LIC altogether, while 1.0 implies + // show LIC result alone. + void SetLICIntensity(double val); + vtkGetMacro(LICIntensity, double); + + // Description: + // Factor used when blend mode is set to COLOR_MODE_MAP. This adds a bias to + // the LIC image. The purpose of this is to adjust the brightness when a + // brighter image is desired. The default of 0.0 results in no change. Values + // gretaer than 0.0 will brighten the image while values less than 0.0 darken + // the image. + void SetMapModeBias(double val); + vtkGetMacro(MapModeBias, double); + + // Description: + // Set the data containing a noise array as active scalars. Active scalars + // array will be converted into a texture for use as noise in the LIC process. + // Noise datasets are expected to be gray scale. + void SetNoiseDataSet(vtkImageData *data); + vtkImageData *GetNoiseDataSet(); + + // Description: + // Set/Get the noise texture source. When not set the default 200x200 white + // noise texture is used (see VTKData/Data/Data/noise.png). When set a noise + // texture is generated based on the following parameters: + // + // NoiseType - select noise type. Gaussian, Uniform, etc + // NoiseTextureSize - number of pixels in square noise texture(side) + // NoiseGrainSize - number of pixels each noise value spans(side) + // MinNoiseValue - minimum noise color >=0 && < MaxNoiseValue + // MaxNoiseValue - maximum noise color <=1 ** > MinNoiseValue + // NumberOfNoiseLevels - number of discrete noise colors + // ImpulseNoiseProbability - impulse noise is generated when < 1 + // ImpulseNoiseBackgroundValue - the background color for untouched pixels + // NoiseGeneratorSeed - seed the random number generators + // + // Changing the noise texture gives one greater control over the look of the + // final image. The default is 0 which results in the use of a static 200x200 + // Gaussian noise texture. See VTKData/Data/Data/noise.png. + void SetGenerateNoiseTexture(int shouldGenerate); + vtkGetMacro(GenerateNoiseTexture, int); + + // Description: + // Select the statistical distribution of randomly generated noise values. + // With uniform noise there is greater control over the range of values + // in the noise texture. The Default is NOISE_TYPE_GAUSSIAN. + enum { + NOISE_TYPE_UNIFORM=0, + NOISE_TYPE_GAUSSIAN=1, + NOISE_TYPE_PERLIN=2 + }; + void SetNoiseType(int type); + vtkGetMacro(NoiseType, int); + + // Description: + // Set/Get the side length in pixels of the noise texture. The texture will + // be length^2 pixels in area. + void SetNoiseTextureSize(int length); + vtkGetMacro(NoiseTextureSize, int); + + // Description: + // Each noise value will be length^2 pixels in area. + void SetNoiseGrainSize(int val); + vtkGetMacro(NoiseGrainSize, int); + + // Description: + // Set/Get the minimum and mximum gray scale values that the generated noise + // can take on. The generated noise will be in the range of MinNoiseValue to + // MaxNoiseValue. Values are clamped within 0 to 1. MinNoiseValue must be + // less than MaxNoiseValue. + void SetMinNoiseValue(double val); + void SetMaxNoiseValue(double val); + vtkGetMacro(MinNoiseValue, double); + vtkGetMacro(MaxNoiseValue, double); + + // Description: + // Set/Get the number of discrete values a noise pixel may take on. Default + // 1024. + void SetNumberOfNoiseLevels(int val); + vtkGetMacro(NumberOfNoiseLevels, int); + + // Description: + // Control the density of of the noise. A value of 1.0 produces uniform random + // noise while values < 1.0 produce impulse noise with the given probabilty. + void SetImpulseNoiseProbability(double val); + vtkGetMacro(ImpulseNoiseProbability, double); + + // Description: + // The color to use for untouched pixels when impulse noise probability < 1. + void SetImpulseNoiseBackgroundValue(double val); + vtkGetMacro(ImpulseNoiseBackgroundValue, double); + + // Description: + // Set/Get the seed value used by the random number generator. + void SetNoiseGeneratorSeed(int val); + vtkGetMacro(NoiseGeneratorSeed, int); + + // Description: + // Control the screen space decomposition where LIC is computed. + enum { + COMPOSITE_INPLACE=0, + COMPOSITE_INPLACE_DISJOINT=1, + COMPOSITE_BALANCED=2, + COMPOSITE_AUTO=3 + }; + void SetCompositeStrategy(int val); + vtkGetMacro(CompositeStrategy, int); + + // Description: + // Returns true if the rendering context supports extensions needed by this + // painter. + static bool IsSupported(vtkRenderWindow *context); + + // Description: + // Methods used for parallel benchmarks. Use cmake to define + // vtkSurfaceLICMapperTIME to enable benchmarks. During each + // update timing information is stored, it can be written to + // disk by calling WriteLog. + virtual void WriteTimerLog(const char *){} + + // Description: + // Make a shallow copy of this interface + void ShallowCopy(vtkSurfaceLICInterface *m); + + // Description: + // Release any graphics resources that are being consumed by this mapper. + // The parameter window could be used to determine which graphic + // resources to release. In this case, releases the display lists. + virtual void ReleaseGraphicsResources(vtkWindow * win); + + // Description: + // Returns true when rendering LIC is possible. + bool CanRenderSurfaceLIC(vtkActor *actor); + + // Description: + // Look for changes that would trigger stage updates + void ValidateContext(vtkRenderer *renderer); + + // Description: + // Creates a new communicator with/without the calling processes + // as indicated by the passed in flag, if not 0 the calling process + // is included in the new communicator. In parallel this call is mpi + // collective on the world communicator. In serial this is a no-op. + virtual vtkPainterCommunicator *CreateCommunicator(int); + + // Description: + // Creates a new communicator for internal use based on this + // rank's visible data. + void CreateCommunicator(vtkRenderer *, vtkActor *, vtkDataObject *data); + + vtkPainterCommunicator *GetCommunicator(); + + // Description: + // Called from a mapper, does what is needed to make sure + // the communicators are ready + void UpdateCommunicator(vtkRenderer *renderer, + vtkActor *actor, vtkDataObject *data); + + // Description: + // Does the data have vectors which we require + void SetHasVectors(bool val); + bool GetHasVectors(); + + // Description: + // resoucre allocators + void InitializeResources(); + + void PrepareForGeometry(); + void CompletedGeometry(); + void GatherVectors(); + void ApplyLIC(); + void CombineColorsAndLIC(); + void CopyToScreen(); + + // Description: + // Get the min/max across all ranks. min/max are in/out. + // In serial operation this is a no-op, in parallel it + // is a global collective reduction. + virtual void GetGlobalMinMax(vtkPainterCommunicator*, float&, float&){} + + // Description: + // Enable/Disable LIC. + vtkSetMacro(Enable, int); + vtkGetMacro(Enable, int); + vtkBooleanMacro(Enable, int); + +protected: + vtkSurfaceLICInterface(); + ~vtkSurfaceLICInterface(); + + // Description: + // Updates the noise texture, downsampling by the requested sample rate. + void UpdateNoiseImage(vtkRenderWindow *renWin); + + // Description: + // Return false if stage can be skipped + virtual bool NeedToUpdateCommunicator(); + bool NeedToRenderGeometry(vtkRenderer *renderer, vtkActor *actor); + bool NeedToGatherVectors(); + bool NeedToComputeLIC(); + bool NeedToColorLIC(); + void SetUpdateAll(); + + int Enable; + + // Unit is a pixel length. + int NumberOfSteps; + double StepSize; + int NormalizeVectors; + + int EnhancedLIC; + int EnhanceContrast; + double LowLICContrastEnhancementFactor; + double HighLICContrastEnhancementFactor; + double LowColorContrastEnhancementFactor; + double HighColorContrastEnhancementFactor; + int AntiAlias; + + int MaskOnSurface; + double MaskThreshold; + double MaskIntensity; + double MaskColor[3]; + + int ColorMode; + double LICIntensity; + double MapModeBias; + + int GenerateNoiseTexture; + int NoiseType; + int NoiseTextureSize; + int NoiseGrainSize; + double MinNoiseValue; + double MaxNoiseValue; + int NumberOfNoiseLevels; + double ImpulseNoiseProbability; + double ImpulseNoiseBackgroundValue; + int NoiseGeneratorSeed; + + int AlwaysUpdate; + int CompositeStrategy; + + vtkSurfaceLICHelper* Internals; + + // save the active fbo and its draw buffer + int PrevDrawBuf; + int PrevFbo; + +private: + vtkSurfaceLICInterface(const vtkSurfaceLICInterface&); // Not implemented. + void operator=(const vtkSurfaceLICInterface&); // Not implemented. +}; + +#endif +// VTK-HeaderTest-Exclude: vtkSurfaceLICInterface.h diff --git a/Rendering/LICOpenGL2/vtkSurfaceLICMapper_CE.glsl b/Rendering/LICOpenGL2/vtkSurfaceLICInterface_CE.glsl similarity index 100% rename from Rendering/LICOpenGL2/vtkSurfaceLICMapper_CE.glsl rename to Rendering/LICOpenGL2/vtkSurfaceLICInterface_CE.glsl diff --git a/Rendering/LICOpenGL2/vtkSurfaceLICMapper_DCpy.glsl b/Rendering/LICOpenGL2/vtkSurfaceLICInterface_DCpy.glsl similarity index 100% rename from Rendering/LICOpenGL2/vtkSurfaceLICMapper_DCpy.glsl rename to Rendering/LICOpenGL2/vtkSurfaceLICInterface_DCpy.glsl diff --git a/Rendering/LICOpenGL2/vtkSurfaceLICMapper_SC.glsl b/Rendering/LICOpenGL2/vtkSurfaceLICInterface_SC.glsl similarity index 100% rename from Rendering/LICOpenGL2/vtkSurfaceLICMapper_SC.glsl rename to Rendering/LICOpenGL2/vtkSurfaceLICInterface_SC.glsl diff --git a/Rendering/LICOpenGL2/vtkSurfaceLICMapper.cxx b/Rendering/LICOpenGL2/vtkSurfaceLICMapper.cxx index 4a78e87df74..ae68a4baea6 100644 --- a/Rendering/LICOpenGL2/vtkSurfaceLICMapper.cxx +++ b/Rendering/LICOpenGL2/vtkSurfaceLICMapper.cxx @@ -14,2444 +14,73 @@ =========================================================================*/ #include "vtkSurfaceLICMapper.h" -#include "vtkActor.h" -#include "vtkBase64Utilities.h" -#include "vtkBoundingBox.h" -#include "vtkCellData.h" -#include "vtkCompositeDataIterator.h" -#include "vtkCompositeDataSet.h" -#include "vtkFloatArray.h" -#include "vtkFrameBufferObject2.h" -#include "vtkGarbageCollector.h" -#include "vtkGenericDataObjectReader.h" -#include "vtkImageData.h" -#include "vtkInformation.h" -#include "vtkLineIntegralConvolution2D.h" -#include "vtkMath.h" -#include "vtkMatrix3x3.h" -#include "vtkMatrix4x4.h" -#include "vtkMinimalStandardRandomSequence.h" -#include "vtkNew.h" -#include "vtkNoise200x200.h" +#include "vtkSurfaceLICInterface.h" + + #include "vtkObjectFactory.h" -#include "vtkOpenGLActor.h" -#include "vtkOpenGLCamera.h" #include "vtkOpenGLError.h" -#include "vtkOpenGLRenderUtilities.h" -#include "vtkOpenGLRenderWindow.h" -#include "vtkOpenGLShaderCache.h" #include "vtkPainterCommunicator.h" -#include "vtkPixelBufferObject.h" -#include "vtkPixelExtent.h" #include "vtkPointData.h" -#include "vtkPolyData.h" -#include "vtkProperty.h" -#include "vtkRenderer.h" -#include "vtkScalarsToColors.h" -#include "vtkShaderProgram.h" -#include "vtkSurfaceLICComposite.h" -#include "vtkTextureObject.h" -#include "vtkTextureObjectVS.h" - - - -#include -#include -#include -#include -#include -#include -#include - -using std::vector; -using std::deque; -using std::string; - -typedef vtkLineIntegralConvolution2D vtkLIC2D; - -// use parallel timer for benchmarks and scaling -// if not defined vtkTimerLOG is used. -// #define vtkSurfaceLICMapperTIME -#if !defined(vtkSurfaceLICMapperTIME) -#include "vtkTimerLog.h" -#endif - -// write intermediate results to disk for debugging -#define vtkSurfaceLICMapperDEBUG 0 -#if vtkSurfaceLICMapperDEBUG >= 2 -#include "vtkTextureIO.h" -#include -using std::ostringstream; -//---------------------------------------------------------------------------- -static -string mpifn(vtkPainterCommunicator *comm, const char *fn) -{ - ostringstream oss; - oss << comm->GetRank() << "_" << fn; - return oss.str(); -} -#endif - -// Enable stream min/max computations. Streaming is accomplished -// via PBO+glReadPixels to read just the regions we are updating. -// Without streaming PBO+glGetTexImage is used to uplaod the entire -// screen sized texture, of which (in parallel) we are updating only -// a small part of. -#define STREAMING_MIN_MAX - -// store depths in a texture. if not a renderbuffer object is used. -// NOTE: this must be on because of a slight diffference in how -// texture filtering is implemented by os mesa. -#define USE_DEPTH_TEXTURE - -//#include "vtkSurfaceLICMapper_GeomFs.h" -//#include "vtkSurfaceLICMapper_GeomVs.h" -#include "vtkSurfaceLICMapper_SC.h" -#include "vtkSurfaceLICMapper_CE.h" -#include "vtkSurfaceLICMapper_DCpy.h" - -namespace vtkSurfaceLICMapperUtil -{ - -// Description -// find min/max of unmasked fragments across all regions -// download the entire screen then search each region -void FindMinMax( - vtkTextureObject *tex, - deque &blockExts, - float &min, - float &max) -{ - // download entire screen - vtkPixelBufferObject *pbo = tex->Download(); - float *pHSLColors = static_cast(pbo->MapPackedBuffer()); - // search regions - int size0 = tex->GetWidth(); - size_t nBlocks = blockExts.size(); - for (size_t e=0; e L ? L : min; - max = max < L ? L : max; - } - } - } - } - pbo->UnmapPackedBuffer(); - pbo->Delete(); - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr << "min=" << min << " max=" << max << endl; - #endif -} - -// Description -// find min/max of unmasked fragments across all regions -// download each search each region individually -void StreamingFindMinMax( - vtkFrameBufferObject2 *fbo, - deque &blockExts, - float &min, - float &max) -{ - size_t nBlocks = blockExts.size(); - // initiate download - fbo->ActivateReadBuffer(1U); - vtkStaticCheckFrameBufferStatusMacro(GL_FRAMEBUFFER); - vector pbos(nBlocks, NULL); - for (size_t e=0; eDownload( - blockExts[e].GetData(), - VTK_FLOAT, - 4, - GL_FLOAT, - GL_RGBA); - } - fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 0U); - fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 1U); - fbo->DeactivateDrawBuffers(); - fbo->DeactivateReadBuffer(); - // map search and release each region - for (size_t e=0; eMapPackedBuffer(); - - size_t n = blockExts[e].Size(); - for (size_t i = 0; i L ? L : min; - max = max < L ? L : max; - } - } - pbo->UnmapPackedBuffer(); - pbo->Delete(); - pbo = NULL; - } - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr << "min=" << min << " max=" << max << endl; - #endif -} - -/** -integer log base 2 -*/ -int ilog2(unsigned int n) -{ - if (n == 0) - { - return -1; - } - unsigned int r = 0; - while ((n >>= 1)) - { - r += 1; - } - return r; -} - -/** -An interface to a random number generator. We can't use -c stdlib since we're not gauranteed to get consistent. -sequences across platform or library version and that -would prevent consistent output during regression tests. -*/ -class RandomNumberGeneratorInterface -{ -public: - RandomNumberGeneratorInterface() - { - this->RNG = vtkMinimalStandardRandomSequence::New(); - } - - ~RandomNumberGeneratorInterface() - { - this->RNG->Delete(); - } - - /** - Seed the random number generator - */ - void SetSeed(int seedVal) - { - #if 0 - srand(seedVal); - #else - this->RNG->SetSeed(seedVal); - #endif - } - - /** - Get a random number in the range of 0 to 1. - */ - double GetRandomNumber() - { - #if 0 - double val = static_cast(rand())/RAND_MAX; - #else - double val = this->RNG->GetValue(); - this->RNG->Next(); - #endif - return val; - } - -private: - void operator=(const RandomNumberGeneratorInterface &); // not implemented - RandomNumberGeneratorInterface(const RandomNumberGeneratorInterface &); // not implemented - -private: - vtkMinimalStandardRandomSequence *RNG; -}; - -/** -2D Noise Generator. Generate arrays for use as noise texture -in the LIC algorithm. Can generate noise with uniform or Gaussian -distributions, with a desired number of noise levels, and a -desired frequency (f < 1 is impulse noise). -*/ -class RandomNoise2D -{ -public: - RandomNoise2D(){} - - // Description: - // Generate a patch of random gray scale values along with an - // alpha channel (in vtk array format). The data should be - // deleted by later calling DeleteValues. Grain size and sideLen - // may be modified to match the noise generator requirements, - // returned arrays will be sized accordingly. - // - // type - UNIFORM=0, GAUSSIAN=1, PERLIN=2 - // sideLen - side length of square patch in pixels (in/out) - // grainSize - grain size of noise values in pixels (in/out) - // nLevels - number of noise intesity levels - // minNoiseVal - set the min for noise pixels (position distribution) - // maxNoiseVal - set the max for noise pixels (position distribution) - // impulseProb - probability of impulse noise,1 touches every pixel - // impulseBgNoiseVal - set the background color for impulse noise - // seed - seed for random number generator - enum { - UNIFORM = 0, - GAUSSIAN = 1, - PERLIN = 2 - }; - float *Generate( - int type, - int &sideLen, - int &grainLize, - float minNoiseVal, - float maxNoiseVal, - int nLevels, - double impulseProb, - float impulseBgNoiseVal, - int seed); - - // Description - // Delete the passed in array of values. - void DeleteValues(unsigned char *vals){ free(vals); } - -private: - // Description: - // Generate noise with a uniform distribution. - float *GenerateUniform( - int sideLen, - int grainLize, - float minNoiseVal, - float maxNoiseVal, - int nLevels, - double impulseProb, - float impulseBgNoiseVal, - int seed); - - // Description: - // Generate noise with a Gaussian distribution. - float *GenerateGaussian( - int sideLen, - int grainLize, - float minNoiseVal, - float maxNoiseVal, - int nLevels, - double impulseProb, - float impulseBgNoiseVal, - int seed); - - // Description: - // Generate Perlin noise with a Gaussian distribution. - float *GeneratePerlin( - int sideLen, - int grainLize, - float minNoiseVal, - float maxNoiseVal, - int nLevels, - double impulseProb, - float impulseBgNoiseVal, - int seed); - - // Description: - // A way of controling the probability (from 0.0 to 1.0) that you - // generate values. returns 1 if you should generate a value. - // for example this is used to control the frequency of impulse - // noise. - int ShouldGenerateValue(double prob); - - // Description: - // Get a valid the length of the side of the patch and grains size in pixels - // given a desired patch side length and a grain size. This ensures that all - // grains are the same size. - void GetValidDimensionAndGrainSize(int type, int &dim, int &grainSize); - -private: - RandomNumberGeneratorInterface ValueGen; - RandomNumberGeneratorInterface ProbGen; -}; - -//----------------------------------------------------------------------------- -void RandomNoise2D::GetValidDimensionAndGrainSize(int type, int &sideLen, int &grainSize) -{ - // perlin noise both side len and grain size need to be powers of 2 - if (type == PERLIN) - { - sideLen = 1 << ilog2(sideLen); - grainSize = 1 << ilog2(grainSize); - } - - // grains can't be larger than the patch - if (sideLen < grainSize) - { - sideLen = grainSize; - } - - // generate noise with agiven grainSize size on the patch - if (sideLen % grainSize) - { - // grainSize is not an even divsior of sideLen, adjust sideLen to - // next larger even divisor - sideLen = grainSize * (sideLen/grainSize + 1); - } -} - -//----------------------------------------------------------------------------- -int RandomNoise2D::ShouldGenerateValue(double prob) -{ - if (this->ProbGen.GetRandomNumber() > (1.0 - prob)) - { - return 1; - } - return 0; -} - -//----------------------------------------------------------------------------- -float *RandomNoise2D::Generate( - int type, - int &sideLen, - int &grainSize, - float minNoiseVal, - float maxNoiseVal, - int nLevels, - double impulseProb, - float impulseBgNoiseVal, - int seed) -{ - this->GetValidDimensionAndGrainSize(type, sideLen, grainSize); - - switch (type) - { - case GAUSSIAN: - return this->GenerateGaussian( - sideLen, - grainSize, - minNoiseVal, - maxNoiseVal, - nLevels, - impulseProb, - impulseBgNoiseVal, - seed); - - case UNIFORM: - return this->GenerateUniform( - sideLen, - grainSize, - minNoiseVal, - maxNoiseVal, - nLevels, - impulseProb, - impulseBgNoiseVal, - seed); - - case PERLIN: - return this->GeneratePerlin( - sideLen, - grainSize, - minNoiseVal, - maxNoiseVal, - nLevels, - impulseProb, - impulseBgNoiseVal, - seed); - } - return NULL; -} - -//----------------------------------------------------------------------------- -float *RandomNoise2D::GenerateUniform( - int sideLen, - int grainSize, - float minNoiseVal, - float maxNoiseVal, - int nLevels, - double impulseProb, - float impulseBgNoiseVal, - int seed) -{ - // generate a patch of single pixel random values - // with a uniform distribution and fixed number of levels - nLevels = nLevels < 1 ? 1 : nLevels; - int maxLevel = nLevels-1; - float delta = maxLevel != 0 ? 1.0f/maxLevel : 0.0f; - minNoiseVal = minNoiseVal < 0.0f ? 0.0f : minNoiseVal; - maxNoiseVal = maxNoiseVal > 1.0f ? 1.0f : maxNoiseVal; - float noiseRange = maxNoiseVal - minNoiseVal; - impulseProb = impulseProb < 0.0 ? 0.0 : impulseProb; - impulseProb = impulseProb > 1.0 ? 1.0 : impulseProb; - impulseBgNoiseVal = impulseBgNoiseVal < 0.0f ? 0.0f : impulseBgNoiseVal; - impulseBgNoiseVal = impulseBgNoiseVal > 1.0f ? 1.0f : impulseBgNoiseVal; - this->ValueGen.SetSeed(seed); - this->ProbGen.SetSeed(seed); - const int sdim = sideLen/grainSize; - const int sdim2 = sdim*sdim; - float *rvals=(float*)malloc(sdim2*sizeof(float)); - for (int i=0; iShouldGenerateValue(impulseProb)) - { - int l = static_cast(this->ValueGen.GetRandomNumber()*nLevels); - l = l > maxLevel ? maxLevel : l; // needed for 1.0 - rvals[idx] = nLevels == 1 ? maxNoiseVal : minNoiseVal + (l*delta) * noiseRange; - } - } - } - - // map single pixel random values onto a patch of values of - // the requested grain size - const int ncomp = 2; - const int dim2 = sideLen*sideLen; - const int ntup = ncomp*dim2; - float *noise = (float*)malloc(ntup*sizeof(float)); - for (int j=0; j 1.0 ? 1.0 : impulseProb; - impulseBgNoiseVal = impulseBgNoiseVal < 0.0f ? 0.0f : impulseBgNoiseVal; - impulseBgNoiseVal = impulseBgNoiseVal > 1.0f ? 1.0f : impulseBgNoiseVal; - this->ValueGen.SetSeed(seed); - this->ProbGen.SetSeed(seed); - const int sdim = sideLen/grainSize; - const int sdim2 = sdim*sdim; - float *rvals = (float*)malloc(sdim2*sizeof(float)); - for (int i=0; iShouldGenerateValue(impulseProb)) - { - double val = 0.0; - for (int q=0; qValueGen.GetRandomNumber(); - } - rvals[idx] = static_cast(val); - } - } - } - - // normalize noise field from eps to nLevels onto 0 to 1 - // and restrict to the requested number of levels - // min/max - float minVal = static_cast(N+1); - float maxVal = 0.0f; - for (int i=0; i 0.0f ? rvals[i] : minVal); - - maxVal = rvals[i]>maxVal ? rvals[i] : maxVal; - } - float maxMinDiff = maxVal-minVal; - // because we ignore zero when impulseProb<1 we have to be careful - // here so that we can support one noise level. - minVal = maxMinDiff == 0.0f ? 0.0f : minVal; - maxMinDiff = maxMinDiff == 0.0f ? (maxVal == 0.0f ? 1.0f : maxVal) : maxMinDiff; - - nLevels = nLevels < 1 ? 1 : nLevels; - int maxLevel = nLevels-1; - float delta = maxLevel != 0 ? 1.0f/maxLevel : 0.0f; - minNoiseVal = minNoiseVal < 0.0f ? 0.0f : minNoiseVal; - maxNoiseVal = maxNoiseVal > 1.0f ? 1.0f : maxNoiseVal; - float noiseRange = maxNoiseVal - minNoiseVal; - for (int i=0; i(val*nLevels); - l = l > maxLevel ? maxLevel : l; - rvals[i] - = rvals[i] < minVal ? impulseBgNoiseVal - : nLevels == 1 ? maxNoiseVal : minNoiseVal + (l*delta) * noiseRange; - } - - // map single pixel random values onto a patch of values of - // the requested grain size - const int ncomp = 2; - const int dim2 = sideLen*sideLen; - const int ntup = ncomp*dim2; - float *noise = (float*)malloc(ntup*sizeof(float)); - for (int j=0; j grainSize - const int ncomp = 2; - const int dim2 = sideLen*sideLen; - const int ntup = ncomp*dim2; - float *noise = static_cast(malloc(ntup*sizeof(float))); - for (int i=0; i 1.0 ? 1.0 : impulseProb; - impulseBgNoiseVal = impulseBgNoiseVal < 0.0f ? 0.0f : impulseBgNoiseVal; - impulseBgNoiseVal = impulseBgNoiseVal > 1.0f ? 1.0f : impulseBgNoiseVal; - minNoiseVal = minNoiseVal < 0.0f ? 0.0f : minNoiseVal; - maxNoiseVal = maxNoiseVal > 1.0f ? 1.0f : maxNoiseVal; - - //int nIter = ilog2(static_cast(sideLen-1(grainSize)); - for (int w=0; w(1<<(nIter-1-w)); - //float levelNoiseMax = 1.0f - levelNoiseMin; - // generate a level of noise - int levelGrainSize = 1<= sideLen ? i : ii; - int jj = j+q-1; - jj = jj < 0 ? j : jj; - jj = jj >= sideLen ? j : jj; - int idx = 2*(sideLen*jj+ii); - val += levelNoise[idx]*K[q*3+p]; - } - } - levelNoise[2*(sideLen*j+i)] = val; - } - } - }*/ - // accumulate - for (int i=0; i(nIter+1); - float maxVal = 0.0f; - for (int i=0; imaxVal ? val : maxVal; - } - float maxMinDiff = maxVal - minVal; - if ( maxMinDiff <= 0.0f ) - { - maxMinDiff = 1.0f; - minVal = 0.0f; - } - for (int i=0; i(file_noise200x200_vtk_sections[cc]); - } - - unsigned char* binaryInput - = new unsigned char[file_noise200x200_vtk_decoded_length + 10]; - - unsigned long binarylength = vtkBase64Utilities::DecodeSafely( - reinterpret_cast(base64string.c_str()), - base64string.length(), - binaryInput, - file_noise200x200_vtk_decoded_length + 10); - - assert("check valid_length" - && (binarylength == file_noise200x200_vtk_decoded_length)); - - vtkGenericDataObjectReader* reader = vtkGenericDataObjectReader::New(); - reader->ReadFromInputStringOn(); - - reader->SetBinaryInputString( - reinterpret_cast(binaryInput), - static_cast(binarylength)); - - reader->Update(); - vtkImageData* data = vtkImageData::New(); - data->ShallowCopy(reader->GetOutput()); - - delete [] binaryInput; - reader->Delete(); - return data; -} - -}; -using namespace vtkSurfaceLICMapperUtil; - -/** -Internal data -*/ -class vtkSurfaceLICMapper::vtkInternals -{ -public: - vtkWeakPointer Context; - bool GLSupport; - int Viewsize[2]; - long long LastInputDataSetMTime; - long long LastPropertyMTime; - long long LastLUTMTime; - - deque BlockExts; - vtkPixelExtent DataSetExt; - - bool ContextNeedsUpdate; - bool OutputDataNeedsUpdate; - bool CommunicatorNeedsUpdate; - bool GeometryNeedsUpdate; - bool GatherNeedsUpdate; - bool LICNeedsUpdate; - bool ColorNeedsUpdate; - - vtkPainterCommunicator *Communicator; - - #ifdef USE_DEPTH_TEXTURE - vtkSmartPointer DepthImage; - #else - vtkSmartPointer DepthImage; - #endif - vtkSmartPointer GeometryImage; - vtkSmartPointer VectorImage; - vtkSmartPointer CompositeVectorImage; - vtkSmartPointer MaskVectorImage; - vtkSmartPointer CompositeMaskVectorImage; - vtkSmartPointer NoiseImage; - vtkSmartPointer LICImage; - vtkSmartPointer RGBColorImage; - vtkSmartPointer HSLColorImage; - vtkSmartPointer Noise; - - vtkSmartPointer FBO; - - vtkOpenGLHelper *ColorPass; - vtkOpenGLHelper *ColorEnhancePass; - vtkOpenGLHelper *CopyPass; - - vtkSmartPointer Compositor; - vtkSmartPointer LICer; - - int FieldAssociation; - int FieldAttributeType; - std::string FieldName; - bool FieldNameSet; - bool HasVectors; - - - - // Description: - // Constructor - vtkInternals() - { - this->Viewsize[0] = this->Viewsize[1] = 0; - this->LastInputDataSetMTime = 0; - this->LastPropertyMTime = 0; - this->LastLUTMTime = 0; - this->GLSupport = false; - - this->ContextNeedsUpdate = true; - this->OutputDataNeedsUpdate = true; - this->CommunicatorNeedsUpdate = true; - this->GeometryNeedsUpdate = true; - this->LICNeedsUpdate = true; - this->GatherNeedsUpdate = true; - this->ColorNeedsUpdate = true; - - this->Communicator = new vtkPainterCommunicator; - - this->HasVectors = false; - this->FieldNameSet = false; - this->FieldAttributeType = 0; - this->FieldAssociation = 0; - - this->ColorPass = NULL; - this->ColorEnhancePass = NULL; - this->CopyPass = NULL; - } - - // Description: - // Destructor - ~vtkInternals() - { - this->ClearGraphicsResources(); - - if (this->ColorPass) - { - delete this->ColorPass; - } - if (this->ColorEnhancePass) - { - delete this->ColorEnhancePass; - } - if (this->CopyPass) - { - delete this->CopyPass; - } - this->ColorPass = NULL; - this->ColorEnhancePass = NULL; - this->CopyPass = NULL; - - - delete this->Communicator; - } - - // Description: - // Check for OpenGL support - static bool IsSupported(vtkOpenGLRenderWindow *context) - { - if (context == NULL) - { - vtkGenericWarningMacro("OpenGL render window required"); - return false; - } - - bool lic2d = vtkLineIntegralConvolution2D::IsSupported(context); - - bool floatFormats - = vtkTextureObject::IsSupported(context, true, true, false); - - bool renderbuffer = true; - #if !defined(USE_DEPTH_TEXTURE) - renderbuffer = vtkRenderbuffer::IsSupported(context); - #endif - - bool support = lic2d && floatFormats && renderbuffer; - - if (!support) - { - vtkGenericWarningMacro( - << "SurfaceLIC is not supported" << endl - << context->GetClassName() << endl - << "LIC support = " << lic2d << endl - << "floating point texture formats = " << floatFormats << endl - << "render buffers = " << renderbuffer); - return false; - } - return true; - } - - // Description: - // Free textures and shader programs we're holding a reference to. - void ClearGraphicsResources() - { - this->ClearTextures(); - - this->Compositor = NULL; - this->LICer = NULL; - this->FBO = NULL; - } - - // Description: - // Free textures we're holding a reference to. - void ClearTextures() - { - this->DepthImage = NULL; - this->GeometryImage = NULL; - this->VectorImage = NULL; - this->MaskVectorImage = NULL; - this->CompositeVectorImage = NULL; - this->CompositeMaskVectorImage = NULL; - this->NoiseImage = NULL; - this->LICImage = NULL; - this->RGBColorImage = NULL; - this->HSLColorImage = NULL; - } - - // Description: - // Allocate textures. - void AllocateTextures( - vtkOpenGLRenderWindow *context, - int *viewsize) - { - this->AllocateDepthTexture(context, viewsize, this->DepthImage); - this->AllocateTexture(context, viewsize, this->GeometryImage, vtkTextureObject::Nearest); - this->AllocateTexture(context, viewsize, this->VectorImage, vtkTextureObject::Linear); - this->AllocateTexture(context, viewsize, this->MaskVectorImage, vtkTextureObject::Linear); - this->AllocateTexture(context, viewsize, this->CompositeVectorImage, vtkTextureObject::Linear); - this->AllocateTexture(context, viewsize, this->CompositeMaskVectorImage, vtkTextureObject::Linear); - this->AllocateTexture(context, viewsize, this->LICImage, vtkTextureObject::Nearest); - this->AllocateTexture(context, viewsize, this->RGBColorImage, vtkTextureObject::Nearest); - this->AllocateTexture(context, viewsize, this->HSLColorImage, vtkTextureObject::Nearest); - } - - // Description: - // Allocate a size texture, store in the given smart pointer. - void AllocateTexture( - vtkOpenGLRenderWindow *context, - int *viewsize, - vtkSmartPointer &tex, - int filter = vtkTextureObject::Nearest) - { - if ( !tex ) - { - vtkTextureObject * newTex = vtkTextureObject::New(); - newTex->SetContext(context); - newTex->SetBaseLevel(0); - newTex->SetMaxLevel(0); - newTex->SetWrapS(vtkTextureObject::ClampToEdge); - newTex->SetWrapT(vtkTextureObject::ClampToEdge); - newTex->SetMinificationFilter(filter); - newTex->SetMagnificationFilter(filter); - newTex->SetBorderColor(0.0f, 0.0f, 0.0f, 0.0f); - newTex->Create2D(viewsize[0], viewsize[1], 4, VTK_FLOAT, false); - newTex->SetAutoParameters(0); - tex = newTex; - newTex->Delete(); - } - } - - // Description: - // Allocate a size texture, store in the given smart pointer. - #ifdef USE_DEPTH_TEXTURE - void AllocateDepthTexture( - vtkOpenGLRenderWindow *context, - int *viewsize, - vtkSmartPointer &tex) - { - if ( !tex ) - { - vtkTextureObject * newTex = vtkTextureObject::New(); - newTex->SetContext(context); - newTex->AllocateDepth(viewsize[0], viewsize[1], vtkTextureObject::Float32); - newTex->SetAutoParameters(0); - tex = newTex; - newTex->Delete(); - } - } - #else - void AllocateDepthTexture( - vtkOpenGLRenderWindow *context, - int *viewsize, - vtkSmartPointer &buf) - { - if ( !buf ) - { - vtkRenderbuffer * newBuf = vtkRenderbuffer::New(); - newBuf->SetContext(context); - newBuf->CreateDepthAttachment(viewsize[0], viewsize[1]); - buf = newBuf; - newBuf->Delete(); - } - } - #endif - - // Description: - // After LIC has been computed reset/clean internal state - void Updated() - { - this->ContextNeedsUpdate = false; - this->OutputDataNeedsUpdate = false; - this->CommunicatorNeedsUpdate = false; - this->GeometryNeedsUpdate = false; - this->GatherNeedsUpdate = false; - this->LICNeedsUpdate = false; - this->ColorNeedsUpdate = false; - } - - // Description: - // Force all stages to re-execute. Necessary if the - // context or communicator changes. - void UpdateAll() - { - this->ContextNeedsUpdate = true; - this->OutputDataNeedsUpdate= true; - this->CommunicatorNeedsUpdate= true; - this->GeometryNeedsUpdate= true; - this->GatherNeedsUpdate= true; - this->LICNeedsUpdate= true; - this->ColorNeedsUpdate= true; - } - - // Description: - // Convert viewport to texture coordinates - void ViewportQuadTextureCoords(GLfloat *tcoords) - { - tcoords[0] = tcoords[2] = 0.0f; - tcoords[1] = tcoords[3] = 1.0f; - } - - // Description: - // Convert a viewport to a bounding box and it's texture coordinates for a - // screen size texture. - void ViewportQuadPoints(const vtkPixelExtent &viewportExt, GLfloat *quadpts) - { - viewportExt.GetData(quadpts); - } - - // Description: - // Convert a viewport to a bounding box and it's texture coordinates for a - // screen size texture. - void ViewportQuadTextureCoords( - const vtkPixelExtent &viewExt, - const vtkPixelExtent &viewportExt, - GLfloat *tcoords) - { - GLfloat viewsize[2]; - viewExt.Size(viewsize); - - // cell to node - vtkPixelExtent next(viewportExt); - next.CellToNode(); - next.GetData(tcoords); - - tcoords[0] = tcoords[0]/viewsize[0]; - tcoords[1] = tcoords[1]/viewsize[0]; - tcoords[2] = tcoords[2]/viewsize[1]; - tcoords[3] = tcoords[3]/viewsize[1]; - } - - // Description: - // Convert the entire view to a bounding box and it's texture coordinates for - // a screen size texture. - void ViewQuadPoints(GLfloat *quadpts) - { - quadpts[0] = quadpts[2] = 0.0f; - quadpts[1] = quadpts[3] = 1.0f; - } - - // Description: - // Convert the entire view to a bounding box and it's texture coordinates for - // a screen size texture. - void ViewQuadTextureCoords(GLfloat *tcoords) - { - tcoords[0] = tcoords[2] = 0.0f; - tcoords[1] = tcoords[3] = 1.0f; - } - - // Description: - // Render a quad (to trigger a shader to run) - void RenderQuad( - const vtkPixelExtent &viewExt, - const vtkPixelExtent &viewportExt, - vtkOpenGLHelper *cbo) - { - // cell to node - vtkPixelExtent next(viewportExt); - next.CellToNode(); - - GLfloat quadPts[4]; - next.GetData(quadPts); - - GLfloat quadTCoords[4]; - this->ViewportQuadTextureCoords(viewExt, viewportExt, quadTCoords); - - float tcoords[] = { - quadTCoords[0], quadTCoords[2], - quadTCoords[1], quadTCoords[2], - quadTCoords[1], quadTCoords[3], - quadTCoords[0], quadTCoords[3]}; - - float verts[] = { - quadTCoords[0]*2.0f-1.0f, quadTCoords[2]*2.0f-1.0f, 0.0f, - quadTCoords[1]*2.0f-1.0f, quadTCoords[2]*2.0f-1.0f, 0.0f, - quadTCoords[1]*2.0f-1.0f, quadTCoords[3]*2.0f-1.0f, 0.0f, - quadTCoords[0]*2.0f-1.0f, quadTCoords[3]*2.0f-1.0f, 0.0f}; - - vtkOpenGLRenderUtilities::RenderQuad(verts, tcoords, - cbo->Program, cbo->VAO); - vtkOpenGLStaticCheckErrorMacro("failed at RenderQuad"); - } - - // always return true as these state monitors do not exist in the - // new backend - bool LightingChanged() - { - return true; - } - bool ViewChanged() - { - return true; - } - bool BackgroundChanged(vtkRenderer *) - { - return true; - } - - // Description: - // Compute the index into the 4x4 OpenGL ordered matrix. - inline - int idx(int row, int col) { return 4*col+row; } - - // Description: - // given a axes aligned bounding box in - // normalized device coordinates test for - // view frustum visibility. - // if all points are outside one of the - // view frustum planes then this box - // is not visible. we might have false - // positive where more than one clip - // plane intersects the box. - bool VisibilityTest(double ndcBBox[24]) - { - // check all points in the direction d - // at the same time. - for (int d=0; d<3; ++d) - { - if (((ndcBBox[ d] < -1.0) - && (ndcBBox[3 + d] < -1.0) - && (ndcBBox[6 + d] < -1.0) - && (ndcBBox[9 + d] < -1.0) - && (ndcBBox[12 + d] < -1.0) - && (ndcBBox[15 + d] < -1.0) - && (ndcBBox[18 + d] < -1.0) - && (ndcBBox[21 + d] < -1.0)) - ||((ndcBBox[ d] > 1.0) - && (ndcBBox[3 + d] > 1.0) - && (ndcBBox[6 + d] > 1.0) - && (ndcBBox[9 + d] > 1.0) - && (ndcBBox[12 + d] > 1.0) - && (ndcBBox[15 + d] > 1.0) - && (ndcBBox[18 + d] > 1.0) - && (ndcBBox[21 + d] > 1.0)) ) - { - return false; - } - } - return true; - } - - // Description: - // Given world space bounds, - // compute bounding boxes in clip and normalized device - // coordinates and perform view frustum visiblity test. - // return true if the bounds are visible. If so the passed - // in extent object is initialized with the corresponding - //screen space extents. - bool ProjectBounds( - double PMV[16], - int viewsize[2], - double bounds[6], - vtkPixelExtent &screenExt) - { - // this is how to get the 8 corners of a bounding - // box from the VTK bounds - int bbIds[24] = { - 0,2,4, - 1,2,4, - 1,3,4, - 0,3,4, - 0,2,5, - 1,2,5, - 1,3,5, - 0,3,5 - }; - - // normalized device coordinate bounding box - double ndcBBox[24]; - for (int q = 0; q<8; ++q) - { - int qq = 3*q; - // bounding box corner - double wx = bounds[bbIds[qq ]]; - double wy = bounds[bbIds[qq+1]]; - double wz = bounds[bbIds[qq+2]]; - // to clip coordinates - ndcBBox[qq ] = wx * PMV[idx(0,0)] + wy * PMV[idx(0,1)] + wz * PMV[idx(0,2)] + PMV[idx(0,3)]; - ndcBBox[qq+1] = wx * PMV[idx(1,0)] + wy * PMV[idx(1,1)] + wz * PMV[idx(1,2)] + PMV[idx(1,3)]; - ndcBBox[qq+2] = wx * PMV[idx(2,0)] + wy * PMV[idx(2,1)] + wz * PMV[idx(2,2)] + PMV[idx(2,3)]; - double ndcw = wx * PMV[idx(3,0)] + wy * PMV[idx(3,1)] + wz * PMV[idx(3,2)] + PMV[idx(3,3)]; - - // TODO - // if the point is past the near clipping plane - // we need to do something more robust. this ensures - // the correct result but its inefficient - if (ndcw < 0.0) - { - screenExt = vtkPixelExtent(viewsize[0], viewsize[1]); - //cerr << "W<0!!!!!!!!!!!!!" << endl; - return true; - } - - // to normalized device coordinates - ndcw = (ndcw == 0.0 ? 1.0 : 1.0/ndcw); - ndcBBox[qq ] *= ndcw; - ndcBBox[qq+1] *= ndcw; - ndcBBox[qq+2] *= ndcw; - } - - // compute screen extent only if the object - // is inside the view frustum. - if (VisibilityTest(ndcBBox)) - { - // these bounds are visible. compute screen - // space exents - double vx = viewsize[0] - 1.0; - double vy = viewsize[1] - 1.0; - double vx2 = viewsize[0] * 0.5; - double vy2 = viewsize[1] * 0.5; - vtkBoundingBox box; - for (int q=0; q<8; ++q) - { - int qq = 3*q; - double sx = (ndcBBox[qq ] + 1.0) * vx2; - double sy = (ndcBBox[qq+1] + 1.0) * vy2; - box.AddPoint( - vtkMath::ClampValue(sx, 0.0, vx), - vtkMath::ClampValue(sy, 0.0, vy), - 0.0); - } - // to screen extent - const double *s0 = box.GetMinPoint(); - const double *s1 = box.GetMaxPoint(); - screenExt[0] = static_cast(s0[0]); - screenExt[1] = static_cast(s1[0]); - screenExt[2] = static_cast(s0[1]); - screenExt[3] = static_cast(s1[1]); - return true; - } - - // these bounds aren't visible - return false; - } - - // Description: - // Compute screen space extents for each block in the input - // dataset and for the entire dataset. Only visible blocks - // are used in the computations. - int ProjectBounds( - vtkRenderer *ren, - vtkActor *actor, - vtkDataObject *dobj, - int viewsize[2], - vtkPixelExtent &dataExt, - deque &blockExts) - { - // get the modelview projection matrix - vtkNew tmpMatrix; - - vtkOpenGLCamera *oglCam = - vtkOpenGLCamera::SafeDownCast(ren->GetActiveCamera()); - vtkMatrix4x4 *wcdc; - vtkMatrix4x4 *wcvc; - vtkMatrix3x3 *norms; - vtkMatrix4x4 *vcdc; - oglCam->GetKeyMatrices(ren,wcvc,norms,vcdc,wcdc); - - if (!actor->GetIsIdentity()) - { - vtkMatrix4x4 *mcwc; - vtkMatrix3x3 *anorms; - ((vtkOpenGLActor *)actor)->GetKeyMatrices(mcwc,anorms); - vtkMatrix4x4::Multiply4x4(mcwc, wcdc, tmpMatrix.GetPointer()); - } - else - { - tmpMatrix->DeepCopy(wcdc); - } -/* - for ( int c = 0; c < 4; c ++ ) - { - for ( int r = 0; r < 4; r ++ ) - { - PMV[c*4+r] - = P[idx(r,0)] * MV[idx(0,c)] - + P[idx(r,1)] * MV[idx(1,c)] - + P[idx(r,2)] * MV[idx(2,c)] - + P[idx(r,3)] * MV[idx(3,c)]; - } - } -*/ - // dataset case - vtkDataSet* ds = dynamic_cast(dobj); - if (ds && ds->GetNumberOfCells()) - { - double bounds[6]; - ds->GetBounds(bounds); - if ( vtkBoundingBox::IsValid(bounds) - && this->ProjectBounds(tmpMatrix->Element[0], viewsize, bounds, dataExt) ) - { - // the dataset is visible - // add its extent - blockExts.push_back(dataExt); - return 1; - } - //cerr << "ds " << ds << " not visible " << endl; - return 0; - } - // composite dataset case - vtkCompositeDataSet* cd = dynamic_cast(dobj); - if (cd) - { - // process each block's bounds - vtkBoundingBox bbox; - vtkCompositeDataIterator* iter = cd->NewIterator(); - for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) - { - ds = dynamic_cast(iter->GetCurrentDataObject()); - if (ds && ds->GetNumberOfCells()) - { - double bounds[6]; - ds->GetBounds(bounds); - vtkPixelExtent screenExt; - if ( vtkBoundingBox::IsValid(bounds) - && this->ProjectBounds(tmpMatrix->Element[0], viewsize, bounds, screenExt) ) - { - // this block is visible - // save it's screen extent - // and accumulate its bounds - blockExts.push_back(screenExt); - bbox.AddBounds(bounds); - } - //else { cerr << "leaf " << ds << " not visible " << endl << endl;} - } - } - iter->Delete(); - // process accumulated dataset bounds - double bounds[6]; - bbox.GetBounds(bounds); - if ( vtkBoundingBox::IsValid(bounds) - && this->ProjectBounds(tmpMatrix->Element[0], viewsize, bounds, dataExt) ) - { - return 1; - } - return 0; - } - //cerr << "ds " << ds << " no cells " << endl; - return 0; - } - - // Description: - // Shrink an extent to tightly bound non-zero values - void GetPixelBounds(float *rgba, int ni, vtkPixelExtent &ext) - { - vtkPixelExtent text; - for (int j=ext[2]; j<=ext[3]; ++j) - { - for (int i=ext[0]; i<=ext[1]; ++i) - { - if (rgba[4*(j*ni+i)+3] > 0.0f) - { - text[0] = text[0] > i ? i : text[0]; - text[1] = text[1] < i ? i : text[1]; - text[2] = text[2] > j ? j : text[2]; - text[3] = text[3] < j ? j : text[3]; - } - } - } - ext = text; - } - - // Description: - // Shrink a set of extents to tightly bound non-zero values - // cull extent if it's empty - void GetPixelBounds(float *rgba, int ni, deque &blockExts) - { - vector tmpExts(blockExts.begin(),blockExts.end()); - blockExts.clear(); - size_t nBlocks = tmpExts.size(); - for (size_t b=0; bInternals = new vtkInternals(); - this->Output = 0; - - this->Enable = 1; - this->AlwaysUpdate = 0; - - this->StepSize = 1; - this->NumberOfSteps = 20; - this->NormalizeVectors = 1; - - this->EnhancedLIC = 1; - - this->EnhanceContrast = 0; - this->LowLICContrastEnhancementFactor = 0.0; - this->HighLICContrastEnhancementFactor = 0.0; - this->LowColorContrastEnhancementFactor = 0.0; - this->HighColorContrastEnhancementFactor = 0.0; - this->AntiAlias = 0; - this->ColorMode = COLOR_MODE_BLEND; - this->LICIntensity = 0.8; - this->MapModeBias = 0.0; - - this->GenerateNoiseTexture = 0; - this->NoiseType = NOISE_TYPE_GAUSSIAN; - this->NoiseTextureSize = 200; - this->MinNoiseValue = 0.0; - this->MaxNoiseValue = 0.8; - this->NoiseGrainSize = 1; - this->NumberOfNoiseLevels = 256; - this->ImpulseNoiseProbability = 1.0; - this->ImpulseNoiseBackgroundValue = 0.0; - this->NoiseGeneratorSeed = 1; - - this->MaskOnSurface = 0; - this->MaskThreshold = 0.0; - this->MaskIntensity = 0.0; - this->MaskColor[0] = 0.5; - this->MaskColor[1] = 0.5; - this->MaskColor[2] = 0.5; - - this->CompositeStrategy = COMPOSITE_AUTO; - - this->SetInputArrayToProcess(0,0,0, - vtkDataObject::FIELD_ASSOCIATION_POINTS_THEN_CELLS, - vtkDataSetAttributes::VECTORS); - - // we always want texture coordinates - // they are the vector field we LIC on - this->ForceTextureCoordinates = true; -} - -//---------------------------------------------------------------------------- -vtkSurfaceLICMapper::~vtkSurfaceLICMapper() -{ - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr << "=====vtkSurfaceLICMapper::~vtkSurfaceLICMapper" << endl; - #endif - - this->ReleaseGraphicsResources(this->Internals->Context); - delete this->Internals; - - if (this->Output) - { - this->Output->Delete(); - this->Output = 0; - } -} - -void vtkSurfaceLICMapper::ShallowCopy(vtkAbstractMapper *mapper) -{ - vtkSurfaceLICMapper *m = vtkSurfaceLICMapper::SafeDownCast(mapper); - if ( m != NULL ) - { - this->SetScalarVisibility(m->GetScalarVisibility()); - - this->SetNumberOfSteps(m->GetNumberOfSteps()); - this->SetStepSize(m->GetStepSize()); - this->SetEnhancedLIC(m->GetEnhancedLIC()); - this->SetGenerateNoiseTexture(m->GetGenerateNoiseTexture()); - this->SetNoiseType(m->GetNoiseType()); - this->SetNormalizeVectors(m->GetNormalizeVectors()); - this->SetNoiseTextureSize(m->GetNoiseTextureSize()); - this->SetNoiseGrainSize(m->GetNoiseGrainSize()); - this->SetMinNoiseValue(m->GetMinNoiseValue()); - this->SetMaxNoiseValue(m->GetMaxNoiseValue()); - this->SetNumberOfNoiseLevels(m->GetNumberOfNoiseLevels()); - this->SetImpulseNoiseProbability(m->GetImpulseNoiseProbability()); - this->SetImpulseNoiseBackgroundValue(m->GetImpulseNoiseBackgroundValue()); - this->SetNoiseGeneratorSeed(m->GetNoiseGeneratorSeed()); - this->SetEnhanceContrast(m->GetEnhanceContrast()); - this->SetLowLICContrastEnhancementFactor( - m->GetLowLICContrastEnhancementFactor()); - this->SetHighLICContrastEnhancementFactor( - m->GetHighLICContrastEnhancementFactor()); - this->SetLowColorContrastEnhancementFactor( - m->GetLowColorContrastEnhancementFactor()); - this->SetHighColorContrastEnhancementFactor( - m->GetHighColorContrastEnhancementFactor()); - this->SetAntiAlias(m->GetAntiAlias()); - this->SetColorMode(m->GetColorMode()); - this->SetLICIntensity(m->GetLICIntensity()); - this->SetMapModeBias(m->GetMapModeBias()); - this->SetMaskOnSurface(m->GetMaskOnSurface()); - this->SetMaskThreshold(m->GetMaskThreshold()); - this->SetMaskIntensity(m->GetMaskIntensity()); - this->SetMaskColor(m->GetMaskColor()); - this->SetInputArrayToProcess(0, - m->GetInputArrayInformation(0)); - } - - // Now do superclass - this->vtkOpenGLPolyDataMapper::ShallowCopy(mapper); -} - -//---------------------------------------------------------------------------- -void vtkSurfaceLICMapper::ReleaseGraphicsResources(vtkWindow* win) -{ - this->Internals->ClearGraphicsResources(); - this->Internals->Context = NULL; - if (this->Output) - { - this->Output->Delete(); - this->Output = NULL; - } - this->Superclass::ReleaseGraphicsResources(win); -} - -//---------------------------------------------------------------------------- -#define vtkSetMonitoredParameterMacro(_name, _type, _code) \ -void vtkSurfaceLICMapper::Set##_name (_type val) \ -{ \ - if (val == this->_name) \ - { \ - return; \ - } \ - _code \ - this->_name = val; \ - this->Modified(); \ -} -// output dataset -vtkSetMonitoredParameterMacro( - Enable, - int, - this->Internals->OutputDataNeedsUpdate = true;) -// lic -vtkSetMonitoredParameterMacro( - GenerateNoiseTexture, - int, - this->Internals->Noise = NULL; - this->Internals->NoiseImage = NULL; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - NoiseType, - int, - this->Internals->Noise = NULL; - this->Internals->NoiseImage = NULL; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - NoiseTextureSize, - int, - this->Internals->Noise = NULL; - this->Internals->NoiseImage = NULL; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - NoiseGrainSize, - int, - this->Internals->Noise = NULL; - this->Internals->NoiseImage = NULL; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - MinNoiseValue, - double, - val = val < 0.0 ? 0.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->Noise = NULL; - this->Internals->NoiseImage = NULL; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - MaxNoiseValue, - double, - val = val < 0.0 ? 0.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->Noise = NULL; - this->Internals->NoiseImage = NULL; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - NumberOfNoiseLevels, - int, - this->Internals->Noise = NULL; - this->Internals->NoiseImage = NULL; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - ImpulseNoiseProbability, - double, - val = val < 0.0 ? 0.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->Noise = NULL; - this->Internals->NoiseImage = NULL; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - ImpulseNoiseBackgroundValue, - double, - val = val < 0.0 ? 0.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->Noise = NULL; - this->Internals->NoiseImage = NULL; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - NoiseGeneratorSeed, - int, - this->Internals->Noise = NULL; - this->Internals->NoiseImage = NULL; - this->Internals->LICNeedsUpdate = true;) - -// compositor -vtkSetMonitoredParameterMacro( - CompositeStrategy, - int, - this->Internals->GatherNeedsUpdate = true;) - -// lic/compositor -vtkSetMonitoredParameterMacro( - NumberOfSteps, - int, - this->Internals->GatherNeedsUpdate = true; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - StepSize, - double, - this->Internals->GatherNeedsUpdate = true; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - NormalizeVectors, - int, - val = val < 0 ? 0 : val; - val = val > 1 ? 1 : val; - this->Internals->GatherNeedsUpdate = true; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - MaskThreshold, - double, - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - EnhancedLIC, - int, - this->Internals->GatherNeedsUpdate = true; - this->Internals->LICNeedsUpdate = true;) - -// lic -vtkSetMonitoredParameterMacro( - LowLICContrastEnhancementFactor, - double, - val = val < 0.0 ? 0.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - HighLICContrastEnhancementFactor, - double, - val = val < 0.0 ? 0.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->LICNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - AntiAlias, - int, - val = val < 0 ? 0 : val; - this->Internals->GatherNeedsUpdate = true; - this->Internals->LICNeedsUpdate = true;) - -// geometry -vtkSetMonitoredParameterMacro( - MaskOnSurface, - int, - val = val < 0 ? 0 : val; - val = val > 1 ? 1 : val; - this->Internals->GeometryNeedsUpdate = true;) - -// colors -vtkSetMonitoredParameterMacro( - ColorMode, - int, - this->Internals->ColorNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - LICIntensity, - double, - val = val < 0.0 ? 0.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->ColorNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - MaskIntensity, - double, - val = val < 0.0 ? 0.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->ColorNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - MapModeBias, - double, - val = val <-1.0 ? -1.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->ColorNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - LowColorContrastEnhancementFactor, - double, - val = val < 0.0 ? 0.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->ColorNeedsUpdate = true;) - -vtkSetMonitoredParameterMacro( - HighColorContrastEnhancementFactor, - double, - val = val < 0.0 ? 0.0 : val; - val = val > 1.0 ? 1.0 : val; - this->Internals->ColorNeedsUpdate = true;) - -//---------------------------------------------------------------------------- -void vtkSurfaceLICMapper::SetMaskColor(double *val) -{ - double rgb[3]; - for (int q=0; q<3; ++q) - { - rgb[q] = val[q]; - rgb[q] = rgb[q] < 0.0 ? 0.0 : rgb[q]; - rgb[q] = rgb[q] > 1.0 ? 1.0 : rgb[q]; - } - if ( (rgb[0] == this->MaskColor[0]) - && (rgb[1] == this->MaskColor[1]) - && (rgb[2] == this->MaskColor[2]) ) - { - return; - } - for (int q=0; q<3; ++q) - { - this->MaskColor[q] = rgb[q]; - } - this->Internals->ColorNeedsUpdate = true; - this->Modified(); -} - -//---------------------------------------------------------------------------- -void vtkSurfaceLICMapper::SetEnhanceContrast(int val) -{ - val = val < ENHANCE_CONTRAST_OFF ? ENHANCE_CONTRAST_OFF : val; - val = val > ENHANCE_CONTRAST_BOTH ? ENHANCE_CONTRAST_BOTH : val; - if (val == this->EnhanceContrast) - { - return; - } - - switch ( this->EnhanceContrast ) - { - case ENHANCE_CONTRAST_OFF: - switch ( val ) - { - case ENHANCE_CONTRAST_LIC: - case ENHANCE_CONTRAST_BOTH: - this->Internals->LICNeedsUpdate = true; - break; - case ENHANCE_CONTRAST_COLOR: - this->Internals->ColorNeedsUpdate = true; - break; - } - break; - - case ENHANCE_CONTRAST_LIC: - switch ( val ) - { - case ENHANCE_CONTRAST_OFF: - case ENHANCE_CONTRAST_COLOR: - this->Internals->LICNeedsUpdate = true; - break; - case ENHANCE_CONTRAST_BOTH: - this->Internals->ColorNeedsUpdate = true; - break; - } - break; - - case ENHANCE_CONTRAST_COLOR: - switch ( val ) - { - case ENHANCE_CONTRAST_LIC: - case ENHANCE_CONTRAST_BOTH: - this->Internals->LICNeedsUpdate = true; - break; - case ENHANCE_CONTRAST_OFF: - this->Internals->ColorNeedsUpdate = true; - break; - } - break; - - case ENHANCE_CONTRAST_BOTH: - switch ( val ) - { - case ENHANCE_CONTRAST_OFF: - this->Internals->LICNeedsUpdate = true; - break; - case ENHANCE_CONTRAST_COLOR: - this->Internals->LICNeedsUpdate = true; - case ENHANCE_CONTRAST_LIC: - this->Internals->ColorNeedsUpdate = true; - break; - } - break; - } - - this->EnhanceContrast = val; - this->Modified(); -} - -//---------------------------------------------------------------------------- -void vtkSurfaceLICMapper::SetNoiseDataSet(vtkImageData *data) -{ - if (data == this->Internals->Noise) - { - return; - } - this->Internals->Noise = data; - this->Internals->NoiseImage = NULL; - this->Modified(); -} - -//---------------------------------------------------------------------------- -vtkImageData *vtkSurfaceLICMapper::GetNoiseDataSet() -{ - if (this->Internals->Noise == NULL) - { - vtkImageData *noise = NULL; - if ( this->GenerateNoiseTexture ) - { - // report potential issues - if ( this->NoiseGrainSize >= this->NoiseTextureSize ) - { - vtkErrorMacro( - "NoiseGrainSize must be smaller than NoiseTextureSize"); - } - if ( this->MinNoiseValue >= this->MaxNoiseValue ) - { - vtkErrorMacro( - "MinNoiseValue must be smaller than MaxNoiseValue"); - } - if ( (this->ImpulseNoiseProbability == 1.0) - && (this->NumberOfNoiseLevels < 2) ) - { - vtkErrorMacro( - "NumberOfNoiseLevels must be greater than 1 " - "when not generating impulse noise"); - } - - // generate a custom noise texture based on the - // current settings. - int noiseTextureSize = this->NoiseTextureSize; - int noiseGrainSize = this->NoiseGrainSize; - RandomNoise2D noiseGen; - float *noiseValues = noiseGen.Generate( - this->NoiseType, - noiseTextureSize, - noiseGrainSize, - static_cast(this->MinNoiseValue), - static_cast(this->MaxNoiseValue), - this->NumberOfNoiseLevels, - this->ImpulseNoiseProbability, - static_cast(this->ImpulseNoiseBackgroundValue), - this->NoiseGeneratorSeed); - if ( noiseValues == NULL ) - { - vtkErrorMacro("Failed to generate noise."); - } - - vtkFloatArray *noiseArray = vtkFloatArray::New(); - noiseArray->SetNumberOfComponents(2); - noiseArray->SetName("noise"); - vtkIdType arraySize = 2*noiseTextureSize*noiseTextureSize; - noiseArray->SetArray(noiseValues, arraySize, 0); - - noise = vtkImageData::New(); - noise->SetSpacing(1.0, 1.0, 1.0); - noise->SetOrigin(0.0, 0.0, 0.0); - noise->SetDimensions(noiseTextureSize, noiseTextureSize, 1); - noise->GetPointData()->SetScalars(noiseArray); - - noiseArray->Delete(); - } - else - { - // load a predefined noise texture. - noise = vtkGetNoiseResource(); - } - - this->Internals->Noise = noise; - this->Internals->NoiseImage = NULL; - noise->Delete(); - noise = NULL; - } - - return this->Internals->Noise; -} - -//---------------------------------------------------------------------------- -void vtkSurfaceLICMapper::UpdateNoiseImage(vtkRenderWindow *renWin) -{ - vtkOpenGLRenderWindow *rw = vtkOpenGLRenderWindow::SafeDownCast(renWin); - vtkImageData *noiseDataSet = this->GetNoiseDataSet(); - - int ext[6]; - noiseDataSet->GetExtent(ext); - unsigned int dataWidth = ext[1]-ext[0]+1; - unsigned int dataHeight = ext[3]-ext[2]+1; - - vtkDataArray *noiseArray = noiseDataSet->GetPointData()->GetScalars(); - int dataType = noiseArray->GetDataType(); - void *data = noiseArray->GetVoidPointer(0); - int dataComps = noiseArray->GetNumberOfComponents(); - unsigned int dataSize = noiseArray->GetNumberOfTuples()*dataComps; - - vtkPixelBufferObject *pbo = vtkPixelBufferObject::New(); - pbo->SetContext(renWin); - pbo->Upload1D(dataType, data, dataSize, 1, 0); - - vtkTextureObject *tex = vtkTextureObject::New(); - tex->SetContext(rw); - tex->SetBaseLevel(0); - tex->SetMaxLevel(0); - tex->SetWrapS(vtkTextureObject::Repeat); - tex->SetWrapT(vtkTextureObject::Repeat); - tex->SetMinificationFilter(vtkTextureObject::Nearest); - tex->SetMagnificationFilter(vtkTextureObject::Nearest); - tex->Create2D(dataWidth, dataHeight, dataComps, pbo, false); - tex->SetAutoParameters(0); - pbo->Delete(); - - this->Internals->NoiseImage = tex; - tex->Delete(); -} - - -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::IsSupported(vtkRenderWindow *renWin) -{ - vtkOpenGLRenderWindow *context - = vtkOpenGLRenderWindow::SafeDownCast(renWin); - - return vtkInternals::IsSupported(context); -} - -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::CanRenderSurfaceLIC(vtkActor *actor) -{ - // check the render context for GL fetaure support - // note this also handles non-opengl render window - if ( this->Internals->ContextNeedsUpdate - && !vtkSurfaceLICMapper::IsSupported(this->Internals->Context) ) - { - vtkErrorMacro("SurfaceLIC is not supported"); - return false; - } - - bool canRender = false; - - int rep = actor->GetProperty()->GetRepresentation(); - - if ( this->Enable - && this->Internals->HasVectors - && (rep == VTK_SURFACE)) - { - canRender = true; - } - - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " CanRender " << canRender << endl; - #endif - - return canRender; -} - -namespace { - void BuildAShader(vtkOpenGLRenderWindow *renWin, - vtkOpenGLHelper **cbor, const char * vert, - const char *frag) - { - if (*cbor == NULL) - { - *cbor = new vtkOpenGLHelper; - std::string GSSource; - (*cbor)->Program = - renWin->GetShaderCache()->ReadyShaderProgram(vert, - frag, - GSSource.c_str()); - } - else - { - renWin->GetShaderCache()->ReadyShaderProgram((*cbor)->Program); - } - } -} - -//---------------------------------------------------------------------------- -void vtkSurfaceLICMapper::InitializeResources() -{ - bool initialized = true; - - // noise image - if (!this->Internals->NoiseImage) - { - initialized = false; - - this->UpdateNoiseImage(this->Internals->Context); - } - - // compositer for parallel operation - if (!this->Internals->Compositor) - { - this->Internals->UpdateAll(); - vtkSurfaceLICComposite *compositor = vtkSurfaceLICComposite::New(); - compositor->SetContext(this->Internals->Context); - this->Internals->Compositor = compositor; - compositor->Delete(); - } - - // image LIC - if (!this->Internals->LICer) - { - initialized = false; - - vtkLineIntegralConvolution2D *LICer = vtkLineIntegralConvolution2D::New(); - LICer->SetContext(this->Internals->Context); - this->Internals->LICer = LICer; - LICer->Delete(); - } - - // frame buffers - if (!this->Internals->FBO) - { - initialized = false; - - vtkFrameBufferObject2 * fbo = vtkFrameBufferObject2::New(); - fbo->SetContext(this->Internals->Context); - this->Internals->FBO = fbo; - fbo->Delete(); - } - - // load shader codes - vtkOpenGLRenderWindow *renWin = this->Internals->Context; - - if (!this->Internals->ColorPass) - { - initialized = false; - BuildAShader(renWin, &this->Internals->ColorPass, - vtkTextureObjectVS, vtkSurfaceLICMapper_SC); - } - - if (!this->Internals->ColorEnhancePass) - { - initialized = false; - BuildAShader(renWin, &this->Internals->ColorEnhancePass, - vtkTextureObjectVS, vtkSurfaceLICMapper_CE); - } - - if (!this->Internals->CopyPass) - { - initialized = false; - BuildAShader(renWin, &this->Internals->CopyPass, - vtkTextureObjectVS, vtkSurfaceLICMapper_DCpy); - } - - // if any of the above were not already initialized - // then execute all stages - if (!initialized) - { - this->Internals->UpdateAll(); - } -} - -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::NeedToColorLIC() -{ - if ( this->Internals->ColorNeedsUpdate - || this->Internals->LICNeedsUpdate - || this->Internals->GatherNeedsUpdate - || this->Internals->GeometryNeedsUpdate - || this->Internals->CommunicatorNeedsUpdate - || this->Internals->OutputDataNeedsUpdate - || this->Internals->ContextNeedsUpdate - || this->AlwaysUpdate ) - { - this->Internals->ColorNeedsUpdate = true; - } - - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " NeedToColorLIC " << this->Internals->ColorNeedsUpdate << endl; - #endif - return this->Internals->ColorNeedsUpdate; -} - -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::NeedToComputeLIC() -{ - if ( this->Internals->LICNeedsUpdate - || this->Internals->GatherNeedsUpdate - || this->Internals->GeometryNeedsUpdate - || this->Internals->CommunicatorNeedsUpdate - || this->Internals->OutputDataNeedsUpdate - || this->Internals->ContextNeedsUpdate - || this->AlwaysUpdate ) - { - this->Internals->LICNeedsUpdate = true; - } - - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " NeedToComputeLIC " << this->Internals->LICNeedsUpdate << endl; - #endif - return this->Internals->LICNeedsUpdate; -} - -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::NeedToGatherVectors() -{ - if ( this->Internals->GatherNeedsUpdate - || this->Internals->GeometryNeedsUpdate - || this->Internals->OutputDataNeedsUpdate - || this->Internals->CommunicatorNeedsUpdate - || this->Internals->ContextNeedsUpdate - || this->AlwaysUpdate ) - { - this->Internals->GatherNeedsUpdate = true; - } - - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " NeedToGatherVectors " - << this->Internals->GatherNeedsUpdate << endl; - #endif - return this->Internals->GatherNeedsUpdate; -} - -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::NeedToRenderGeometry( - vtkRenderer *renderer, - vtkActor *actor) -{ - // view changed or - // user modifiable parameters - if ( this->Internals->GeometryNeedsUpdate - || this->Internals->CommunicatorNeedsUpdate - || this->Internals->OutputDataNeedsUpdate - || this->Internals->ContextNeedsUpdate - || this->AlwaysUpdate ) - { - this->Internals->GeometryNeedsUpdate = true; - } - - // lights changed - if ( this->Internals->LightingChanged() ) - { - this->Internals->GeometryNeedsUpdate = true; - } - - // props changed - long long propMTime = actor->GetProperty()->GetMTime(); - if ( this->Internals->LastPropertyMTime != propMTime ) - { - this->Internals->LastPropertyMTime = propMTime; - this->Internals->GeometryNeedsUpdate = true; - } - - // background colors changed - if (this->Internals->BackgroundChanged(renderer)) - { - this->Internals->GeometryNeedsUpdate = true; - this->Internals->ColorNeedsUpdate = true; - } - - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " NeedToUpdateGeometry " - << this->Internals->GeometryNeedsUpdate << endl; - #endif - return this->Internals->GeometryNeedsUpdate; -} - -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::NeedToUpdateCommunicator() -{ - // no comm or externally modfied paramters - if ( this->Internals->CommunicatorNeedsUpdate - || this->Internals->ContextNeedsUpdate - || this->Internals->OutputDataNeedsUpdate - || !this->Internals->Communicator - || this->AlwaysUpdate ) - { - this->Internals->CommunicatorNeedsUpdate = true; - this->Internals->UpdateAll(); - } - - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " NeedToUpdateCommunicator " - << this->Internals->CommunicatorNeedsUpdate << endl; - #endif - - return this->Internals->CommunicatorNeedsUpdate; -} - -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::NeedToUpdateOutputData() -{ - vtkDataObject *input = this->GetInput(); - // input dataset changed - long long inputMTime = input->GetMTime(); - if ( (this->Internals->LastInputDataSetMTime < inputMTime) - || !this->Output - || this->AlwaysUpdate) - { - this->Internals->LastInputDataSetMTime = inputMTime; - this->Internals->UpdateAll(); - } - - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " NeedToUpdateOutputData " << this->Internals->OutputDataNeedsUpdate << endl; - #endif - return this->Internals->OutputDataNeedsUpdate; -} - -//---------------------------------------------------------------------------- -void vtkSurfaceLICMapper::ValidateContext(vtkRenderer *renderer) -{ - bool modified = false; - - vtkOpenGLRenderWindow *context - = vtkOpenGLRenderWindow::SafeDownCast(renderer->GetRenderWindow()); - - // context changed - if (this->Internals->Context != context) - { - modified = true; - if (this->Internals->Context) - { - this->ReleaseGraphicsResources(this->Internals->Context); - } - this->Internals->Context = context; - } - - // viewport size changed - int viewsize[2]; - renderer->GetTiledSize(&viewsize[0], &viewsize[1]); - if ( this->Internals->Viewsize[0] != viewsize[0] - || this->Internals->Viewsize[1] != viewsize[1] ) - { - modified = true; - - // udpate view size - this->Internals->Viewsize[0] = viewsize[0]; - this->Internals->Viewsize[1] = viewsize[1]; - - // resize textures - this->Internals->ClearTextures(); - this->Internals->AllocateTextures(context, viewsize); - } +#include "vtkPolyData.h" +#include "vtkShaderProgram.h" - // view changed - if (this->Internals->ViewChanged()) - { - modified = true; - } +#include "vtkOpenGLVertexBufferObject.h" +#include "vtkOpenGLVertexArrayObject.h" +#include "vtkOpenGLIndexBufferObject.h" - // if anything changed execute all stages - if (modified) - { - this->Internals->UpdateAll(); - } +// use parallel timer for benchmarks and scaling +// if not defined vtkTimerLOG is used. +// #define vtkSurfaceLICMapperTIME +#if !defined(vtkSurfaceLICMapperTIME) +#include "vtkTimerLog.h" +#endif - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " NeedToUpdatContext " << modified << endl; - #endif -} +//---------------------------------------------------------------------------- +vtkObjectFactoryNewMacro(vtkSurfaceLICMapper); //---------------------------------------------------------------------------- -vtkPainterCommunicator *vtkSurfaceLICMapper::CreateCommunicator(int) +vtkSurfaceLICMapper::vtkSurfaceLICMapper() { - return new vtkPainterCommunicator; + this->SetInputArrayToProcess(0,0,0, + vtkDataObject::FIELD_ASSOCIATION_POINTS_THEN_CELLS, + vtkDataSetAttributes::VECTORS); + + this->VectorVBO = vtkOpenGLVertexBufferObject::New(); + this->LICInterface = vtkSurfaceLICInterface::New(); } //---------------------------------------------------------------------------- -void vtkSurfaceLICMapper::CreateCommunicator( - vtkRenderer *ren, - vtkActor *act) +vtkSurfaceLICMapper::~vtkSurfaceLICMapper() { - // compute screen space pixel extent of local blocks and - // union of local blocks. only blocks that pass view frustum - // visibility test are used in the computation. - - vtkDataObject *input = this->GetInput(); - - - this->Internals->DataSetExt.Clear(); - this->Internals->BlockExts.clear(); - - int includeRank = this->Internals->ProjectBounds( - ren, act, input, - this->Internals->Viewsize, - this->Internals->DataSetExt, - this->Internals->BlockExts); - - delete this->Internals->Communicator; - this->Internals->Communicator = this->CreateCommunicator(includeRank); - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " is rendering " << includeRank << endl; + cerr << "=====vtkSurfaceLICMapper::~vtkSurfaceLICMapper" << endl; #endif + + this->VectorVBO->Delete(); + this->VectorVBO = 0; + this->LICInterface->Delete(); + this->LICInterface = 0; } -//----------------------------------------------------------------------------- -void vtkSurfaceLICMapper::ProcessInformation( - vtkInformation* vtkNotUsed(info)) +void vtkSurfaceLICMapper::ShallowCopy(vtkAbstractMapper *mapper) { - #if vtkSurfaceLICMapperDEBUG >= 1 - bool LUTNeedsUpdate = false; - #endif + vtkSurfaceLICMapper *m = vtkSurfaceLICMapper::SafeDownCast(mapper); + this->LICInterface->ShallowCopy(m->GetLICInterface()); - // detect when the LUT has been modified - vtkScalarsToColors *lut = this->GetLookupTable(); - long long lutMTime; - if (lut && ((lutMTime = lut->GetMTime()) > this->Internals->LastLUTMTime)) - { - this->Internals->LastLUTMTime = lutMTime; - this->Internals->UpdateAll(); - #if vtkSurfaceLICMapperDEBUG >= 1 - LUTNeedsUpdate = true; - #endif - } + this->SetInputArrayToProcess(0, + m->GetInputArrayInformation(0)); + this->SetScalarVisibility(m->GetScalarVisibility()); - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " NeedToUpdateLUT " << LUTNeedsUpdate << endl; - #endif + // Now do superclass + this->vtkOpenGLPolyDataMapper::ShallowCopy(mapper); } //---------------------------------------------------------------------------- -void vtkSurfaceLICMapper::SetUpdateAll() +void vtkSurfaceLICMapper::ReleaseGraphicsResources(vtkWindow* win) { - this->Internals->UpdateAll(); + this->LICInterface->ReleaseGraphicsResources(win); + this->VectorVBO->ReleaseGraphicsResources(); + this->Superclass::ReleaseGraphicsResources(win); } void vtkSurfaceLICMapper::ReplaceShaderValues( @@ -2464,12 +93,12 @@ void vtkSurfaceLICMapper::ReplaceShaderValues( // add some code to handle the LIC vectors and mask vtkShaderProgram::Substitute(VSSource, "//VTK::TCoord::Dec", - "attribute vec3 tcoordMC;\n" + "attribute vec3 vecsMC;\n" "varying vec3 tcoordVCVSOutput;\n" ); vtkShaderProgram::Substitute(VSSource, "//VTK::TCoord::Impl", - "tcoordVCVSOutput = tcoordMC;" + "tcoordVCVSOutput = vecsMC;" ); vtkShaderProgram::Substitute(FSSource, @@ -2511,8 +140,22 @@ void vtkSurfaceLICMapper::SetMapperShaderParameters( vtkOpenGLHelper &cellBO, vtkRenderer* ren, vtkActor *actor) { + if (cellBO.IBO->IndexCount && (this->VBOBuildTime > cellBO.AttributeUpdateTime || + cellBO.ShaderSourceTime > cellBO.AttributeUpdateTime)) + { + cellBO.VAO->Bind(); + if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VectorVBO, + "vecsMC", this->VectorVBO->TCoordOffset, + this->VectorVBO->Stride, VTK_FLOAT, this->VectorVBO->TCoordComponents, + false)) + { + vtkErrorMacro(<< "Error setting 'vecsMC' in shader VAO."); + } + } + this->Superclass::SetMapperShaderParameters(cellBO, ren, actor); - cellBO.Program->SetUniformi("uMaskOnSurface", this->MaskOnSurface); + cellBO.Program->SetUniformi("uMaskOnSurface", + this->LICInterface->GetMaskOnSurface()); } //---------------------------------------------------------------------------- @@ -2520,12 +163,6 @@ void vtkSurfaceLICMapper::RenderPiece( vtkRenderer *renderer, vtkActor *actor) { - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr - << this->Internals->Communicator->GetWorldRank() - << " ===== " << this->GetClassName() << "::RenderInternal" << endl; - #endif - #ifdef vtkSurfaceLICMapperTIME this->StartTimerEvent("vtkSurfaceLICMapper::RenderInternal"); #else @@ -2535,45 +172,25 @@ void vtkSurfaceLICMapper::RenderPiece( vtkOpenGLClearErrorMacro(); - this->ValidateContext(renderer); - vtkOpenGLRenderWindow *renWin = - vtkOpenGLRenderWindow::SafeDownCast(renderer->GetVTKWindow()); + this->LICInterface->ValidateContext(renderer); - if (this->NeedToUpdateOutputData()) - { - // if the input data has changed we need to - // reload vector attributes and recompute - // all, but only if the output is valid. - this->PrepareOutput(); - } + this->LICInterface->UpdateCommunicator(renderer, actor, this->GetInput()); - if (this->NeedToUpdateCommunicator()) - { - #ifdef vtkSurfaceLICMapperTIME - this->StartTimerEvent("vtkSurfaceLICMapper::CreateCommunicator"); - #endif - // create a communicator that contains only ranks - // that have visible data. In parallel this is a - // collective operation accross all ranks. In - // serial this is a no-op. - this->CreateCommunicator(renderer,actor); - #ifdef vtkSurfaceLICMapperTIME - this->EndTimerEvent("vtkSurfaceLICMapper::CreateCommunicator"); - #endif - } - vtkPainterCommunicator *comm = this->Internals->Communicator; + vtkPainterCommunicator *comm = this->LICInterface->GetCommunicator(); if (comm->GetIsNull()) { // other rank's may have some visible data but we // have none and should not participate further - #ifdef vtkSurfaceLICMapperTIME - this->EndTimerEvent("vtkSurfaceLICMapper::RenderInternal"); - #endif return; } - if (!this->CanRenderSurfaceLIC(actor)) + this->CurrentInput = this->GetInput(); + vtkDataArray *vectors = NULL; + vectors = this->GetInputArrayToProcess(0, this->CurrentInput); + this->LICInterface->SetHasVectors(vectors != NULL ? true : false); + + if (!this->LICInterface->CanRenderSurfaceLIC(actor)) { // we've determined that there's no work for us, or that the // requisite opengl extensions are not available. pass control on @@ -2587,560 +204,27 @@ void vtkSurfaceLICMapper::RenderPiece( // allocate rendering resources, initialize or update // textures and shaders. - this->InitializeResources(); - - vtkPixelExtent viewExt( - this->Internals->Viewsize[0], - this->Internals->Viewsize[1]); - - // save the active fbo and its draw buffer - int prevDrawBuf = 0; - glGetIntegerv(GL_DRAW_BUFFER, &prevDrawBuf); - - int prevFbo = 0; - glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &prevFbo); - - // ------------------------------------------- render geometry, project vectors onto screen, etc - if (this->NeedToRenderGeometry(renderer, actor)) - { - #ifdef vtkSurfaceLICMapperTIME - this->StartTimerEvent("vtkSurfaceLICMapper::RenderGeometry"); - #endif + this->LICInterface->InitializeResources(); - // setup our fbo - vtkFrameBufferObject2 *fbo = this->Internals->FBO; - fbo->SaveCurrentBindings(); - fbo->Bind(GL_FRAMEBUFFER); - fbo->AddDepthAttachment(GL_DRAW_FRAMEBUFFER, this->Internals->DepthImage); - fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 0U, this->Internals->GeometryImage); - fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 1U, this->Internals->VectorImage); - fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 2U, this->Internals->MaskVectorImage); - fbo->ActivateDrawBuffers(3); - vtkCheckFrameBufferStatusMacro(GL_FRAMEBUFFER); - - // clear internal color and depth buffers - // the LIC'er requires *all* fragments in the vector - // texture to be initialized to 0 - glDisable(GL_BLEND); - glEnable(GL_DEPTH_TEST); - glDisable(GL_SCISSOR_TEST); - glClearColor(0.0, 0.0, 0.0, 0.0); - glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT); - - this->CurrentInput = vtkPolyData::SafeDownCast(this->Output); - - this->RenderPieceStart(renderer, actor); - this->RenderPieceDraw(renderer, actor); - this->RenderEdges(renderer,actor); - this->RenderPieceFinish(renderer, actor); -// this->Superclass::RenderPiece(renderer, actor); - - fbo->RemoveRenDepthAttachment(GL_DRAW_FRAMEBUFFER); - fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 0U); - fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 1U); - fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 2U); - fbo->DeactivateDrawBuffers(); - fbo->UnBind(GL_FRAMEBUFFER); - - #ifdef vtkSurfaceLICMapperTIME - this->EndTimerEvent("vtkSurfaceLICMapper::RenderGeometry"); - #endif - #if vtkSurfaceLICMapperDEBUG >= 2 - vtkTextureIO::Write( - mpifn(comm,"slicp_geometry_image.vtm"), - this->Internals->GeometryImage, - this->Internals->BlockExts); - vtkTextureIO::Write( - mpifn(comm,"slicp_vector_image.vtm"), - this->Internals->VectorImage, - this->Internals->BlockExts); - vtkTextureIO::Write( - mpifn(comm,"slicp_mask_vector_image.vtm"), - this->Internals->MaskVectorImage, - this->Internals->BlockExts); - #if defined(USE_DEPTH_TEXTURE) - vtkTextureIO::Write( - mpifn(comm,"slicp_depth_image.vtm"), - this->Internals->DepthImage, - this->Internals->BlockExts); - #endif - #endif - } + // draw the geometry + this->LICInterface->PrepareForGeometry(); + this->RenderPieceStart(renderer, actor); + this->RenderPieceDraw(renderer, actor); + this->RenderEdges(renderer,actor); + this->RenderPieceFinish(renderer, actor); + this->LICInterface->CompletedGeometry(); // --------------------------------------------- compoiste vectors for parallel LIC - if (this->NeedToGatherVectors()) - { - #ifdef vtkSurfaceLICMapperTIME - this->StartTimerEvent("vtkSurfaceLICMapper::GatherVectors"); - #endif - - // get tight screen space bounds to reduce communication/computation - vtkPixelBufferObject *vecPBO = this->Internals->VectorImage->Download(); - void *pVecPBO = vecPBO->MapPackedBuffer(); - - this->Internals->GetPixelBounds( - (float*)pVecPBO, - this->Internals->Viewsize[0], - this->Internals->BlockExts); - - // initialize compositor - this->Internals->Compositor->Initialize( - viewExt, - this->Internals->BlockExts, - this->CompositeStrategy, - this->StepSize, - this->NumberOfSteps, - this->NormalizeVectors, - this->EnhancedLIC, - this->AntiAlias); - - if (comm->GetMPIInitialized()) - { - // parallel run - // need to use the communicator provided by the rendering engine - this->Internals->Compositor->SetCommunicator(comm); - - // build compositing program and set up the screen space decomp - // with guard pixels - int iErr = 0; - iErr = this->Internals->Compositor->BuildProgram((float*)pVecPBO); - if (iErr) - { - vtkErrorMacro("Failed to construct program, reason " << iErr); - } - - // composite vectors - vtkTextureObject *compositeVectors = this->Internals->CompositeVectorImage; - iErr = this->Internals->Compositor->Gather( - pVecPBO, - VTK_FLOAT, - 4, - compositeVectors); - if (iErr) - { - vtkErrorMacro("Failed to composite vectors, reason " << iErr); - } - - // composite mask vectors - vtkTextureObject *compositeMaskVectors = this->Internals->CompositeMaskVectorImage; - vtkPixelBufferObject *maskVecPBO = this->Internals->MaskVectorImage->Download(); - void *pMaskVecPBO = maskVecPBO->MapPackedBuffer(); - iErr = this->Internals->Compositor->Gather( - pMaskVecPBO, - VTK_FLOAT, - 4, - compositeMaskVectors); - if (iErr) - { - vtkErrorMacro("Failed to composite mask vectors, reason " << iErr); - } - maskVecPBO->UnmapPackedBuffer(); - maskVecPBO->Delete(); - - // restore the default communicator - this->Internals->Compositor->RestoreDefaultCommunicator(); - - #if vtkSurfaceLICMapperDEBUG >= 2 - vtkTextureIO::Write( - mpifn(comm,"slicp_new_vector_image.vtm"), - this->Internals->CompositeVectorImage, - this->Internals->Compositor->GetDisjointGuardExtents()); - - vtkTextureIO::Write( - mpifn(comm,"slicp_new_mask_vector_image.vtm"), - this->Internals->CompositeMaskVectorImage, - this->Internals->Compositor->GetDisjointGuardExtents()); - #endif - } - else - { - // serial run - // make the decomposition disjoint and add guard pixels - this->Internals->Compositor->InitializeCompositeExtents((float*)pVecPBO); - - // use the lic decomp from here on out, in serial we have this - // flexibility because we don't need to worry about ordered compositing - // or IceT's scissor boxes - this->Internals->BlockExts - = this->Internals->Compositor->GetCompositeExtents(); - - // pass through without compositing - this->Internals->CompositeVectorImage = this->Internals->VectorImage; - this->Internals->CompositeMaskVectorImage = this->Internals->MaskVectorImage; - } - - vecPBO->UnmapPackedBuffer(); - vecPBO->Delete(); - - #ifdef vtkSurfaceLICMapperTIME - this->EndTimerEvent("vtkSurfaceLICMapper::GatherVectors"); - #endif - } + this->LICInterface->GatherVectors(); // ------------------------------------------- LIC on screen - if ( this->NeedToComputeLIC() ) - { - #if vtkSurfaceLICMapperDEBUG >= 2 - ostringstream oss; - if ( this->GenerateNoiseTexture ) - { - const char *noiseType[3]={"unif","gauss","perl"}; - oss - << "slicp_noise_" - << noiseType[this->NoiseType] - << "_size_" << this->NoiseTextureSize - << "_grain_" << this->NoiseGrainSize - << "_minval_" << this->MinNoiseValue - << "_maxval_" << this->MaxNoiseValue - << "_nlevels_" << this->NumberOfNoiseLevels - << "_impulseprob_" << this->ImpulseNoiseProbability - << "_impulseprob_" << this->ImpulseNoiseBackgroundValue - << ".vtk"; - } - else - { - oss << "slicp_noise_default.vtk"; - } - vtkTextureIO::Write( - mpifn(comm, oss.str().c_str()), - this->Internals->NoiseImage); - #endif - #ifdef vtkSurfaceLICMapperTIME - this->StartTimerEvent("vtkSurfaceLICMapper::ComputeLIC"); - #endif - - // TODO -- this means that the steps size is a function - // of aspect ratio which is pretty insane... - // convert from window units to texture units - // this isn't correct since there's no way to account - // for anisotropy in the trasnform to texture space - double tcScale[2] = { - 1.0/this->Internals->Viewsize[0], - 1.0/this->Internals->Viewsize[1]}; - - double stepSize - = this->StepSize*sqrt(tcScale[0]*tcScale[0]+tcScale[1]*tcScale[1]); - - stepSize = stepSize <= 0.0 ? 1.0e-10 : stepSize; - - // configure image lic - vtkLineIntegralConvolution2D *LICer = this->Internals->LICer; - - LICer->SetStepSize(stepSize); - LICer->SetNumberOfSteps(this->NumberOfSteps); - LICer->SetEnhancedLIC(this->EnhancedLIC); - switch (this->EnhanceContrast) - { - case ENHANCE_CONTRAST_LIC: - case ENHANCE_CONTRAST_BOTH: - LICer->SetEnhanceContrast(vtkLIC2D::ENHANCE_CONTRAST_ON); - break; - default: - LICer->SetEnhanceContrast(vtkLIC2D::ENHANCE_CONTRAST_OFF); - } - LICer->SetLowContrastEnhancementFactor(this->LowLICContrastEnhancementFactor); - LICer->SetHighContrastEnhancementFactor(this->HighLICContrastEnhancementFactor); - LICer->SetAntiAlias(this->AntiAlias); - LICer->SetComponentIds(0, 1); - LICer->SetNormalizeVectors(this->NormalizeVectors); - LICer->SetMaskThreshold(this->MaskThreshold); - LICer->SetCommunicator(comm); - - // loop over composited extents - const deque &compositeExts - = this->Internals->Compositor->GetCompositeExtents(); - - const deque &disjointGuardExts - = this->Internals->Compositor->GetDisjointGuardExtents(); - - this->Internals->LICImage.TakeReference( - LICer->Execute( - viewExt, // screen extent - disjointGuardExts, // disjoint extent of valid vectors - compositeExts, // disjoint extent where lic is needed - this->Internals->CompositeVectorImage, - this->Internals->CompositeMaskVectorImage, - this->Internals->NoiseImage)); - - if (!this->Internals->LICImage) - { - vtkErrorMacro("Failed to compute image LIC"); - return; - } - - #ifdef vtkSurfaceLICMapperTIME - this->EndTimerEvent("vtkSurfaceLICMapper::ComputeLIC"); - #endif - #if vtkSurfaceLICMapperDEBUG >= 2 - vtkTextureIO::Write( - mpifn(comm,"slicp_lic.vtm"), - this->Internals->LICImage, - compositeExts); - #endif - - // ------------------------------------------- move from LIC decomp back to geometry decomp - if ( comm->GetMPIInitialized() - && (this->Internals->Compositor->GetStrategy()!=COMPOSITE_INPLACE ) ) - { - #ifdef vtkSurfaceLICMapperTIME - this->StartTimerEvent("vtkSurfaceLICMapper::ScatterLIC"); - #endif - - // parallel run - // need to use the communicator provided by the rendering engine - this->Internals->Compositor->SetCommunicator(comm); - - vtkPixelBufferObject *licPBO = this->Internals->LICImage->Download(); - void *pLicPBO = licPBO->MapPackedBuffer(); - vtkTextureObject *newLicImage = NULL; - int iErr = this->Internals->Compositor->Scatter(pLicPBO, VTK_FLOAT, 4, newLicImage); - if (iErr) - { - vtkErrorMacro("Failed to scatter lic"); - } - licPBO->UnmapPackedBuffer(); - licPBO->Delete(); - this->Internals->LICImage = NULL; - this->Internals->LICImage = newLicImage; - newLicImage->Delete(); - - // restore the default communicator - this->Internals->Compositor->RestoreDefaultCommunicator(); - - #ifdef vtkSurfaceLICMapperTIME - this->EndTimerEvent("vtkSurfaceLICMapper::ScatterLIC"); - #endif - #if vtkSurfaceLICMapperDEBUG >= 2 - vtkTextureIO::Write( - mpifn(comm,"slicp_new_lic.vtm"), - this->Internals->LICImage, - this->Internals->BlockExts); - #endif - } - } + this->LICInterface->ApplyLIC(); // ------------------------------------------- combine scalar colors + LIC - if ( this->NeedToColorLIC() ) - { - #ifdef vtkSurfaceLICMapperTIME - this->StartTimerEvent("vtkSurfaceLICMapper::ColorLIC"); - #endif - vtkFrameBufferObject2 *fbo = this->Internals->FBO; - fbo->SaveCurrentBindings(); - fbo->Bind(GL_FRAMEBUFFER); - fbo->InitializeViewport(this->Internals->Viewsize[0], this->Internals->Viewsize[1]); - fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 0U, this->Internals->RGBColorImage); - fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 1U, this->Internals->HSLColorImage); - fbo->ActivateDrawBuffers(2U); - vtkCheckFrameBufferStatusMacro(GL_FRAMEBUFFER); - - #if 0 - glDisable(GL_SCISSOR_TEST); - glClearColor(0.0, 0.0, 0.0, 0.0); - glClear(GL_COLOR_BUFFER_BIT); - #else - // clear the parts of the screen which we will modify - glEnable(GL_SCISSOR_TEST); - glClearColor(0.0, 0.0, 0.0, 0.0); - size_t nBlocks = this->Internals->BlockExts.size(); - for (size_t e=0; eInternals->BlockExts[e]; - ext.Grow(2); // halo for linear filtering - ext &= viewExt; - - unsigned int extSize[2]; - ext.Size(extSize); - - glScissor(ext[0], ext[2], extSize[0], extSize[1]); - glClear(GL_COLOR_BUFFER_BIT); - } - glDisable(GL_SCISSOR_TEST); - #endif - - this->Internals->VectorImage->Activate(); - this->Internals->GeometryImage->Activate(); - this->Internals->LICImage->Activate(); - - vtkShaderProgram *colorPass = this->Internals->ColorPass->Program; - renWin->GetShaderCache()->ReadyShaderProgram(colorPass); - colorPass->SetUniformi("texVectors", - this->Internals->VectorImage->GetTextureUnit()); - colorPass->SetUniformi("texGeomColors", - this->Internals->GeometryImage->GetTextureUnit()); - colorPass->SetUniformi("texLIC", - this->Internals->LICImage->GetTextureUnit()); - colorPass->SetUniformi("uScalarColorMode", this->ColorMode); - colorPass->SetUniformf("uLICIntensity", this->LICIntensity); - colorPass->SetUniformf("uMapBias", this->MapModeBias); - colorPass->SetUniformf("uMaskIntensity", this->MaskIntensity); - float fMaskColor[3]; - fMaskColor[0] = this->MaskColor[0]; - fMaskColor[1] = this->MaskColor[1]; - fMaskColor[2] = this->MaskColor[2]; - colorPass->SetUniform3f("uMaskColor", fMaskColor); - - for (size_t e=0; eInternals->RenderQuad(viewExt, this->Internals->BlockExts[e], - this->Internals->ColorPass); - } - - this->Internals->VectorImage->Deactivate(); - this->Internals->GeometryImage->Deactivate(); - this->Internals->LICImage->Deactivate(); - - #ifdef vtkSurfaceLICMapperTIME - this->EndTimerEvent("vtkSurfaceLICMapper::ColorLIC"); - #endif - - // --------------------------------------------- color contrast enhance - if ( ( this->EnhanceContrast == ENHANCE_CONTRAST_COLOR ) - || ( this->EnhanceContrast == ENHANCE_CONTRAST_BOTH ) ) - { - #if vtkSurfaceLICMapperDEBUG >= 2 - vtkTextureIO::Write( - mpifn(comm,"slic_color_rgb_in.vtm"), - this->Internals->RGBColorImage, - this->Internals->BlockExts); - vtkTextureIO::Write( - mpifn(comm,"slic_color_hsl_in.vtm"), - this->Internals->HSLColorImage, - this->Internals->BlockExts); - #endif - #ifdef vtkSurfaceLICMapperTIME - this->StartTimerEvent("vtkSurfaceLICMapper::ContrastEnhance"); - #endif - - // find min/max lighness value for color contrast enhancement. - float LMin = VTK_FLOAT_MAX; - float LMax = -VTK_FLOAT_MAX; - float LMaxMinDiff = VTK_FLOAT_MAX; - - #ifdef STREAMING_MIN_MAX - StreamingFindMinMax(fbo, this->Internals->BlockExts, LMin, LMax); - #else - FindMinMax( - this->Internals->HSLColorImage, - this->Internals->BlockExts, - LMin, - LMax); - #endif - - if ( this->Internals->BlockExts.size() - && ((LMax <= LMin) || (LMin < 0.0f) || (LMax > 1.0f)) ) - { - vtkErrorMacro( - << comm->GetRank() - << ": Invalid range " << LMin << ", " << LMax - << " for color contrast enhancement"); - LMin = 0.0; - LMax = 1.0; - LMaxMinDiff = 1.0; - } - - // global collective reduction for parallel operation - this->GetGlobalMinMax(comm, LMin, LMax); - - // set M and m as a fraction of the range. - LMaxMinDiff = LMax-LMin; - LMin += LMaxMinDiff*this->LowColorContrastEnhancementFactor; - LMax -= LMaxMinDiff*this->HighColorContrastEnhancementFactor; - LMaxMinDiff = LMax-LMin; - - // normalize shader - fbo->AddColorAttachment(GL_DRAW_FRAMEBUFFER, 0U, this->Internals->RGBColorImage); - fbo->ActivateDrawBuffer(0U); - vtkCheckFrameBufferStatusMacro(GL_DRAW_FRAMEBUFFER); - - this->Internals->GeometryImage->Activate(); - this->Internals->HSLColorImage->Activate(); - this->Internals->LICImage->Activate(); - - vtkShaderProgram *colorEnhancePass = - this->Internals->ColorEnhancePass->Program; - renWin->GetShaderCache()->ReadyShaderProgram(colorEnhancePass); - colorEnhancePass->SetUniformi("texGeomColors", - this->Internals->GeometryImage->GetTextureUnit()); - colorEnhancePass->SetUniformi("texHSLColors", - this->Internals->HSLColorImage->GetTextureUnit()); - colorEnhancePass->SetUniformi("texLIC", - this->Internals->LICImage->GetTextureUnit()); - colorEnhancePass->SetUniformf("uLMin", LMin); - colorEnhancePass->SetUniformf("uLMaxMinDiff", LMaxMinDiff); - - for (size_t e=0; eInternals->RenderQuad(viewExt, this->Internals->BlockExts[e], - this->Internals->ColorEnhancePass); - } - - this->Internals->GeometryImage->Deactivate(); - this->Internals->HSLColorImage->Deactivate(); - this->Internals->LICImage->Deactivate(); - - fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 0U); - fbo->DeactivateDrawBuffers(); - - #ifdef vtkSurfaceLICMapperTIME - this->EndTimerEvent("vtkSurfaceLICMapper::ContrastEnhance"); - #endif - } - else - { - fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 0U); - fbo->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 1U); - fbo->DeactivateDrawBuffers(); - } - - fbo->UnBind(GL_FRAMEBUFFER); - - #if vtkSurfaceLICMapperDEBUG >= 2 - vtkTextureIO::Write( - mpifn(comm,"slicp_new_rgb.vtm"), - this->Internals->RGBColorImage, - this->Internals->BlockExts); - #endif - } + this->LICInterface->CombineColorsAndLIC(); // ----------------------------------------------- depth test and copy to screen - #ifdef vtkSurfaceLICMapperTIME - this->StartTimerEvent("vtkSurfaceLICMapper::DepthCopy"); - #endif - glBindFramebuffer(GL_FRAMEBUFFER, prevFbo); - glDrawBuffer(prevDrawBuf); - vtkFrameBufferObject2::InitializeViewport( - this->Internals->Viewsize[0], - this->Internals->Viewsize[1]); - glEnable(GL_DEPTH_TEST); - - this->Internals->DepthImage->Activate(); - this->Internals->RGBColorImage->Activate(); - - vtkShaderProgram *copyPass = - this->Internals->CopyPass->Program; - renWin->GetShaderCache()->ReadyShaderProgram(copyPass); - copyPass->SetUniformi("texDepth", - this->Internals->DepthImage->GetTextureUnit()); - copyPass->SetUniformi("texRGBColors", - this->Internals->RGBColorImage->GetTextureUnit()); - - size_t nBlocks = this->Internals->BlockExts.size(); - for (size_t e=0; eInternals->RenderQuad(viewExt, this->Internals->BlockExts[e], - this->Internals->CopyPass); - } - - this->Internals->DepthImage->Deactivate(); - this->Internals->RGBColorImage->Deactivate(); - - #ifdef vtkSurfaceLICMapperTIME - this->EndTimerEvent("vtkSurfaceLICMapper::DepthCopy"); - #endif - - // - this->Internals->Updated(); + this->LICInterface->CopyToScreen(); // clear opengl error flags and be absolutely certain that nothing failed. vtkOpenGLCheckErrorMacro("failed during surface lic painter"); @@ -3152,180 +236,55 @@ void vtkSurfaceLICMapper::RenderPiece( #endif } -//----------------------------------------------------------------------------- -void vtkSurfaceLICMapper::ReportReferences(vtkGarbageCollector *collector) -{ - this->Superclass::ReportReferences(collector); - - vtkGarbageCollectorReport(collector, this->Output, "Output PolyData"); -} - -//---------------------------------------------------------------------------- -vtkDataObject* vtkSurfaceLICMapper::GetOutput() -{ - #if vtkSurfaceLICMapperDEBUG >= 1 - cerr << "=====vtkSurfaceLICMapper::GetOutput" << endl; - #endif - - if (this->Enable && this->Output) - { - return this->Output; - } - return this->GetInput(); -} - -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::PrepareOutput() +//------------------------------------------------------------------------- +void vtkSurfaceLICMapper::BuildBufferObjects(vtkRenderer *ren, vtkActor *act) { - vtkDataObject* input = this->GetInput(); - if ((input == NULL) || !this->Enable) - { - if (this->Output) - { - this->Output->Delete(); - this->Output = NULL; - this->Internals->HasVectors = false; - } - return false; - } - - if (this->Internals->OutputDataNeedsUpdate) - { - if (this->Output) - { - this->Output->Delete(); - this->Output = NULL; - } - - this->Output = input->NewInstance(); - this->Output->ShallowCopy(input); - this->Internals->HasVectors = false; - } + this->Superclass::BuildBufferObjects(ren,act); - if (!this->Internals->HasVectors) + if (!this->LICInterface->GetHasVectors()) { - this->Internals->HasVectors = this->VectorsToTCoords(this->Output); + return; } - return this->Internals->HasVectors; -} + vtkDataArray *vectors = NULL; + vectors = this->GetInputArrayToProcess(0, this->CurrentInput); -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::VectorsToTCoords(vtkDataObject *dataObj) -{ - bool hasVectors = false; + int numComp = vectors->GetNumberOfComponents(); + this->VectorVBO->VertexCount = vectors->GetNumberOfTuples(); + this->VectorVBO->TCoordComponents = numComp; + this->VectorVBO->TCoordOffset = 0; + this->VectorVBO->Stride = this->VectorVBO->TCoordComponents*sizeof(float); - vtkCompositeDataSet *cd = vtkCompositeDataSet::SafeDownCast(dataObj); - if (cd) + if (vectors->GetDataType() != VTK_FLOAT) { - vtkCompositeDataIterator* iter = cd->NewIterator(); - for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) + float *data = new float[vectors->GetNumberOfTuples()*numComp]; + double *tuple = new double [numComp]; + for (int i = 0; i < vectors->GetNumberOfTuples(); i++) { - vtkDataSet* ds = vtkDataSet::SafeDownCast(iter->GetCurrentDataObject()); - if (ds && ds->GetNumberOfCells()) + vectors->GetTuple(i,tuple); + for (int j = 0; j < numComp; j++) { - this->ClearTCoords(ds); - hasVectors |= this->VectorsToTCoords(ds); + data[i*numComp+j] = tuple[j]; } } - iter->Delete(); - return hasVectors; - } - - vtkDataSet* ds = vtkDataSet::SafeDownCast(dataObj); - if (ds && ds->GetNumberOfCells()) - { - this->ClearTCoords(ds); - hasVectors |= this->VectorsToTCoords(ds); - } - - if ( hasVectors ) - { - // force downstream updates (display lists, etc) - this->Output->Modified(); - } - - return hasVectors; -} - -//---------------------------------------------------------------------------- -bool vtkSurfaceLICMapper::VectorsToTCoords(vtkDataSet *data) -{ - // don't use SafeDownCast here for rendering performance - vtkDataArray *vectors = NULL; - - vectors = this->GetInputArrayToProcess(0, data); - - if ( vectors == NULL ) - { - return false; - } - - vtkDataSetAttributes *atts = NULL; - atts = data->GetPointData(); - int nArrays = atts->GetNumberOfArrays(); - for (int i=0; iGetArray(i) == vectors ) - { - atts->SetActiveAttribute(i, vtkDataSetAttributes::TCOORDS); - return true; - } + this->VectorVBO->Upload(data, + vectors->GetNumberOfTuples()*numComp, + vtkOpenGLBufferObject::ArrayBuffer); + delete [] data; + delete [] tuple; } - - atts = data->GetCellData(); - nArrays = atts->GetNumberOfArrays(); - for (int i=0; iGetArray(i) == vectors ) - { - atts->SetActiveAttribute(i, vtkDataSetAttributes::TCOORDS); - return true; - } + // and add our vector VBO + this->VectorVBO->Upload(static_cast(vectors->GetVoidPointer(0)), + vectors->GetNumberOfTuples()*numComp, + vtkOpenGLBufferObject::ArrayBuffer); } - return false; } -//---------------------------------------------------------------------------- -void vtkSurfaceLICMapper::ClearTCoords(vtkDataSet *data) -{ - data->GetCellData()->SetActiveAttribute(-1, vtkDataSetAttributes::TCOORDS); - data->GetPointData()->SetActiveAttribute(-1, vtkDataSetAttributes::TCOORDS); -} //---------------------------------------------------------------------------- void vtkSurfaceLICMapper::PrintSelf(ostream & os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); - os - << indent << "NumberOfSteps=" << this->NumberOfSteps << endl - << indent << "StepSize=" << this->StepSize << endl - << indent << "NormalizeVectors=" << this->NormalizeVectors << endl - << indent << "EnhancedLIC=" << this->EnhancedLIC << endl - << indent << "EnhanceContrast=" << this->EnhanceContrast << endl - << indent << "LowLICContrastEnhancementFactor=" << this->LowLICContrastEnhancementFactor << endl - << indent << "HighLICContrastEnhancementFactor=" << this->HighLICContrastEnhancementFactor << endl - << indent << "LowColorContrastEnhancementFactor=" << this->LowColorContrastEnhancementFactor << endl - << indent << "HighColorContrastEnhancementFactor=" << this->HighColorContrastEnhancementFactor << endl - << indent << "AntiAlias=" << this->AntiAlias << endl - << indent << "MaskOnSurface=" << this->MaskOnSurface << endl - << indent << "MaskThreshold=" << this->MaskThreshold << endl - << indent << "MaskIntensity=" << this->MaskIntensity << endl - << indent << "MaskColor=" << this->MaskColor[0] << ", " << this->MaskColor[1] << ", " << this->MaskColor[2] << endl - << indent << "ColorMode=" << this->ColorMode << endl - << indent << "LICIntensity=" << this->LICIntensity << endl - << indent << "MapModeBias=" << this->MapModeBias << endl - << indent << "GenerateNoiseTexture=" << this->GenerateNoiseTexture << endl - << indent << "NoiseType=" << this->NoiseType << endl - << indent << "NoiseTextureSize=" << this->NoiseTextureSize << endl - << indent << "NoiseGrainSize=" << this->NoiseGrainSize << endl - << indent << "MinNoiseValue=" << this->MinNoiseValue << endl - << indent << "MaxNoiseValue=" << this->MaxNoiseValue << endl - << indent << "NumberOfNoiseLevels=" << this->NumberOfNoiseLevels << endl - << indent << "ImpulseNoiseProbablity=" << this->ImpulseNoiseProbability << endl - << indent << "ImpulseNoiseBackgroundValue=" << this->ImpulseNoiseBackgroundValue << endl - << indent << "NoiseGeneratorSeed=" << this->NoiseGeneratorSeed << endl - << indent << "AlwaysUpdate=" << this->AlwaysUpdate << endl - << indent << "Enable=" << this->Enable << endl - << indent << "CompositeStrategy=" << this->CompositeStrategy << endl; } diff --git a/Rendering/LICOpenGL2/vtkSurfaceLICMapper.h b/Rendering/LICOpenGL2/vtkSurfaceLICMapper.h index 65b9892a3c4..b149233d8f8 100644 --- a/Rendering/LICOpenGL2/vtkSurfaceLICMapper.h +++ b/Rendering/LICOpenGL2/vtkSurfaceLICMapper.h @@ -55,12 +55,7 @@ #include "vtkRenderingLICOpenGL2Module.h" // For export macro #include "vtkOpenGLPolyDataMapper.h" -class vtkRenderWindow; -class vtkRenderer; -class vtkActor; -class vtkImageData; -class vtkDataObject; -class vtkDataArray; +class vtkSurfaceLICInterface; class vtkPainterCommunicator; class VTKRENDERINGLICOPENGL2_EXPORT vtkSurfaceLICMapper : public vtkOpenGLPolyDataMapper @@ -76,313 +71,6 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkSurfaceLICMapper : public vtkOpenGLPolyDa // resources to release. In this case, releases the display lists. virtual void ReleaseGraphicsResources(vtkWindow * win); - // Description: - // Get the output data object from this painter. - // Overridden to pass the input points (or cells) vectors as the tcoords to - // the deletage painters. This is required by the internal GLSL shader - // programs used for generating LIC. - virtual vtkDataObject* GetOutput(); - - // Description: - // Enable/Disable this painter. - void SetEnable(int val); - vtkGetMacro(Enable, int); - void SetEnableOn(){ this->SetEnable(1); } - void SetEnableOff(){ this->SetEnable(0); } - - // Description: - // Get/Set the number of integration steps in each direction. - void SetNumberOfSteps(int val); - vtkGetMacro(NumberOfSteps, int); - - // Description: - // Get/Set the step size (in pixels). - void SetStepSize(double val); - vtkGetMacro(StepSize, double); - - // Description: - // Normalize vectors during integration. When set(the default) the - // input vector field is normalized during integration, and each - // integration occurs over the same arclength. When not set each - // integration occurs over an arc length proportional to the field - // magnitude as is customary in traditional numerical methods. See, - // "Imaging Vector Fields Using Line Integral Convolution" for an - // axample where normalization is used. See, "Image Space Based - // Visualization of Unsteady Flow on Surfaces" for an example - // of where no normalization is used. - void SetNormalizeVectors(int val); - vtkBooleanMacro(NormalizeVectors, int); - vtkGetMacro(NormalizeVectors, int); - - // Description: - // When set MaskOnSurface computes |V| for use in the fragment masking - // tests on the surface. When not set the original un-projected - // un-transformed |V| is used. - void SetMaskOnSurface(int val); - vtkBooleanMacro(MaskOnSurface, int); - vtkGetMacro(MaskOnSurface, int); - - // Description: - // The MaskThreshold controls the rendering of fragments in stagnant - // regions of flow. // In these regions LIC noise texture will be masked, - // where |V| < MaskThreshold is satisifed. The masking process blends a - // the MaskColor with the scalar color of the surface proportional to - // MaskIntesnsity. See MaskIntensity for more information on the blending - // algorithm. This blending allows one control over the masking process - // so that masked fragments may be: highlighted (by setting a unique - // mask color and mask intensity > 0), made invisible with and without - // passing the un-convolved noise texture (by setting mask intensity 0), - // made to blend into the LIC. - // - // MaskThreshold units are in the original vector space. Note that the - // threshold can be applied to the original vector field or to the surface - // projected vector field. See MaskOnSurface. - void SetMaskThreshold(double val); - vtkGetMacro(MaskThreshold, double); - - // Description: - // The MaskColor is used on masked fragments. The default of (0.5, 0.5, 0.5) - // makes the masked fragments look similar to the LIC'd fragments. The mask - // color is applied only when MaskIntensity > 0. - void SetMaskColor(double *val); - void SetMaskColor(double r, double g, double b) - { double rgb[3]={r,g,b}; this->SetMaskColor(rgb); } - vtkGetVector3Macro(MaskColor, double); - - // Description: - // The MaskIntensity controls the blending of the mask color and the geometry - // color. The color of masked fragments is given by: - // - // c = maskColor * maskIntensity + geomColor * (1 - maskIntensity) - // - // The default value of 0.0 results in the geometry color being used. - void SetMaskIntensity(double val); - vtkGetMacro(MaskIntensity, double); - - // Description: - // EnhancedLIC mean compute the LIC twice with the second pass using - // the edge-enhanced result of the first pass as a noise texture. Edge - // enhancedment is made by a simple Laplace convolution. - void SetEnhancedLIC(int val); - vtkGetMacro(EnhancedLIC, int); - vtkBooleanMacro(EnhancedLIC, int); - - // Description: - // Enable/Disable contrast and dynamic range correction stages. Contrast - // enhancement can be enabled during LIC computations (See - // vtkLineINtegralComvolution2D) and after the scalar colors have been - // combined with the LIC. - // - // The best appraoch for using this feature is to enable LIC enhancement, - // and only if the image is to dark or dull enable COLOR enhancement. - // - // Both stages are implemented by a histogram stretching algorithm. During - // LIC stages the contrast enhancement is applied to gray scale LIC image. - // During the scalar coloring stage the contrast enhancement is applied to - // the lightness channel of the color image in HSL color space. The - // histogram stretching is implemented as follows: - // - // L = (L-m)/(M-m) - // - // where, L is the fragment intensity/lightness, m is the intensity/lightness - // to map to 0, M is the intensity/lightness to map to 1. The default values - // of m and M are the min and max taken over all fragments. - // - // This increase the dynamic range and contrast in the LIC'd image, both of - // which are natuarly attenuated by the convolution proccess. - // - // Values - // - // ENHANCE_CONTRAST_OFF -- don't enhance LIC or scalar colors - // ENHANCE_CONTRAST_LIC -- enhance in LIC high-pass input and output - // ENHANCE_CONTRAST_COLOR -- enhance after scalars are combined with LIC - // ENHANCE_CONTRAST_BOTH -- enhance in LIC stages and after scalar colors - // - // This feature is disabled by default. - enum { - ENHANCE_CONTRAST_OFF=0, - ENHANCE_CONTRAST_LIC=1, - ENHANCE_CONTRAST_COLOR=3, - ENHANCE_CONTRAST_BOTH=4 - }; - void SetEnhanceContrast(int val); - vtkGetMacro(EnhanceContrast, int); - - // Description: - // This feature is used to fine tune the contrast enhancement. There are two - // modes AUTOMATIC and MANUAL.In AUTOMATIC mode values are provided indicating - // the fraction of the range to adjust M and m by, during contrast enahncement - // histogram stretching. M and m are the intensity/lightness values that map - // to 1 and 0. (see EnhanceContrast for an explanation of the mapping - // procedure). m and M are computed using the factors as follows: - // - // m = min(C) + mFactor * (max(C) - min(C)) - // M = max(C) - MFactor * (max(C) - min(C)) - // - // the default values for mFactor and MFactor are 0 which result in - // m = min(C), M = max(C), taken over the entire image. Modifying mFactor and - // MFactor above or below zero provide control over the saturation/ - // de-saturation during contrast enhancement. - vtkGetMacro(LowLICContrastEnhancementFactor, double); - vtkGetMacro(HighLICContrastEnhancementFactor, double); - void SetLowLICContrastEnhancementFactor(double val); - void SetHighLICContrastEnhancementFactor(double val); - // - vtkGetMacro(LowColorContrastEnhancementFactor, double); - vtkGetMacro(HighColorContrastEnhancementFactor, double); - void SetLowColorContrastEnhancementFactor(double val); - void SetHighColorContrastEnhancementFactor(double val); - - // Description: - // Enable/Disable the anti-aliasing pass. This optional pass (disabled by - // default) can be enabled to reduce jagged patterns in the final LIC image. - // Values greater than 0 control the number of iterations, 1 is typically - // sufficient. - void SetAntiAlias(int val); - vtkBooleanMacro(AntiAlias, int); - vtkGetMacro(AntiAlias, int); - - // Description: - // Set/Get the color mode. The color mode controls how scalar colors are - // combined with the LIC in the final image. The BLEND mode combines scalar - // colors with LIC intensities with proportional blending controled by the - // LICIntensity parameter. The MAP mode combines scalar colors with LIC, - // by multiplication the HSL represntation of color's lightness. - // - // The default is COLOR_MODE_BLEND. - enum { - COLOR_MODE_BLEND=0, - COLOR_MODE_MAP - }; - void SetColorMode(int val); - vtkGetMacro(ColorMode, int); - - // Description: - // Factor used when blend mode is set to COLOR_MODE_BLEND. This controls the - // contribution of the LIC in the final output image as follows: - // - // c = LIC * LICIntensity + scalar * (1 - LICIntensity); - // - // 0.0 produces same result as disabling LIC altogether, while 1.0 implies - // show LIC result alone. - void SetLICIntensity(double val); - vtkGetMacro(LICIntensity, double); - - // Description: - // Factor used when blend mode is set to COLOR_MODE_MAP. This adds a bias to - // the LIC image. The purpose of this is to adjust the brightness when a - // brighter image is desired. The default of 0.0 results in no change. Values - // gretaer than 0.0 will brighten the image while values less than 0.0 darken - // the image. - void SetMapModeBias(double val); - vtkGetMacro(MapModeBias, double); - - // Description: - // Set the data containing a noise array as active scalars. Active scalars - // array will be converted into a texture for use as noise in the LIC process. - // Noise datasets are expected to be gray scale. - void SetNoiseDataSet(vtkImageData *data); - vtkImageData *GetNoiseDataSet(); - - // Description: - // Set/Get the noise texture source. When not set the default 200x200 white - // noise texture is used (see VTKData/Data/Data/noise.png). When set a noise - // texture is generated based on the following parameters: - // - // NoiseType - select noise type. Gaussian, Uniform, etc - // NoiseTextureSize - number of pixels in square noise texture(side) - // NoiseGrainSize - number of pixels each noise value spans(side) - // MinNoiseValue - minimum noise color >=0 && < MaxNoiseValue - // MaxNoiseValue - maximum noise color <=1 ** > MinNoiseValue - // NumberOfNoiseLevels - number of discrete noise colors - // ImpulseNoiseProbability - impulse noise is generated when < 1 - // ImpulseNoiseBackgroundValue - the background color for untouched pixels - // NoiseGeneratorSeed - seed the random number generators - // - // Changing the noise texture gives one greater control over the look of the - // final image. The default is 0 which results in the use of a static 200x200 - // Gaussian noise texture. See VTKData/Data/Data/noise.png. - void SetGenerateNoiseTexture(int shouldGenerate); - vtkGetMacro(GenerateNoiseTexture, int); - - // Description: - // Select the statistical distribution of randomly generated noise values. - // With uniform noise there is greater control over the range of values - // in the noise texture. The Default is NOISE_TYPE_GAUSSIAN. - enum { - NOISE_TYPE_UNIFORM=0, - NOISE_TYPE_GAUSSIAN=1, - NOISE_TYPE_PERLIN=2 - }; - void SetNoiseType(int type); - vtkGetMacro(NoiseType, int); - - // Description: - // Set/Get the side length in pixels of the noise texture. The texture will - // be length^2 pixels in area. - void SetNoiseTextureSize(int length); - vtkGetMacro(NoiseTextureSize, int); - - // Description: - // Each noise value will be length^2 pixels in area. - void SetNoiseGrainSize(int val); - vtkGetMacro(NoiseGrainSize, int); - - // Description: - // Set/Get the minimum and mximum gray scale values that the generated noise - // can take on. The generated noise will be in the range of MinNoiseValue to - // MaxNoiseValue. Values are clamped within 0 to 1. MinNoiseValue must be - // less than MaxNoiseValue. - void SetMinNoiseValue(double val); - void SetMaxNoiseValue(double val); - vtkGetMacro(MinNoiseValue, double); - vtkGetMacro(MaxNoiseValue, double); - - // Description: - // Set/Get the number of discrete values a noise pixel may take on. Default - // 1024. - void SetNumberOfNoiseLevels(int val); - vtkGetMacro(NumberOfNoiseLevels, int); - - // Description: - // Control the density of of the noise. A value of 1.0 produces uniform random - // noise while values < 1.0 produce impulse noise with the given probabilty. - void SetImpulseNoiseProbability(double val); - vtkGetMacro(ImpulseNoiseProbability, double); - - // Description: - // The color to use for untouched pixels when impulse noise probability < 1. - void SetImpulseNoiseBackgroundValue(double val); - vtkGetMacro(ImpulseNoiseBackgroundValue, double); - - // Description: - // Set/Get the seed value used by the random number generator. - void SetNoiseGeneratorSeed(int val); - vtkGetMacro(NoiseGeneratorSeed, int); - - // Description: - // Control the screen space decomposition where LIC is computed. - enum { - COMPOSITE_INPLACE=0, - COMPOSITE_INPLACE_DISJOINT=1, - COMPOSITE_BALANCED=2, - COMPOSITE_AUTO=3 - }; - void SetCompositeStrategy(int val); - vtkGetMacro(CompositeStrategy, int); - - // Description: - // Returns true if the rendering context supports extensions needed by this - // painter. - static bool IsSupported(vtkRenderWindow *context); - - // Description: - // Methods used for parallel benchmarks. Use cmake to define - // vtkSurfaceLICMapperTIME to enable benchmarks. During each - // update timing information is stored, it can be written to - // disk by calling WriteLog. - virtual void WriteTimerLog(const char *){} - // Description: // Implemented by sub classes. Actual rendering is done here. virtual void RenderPiece(vtkRenderer *ren, vtkActor *act); @@ -391,22 +79,14 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkSurfaceLICMapper : public vtkOpenGLPolyDa // Shallow copy of an actor. void ShallowCopy(vtkAbstractMapper *); + // Description: + // Get the vtkSurfaceLICInterface used by this mapper + vtkGetObjectMacro(LICInterface,vtkSurfaceLICInterface); + protected: vtkSurfaceLICMapper(); ~vtkSurfaceLICMapper(); - // Description: - // Called before RenderInternal() if the Information has been changed - // since the last time this method was called. We use this to detect - // when LUT has changed. - virtual void ProcessInformation(vtkInformation* info); - - // Description: - // Get the min/max across all ranks. min/max are in/out. - // In serial operation this is a no-op, in parallel it - // is a global collective reduction. - virtual void GetGlobalMinMax(vtkPainterCommunicator*, float&, float&){} - // Description: // Methods used for parallel benchmarks. Use cmake to define // vtkSurfaceLICMapperTIME to enable benchmarks. During each @@ -416,96 +96,10 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkSurfaceLICMapper : public vtkOpenGLPolyDa virtual void EndTimerEvent(const char *){} // Description: - // Creates a new communicator with/without the calling processes - // as indicated by the passed in flag, if not 0 the calling process - // is included in the new communicator. In parallel this call is mpi - // collective on the world communicator. In serial this is a no-op. - virtual vtkPainterCommunicator *CreateCommunicator(int); - - // Description: - // Creates a new communicator for internal use based on this - // rank's visible data. - void CreateCommunicator(vtkRenderer *, vtkActor *); - - // Description: - // Take part in garbage collection. - virtual void ReportReferences(vtkGarbageCollector *collector); - - // Description: - // Updates the noise texture, downsampling by the requested sample rate. - void UpdateNoiseImage(vtkRenderWindow *renWin); - - // Description: - // Look for changes that would trigger stage updates - void ValidateContext(vtkRenderer *renderer); - - // Description: - // Return false if stage can be skipped - bool NeedToUpdateOutputData(); - virtual bool NeedToUpdateCommunicator(); - bool NeedToRenderGeometry(vtkRenderer *renderer, vtkActor *actor); - bool NeedToGatherVectors(); - bool NeedToComputeLIC(); - bool NeedToColorLIC(); - void SetUpdateAll(); - - // Description: - // resoucre allocators - bool PrepareOutput(); - void InitializeResources(); - - // Description: - // set tcoords with vectors - bool VectorsToTCoords(vtkDataObject *dataObj); - bool VectorsToTCoords(vtkDataSet *dataObj); - void ClearTCoords(vtkDataSet *data); - - // Description: - // Returns true when rendering LIC is possible. - bool CanRenderSurfaceLIC(vtkActor *actor); + // Build the VBO/IBO, called by UpdateBufferObjects + virtual void BuildBufferObjects(vtkRenderer *ren, vtkActor *act); protected: - // Unit is a pixel length. - int NumberOfSteps; - double StepSize; - int NormalizeVectors; - - int EnhancedLIC; - int EnhanceContrast; - double LowLICContrastEnhancementFactor; - double HighLICContrastEnhancementFactor; - double LowColorContrastEnhancementFactor; - double HighColorContrastEnhancementFactor; - int AntiAlias; - - int MaskOnSurface; - double MaskThreshold; - double MaskIntensity; - double MaskColor[3]; - - int ColorMode; - double LICIntensity; - double MapModeBias; - - int GenerateNoiseTexture; - int NoiseType; - int NoiseTextureSize; - int NoiseGrainSize; - double MinNoiseValue; - double MaxNoiseValue; - int NumberOfNoiseLevels; - double ImpulseNoiseProbability; - double ImpulseNoiseBackgroundValue; - int NoiseGeneratorSeed; - - int AlwaysUpdate; - int Enable; - int CompositeStrategy; - - vtkDataObject* Output; - class vtkInternals; - vtkInternals* Internals; - // Description: // Set the shader parameteres related to the mapper/input data, called by UpdateShader virtual void SetMapperShaderParameters(vtkOpenGLHelper &cellBO, vtkRenderer *ren, vtkActor *act); @@ -516,6 +110,11 @@ class VTKRENDERINGLICOPENGL2_EXPORT vtkSurfaceLICMapper : public vtkOpenGLPolyDa std::map shaders, vtkRenderer *ren, vtkActor *act); + // The vector VBO and its layout. + vtkOpenGLVertexBufferObject *VectorVBO; + + vtkSurfaceLICInterface *LICInterface; + private: vtkSurfaceLICMapper(const vtkSurfaceLICMapper&); // Not implemented. void operator=(const vtkSurfaceLICMapper&); // Not implemented. diff --git a/Rendering/LOD/vtkQuadricLODActor.h b/Rendering/LOD/vtkQuadricLODActor.h index 33a78e8197d..8bdeb2ad84f 100644 --- a/Rendering/LOD/vtkQuadricLODActor.h +++ b/Rendering/LOD/vtkQuadricLODActor.h @@ -84,7 +84,6 @@ class VTKRENDERINGLOD_EXPORT vtkQuadricLODActor : public vtkActor vtkGetMacro(Static, int); vtkBooleanMacro(Static, int); -//BTX enum DataConfigurationEnum { UNKNOWN = 0, @@ -92,7 +91,7 @@ class VTKRENDERINGLOD_EXPORT vtkQuadricLODActor : public vtkActor XYPLANE, XZPLANE, YZPLANE, XYZVOLUME }; -//ETX + // Description: // Force the binning of the quadric clustering according to application // knowledge relative to the dimension of the data. For example, if you @@ -150,13 +149,12 @@ class VTKRENDERINGLOD_EXPORT vtkQuadricLODActor : public vtkActor vtkSetClampMacro(MaximumDisplayListSize, int, 1000, VTK_INT_MAX); vtkGetMacro(MaximumDisplayListSize, int); -//BTX enum PropTypeEnum { FOLLOWER = 0, ACTOR }; -//ETX + // Description: // Indicate that this actor is actually a follower. // By default, the prop type is a vtkActor. diff --git a/Rendering/Label/vtkDynamic2DLabelMapper.cxx b/Rendering/Label/vtkDynamic2DLabelMapper.cxx index d9b800bd882..a808c4f1810 100644 --- a/Rendering/Label/vtkDynamic2DLabelMapper.cxx +++ b/Rendering/Label/vtkDynamic2DLabelMapper.cxx @@ -160,7 +160,7 @@ void vtkDynamic2DLabelMapper::RenderOpaqueGeometry(vtkViewport *viewport, { vtkDebugMacro(<<"Rebuilding labels"); - vtkIntArray *typeArr = vtkIntArray::SafeDownCast( + vtkIntArray *typeArr = vtkArrayDownCast( this->GetInputAbstractArrayToProcess(0, input)); // figure out what to label, and if we can label it @@ -217,9 +217,9 @@ void vtkDynamic2DLabelMapper::RenderOpaqueGeometry(vtkViewport *viewport, this->FieldDataArray : pd->GetNumberOfArrays() - 1); abstractData = pd->GetAbstractArray(arrayNum); } - numericData = vtkDataArray::SafeDownCast(abstractData); - stringData = vtkStringArray::SafeDownCast(abstractData); - uStringData = vtkUnicodeStringArray::SafeDownCast(abstractData); + numericData = vtkArrayDownCast(abstractData); + stringData = vtkArrayDownCast(abstractData); + uStringData = vtkArrayDownCast(abstractData); }; break; } diff --git a/Rendering/Label/vtkLabelHierarchy.h b/Rendering/Label/vtkLabelHierarchy.h index 81ad0e7948f..0a1af1a81a1 100644 --- a/Rendering/Label/vtkLabelHierarchy.h +++ b/Rendering/Label/vtkLabelHierarchy.h @@ -98,7 +98,6 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelHierarchy : public vtkPointSet vtkSetMacro(MaximumDepth,int); vtkGetMacro(MaximumDepth,int); - //BTX // Description: // Enumeration of iterator types. enum IteratorType { @@ -107,7 +106,6 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelHierarchy : public vtkPointSet DEPTH_FIRST, FRUSTUM }; - //ETX // Description: // The default text property assigned to labels in this hierarchy. @@ -144,7 +142,6 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelHierarchy : public vtkPointSet virtual void SetBoundedSizes(vtkDataArray* arr); vtkGetObjectMacro(BoundedSizes,vtkDataArray); - //BTX // Description: // Returns an iterator for this data object. // positionsAsNormals should only be true when labels are on a sphere centered at the origin @@ -155,9 +152,8 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelHierarchy : public vtkPointSet // @param frustumPlanes - should be the output of the camera's frustum planes. // @param positionsAsNormals - throws out octree nodes on the opposite side of the origin. // @param bucketSize - an array of 2 integers describing the width and height of label placer buckets. - vtkLabelHierarchyIterator* NewIterator( + VTK_NEWINSTANCE vtkLabelHierarchyIterator* NewIterator( int type, vtkRenderer* ren, vtkCamera* cam, double frustumPlanes[24], bool positionsAsNormals, float bucketSize[2] ); - //ETX // Description: // Given a depth in the hierarchy (\a level) and a point \a pt in world space, compute \a ijk. @@ -193,10 +189,8 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelHierarchy : public vtkPointSet virtual vtkIdType FindCell(double*, vtkCell*, vtkGenericCell*, vtkIdType, double, int&, double*, double*); virtual int GetMaxCellSize(); - //BTX class Implementation; Implementation* GetImplementation() { return this->Impl; } - //ETX // Description: // Provide access to original coordinates of sets of coincident points @@ -224,13 +218,11 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelHierarchy : public vtkPointSet vtkPoints* CenterPts; vtkTextProperty* TextProperty; - //BTX Implementation* Impl; friend class vtkLabelHierarchyFrustumIterator; friend class vtkLabelHierarchyFullSortIterator; friend class implementation; - //ETX private: vtkLabelHierarchy( const vtkLabelHierarchy& ); // Not implemented. diff --git a/Rendering/Label/vtkLabelHierarchyCompositeIterator.h b/Rendering/Label/vtkLabelHierarchyCompositeIterator.h index ec6c3a9afa9..859790d7f87 100644 --- a/Rendering/Label/vtkLabelHierarchyCompositeIterator.h +++ b/Rendering/Label/vtkLabelHierarchyCompositeIterator.h @@ -103,10 +103,8 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelHierarchyCompositeIterator : public vtkLa vtkLabelHierarchyCompositeIterator(); virtual ~vtkLabelHierarchyCompositeIterator(); - //BTX class Internal; Internal* Implementation; - //ETX private: vtkLabelHierarchyCompositeIterator( const vtkLabelHierarchyCompositeIterator& ); // Not implemented. diff --git a/Rendering/Label/vtkLabelHierarchyIterator.cxx b/Rendering/Label/vtkLabelHierarchyIterator.cxx index bd4ac6626a4..46cc946b144 100644 --- a/Rendering/Label/vtkLabelHierarchyIterator.cxx +++ b/Rendering/Label/vtkLabelHierarchyIterator.cxx @@ -104,7 +104,7 @@ int vtkLabelHierarchyIterator::GetType() { return -1; } - vtkIntArray* labelTypeIArr = vtkIntArray::SafeDownCast( labelTypeArr ); + vtkIntArray* labelTypeIArr = vtkArrayDownCast( labelTypeArr ); if ( ! labelTypeIArr ) { return -1; diff --git a/Rendering/Label/vtkLabelPlacementMapper.h b/Rendering/Label/vtkLabelPlacementMapper.h index 973bd0bfe0e..4f2093d626a 100644 --- a/Rendering/Label/vtkLabelPlacementMapper.h +++ b/Rendering/Label/vtkLabelPlacementMapper.h @@ -108,14 +108,12 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelPlacementMapper : public vtkMapper2D vtkGetMacro(OutputTraversedBounds, bool); vtkBooleanMacro(OutputTraversedBounds, bool); - //BTX enum LabelShape { NONE, RECT, ROUNDED_RECT, NUMBER_OF_LABEL_SHAPES }; - //ETX // Description: // The shape of the label background, should be one of the @@ -129,13 +127,11 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelPlacementMapper : public vtkMapper2D virtual void SetShapeToRoundedRect() { this->SetShape(ROUNDED_RECT); } - //BTX enum LabelStyle { FILLED, OUTLINE, NUMBER_OF_LABEL_STYLES }; - //ETX // Description: // The style of the label background shape, should be one of the @@ -181,10 +177,8 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelPlacementMapper : public vtkMapper2D virtual int FillInputPortInformation( int port, vtkInformation* info ); - //BTX class Internal; Internal* Buckets; - //ETX vtkLabelRenderStrategy* RenderStrategy; vtkCoordinate* AnchorTransform; diff --git a/Rendering/Label/vtkLabelPlacer.cxx b/Rendering/Label/vtkLabelPlacer.cxx index 249d14213e8..e3b29a645f1 100644 --- a/Rendering/Label/vtkLabelPlacer.cxx +++ b/Rendering/Label/vtkLabelPlacer.cxx @@ -439,11 +439,11 @@ int vtkLabelPlacer::RequestData( ouData0->GetPointData()->AddArray( idArr0 ); idArr0->Delete(); - vtkStringArray* nameArr = vtkStringArray::SafeDownCast( + vtkStringArray* nameArr = vtkArrayDownCast( inData->GetLabels()); - vtkUnicodeStringArray* nameUArr = vtkUnicodeStringArray::SafeDownCast( + vtkUnicodeStringArray* nameUArr = vtkArrayDownCast( inData->GetLabels()); - vtkIntArray* iconIndexArr = vtkIntArray::SafeDownCast( + vtkIntArray* iconIndexArr = vtkArrayDownCast( inData->GetIconIndices()); if ( ! inData ) diff --git a/Rendering/Label/vtkLabelPlacer.h b/Rendering/Label/vtkLabelPlacer.h index 428f201f911..8e2da9b5a4f 100644 --- a/Rendering/Label/vtkLabelPlacer.h +++ b/Rendering/Label/vtkLabelPlacer.h @@ -58,7 +58,6 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelPlacer : public vtkPolyDataAlgorithm vtkGetObjectMacro(AnchorTransform,vtkCoordinate); - //BTX /// Specifications for the placement of the label relative to an anchor point. enum LabelGravity { @@ -95,7 +94,6 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelPlacer : public vtkPolyDataAlgorithm WORLD=0, //!< Output 3-D world-space coordinates for each label anchor. DISPLAY=1 //!< Output 2-D display coordinates for each label anchor (3 components but only 2 are significant). }; - //ETX // Description: // The placement of the label relative to the anchor point. @@ -168,10 +166,8 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelPlacer : public vtkPolyDataAlgorithm virtual int RequestData( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector ); - //BTX class Internal; Internal* Buckets; - //ETX vtkRenderer* Renderer; vtkCoordinate* AnchorTransform; diff --git a/Rendering/Label/vtkLabelSizeCalculator.cxx b/Rendering/Label/vtkLabelSizeCalculator.cxx index c346dd97aeb..29285ce1110 100644 --- a/Rendering/Label/vtkLabelSizeCalculator.cxx +++ b/Rendering/Label/vtkLabelSizeCalculator.cxx @@ -138,7 +138,7 @@ int vtkLabelSizeCalculator::RequestData( vtkErrorMacro( "No input array available." ); return 0; } - vtkIntArray* typeArr = vtkIntArray::SafeDownCast( + vtkIntArray* typeArr = vtkArrayDownCast( this->GetInputAbstractArrayToProcess( 1, inputVector )); vtkInformation* inArrInfo = this->GetInputArrayInformation( 0 ); diff --git a/Rendering/Label/vtkLabelSizeCalculator.h b/Rendering/Label/vtkLabelSizeCalculator.h index 4414f5335b2..7ad942029c0 100644 --- a/Rendering/Label/vtkLabelSizeCalculator.h +++ b/Rendering/Label/vtkLabelSizeCalculator.h @@ -90,10 +90,8 @@ class VTKRENDERINGLABEL_EXPORT vtkLabelSizeCalculator : public vtkPassInputTypeA int DPI; - //BTX class Internals; Internals* Implementation; - //ETX private: vtkLabelSizeCalculator( const vtkLabelSizeCalculator& ); // Not implemented. diff --git a/Rendering/Label/vtkLabeledDataMapper.cxx b/Rendering/Label/vtkLabeledDataMapper.cxx index 89142d5b6f7..dcc1309c7b0 100644 --- a/Rendering/Label/vtkLabeledDataMapper.cxx +++ b/Rendering/Label/vtkLabeledDataMapper.cxx @@ -398,9 +398,9 @@ void vtkLabeledDataMapper::BuildLabelsInternal(vtkDataSet* input) this->FieldDataArray : pd->GetNumberOfArrays() - 1); abstractData = pd->GetAbstractArray(arrayNum); } - numericData = vtkDataArray::SafeDownCast(abstractData); - stringData = vtkStringArray::SafeDownCast(abstractData); - uStringData = vtkUnicodeStringArray::SafeDownCast(abstractData); + numericData = vtkArrayDownCast(abstractData); + stringData = vtkArrayDownCast(abstractData); + uStringData = vtkArrayDownCast(abstractData); }; break; } @@ -541,7 +541,7 @@ void vtkLabeledDataMapper::BuildLabelsInternal(vtkDataSet* input) const char *LiveFormatString = FormatString.c_str(); char TempString[1024]; - vtkIntArray *typeArr = vtkIntArray::SafeDownCast( + vtkIntArray *typeArr = vtkArrayDownCast( this->GetInputAbstractArrayToProcess(0, input)); for (i=0; i < numCurLabels; i++) { diff --git a/Rendering/Label/vtkLabeledDataMapper.h b/Rendering/Label/vtkLabeledDataMapper.h index 99917ea6919..d083b776438 100644 --- a/Rendering/Label/vtkLabeledDataMapper.h +++ b/Rendering/Label/vtkLabeledDataMapper.h @@ -161,14 +161,12 @@ class VTKRENDERINGLABEL_EXPORT vtkLabeledDataMapper : public vtkMapper2D vtkGetObjectMacro(Transform, vtkTransform); void SetTransform(vtkTransform* t); - //BTX /// Coordinate systems that output dataset may use. enum Coordinates { WORLD=0, //!< Output 3-D world-space coordinates for each label anchor. DISPLAY=1 //!< Output 2-D display coordinates for each label anchor (3 components but only 2 are significant). }; - //ETX // Description: // Set/get the coordinate system used for output labels. @@ -227,10 +225,8 @@ class VTKRENDERINGLABEL_EXPORT vtkLabeledDataMapper : public vtkMapper2D void BuildLabels(); void BuildLabelsInternal(vtkDataSet*); - //BTX class Internals; Internals* Implementation; - //ETX private: vtkLabeledDataMapper(const vtkLabeledDataMapper&); // Not implemented. diff --git a/Rendering/Label/vtkLabeledTreeMapDataMapper.cxx b/Rendering/Label/vtkLabeledTreeMapDataMapper.cxx index 531ef415db7..35e58422d15 100644 --- a/Rendering/Label/vtkLabeledTreeMapDataMapper.cxx +++ b/Rendering/Label/vtkLabeledTreeMapDataMapper.cxx @@ -346,7 +346,7 @@ void vtkLabeledTreeMapDataMapper::RenderOpaqueGeometry(vtkViewport *viewport, vtkErrorMacro(<< "Input Tree does not have box information."); return; } - vtkFloatArray *boxInfo = vtkFloatArray::SafeDownCast(tempData); + vtkFloatArray *boxInfo = vtkArrayDownCast(tempData); // Check to see whether we have to rebuild everything if ( this->UpdateWindowInfo(viewport) || @@ -417,8 +417,8 @@ void vtkLabeledTreeMapDataMapper::RenderOpaqueGeometry(vtkViewport *viewport, this->FieldDataArray : pd->GetNumberOfArrays() - 1); abstractData = pd->GetAbstractArray(arrayNum); } - numericData = vtkDataArray::SafeDownCast(abstractData); - stringData = vtkStringArray::SafeDownCast(abstractData); + numericData = vtkArrayDownCast(abstractData); + stringData = vtkArrayDownCast(abstractData); }; break; } @@ -515,7 +515,7 @@ void vtkLabeledTreeMapDataMapper::LabelTree(vtkTree *tree, if (level >= this->StartLevel && (this->EndLevel == -1 || level <= this->EndLevel)) { - boxInfo->GetTupleValue(vertex, blimits); // Get the extents of the vertex + boxInfo->GetTypedTuple(vertex, blimits); // Get the extents of the vertex if (this->ConvertToDC(blimits, blimitsDC)) { continue; diff --git a/Rendering/Label/vtkLabeledTreeMapDataMapper.h b/Rendering/Label/vtkLabeledTreeMapDataMapper.h index d447f76c686..4c659deb504 100644 --- a/Rendering/Label/vtkLabeledTreeMapDataMapper.h +++ b/Rendering/Label/vtkLabeledTreeMapDataMapper.h @@ -132,9 +132,9 @@ class VTKRENDERINGLABEL_EXPORT vtkLabeledTreeMapDataMapper : public vtkLabeledDa int MaxTreeLevels; double BoxTrans[2][2]; double WindowLimits[2][2]; - //BTX + float (*LabelMasks)[4]; - //ETX + vtkIdList *VertexList; vtkPoints *TextPoints; vtkCoordinate *VCoord; diff --git a/Rendering/Label/vtkPointSetToLabelHierarchy.cxx b/Rendering/Label/vtkPointSetToLabelHierarchy.cxx index 1d6e102d836..006f145f274 100644 --- a/Rendering/Label/vtkPointSetToLabelHierarchy.cxx +++ b/Rendering/Label/vtkPointSetToLabelHierarchy.cxx @@ -212,17 +212,17 @@ int vtkPointSetToLabelHierarchy::RequestData( pdata = ptset->GetPointData(); } - vtkDataArray* priorities = vtkDataArray::SafeDownCast( + vtkDataArray* priorities = vtkArrayDownCast( this->GetInputAbstractArrayToProcess( 0, inputVector ) ); - vtkDataArray* sizes = vtkDataArray::SafeDownCast( + vtkDataArray* sizes = vtkArrayDownCast( this->GetInputAbstractArrayToProcess( 1, inputVector ) ); vtkAbstractArray* labels = this->GetInputAbstractArrayToProcess( 2, inputVector ); - vtkIntArray* iconIndices = vtkIntArray::SafeDownCast( + vtkIntArray* iconIndices = vtkArrayDownCast( this->GetInputAbstractArrayToProcess( 3, inputVector ) ); - vtkDataArray* orientations = vtkDataArray::SafeDownCast( + vtkDataArray* orientations = vtkArrayDownCast( this->GetInputAbstractArrayToProcess( 4, inputVector ) ); - vtkDataArray* boundedSizes = vtkDataArray::SafeDownCast( + vtkDataArray* boundedSizes = vtkArrayDownCast( this->GetInputAbstractArrayToProcess( 5, inputVector ) ); if ( ! ouData->GetPoints() ) @@ -244,8 +244,8 @@ int vtkPointSetToLabelHierarchy::RequestData( ouData->SetPriorities( priorities ); if ( labels ) { - if ( ( this->UseUnicodeStrings && vtkUnicodeStringArray::SafeDownCast( labels ) ) || - ( !this->UseUnicodeStrings && vtkStringArray::SafeDownCast( labels ) ) ) + if ( ( this->UseUnicodeStrings && vtkArrayDownCast( labels ) ) || + ( !this->UseUnicodeStrings && vtkArrayDownCast( labels ) ) ) { ouData->SetLabels( labels ); } diff --git a/Rendering/Matplotlib/vtkMatplotlibMathTextUtilities.cxx b/Rendering/Matplotlib/vtkMatplotlibMathTextUtilities.cxx index 3196e8923c4..e33cfeaaff7 100644 --- a/Rendering/Matplotlib/vtkMatplotlibMathTextUtilities.cxx +++ b/Rendering/Matplotlib/vtkMatplotlibMathTextUtilities.cxx @@ -76,6 +76,7 @@ vtkMatplotlibMathTextUtilities::CheckMPLAvailability() vtkMplStartUpDebugMacro("Initializing Python, if not already."); vtkPythonInterpreter::Initialize(); vtkMplStartUpDebugMacro("Attempting to import matplotlib."); + vtkPythonScopeGilEnsurer gilEnsurer; if (PyErr_Occurred() || !PyImport_ImportModule("matplotlib") || PyErr_Occurred()) { // FIXME: Check if we need this. Wouldn't pipe-ing the stdout/stderr make @@ -145,13 +146,17 @@ vtkMatplotlibMathTextUtilities::~vtkMatplotlibMathTextUtilities() //---------------------------------------------------------------------------- void vtkMatplotlibMathTextUtilities::CleanupPythonObjects() { - Py_XDECREF(this->MaskParser); - Py_XDECREF(this->PathParser); - Py_XDECREF(this->FontPropertiesClass); - - this->MaskParser = NULL; - this->PathParser = NULL; - this->FontPropertiesClass = NULL; + if (Py_IsInitialized()) + { + vtkPythonScopeGilEnsurer gilEnsurer; + Py_XDECREF(this->MaskParser); + Py_XDECREF(this->PathParser); + Py_XDECREF(this->FontPropertiesClass); + + this->MaskParser = NULL; + this->PathParser = NULL; + this->FontPropertiesClass = NULL; + } } //---------------------------------------------------------------------------- @@ -159,7 +164,7 @@ bool vtkMatplotlibMathTextUtilities::InitializeMaskParser() { // ensure that Python is initialized. vtkPythonInterpreter::Initialize(); - + vtkPythonScopeGilEnsurer gilEnsurer; vtkSmartPyObject mplMathTextLib(PyImport_ImportModule("matplotlib.mathtext")); if (this->CheckForError(mplMathTextLib.GetPointer())) { @@ -190,7 +195,7 @@ bool vtkMatplotlibMathTextUtilities::InitializePathParser() { // ensure that Python is initialized. vtkPythonInterpreter::Initialize(); - + vtkPythonScopeGilEnsurer gilEnsurer; vtkSmartPyObject mplTextPathLib(PyImport_ImportModule("matplotlib.textpath")); if (this->CheckForError(mplTextPathLib.GetPointer())) { @@ -219,7 +224,7 @@ bool vtkMatplotlibMathTextUtilities::InitializeFontPropertiesClass() { // ensure that Python is initialized. vtkPythonInterpreter::Initialize(); - + vtkPythonScopeGilEnsurer gilEnsurer; vtkSmartPyObject mplFontManagerLib( PyImport_ImportModule("matplotlib.font_manager")); if (this->CheckForError(mplFontManagerLib.GetPointer())) @@ -241,6 +246,7 @@ bool vtkMatplotlibMathTextUtilities::InitializeFontPropertiesClass() //---------------------------------------------------------------------------- bool vtkMatplotlibMathTextUtilities::CheckForError() { + vtkPythonScopeGilEnsurer gilEnsurer; PyObject *exception = PyErr_Occurred(); if (exception) { @@ -351,6 +357,7 @@ vtkMatplotlibMathTextUtilities::GetFontProperties(vtkTextProperty *tprop) tpropFontSize = tprop->GetFontSize(); + vtkPythonScopeGilEnsurer gilEnsurer; return PyObject_CallFunction(this->FontPropertiesClass, const_cast("sssssi"), tpropFamily, tpropStyle, tpropVariant, tpropStyle, @@ -545,6 +552,7 @@ bool vtkMatplotlibMathTextUtilities::GetMetrics( long int rows = 0; long int cols = 0; + vtkPythonScopeGilEnsurer gilEnsurer; vtkSmartPyObject resultTuple(PyObject_CallMethod(this->MaskParser, const_cast("to_mask"), const_cast("sii"), @@ -649,6 +657,7 @@ bool vtkMatplotlibMathTextUtilities::RenderString(const char *str, double bgA = tprop->GetBackgroundOpacity(); bool hasBackground = (static_cast(bgA * 255) != 0); + vtkPythonScopeGilEnsurer gilEnsurer; vtkSmartPyObject resultTuple(PyObject_CallMethod(this->MaskParser, const_cast("to_mask"), const_cast("sii"), @@ -875,6 +884,7 @@ bool vtkMatplotlibMathTextUtilities::StringToPath(const char *str, return false; } + vtkPythonScopeGilEnsurer gilEnsurer; vtkSmartPyObject pyResultTuple( PyObject_CallMethod(this->PathParser, const_cast("get_text_path"), diff --git a/Rendering/OSPRay/CMakeLists.txt b/Rendering/OSPRay/CMakeLists.txt new file mode 100644 index 00000000000..890b9280f6b --- /dev/null +++ b/Rendering/OSPRay/CMakeLists.txt @@ -0,0 +1,23 @@ +find_package(OSPRay REQUIRED) +include_directories(${OSPRAY_INCLUDE_DIRS}) + +set(Module_SRCS + vtkOSPRayActorNode.cxx + vtkOSPRayCameraNode.cxx + vtkOSPRayCompositePolyDataMapper2Node.cxx + vtkOSPRayLightNode.cxx + vtkOSPRayPass.cxx + vtkOSPRayPolyDataMapperNode.cxx + vtkOSPRayRendererNode.cxx + vtkOSPRayViewNodeFactory.cxx + vtkOSPRayWindowNode.cxx + ) + +vtk_module_library(vtkRenderingOSPRay ${Module_SRCS}) + +target_link_libraries(${vtk-module} LINK_PUBLIC ${OSPRAY_LIBRARIES}) + +# OSPRay_Core uses MMTime which is in it's own special library. +if(WIN32) + target_link_libraries(${vtk-module} LINK_PRIVATE Winmm) +endif() diff --git a/Rendering/OSPRay/Testing/Cxx/CMakeLists.txt b/Rendering/OSPRay/Testing/Cxx/CMakeLists.txt new file mode 100644 index 00000000000..ca8db622229 --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/CMakeLists.txt @@ -0,0 +1,47 @@ +vtk_add_test_cxx(${vtk-module}CxxTests tests + TestOSPRayCompositePolyDataMapper2.cxx, + TestOSPRayDynamicObject.cxx, + TestOSPRayDynamicScene.cxx, + TestOSPRayImplicits.cxx, + TestOSPRayLayers.cxx, + TestOSPRayLights.cxx, + TestOSPRayMultiBlock.cxx + TestOSPRayMultiBlockPartialArrayFieldData.cxx, + TestOSPRayPass.cxx, + TestOSPRayRenderMesh.cxx, + TestOSPRayScalarBar.cxx + TestOSPRayTime.cxx, + TestOSPRayWindow.cxx + #TODO: interaction, pure offscreen, volumes + ) +vtk_test_cxx_executable(${vtk-module}CxxTests tests RENDERING_FACTORY + vtkOSPRayTestInteractor.cxx + ) + + +# Do we have MPI and parallel support +if (${Module_vtkRenderingParallel} AND ${Module_vtkParallelMPI}) + vtk_module_dep_includes(vtkRenderingParallel) + vtk_module_dep_includes(vtkParallelMPI) + include_directories( + ${vtkRenderingParallel_INCLUDE_DIRS} + ${vtkRenderingParallel_DEPENDS_INCLUDE_DIRS} + ${vtkParallelMPI_INCLUDE_DIRS} + ${vtkParallelMPI_DEPENDS_INCLUDE_DIRS} + ) + + include(vtkMPI) + set(${vtk-module}Cxx-MPI_NUMPROCS 2) + vtk_add_test_mpi(${vtk-module}Cxx-MPI tests + TESTING_DATA + TestOSPRayComposite.cxx + ) + vtk_test_mpi_executable(${vtk-module}Cxx-MPI tests RENDERING_FACTORY + vtkOSPRayTestInteractor.cxx + ) + + target_link_libraries(${vtk-module}Cxx-MPI PRIVATE + ${vtkRenderingParallel_LIBRARIES} + ${vtkParallelMPI_LIBRARIES} + ) +endif() diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayComposite.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayComposite.cxx new file mode 100644 index 00000000000..a8c2ad389cd --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayComposite.cxx @@ -0,0 +1,186 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: $RCSfile$ + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +//This test demonstrates the use of sort last distributed memory parallel +//rendering with OSPRay. +// +//The pipeline is created in parallel and each process is +//assigned 1 piece to process. Each node then renders its local image and +//the image results are depth composited to produce a correct image on the +//root node. + +#include + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkCompositeRenderManager.h" +#include "vtkMPICommunicator.h" +#include "vtkMPIController.h" +#include "vtkObjectFactory.h" +#include "vtkOSPRayPass.h" +#include "vtkPolyDataMapper.h" +#include "vtkProcess.h" +#include "vtkProperty.h" +#include "vtkRegressionTestImage.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkSphereSource.h" + +class MyProcess : public vtkProcess +{ +public: + static MyProcess *New(); + vtkTypeMacro(MyProcess, vtkProcess); + + virtual void Execute(); + + void SetArgs(int argc, char *argv[]) + { + this->Argc = argc; + this->Argv = argv; + } + + void CreatePipeline(vtkRenderer *renderer) + { + int num_procs = this->Controller->GetNumberOfProcesses(); + int my_id = this->Controller->GetLocalProcessId(); + + vtkSmartPointer pdm = + vtkSmartPointer::New(); + vtkSmartPointer actor = + vtkSmartPointer::New(); + + vtkSmartPointer src = + vtkSmartPointer::New(); + src->SetPhiResolution(100); + src->SetThetaResolution(100); + float pFrac = (float)(my_id/(float)(num_procs-1)); + actor->GetProperty()->SetColor(0,pFrac,1.0-pFrac); + pdm->SetInputConnection(src->GetOutputPort()); + pdm->SetPiece(my_id); + pdm->SetNumberOfPieces(num_procs); + actor->SetMapper(pdm); + renderer->AddActor(actor); + } + +protected: + MyProcess() { this->Argc = 0; this->Argv = NULL; } + + int Argc; + char **Argv; +}; + +vtkStandardNewMacro(MyProcess); + +void MyProcess::Execute() +{ + int my_id = this->Controller->GetLocalProcessId(); + + vtkMPICommunicator *comm = + vtkMPICommunicator::SafeDownCast(this->Controller->GetCommunicator()); + comm->Barrier(); + + vtkSmartPointer prm = + vtkSmartPointer::New(); + vtkRenderer *renderer = prm->MakeRenderer(); + vtkRenderWindow *renWin = prm->MakeRenderWindow(); + renWin->AddRenderer(renderer); + renWin->DoubleBufferOn(); + renWin->SetMultiSamples(0); + vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New(); + iren->SetRenderWindow(renWin); + renWin->Render(); + + vtkCamera *cam = renderer->GetActiveCamera(); + cam->SetPosition(0,0.2,1); + + vtkSmartPointer ospray=vtkSmartPointer::New(); + renderer->SetPass(ospray); + + this->CreatePipeline(renderer); + prm->SetRenderWindow(renWin); + prm->SetController(this->Controller); + + if (my_id == 0) + { + prm->ResetAllCameras(); + + this->ReturnValue = + vtkRegressionTester::Test(this->Argc, this->Argv, renWin, 10); + if (this->ReturnValue == vtkRegressionTester::DO_INTERACTOR) + { + renWin->Render(); + prm->StartInteractor(); + } + + this->Controller->TriggerBreakRMIs(); + this->Controller->Barrier(); + } + else + { + prm->StartServices(); + this->Controller->Barrier(); + + // No testing is done here so mark it passed + this->ReturnValue = vtkTesting::PASSED; + } + + renderer->Delete(); + renWin->Delete(); + iren->Delete(); +} + + +int TestOSPRayComposite(int argc, char *argv[]) +{ + // This is here to avoid false leak messages from vtkDebugLeaks when + // using mpich. It appears that the root process which spawns all the + // main processes waits in MPI_Init() and calls exit() when + // the others are done, causing apparent memory leaks for any objects + // created before MPI_Init(). + MPI_Init(&argc, &argv); + + // Note that this will create a vtkMPIController if MPI + // is configured, vtkThreadedController otherwise. + vtkMPIController *contr = vtkMPIController::New(); + contr->Initialize(&argc, &argv, 1); + + int retVal = 1; // 1 == failed + + int numProcs = contr->GetNumberOfProcesses(); + + if (numProcs < 2 && false) + { + cout << "This test requires at least 2 processes" << endl; + contr->Delete(); + return retVal; + } + + vtkMultiProcessController::SetGlobalController(contr); + + MyProcess *p = MyProcess::New(); + p->SetArgs(argc, argv); + + contr->SetSingleProcessObject(p); + contr->SingleMethodExecute(); + + retVal = p->GetReturnValue(); + + p->Delete(); + contr->Finalize(); + contr->Delete(); + vtkMultiProcessController::SetGlobalController(0); + return !retVal; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayCompositePolyDataMapper2.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayCompositePolyDataMapper2.cxx new file mode 100644 index 00000000000..a2eabed9a06 --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayCompositePolyDataMapper2.cxx @@ -0,0 +1,201 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkCompositePolyDataMapper2.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkCompositeDataSet.h" +#include "vtkCompositeDataDisplayAttributes.h" +#include "vtkCompositePolyDataMapper2.h" +#include "vtkCullerCollection.h" +#include "vtkInformation.h" +#include "vtkMath.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkNew.h" +#include "vtkOSPRayPass.h" +#include "vtkOSPRayTestInteractor.h" +#include "vtkProperty.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkSmartPointer.h" +#include "vtkTimerLog.h" +#include "vtkTrivialProducer.h" + +#include +#include + +#define syntheticData +#ifdef syntheticData +#include "vtkCylinderSource.h" +#else +#include "vtkXMLMultiBlockDataReader.h" +#endif + +int TestOSPRayCompositePolyDataMapper2(int argc, char* argv[]) +{ + bool useGL = false; + for (int i = 0; i < argc; i++) + { + if (!strcmp(argv[i], "-GL")) + { + useGL = true; + } + } + + vtkSmartPointer win = + vtkSmartPointer::New(); + vtkSmartPointer iren = + vtkSmartPointer::New(); + vtkSmartPointer ren = + vtkSmartPointer::New(); + win->AddRenderer(ren); + win->SetInteractor(iren); + + vtkSmartPointer mapper = + vtkSmartPointer::New(); + vtkNew cdsa; + mapper->SetCompositeDataDisplayAttributes(cdsa.GetPointer()); + +#ifdef syntheticData + + int resolution = 18; + vtkNew cyl; + cyl->CappingOn(); + cyl->SetRadius(0.2); + cyl->SetResolution(resolution); + + // build a composite dataset + vtkNew data; +// int blocksPerLevel[3] = {1,64,256}; + int blocksPerLevel[3] = {1,16,32}; + std::vector > blocks; + blocks.push_back(data.GetPointer()); + unsigned levelStart = 0; + unsigned levelEnd = 1; + int numLevels = sizeof(blocksPerLevel) / sizeof(blocksPerLevel[0]); + int numLeaves = 0; + int numNodes = 0; + vtkStdString blockName("Rolf"); + for (int level = 1; level < numLevels; ++level) + { + int nblocks=blocksPerLevel[level]; + for (unsigned parent = levelStart; parent < levelEnd; ++parent) + { + blocks[parent]->SetNumberOfBlocks(nblocks); + for (int block=0; block < nblocks; ++block, ++numNodes) + { + if (level == numLevels - 1) + { + vtkNew child; + cyl->SetCenter(block*0.25, 0.0, parent*0.5); + cyl->Update(); + child->DeepCopy(cyl->GetOutput(0)); + blocks[parent]->SetBlock( + block, (block % 2) ? NULL : child.GetPointer()); + blocks[parent]->GetMetaData(block)->Set( + vtkCompositeDataSet::NAME(), blockName.c_str()); + // test not setting it on some + if (block % 11) + { + mapper->SetBlockColor(parent+numLeaves+1, + vtkMath::HSVToRGB(0.8*block/nblocks, 0.2 + 0.8*((parent - levelStart) % 8)/7.0, 1.0)); + mapper->SetBlockOpacity(parent+numLeaves, (block + 3) % 7 == 0 ? 0.3 : 1.0); + mapper->SetBlockVisibility(parent+numLeaves, (block % 7) != 0); + } + ++numLeaves; + } + else + { + vtkNew child; + blocks[parent]->SetBlock(block, child.GetPointer()); + blocks.push_back(child.GetPointer()); + } + } + } + levelStart = levelEnd; + levelEnd = static_cast(blocks.size()); + } + + mapper->SetInputData((vtkPolyData *)(data.GetPointer())); + +#else + + vtkNew reader; + reader->SetFileName("C:/Users/ken.martin/Documents/vtk/data/stargate.vtm"); + mapper->SetInputConnection(reader->GetOutputPort(0)); + + // stargate seems to have cell scalars but all white cell scalars + // are slow slow slow so do not use the unless they add value + mapper->ScalarVisibilityOff(); + + // comment the following in/out for worst/best case + // for (int i = 0; i < 20000; ++i) + // { + // mapper->SetBlockColor(i, + // vtkMath::HSVToRGB(0.8*(i%100)/100.0, 1.0, 1.0)); + // } + +#endif + + vtkSmartPointer actor = + vtkSmartPointer::New(); + actor->SetMapper(mapper); + //actor->GetProperty()->SetEdgeColor(1,0,0); + //actor->GetProperty()->EdgeVisibilityOn(); + ren->AddActor(actor); + win->SetSize(400,400); + + ren->RemoveCuller(ren->GetCullers()->GetLastItem()); + vtkSmartPointer ospray = vtkSmartPointer::New(); + if (!useGL) + { + ren->SetPass(ospray); + } + ren->ResetCamera(); + + vtkSmartPointer timer = vtkSmartPointer::New(); + win->Render(); // get the window up + + vtkSmartPointer style = + vtkSmartPointer::New(); + style-> + SetPipelineControlPoints((vtkOpenGLRenderer*)ren.Get(), ospray, NULL); + iren->SetInteractorStyle(style); + style->SetCurrentRenderer(ren); + + timer->StartTimer(); + win->Render(); + timer->StopTimer(); + cout << "First frame time: " << timer->GetElapsedTime() << "\n"; + + timer->StartTimer(); + + int numFrames = 2; + for (int i = 0; i <= numFrames; i++) + { + ren->GetActiveCamera()->Elevation(40.0/numFrames); + ren->GetActiveCamera()->Zoom(pow(2.0,1.0/numFrames)); + ren->GetActiveCamera()->Roll(20.0/numFrames); + win->Render(); + } + + timer->StopTimer(); + double t = timer->GetElapsedTime(); + cout << "Avg Frame time: " << t/numFrames << " Frame Rate: " << numFrames / t << "\n"; + + iren->Start(); + + return 0; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayDynamicObject.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayDynamicObject.cxx new file mode 100644 index 00000000000..d009aae7947 --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayDynamicObject.cxx @@ -0,0 +1,102 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayDynamicObject.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test verifies that we can render dynamic objects (changing mesh) +// and that changing vtk state changes the resulting image accordingly. +// +// The command line arguments are: +// -I => run in interactive mode; unless this is used, the program will +// not allow interaction and exit + +//TODO: test broken by pre SC15 ospray caching + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkLight.h" +#include "vtkLightCollection.h" +#include "vtkOSPRayPass.h" +#include "vtkPolyDataMapper.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkSmartPointer.h" +#include "vtkSphereSource.h" + +int TestOSPRayDynamicObject(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) +{ + vtkSmartPointer iren = vtkSmartPointer::New(); + vtkSmartPointer renWin = vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + vtkSmartPointer renderer = vtkSmartPointer::New(); + renWin->AddRenderer(renderer); + vtkSmartPointer sphere = vtkSmartPointer::New(); + sphere->SetPhiResolution(100); + vtkSmartPointer mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(sphere->GetOutputPort()); + vtkSmartPointer actor=vtkSmartPointer::New(); + renderer->AddActor(actor); + actor->SetMapper(mapper); + renderer->SetBackground(0.1,0.1,1.0); + renWin->SetSize(400,400); + renWin->Render(); + + vtkSmartPointer ospray=vtkSmartPointer::New(); + + renderer->SetPass(ospray); + renWin->Render(); + + vtkLight *light = vtkLight::SafeDownCast(renderer->GetLights()->GetItemAsObject(0)); + double lColor[3]; + lColor[0] = 0.5; + lColor[1] = 0.5; + lColor[2] = 0.5; + light->SetDiffuseColor(lColor[0],lColor[1],lColor[2]); + + vtkCamera *camera = renderer->GetActiveCamera(); + double position[3]; + camera->GetPosition(position); + camera->SetClippingRange(0.01,1000.0); + +#define MAXFRAME 20 + double inc = 1.0/(double)MAXFRAME; + + for (int i = 0; i < MAXFRAME; i++) + { + double I = (double)i/(double)MAXFRAME; + renWin->SetSize(400+i,400-i); + sphere->SetThetaResolution(3+i); + + lColor[0] += inc/2; + lColor[1] -= inc/2; + light->SetDiffuseColor(lColor[0],lColor[1],lColor[2]); + + if (i < (MAXFRAME/2)) + { + position[2] += inc*5; + } + else + { + position[2] -= inc*5; + } + + camera->SetPosition(position); + + renderer->SetBackground(0.0,I,1-I); + renWin->Render(); + } + + iren->Start(); + + return 0; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayDynamicScene.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayDynamicScene.cxx new file mode 100644 index 00000000000..adf656a5516 --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayDynamicScene.cxx @@ -0,0 +1,132 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayDynamicScene.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test verifies that dynamic scene (vary number of objects) +// contents work acceptably +// +// The command line arguments are: +// -I => run in interactive mode; unless this is used, the program will +// not allow interaction and exit + +//TODO: test broken by pre SC15 ospray caching + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkOSPRayPass.h" +#include "vtkPolyDataMapper.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkSmartPointer.h" +#include "vtkSphereSource.h" + +#include + +int TestOSPRayDynamicScene(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) +{ + vtkSmartPointer iren = vtkSmartPointer::New(); + vtkSmartPointer renWin = vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + vtkSmartPointer renderer = vtkSmartPointer::New(); + renWin->AddRenderer(renderer); + renderer->SetBackground(0.0,0.0,0.0); + renWin->SetSize(400,400); + renWin->Render(); + + vtkSmartPointer ospray=vtkSmartPointer::New(); + renderer->SetPass(ospray); + + #define GRIDDIM 3 + vtkSmartPointer camera = vtkSmartPointer::New(); + camera->SetPosition(GRIDDIM*3,GRIDDIM*3,GRIDDIM*4); + renderer->SetActiveCamera(camera); + + cerr << "ADD" << endl; + std::map actors; + for (int i = 0; i < GRIDDIM; i++) + { + for (int j = 0; j < GRIDDIM; j++) + { + for (int k = 0; k < GRIDDIM; k++) + { + vtkSmartPointer sphere = vtkSmartPointer::New(); + sphere->SetCenter(i,j,k); + sphere->SetPhiResolution(10); + sphere->SetThetaResolution(10); + vtkSmartPointer mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(sphere->GetOutputPort()); + vtkActor *actor= vtkActor::New(); + renderer->AddActor(actor); + actor->SetMapper(mapper); + actors[i*GRIDDIM*GRIDDIM+j*GRIDDIM+k] = actor; + renWin->Render(); + } + } + } + + cerr << "HIDE" << endl; + for (int i = 0; i < GRIDDIM; i++) + { + for (int j = 0; j < GRIDDIM; j++) + { + for (int k = 0; k < GRIDDIM; k++) + { + vtkActor *actor = actors[i*GRIDDIM*GRIDDIM+j*GRIDDIM+k]; + actor->VisibilityOff(); + renWin->Render(); + } + } + } + + cerr << "SHOW" << endl; + for (int i = 0; i < GRIDDIM; i++) + { + for (int j = 0; j < GRIDDIM; j++) + { + for (int k = 0; k < GRIDDIM; k++) + { + vtkActor *actor = actors[i*GRIDDIM*GRIDDIM+j*GRIDDIM+k]; + actor->VisibilityOn(); + renWin->Render(); + } + } + } + + cerr << "REMOVE" << endl; + for (int i = 0; i < GRIDDIM; i++) + { + for (int j = 0; j < GRIDDIM; j++) + { + for (int k = 0; k < GRIDDIM; k++) + { + vtkActor *actor = actors[i*GRIDDIM*GRIDDIM+j*GRIDDIM+k]; + //leaving one to have a decent image to compare against + bool killme = !(i==0 && j==1 && k==0); + if (killme) + { + renderer->RemoveActor(actor); + actor->Delete(); + renWin->Render(); + } + } + } + } + + iren->Start(); + + renderer->RemoveActor(actors[0*GRIDDIM*GRIDDIM+1*GRIDDIM+0]); + actors[0*GRIDDIM*GRIDDIM+1*GRIDDIM+0]->Delete(); + + return 0; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayImplicits.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayImplicits.cxx new file mode 100644 index 00000000000..3c5840f4000 --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayImplicits.cxx @@ -0,0 +1,265 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayImplicits.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test verifies that sizing of implicits spheres and cylinders for +// points and lines works as expected. +// +// The command line arguments are: +// -I => run in interactive mode; unless this is used, the program will +// not allow interaction and exit. +// In interactive mode it responds to the keys listed +// vtkOSPRayTestInteractor.h +// -GL => users OpenGL instead of OSPRay to render + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkDataSetSurfaceFilter.h" +#include "vtkDataArray.h" +#include "vtkDoubleArray.h" +#include "vtkExtractEdges.h" +#include "vtkGlyph3D.h" +#include "vtkGlyphSource2D.h" +#include "vtkImageData.h" +#include "vtkInformation.h" +#include "vtkOpenGLRenderer.h" +#include "vtkOSPRayActorNode.h" +#include "vtkOSPRayPass.h" +#include "vtkPiecewiseFunction.h" +#include "vtkPointData.h" +#include "vtkPolyData.h" +#include "vtkPolyDataMapper.h" +#include "vtkProperty.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkRTAnalyticSource.h" +#include "vtkScalarsToColors.h" +#include "vtkShrinkFilter.h" +#include "vtkSmartPointer.h" + +#include +#include + +#include "vtkOSPRayTestInteractor.h" + +int TestOSPRayImplicits(int argc, char* argv[]) +{ + bool useGL = false; + for (int i = 0; i < argc; i++) + { + if (!strcmp(argv[i], "-GL")) + { + useGL = true; + } + } + + vtkSmartPointer iren = + vtkSmartPointer::New(); + vtkSmartPointer renWin = + vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + vtkSmartPointer renderer = vtkSmartPointer::New(); + renWin->AddRenderer(renderer); + renderer->AutomaticLightCreationOn(); + renderer->SetBackground(0.75,0.75,0.75); + renWin->SetSize(600,550); + + vtkSmartPointer ospray = vtkSmartPointer::New(); + if (!useGL) + { + renderer->SetPass(ospray); + } + + vtkSmartPointer wavelet = vtkSmartPointer::New(); + wavelet->SetWholeExtent(-10,10,-10,10,-10,10); + wavelet->SetSubsampleRate(5); + wavelet->Update(); + //use a more predictable array + vtkSmartPointer da = vtkSmartPointer::New(); + da->SetName("testarray1"); + da->SetNumberOfComponents(1); + vtkDataSet * ds = wavelet->GetOutput(); + ds->GetPointData()->AddArray(da); + int np = ds->GetNumberOfPoints(); + for (int i = 0; i < np; i++) + { + da->InsertNextValue((double)i/(double)np); + } + + vtkSmartPointer surfacer = vtkSmartPointer::New(); + surfacer->SetInputData(ds); + vtkSmartPointer shrinker = vtkSmartPointer::New(); + shrinker->SetShrinkFactor(0.5); + shrinker->SetInputConnection(surfacer->GetOutputPort()); + + //measure it for placements + shrinker->Update(); + double *bds = vtkDataSet::SafeDownCast(shrinker->GetOutputDataObject(0))->GetBounds(); + double x0 = bds[0]; + double y0 = bds[2]; + double z0 = bds[4]; + double dx = (bds[1]-bds[0])*1.2; + double dy = (bds[3]-bds[2])*1.2; + double dz = (bds[5]-bds[4])*1.2; + + //make points, point rep works too but only gets outer shell + vtkSmartPointer glyph = vtkSmartPointer::New(); + glyph->SetGlyphTypeToVertex(); + vtkSmartPointer glyphFilter = vtkSmartPointer::New(); + glyphFilter->SetInputConnection(shrinker->GetOutputPort()); + glyphFilter->SetSourceConnection(glyph->GetOutputPort()); + + vtkSmartPointer edgeFilter = + vtkSmartPointer::New(); + edgeFilter->SetInputConnection(shrinker->GetOutputPort()); + + //spheres /////////////////////// + vtkSmartPointer mapper = vtkSmartPointer::New(); + mapper->SetInputConnection(glyphFilter->GetOutputPort()); + vtkSmartPointer actor = vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetRepresentationToPoints(); + renderer->AddActor(actor); + actor->SetPosition(x0+dx*0, y0+dy*0, z0+dz*0); + vtkOSPRayTestInteractor::AddName("Points default"); + + mapper = vtkSmartPointer::New(); + mapper->SetInputConnection(glyphFilter->GetOutputPort()); + actor = vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetRepresentationToPoints(); + renderer->AddActor(actor); + actor->SetPosition(x0+dx*1, y0+dy*0, z0+dz*0); + actor->GetProperty()->SetPointSize(5); + vtkOSPRayTestInteractor::AddName("Points SetPointSize()"); + + mapper = vtkSmartPointer::New(); + mapper->SetInputConnection(glyphFilter->GetOutputPort()); + actor = vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetRepresentationToPoints(); + renderer->AddActor(actor); + actor->SetPosition(x0+dx*2, y0+dy*0, z0+dz*0); + vtkInformation *mapInfo = mapper->GetInformation(); + mapInfo = mapper->GetInformation(); + mapInfo->Set(vtkOSPRayActorNode::ENABLE_SCALING(), 1); + mapInfo->Set(vtkOSPRayActorNode::SCALE_ARRAY_NAME(),"testarray1"); + vtkOSPRayTestInteractor::AddName("Points SCALE_ARRAY"); + + mapper = vtkSmartPointer::New(); + mapper->SetInputConnection(glyphFilter->GetOutputPort()); + actor = vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetRepresentationToPoints(); + renderer->AddActor(actor); + actor->SetPosition(x0+dx*3, y0+dy*0, z0+dz*0); + mapInfo = mapper->GetInformation(); + mapInfo->Set(vtkOSPRayActorNode::ENABLE_SCALING(), 1); + mapInfo->Set(vtkOSPRayActorNode::SCALE_ARRAY_NAME(),"testarray1"); + vtkSmartPointer scaleFunction = + vtkSmartPointer::New(); + scaleFunction->AddPoint(0.00, 0.0); + scaleFunction->AddPoint(0.50, 0.0); + scaleFunction->AddPoint(0.51, 0.1); + scaleFunction->AddPoint(1.00, 1.2); + mapInfo->Set(vtkOSPRayActorNode::SCALE_FUNCTION(), + scaleFunction); + vtkOSPRayTestInteractor::AddName("Points SCALE_FUNCTION on SCALE_ARRAY"); + + + // cylinders //////////////// + mapper = vtkSmartPointer::New(); + mapper->SetInputConnection(edgeFilter->GetOutputPort()); + actor = vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetRepresentationToWireframe(); + renderer->AddActor(actor); + actor->SetPosition(x0+dx*0, y0+dy*2, z0+dz*0); + vtkOSPRayTestInteractor::AddName("Wireframe default"); + + mapper = vtkSmartPointer::New(); + mapper->SetInputConnection(edgeFilter->GetOutputPort()); + actor = vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetRepresentationToWireframe(); + renderer->AddActor(actor); + actor->SetPosition(x0+dx*1, y0+dy*2, z0+dz*0); + actor->GetProperty()->SetLineWidth(5); + vtkOSPRayTestInteractor::AddName("Wireframe LineWidth"); + + mapper = vtkSmartPointer::New(); + mapper->SetInputConnection(edgeFilter->GetOutputPort()); + actor = vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetRepresentationToWireframe(); + renderer->AddActor(actor); + actor->SetPosition(x0+dx*2, y0+dy*2, z0+dz*0); + vtkOSPRayActorNode::SetEnableScaling(1, actor); + vtkOSPRayActorNode::SetScaleArrayName("testarray1",actor); + vtkOSPRayTestInteractor::AddName("Wireframe SCALE_ARRAY"); + + mapper = vtkSmartPointer::New(); + mapper->SetInputConnection(edgeFilter->GetOutputPort()); + actor = vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetRepresentationToWireframe(); + renderer->AddActor(actor); + actor->SetPosition(x0+dx*3, y0+dy*2, z0+dz*0); + mapInfo = mapper->GetInformation(); + mapInfo->Set(vtkOSPRayActorNode::ENABLE_SCALING(), 1); + mapInfo->Set(vtkOSPRayActorNode::SCALE_ARRAY_NAME(), "testarray1"); + scaleFunction = + vtkSmartPointer::New(); + scaleFunction->AddPoint(0.00, 0.0); + scaleFunction->AddPoint(0.50, 0.0); + scaleFunction->AddPoint(0.51, 0.1); + scaleFunction->AddPoint(1.00, 1.2); + mapInfo->Set(vtkOSPRayActorNode::SCALE_FUNCTION(), + scaleFunction); + vtkOSPRayTestInteractor::AddName("Wireframe SCALE_FUNCTION on SCALE_ARRAY"); + + // reference values shown as colors ///////////////// + mapper = vtkSmartPointer::New(); + mapper->SetInputConnection(surfacer->GetOutputPort()); + surfacer->Update(); + mapper->ScalarVisibilityOn(); + mapper->CreateDefaultLookupTable(); + mapper->SetColorModeToMapScalars(); + mapper->SetScalarModeToUsePointFieldData(); + mapper->SelectColorArray("testarray1"); + double *range = surfacer->GetOutput()->GetPointData()->GetArray("testarray1")->GetRange(); + mapper->SetScalarRange(range); + actor = vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetRepresentationToSurface(); + + renderer->AddActor(actor); + actor->SetPosition(x0+dx*2, y0+dy*1, z0+dz*0); + vtkOSPRayTestInteractor::AddName("Reference values as colors"); + + //just show it ////////////////// + renWin->Render(); + renderer->ResetCamera(); + + vtkSmartPointer style = + vtkSmartPointer::New(); + style-> + SetPipelineControlPoints((vtkOpenGLRenderer*)renderer.Get(), ospray, NULL); + iren->SetInteractorStyle(style); + style->SetCurrentRenderer(renderer); + + iren->Start(); + + return 0; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayLayers.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayLayers.cxx new file mode 100644 index 00000000000..f186a4942f5 --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayLayers.cxx @@ -0,0 +1,74 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayLayers.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test verifies that we can have multiple render layers +// +// The command line arguments are: +// -I => run in interactive mode; unless this is used, the program will +// not allow interaction and exit + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkConeSource.h" +#include "vtkOSPRayPass.h" +#include "vtkPolyDataMapper.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkSmartPointer.h" +#include "vtkSphereSource.h" + +int TestOSPRayLayers(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) +{ + vtkSmartPointer iren = vtkSmartPointer::New(); + vtkSmartPointer renWin = vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + renWin->SetNumberOfLayers(2); + + vtkSmartPointer renderer = vtkSmartPointer::New(); + renWin->AddRenderer(renderer); + vtkSmartPointer sphere = vtkSmartPointer::New(); + sphere->SetPhiResolution(10); + vtkSmartPointer mapper = vtkSmartPointer::New(); + mapper->SetInputConnection(sphere->GetOutputPort()); + vtkSmartPointer actor=vtkSmartPointer::New(); + renderer->AddActor(actor); + actor->SetMapper(mapper); + renderer->SetBackground(0.5,0.5,1.0); //should see a light blue background + + vtkSmartPointer renderer2 = vtkSmartPointer::New(); + renderer2->SetLayer(1); + renWin->AddRenderer(renderer2); + renderer2->SetBackground(1.0,0.0,0.0); //should not see red background + vtkSmartPointer cone = vtkSmartPointer::New(); + vtkSmartPointer mapper2 = vtkSmartPointer::New(); + mapper2->SetInputConnection(cone->GetOutputPort()); + vtkSmartPointer actor2 = vtkSmartPointer::New(); + renderer2->AddActor(actor2); + actor2->SetMapper(mapper2); + + renWin->SetSize(400,400); + renWin->Render(); + + vtkSmartPointer ospray=vtkSmartPointer::New(); + vtkSmartPointer ospray2=vtkSmartPointer::New(); + + renderer->SetPass(ospray); + renderer2->SetPass(ospray2); + renWin->Render(); + + iren->Start(); + + return 0; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayLights.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayLights.cxx new file mode 100644 index 00000000000..7e5bb5b4b94 --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayLights.cxx @@ -0,0 +1,215 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayLights.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test verifies that lighting works as expected with ospray. +// When advanced materials are exposed in ospray, it will also validate +// refractions and reflections +// +// The command line arguments are: +// -I => run in interactive mode; unless this is used, the program will +// not allow interaction and exit +// In interactive mode it responds to the keys listed +// vtkOSPRayTestInteractor.h + +#include "vtkTestUtilities.h" + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkLight.h" +#include "vtkOpenGLRenderer.h" +#include "vtkOSPRayPass.h" +#include "vtkOSPRayRendererNode.h" +#include "vtkPlaneSource.h" +#include "vtkPLYReader.h" +#include "vtkPolyDataMapper.h" +#include "vtkPolyDataNormals.h" +#include "vtkProperty.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkSmartPointer.h" +#include "vtkSphereSource.h" + +#include "vtkOSPRayTestInteractor.h" + +int TestOSPRayLights(int argc, char* argv[]) +{ + vtkSmartPointer iren = vtkSmartPointer::New(); + vtkSmartPointer renWin = vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + vtkSmartPointer renderer = vtkSmartPointer::New(); + renderer->AutomaticLightCreationOff(); + renWin->AddRenderer(renderer); + + const char* fileName = + vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/bunny.ply"); + vtkSmartPointer polysource = vtkSmartPointer::New(); + polysource->SetFileName(fileName); + + //measure so we can place things sensibly + polysource->Update(); + double bds[6]; + polysource->GetOutput()->GetBounds(bds); + double x0 = bds[0]*2; + double x1 = bds[1]*2; + double y0 = bds[2]; + double y1 = bds[3]*2; + double z0 = bds[4]; + double z1 = bds[5]*4; + + //TODO: ospray acts strangely without these such that Diff and Spec are not 0..255 instead of 0..1 + vtkSmartPointer normals = vtkSmartPointer::New(); + normals->SetInputConnection(polysource->GetOutputPort()); + + vtkSmartPointer mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(normals->GetOutputPort()); + vtkSmartPointer actor=vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetColor(1.0,1.0,1.0); + actor->GetProperty()->SetAmbient(0.1); + actor->GetProperty()->SetDiffuse(1); + actor->GetProperty()->SetSpecularColor(1,1,1); + actor->GetProperty()->SetSpecular(0.9); + actor->GetProperty()->SetSpecularPower(500); + renderer->AddActor(actor); + + vtkSmartPointer backwall = vtkSmartPointer::New(); + backwall->SetOrigin(x0,y0,z0); + backwall->SetPoint1(x1,y0,z0); + backwall->SetPoint2(x0,y1,z0); + mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(backwall->GetOutputPort()); + actor=vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetColor(1.0,1.0,1.0); + actor->GetProperty()->SetAmbient(0.1); + actor->GetProperty()->SetDiffuse(1); + actor->GetProperty()->SetSpecular(0); + renderer->AddActor(actor); + + vtkSmartPointer floor = vtkSmartPointer::New(); + floor->SetOrigin(x0,y0,z0); + floor->SetPoint1(x0,y0,z1); + floor->SetPoint2(x1,y0,z0); + mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(floor->GetOutputPort()); + actor=vtkSmartPointer::New(); + actor->GetProperty()->SetColor(1.0,1.0,1.0); + actor->GetProperty()->SetAmbient(0.1); + actor->GetProperty()->SetDiffuse(1); + actor->GetProperty()->SetSpecular(0); + actor->SetMapper(mapper); + renderer->AddActor(actor); + + vtkSmartPointer left = vtkSmartPointer::New(); + left->SetOrigin(x0,y0,z0); + left->SetPoint1(x0,y1,z0); + left->SetPoint2(x0,y0,z1); + mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(left->GetOutputPort()); + actor=vtkSmartPointer::New(); + actor->GetProperty()->SetColor(1.0,1.0,1.0); + actor->GetProperty()->SetAmbient(0.1); + actor->GetProperty()->SetDiffuse(1); + actor->GetProperty()->SetSpecular(0); + actor->SetMapper(mapper); + renderer->AddActor(actor); + + vtkSmartPointer magnifier = vtkSmartPointer::New(); + //TODO: use PathTracer_Dielectric material for this when available + magnifier->SetCenter(x0+(x1-x0)*0.6, y0+(y1-y0)*0.2, z0+(z1-z0)*0.7); + magnifier->SetRadius((x1-x0)*0.05); + magnifier->SetPhiResolution(30); + magnifier->SetThetaResolution(30); + mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(magnifier->GetOutputPort()); + actor=vtkSmartPointer::New(); + actor->GetProperty()->SetColor(1.0,1.0,1.0); + actor->GetProperty()->SetAmbient(0.1); + actor->GetProperty()->SetDiffuse(1); + actor->GetProperty()->SetSpecular(0); + actor->SetMapper(mapper); + renderer->AddActor(actor); + + vtkSmartPointer discoball = vtkSmartPointer::New(); + //TODO: use PathTracer_Metal material for this when available + discoball->SetCenter(x0+(x1-x0)*0.5, y0+(y1-y0)*0.85, z0+(z1-z0)*0.5); + discoball->SetRadius((x1-x0)*0.1); + discoball->SetPhiResolution(30); + discoball->SetThetaResolution(30); + mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(discoball->GetOutputPort()); + actor=vtkSmartPointer::New(); + actor->GetProperty()->SetColor(1.0,1.0,1.0); + actor->GetProperty()->SetAmbient(0.1); + actor->GetProperty()->SetDiffuse(1); + actor->GetProperty()->SetSpecular(0); + actor->SetMapper(mapper); + renderer->AddActor(actor); + + vtkSmartPointer light = vtkSmartPointer::New(); + //blue light casting shadows from infinity toward bottom left back corner + light->PositionalOff(); + light->SetPosition(x0+(x1-x0)*1, y0+(y1-y0)*1, z0+(z1+z0)*1); + light->SetFocalPoint(x0, y0, z0); + light->SetLightTypeToSceneLight(); + light->SetColor(0.0,0.0,1.0); + light->SetIntensity(0.3); + light->SwitchOn(); + renderer->AddLight(light); + + light = vtkSmartPointer::New(); + //red light casting shadows from top to bottom + light->PositionalOn(); + double t = 1.8; //adjust t to see effect of positional + light->SetPosition( x0+(x1-x0)*0.5, y0+(y1-y0)*t, z0+(z1-z0)*0.5); + light->SetFocalPoint(x0+(x1-x0)*0.5, y0+(y1-y0)*0, z0+(z1-z0)*0.5); + light->SetLightTypeToSceneLight(); + light->SetColor(1.0,0.0,0.0); + light->SetIntensity(0.3); + light->SwitchOn(); + renderer->AddLight(light); + + light = vtkSmartPointer::New(); + //green light following camera + light->PositionalOn(); + light->SetLightTypeToHeadlight(); + light->SetColor(0.0,1.0,0.0); + light->SetIntensity(0.3); + light->SwitchOn(); + renderer->AddLight(light); + + renderer->SetBackground(0.0,0.0,0.0); + renWin->SetSize(400,400); + + vtkSmartPointer ospray=vtkSmartPointer::New(); + renderer->SetPass(ospray); + + //increase image quality from default (otherwise subsampling artifacts) + renWin->Render(); + vtkOSPRayRendererNode *renNode = ospray->GetSceneGraph(); + renderer->UseShadowsOn(); + renNode->SetMaxFrames(5, renderer); + renNode->SetSamplesPerPixel(4, renderer); + + vtkSmartPointer style = + vtkSmartPointer::New(); + style->SetPipelineControlPoints((vtkOpenGLRenderer*)renderer.Get(), ospray, NULL); + iren->SetInteractorStyle(style); + style->SetCurrentRenderer(renderer); + + iren->Start(); + + return 0; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayMultiBlock.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayMultiBlock.cxx new file mode 100644 index 00000000000..3dc660fe156 --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayMultiBlock.cxx @@ -0,0 +1,79 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayMultiBlock.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test verifies that treatment of multiblock data is correct +// +// The command line arguments are: +// -I => run in interactive mode; unless this is used, the program will +// not allow interaction and exit +// In interactive mode it responds to the keys listed +// vtkOSPRayTestInteractor.h + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkCompositeDataSet.h" +#include "vtkCompositePolyDataMapper2.h" +#include "vtkOSPRayPass.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkSmartPointer.h" +#include "vtkTestUtilities.h" +#include "vtkXMLMultiBlockDataReader.h" + +#include "vtkOSPRayTestInteractor.h" + +int TestOSPRayMultiBlock(int argc, char* argv[]) +{ + vtkSmartPointer iren = vtkSmartPointer::New(); + vtkSmartPointer renWin = vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + vtkSmartPointer renderer = vtkSmartPointer::New(); + renWin->AddRenderer(renderer); + + vtkSmartPointer reader = vtkSmartPointer::New(); + const char* fileName = vtkTestUtilities::ExpandDataFileName(argc, argv, + "Data/many_blocks/many_blocks.vtm"); + reader->SetFileName(fileName); + reader->Update(); + + vtkSmartPointer mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(reader->GetOutputPort()); + vtkSmartPointer actor=vtkSmartPointer::New(); + renderer->AddActor(actor); + actor->SetMapper(mapper); + renderer->SetBackground(0.1,0.1,1.0); + renWin->SetSize(400,400); + renWin->Render(); + + vtkCamera *cam = renderer->GetActiveCamera(); + cam->SetPosition(1.5,1.5,0.75); + + vtkSmartPointer ospray=vtkSmartPointer::New(); + + renderer->SetPass(ospray); + + renWin->Render(); + + vtkSmartPointer style = + vtkSmartPointer::New(); + style-> + SetPipelineControlPoints((vtkOpenGLRenderer*)renderer.Get(), ospray, NULL); + iren->SetInteractorStyle(style); + style->SetCurrentRenderer(renderer); + + iren->Start(); + + return 0; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayMultiBlockPartialArrayFieldData.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayMultiBlockPartialArrayFieldData.cxx new file mode 100644 index 00000000000..09bdfa0fb2f --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayMultiBlockPartialArrayFieldData.cxx @@ -0,0 +1,151 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkCompositePolyDataMapper2.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkColorTransferFunction.h" +#include "vtkCompositeDataDisplayAttributes.h" +#include "vtkCompositePolyDataMapper2.h" +#include "vtkCylinderSource.h" +#include "vtkDoubleArray.h" +#include "vtkFieldData.h" +#include "vtkMultiBlockDataSet.h" +#include "vtkNew.h" +#include "vtkOSPRayPass.h" +#include "vtkProperty.h" +#include "vtkRegressionTestImage.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkSmartPointer.h" +#include "vtkSphereSource.h" + +// Test for multiblock data sets with field data arrays defined on +// only a subset of the blocks. The expected behavior is to have +// coloring by scalars on the blocks with the data array and coloring +// as though scalar mapping is turned off in the blocks without the +// data array. +int TestOSPRayMultiBlockPartialArrayFieldData(int argc, char* argv[]) +{ + bool useGL = false; + for (int i = 0; i < argc; i++) + { + if (!strcmp(argv[i], "-GL")) + { + useGL = true; + } + } + + vtkSmartPointer win = + vtkSmartPointer::New(); + vtkSmartPointer iren = + vtkSmartPointer::New(); + vtkSmartPointer ren = + vtkSmartPointer::New(); + win->AddRenderer(ren); + win->SetInteractor(iren); + + // Components of the multiblock data set + vtkNew sphereSource; + sphereSource->SetRadius(2.0); + + vtkNew cylinderSource; + cylinderSource->SetRadius(1.5); + cylinderSource->SetHeight(2.0); + cylinderSource->SetResolution(32); + + // Set up the multiblock data set consisting of a ring of blocks + vtkSmartPointer data = vtkSmartPointer::New(); + + int numBlocks = 16; + data->SetNumberOfBlocks(numBlocks); + + double radius = 10.0; + double deltaTheta = 2.0*3.1415926 / numBlocks; + for (int i = 0; i < numBlocks; ++i) + { + double theta = i * deltaTheta; + double x = radius * cos(theta); + double y = radius * sin(theta); + + vtkPolyData* pd = vtkPolyData::New(); + + // Every third block does not have the color array + if (i % 3 == 0) + { + sphereSource->SetCenter(x, y, 0.0); + sphereSource->Update(); + pd->DeepCopy(sphereSource->GetOutput()); + } + else + { + cylinderSource->SetCenter(x, y, 0.0); + cylinderSource->Update(); + pd->DeepCopy(cylinderSource->GetOutput()); + + // Add a field data array + vtkSmartPointer dataArray = vtkSmartPointer::New(); + dataArray->SetName("mydata"); + dataArray->SetNumberOfComponents(1); + dataArray->SetNumberOfTuples(1); + dataArray->InsertValue(0, static_cast(i)); + + pd->GetFieldData()->AddArray(dataArray); + + } + data->SetBlock(i, pd); + pd->Delete(); + } + + vtkNew lookupTable; + lookupTable->AddRGBPoint(0.0, 1.0, 1.0, 1.0); + lookupTable->AddRGBPoint(static_cast(numBlocks-1), 0.0, 1.0, 0.0); + + vtkSmartPointer mapper = + vtkSmartPointer::New(); + mapper->SetInputDataObject(data); + + // Tell mapper to use field data for rendering + mapper->SetLookupTable(lookupTable.GetPointer()); + mapper->SetFieldDataTupleId(0); + mapper->SelectColorArray("mydata"); + mapper->SetScalarModeToUseFieldData(); + mapper->UseLookupTableScalarRangeOn(); + mapper->ScalarVisibilityOn(); + + vtkSmartPointer actor = + vtkSmartPointer::New(); + actor->SetMapper(mapper); + actor->GetProperty()->SetColor(1.0, 0.67, 1.0); + + vtkSmartPointer ospray = vtkSmartPointer::New(); + if (!useGL) + { + ren->SetPass(ospray); + } + + ren->AddActor(actor); + win->SetSize(400, 400); + + ren->ResetCamera(); + + win->Render(); + + int retVal = vtkRegressionTestImageThreshold( win.GetPointer(),15); + if ( retVal == vtkRegressionTester::DO_INTERACTOR) + { + iren->Start(); + } + + return !retVal; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayPass.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayPass.cxx new file mode 100644 index 00000000000..29d512e84bc --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayPass.cxx @@ -0,0 +1,95 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayPass.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test verifies that we can hot swap ospray and GL backends. +// +// The command line arguments are: +// -I => run in interactive mode; unless this is used, the program will +// not allow interaction and exit +// In interactive mode it responds to the keys listed +// vtkOSPRayTestInteractor.h + +//TODO: dragon.ply crashes, and removing normals is black (ADS 0..255 instead of 0..1) + +#include "vtkTestUtilities.h" + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkOpenGLRenderer.h" +#include "vtkOSPRayPass.h" +#include "vtkPolyDataMapper.h" +#include "vtkPolyDataNormals.h" +#include "vtkPLYReader.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkSmartPointer.h" + +#include "vtkOSPRayTestInteractor.h" + +int TestOSPRayPass(int argc, char* argv[]) +{ + vtkSmartPointer iren = vtkSmartPointer::New(); + vtkSmartPointer renWin = vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + vtkSmartPointer renderer = vtkSmartPointer::New(); + renWin->AddRenderer(renderer); + + const char* fileName = + vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/bunny.ply"); + vtkSmartPointer polysource = vtkSmartPointer::New(); + polysource->SetFileName(fileName); + + //TODO: ospray acts strangely without these such that Diff and Spec are not 0..255 instead of 0..1 + vtkSmartPointer normals = vtkSmartPointer::New(); + normals->SetInputConnection(polysource->GetOutputPort()); + //normals->ComputePointNormalsOn(); + //normals->ComputeCellNormalsOff(); + + vtkSmartPointer mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(normals->GetOutputPort()); + vtkSmartPointer actor=vtkSmartPointer::New(); + renderer->AddActor(actor); + actor->SetMapper(mapper); + renderer->SetBackground(0.1,0.1,1.0); + renWin->SetSize(400,400); + renWin->Render(); + + vtkSmartPointer ospray=vtkSmartPointer::New(); + + for (int i = 1; i<10; i++) + { + if (i%2) + { + cerr << "Render via OSPRAY" << endl; + renderer->SetPass(ospray); + } + else + { + cerr << "Render via GL" << endl; + renderer->SetPass(NULL); + } + renWin->Render(); + } + + vtkSmartPointer style = + vtkSmartPointer::New(); + style->SetPipelineControlPoints((vtkOpenGLRenderer*)renderer.Get(), ospray, NULL); + iren->SetInteractorStyle(style); + style->SetCurrentRenderer(renderer); + + iren->Start(); + + return 0; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayRenderMesh.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayRenderMesh.cxx new file mode 100644 index 00000000000..fe61bace515 --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayRenderMesh.cxx @@ -0,0 +1,471 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayRenderMesh.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test verifies that we can do simple mesh rendering with ospray +// and that VTK's many standard rendering modes (points, lines, surface, with +// a variety of color controls (actor, point, cell, texture) etc work as +// they should. +// +// The command line arguments are: +// -I => run in interactive mode; unless this is used, the program will +// not allow interaction and exit. +// In interactive mode it responds to the keys listed +// vtkOSPRayTestInteractor.h +// -GL => users OpenGL instead of OSPRay to render +// -type N => where N is one of 0,1,2, or 3 makes meshes consisting of +// points, wireframes, triangles (=the default) or triangle strips +// -rep N => where N is one of 0,1 or 2 draws the meshes as points, lines +// or surfaces + +#include "vtkActor.h" +#include "vtkActorCollection.h" +#include "vtkCamera.h" +#include "vtkCellData.h" +#include "vtkDoubleArray.h" +#include "vtkExtractEdges.h" +#include "vtkImageData.h" +#include "vtkInformation.h" +#include "vtkLight.h" +#include "vtkLightCollection.h" +#include "vtkOpenGLRenderer.h" +#include "vtkOSPRayActorNode.h" +#include "vtkOSPRayPass.h" +#include "vtkPiecewiseFunction.h" +#include "vtkPointData.h" +#include "vtkPolyData.h" +#include "vtkPolyDataMapper.h" +#include "vtkPolyDataNormals.h" +#include "vtkProperty.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkSmartPointer.h" +#include "vtkSphereSource.h" +#include "vtkStripper.h" +#include "vtkTextureMapToSphere.h" +#include "vtkTransformTextureCoords.h" +#include "vtkUnsignedCharArray.h" +#include "vtkVertexGlyphFilter.h" + +#include +#include + +#include "vtkOSPRayTestInteractor.h" + +class renderable +{ +public: + vtkSphereSource *s; + vtkPolyDataMapper *m; + vtkActor *a; + ~renderable() + { + s->Delete(); + m->Delete(); + a->Delete(); + } +}; + +renderable *MakeSphereAt(double x, double y, double z, int res, + int type, int rep, const char *name) +{ + vtkOSPRayTestInteractor::AddName(name); + renderable *ret = new renderable; + ret->s = vtkSphereSource::New(); + ret->s->SetEndTheta(180); //half spheres better show variation and f and back + ret->s->SetStartPhi(30); + ret->s->SetEndPhi(150); + ret->s->SetPhiResolution(res); + ret->s->SetThetaResolution(res); + ret->s->SetCenter(x,y,z); + //make texture coordinate + vtkSmartPointer tc = + vtkSmartPointer::New(); + tc->SetCenter(x,y,z); + tc->PreventSeamOn(); + tc->AutomaticSphereGenerationOff(); + tc->SetInputConnection(ret->s->GetOutputPort()); + vtkSmartPointer tt = + vtkSmartPointer::New(); + tt->SetInputConnection(tc->GetOutputPort()); + //tt->SetScale(1,0.5,1); + //make normals + vtkSmartPointer nl = + vtkSmartPointer::New(); + nl->SetInputConnection(tt->GetOutputPort()); + nl->Update(); + //make more attribute arrays + vtkPolyData *pd = nl->GetOutput(); + //point aligned + vtkSmartPointer da = vtkSmartPointer::New(); + da->SetName("testarray1"); + da->SetNumberOfComponents(1); + pd->GetPointData()->AddArray(da); + int np = pd->GetNumberOfPoints(); + int nc = pd->GetNumberOfCells(); + for (int i = 0; i < np; i++) + { + da->InsertNextValue((double)i/(double)np); + } + da = vtkSmartPointer::New(); + da->SetName("testarray2"); + da->SetNumberOfComponents(3); + pd->GetPointData()->AddArray(da); + for (int i = 0; i < np; i++) + { + double vals[3] = {(double)i/(double)np, (double)(i*4)/(double)np-2.0, 42.0}; + da->InsertNextTuple3(vals[0],vals[1],vals[2]); + } + + vtkSmartPointer pac = + vtkSmartPointer::New(); + pac->SetName("testarrayc1"); + pac->SetNumberOfComponents(3); + pd->GetPointData()->AddArray(pac); + for (int i = 0; i < np; i++) + { + unsigned char vals[3] = + {static_cast(255*((double)i/(double)np)), + static_cast(255*((double)(i*4)/(double)np-2.0)), + 42}; + pac->InsertNextTuple3(vals[0],vals[1],vals[2]); + } + + vtkSmartPointer ca = + vtkSmartPointer::New(); + ca->SetName("testarray3"); + ca->SetNumberOfComponents(3); + pd->GetPointData()->AddArray(ca); + for (int i = 0; i < np; i++) + { + unsigned char vals[3] = + {static_cast((double)i/(double)np*255), + static_cast((double)(1-i)/(double)np), + 42}; + ca->InsertNextTuple3(vals[0],vals[1],vals[2]); + } + //cell aligned + da = vtkSmartPointer::New(); + da->SetName("testarray4"); + da->SetNumberOfComponents(1); + pd->GetCellData()->AddArray(da); + for (int i = 0; i < pd->GetNumberOfCells(); i++) + { + da->InsertNextValue((double)i/(double)pd->GetNumberOfCells()); + } + da = vtkSmartPointer::New(); + da->SetName("testarray5"); + da->SetNumberOfComponents(3); + pd->GetCellData()->AddArray(da); + for (int i = 0; i < nc; i++) + { + double vals[3] = {(double)i/(double)nc, (double)(i*2)/(double)nc, 42.0}; + da->InsertNextTuple3(vals[0],vals[1],vals[2]); + } + ca = vtkSmartPointer::New(); + ca->SetName("testarray6"); + ca->SetNumberOfComponents(3); + pd->GetCellData()->AddArray(ca); + for (int i = 0; i < nc; i++) + { + unsigned char vals[3] = + {static_cast((double)i/(double)np*255), + static_cast((double)(1-i)/(double)np), + 42}; + ca->InsertNextTuple3(vals[0],vals[1],vals[2]); + } + ret->m = vtkPolyDataMapper::New(); + ret->m->SetInputData(pd); + + switch (type) + { + case 0: //points + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData(pd); + filter->Update(); + ret->m->SetInputData(filter->GetOutput()); + break; + } + case 1: //lines + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData(pd); + filter->Update(); + ret->m->SetInputData(filter->GetOutput()); + break; + } + case 2: //polys + break; + case 3: //strips + { + vtkSmartPointer filter = + vtkSmartPointer::New(); + filter->SetInputData(pd); + filter->Update(); + ret->m->SetInputData(filter->GetOutput()); + break; + } + } + ret->a=vtkActor::New(); + ret->a->SetMapper(ret->m); + ret->a->GetProperty()->SetPointSize(20); + ret->a->GetProperty()->SetLineWidth(10); + if (rep != -1) + { + ret->a->GetProperty()->SetRepresentation(rep); + } + return ret; +} + +int TestOSPRayRenderMesh(int argc, char* argv[]) +{ + bool useGL = false; + int type = 2; + int rep = -1; + for (int i = 0; i < argc; i++) + { + if (!strcmp(argv[i], "-GL")) + { + useGL = true; + } + if (!strcmp(argv[i], "-type")) + { + type = atoi(argv[i+1]); + } + if (!strcmp(argv[i], "-rep")) + { + rep = atoi(argv[i+1]); + } + } + + vtkSmartPointer iren = + vtkSmartPointer::New(); + vtkSmartPointer renWin = + vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + vtkSmartPointer renderer = vtkSmartPointer::New(); + renWin->AddRenderer(renderer); + renderer->AutomaticLightCreationOn(); + renderer->SetBackground(0.75,0.75,0.75); + renWin->SetSize(600,550); + vtkSmartPointer camera = vtkSmartPointer::New(); + camera->SetPosition(2.5,11,-3); + camera->SetFocalPoint(2.5,0,-3); + camera->SetViewUp(0,0,1); + renderer->SetActiveCamera(camera); + renWin->Render(); + + vtkSmartPointer ospray = vtkSmartPointer::New(); + if (!useGL) + { + renderer->SetPass(ospray); + } + //Now, vary of most of the many parameters that rendering can vary by. + + //representations points, wireframe, surface + renderable *ren = MakeSphereAt(5,0,-5, 10, type, rep, "points"); + ren->a->GetProperty()->SetRepresentationToPoints(); + renderer->AddActor(ren->a); + delete(ren); + + ren = MakeSphereAt(5,0,-4, 10, type, rep, "wireframe"); + ren->a->GetProperty()->SetRepresentationToWireframe(); + renderer->AddActor(ren->a); + delete(ren); + + ren = MakeSphereAt(5,0,-3, 10, type, rep, "surface"); + ren->a->GetProperty()->SetRepresentationToSurface(); + renderer->AddActor(ren->a); + delete(ren); + + //actor color + ren = MakeSphereAt(4,0,-5, 10, type, rep, "actor_color"); + ren->a->GetProperty()->SetColor(0,1,0); + renderer->AddActor(ren->a); + delete(ren); + + //ambient, diffuse, and specular components + ren = MakeSphereAt(4,0,-4, 7, type, rep, "amb/diff/spec"); + ren->a->GetProperty()->SetAmbient(0.5); + ren->a->GetProperty()->SetAmbientColor(0.1,0.1,0.3); + ren->a->GetProperty()->SetDiffuse(0.4); + ren->a->GetProperty()->SetDiffuseColor(0.5,0.1,0.1); + ren->a->GetProperty()->SetSpecular(0.2); + ren->a->GetProperty()->SetSpecularColor(1,1,1); + ren->a->GetProperty()->SetSpecularPower(100); + ren->a->GetProperty()->SetInterpolationToPhong(); + renderer->AddActor(ren->a); + delete(ren); + + //opacity + ren = MakeSphereAt(4,0,-3, 10, type, rep, "opacity"); + ren->a->GetProperty()->SetOpacity(0.2); + renderer->AddActor(ren->a); + delete(ren); + + //color map cell values + ren = MakeSphereAt(3,0,-5, 10, type, rep, "cell_value"); + ren->m->SetScalarModeToUseCellFieldData(); + ren->m->SelectColorArray(0); + renderer->AddActor(ren->a); + delete(ren); + + //default color component + ren = MakeSphereAt(3,0,-4, 10, type, rep, "cell_default_comp"); + ren->m->SetScalarModeToUseCellFieldData(); + ren->m->SelectColorArray(1); + renderer->AddActor(ren->a); + delete(ren); + + //choose color component + ren = MakeSphereAt(3,0,-3, 10, type, rep, "cell_comp_1"); + ren->m->SetScalarModeToUseCellFieldData(); + ren->m->SelectColorArray(1); + ren->m->ColorByArrayComponent(1,1); //todo, use lut since this is deprecated + renderer->AddActor(ren->a); + delete(ren); + + //RGB direct + ren = MakeSphereAt(3,0,-2, 10, type, rep, "cell_rgb"); + ren->m->SetScalarModeToUseCellFieldData(); + ren->m->SelectColorArray(2); + renderer->AddActor(ren->a); + delete(ren); + + //RGB through LUT + ren = MakeSphereAt(3,0,-1, 10, type, rep, "cell_rgb_through_LUT"); + ren->m->SetScalarModeToUseCellFieldData(); + ren->m->SelectColorArray(2); + ren->m->SetColorModeToMapScalars(); + renderer->AddActor(ren->a); + delete(ren); + + //color map point values + ren = MakeSphereAt(2,0,-5,6, type, rep, "point_value"); + ren->m->SetScalarModeToUsePointFieldData(); + ren->m->SelectColorArray("testarray1"); + renderer->AddActor(ren->a); + delete(ren); + + //interpolate scalars before mapping + ren = MakeSphereAt(2,0,-4,6, type, rep, "point_interp"); + ren->m->SetScalarModeToUsePointFieldData(); + ren->m->SelectColorArray("testarray1"); + ren->m->InterpolateScalarsBeforeMappingOn(); + renderer->AddActor(ren->a); + delete(ren); + + //RGB direct + ren = MakeSphereAt(2,0,-3, 10, type, rep, "point_rgb"); + ren->m->SetScalarModeToUsePointFieldData(); + ren->m->SetColorModeToDefault(); + ren->m->SelectColorArray("testarrayc1"); + renderer->AddActor(ren->a); + delete(ren); + + //RGB mapped + ren = MakeSphereAt(2,0,-2, 10, type, rep, "point_rgb_through_LUT"); + ren->m->SetScalarModeToUsePointFieldData(); + ren->m->SetColorModeToMapScalars(); + ren->m->SelectColorArray("testarrayc1"); + renderer->AddActor(ren->a); + delete(ren); + + //unlit, flat, and gouraud lighting + ren = MakeSphereAt(1,0,-5,7, type, rep, "not_lit"); + ren->a->GetProperty()->LightingOff(); + renderer->AddActor(ren->a); + delete(ren); + + ren = MakeSphereAt(1,0,-4,7, type, rep, "flat"); + ren->a->GetProperty()->SetInterpolationToFlat(); + renderer->AddActor(ren->a); + delete(ren); + + ren = MakeSphereAt(1,0,-3,7, type, rep, "gouraud"); + ren->a->GetProperty()->SetInterpolationToGouraud(); + renderer->AddActor(ren->a); + delete(ren); + + //texture + int maxi = 100; + int maxj = 100; + vtkSmartPointer texin = vtkSmartPointer::New(); + texin->SetExtent(0,maxi,0,maxj,0,0); + texin->AllocateScalars(VTK_UNSIGNED_CHAR, 3); + vtkUnsignedCharArray *aa = + vtkArrayDownCast(texin->GetPointData()->GetScalars()); + int idx = 0; + for (int i = 0; i<=maxi; i++) + { + for (int j = 0; j<=maxj; j++) + { + bool ival = (i/10)%2==1; + bool jval = (j/10)%2==1; + unsigned char val = (ival^jval) ? 255 : 0; + aa->SetTuple3(idx, val, val, val); + if (j <= 3 || j >= maxj-3) + { + aa->SetTuple3(idx, 255, 255, 0); + } + if (i <= 20 || i >= maxi-20) + { + aa->SetTuple3(idx, 255, 0, 0); + } + idx = idx + 1; + } + } + ren = MakeSphereAt(0,0,-5,20,type, rep, "texture"); + renderer->AddActor(ren->a); + vtkSmartPointer texture = + vtkSmartPointer::New(); + texture->SetInputData(texin); + ren->a->SetTexture(texture); + delete(ren); + + //imagespace positional transformations + ren = MakeSphereAt(0,0,-4,10, type, rep, "transform"); + ren->a->SetScale(1.2,1.0,0.87); + renderer->AddActor(ren->a); + delete(ren); + + //TODO: lut manipulation and range effects + //TODO: NaN colors + //TODO: mapper clipping planes + //TODO: hierarchical actors + + renWin->Render(); + + vtkLight *light = + vtkLight::SafeDownCast(renderer->GetLights()->GetItemAsObject(0)); + double lColor[3]; + light->GetDiffuseColor(lColor); + light->SetPosition(2,15,-2); + light->SetFocalPoint(2,0,-2); + light->PositionalOff(); + + vtkSmartPointer style = + vtkSmartPointer::New(); + style-> + SetPipelineControlPoints((vtkOpenGLRenderer*)renderer.Get(), ospray, NULL); + iren->SetInteractorStyle(style); + style->SetCurrentRenderer(renderer); + + iren->Start(); + + return 0; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayScalarBar.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayScalarBar.cxx new file mode 100644 index 00000000000..5949d41524a --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayScalarBar.cxx @@ -0,0 +1,108 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayScalarBar.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkSmartPointer.h" + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkPolyDataMapper.h" +#include "vtkProperty2D.h" +#include "vtkRegressionTestImage.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkScalarBarActor.h" +#include "vtkScalarsToColors.h" +#include "vtkTextProperty.h" +#include "vtkOSPRayPass.h" +#include "vtkSphereSource.h" +#include "vtkNew.h" +#include "vtkScalarBarActor.h" +#include "vtkElevationFilter.h" + +#include "vtkTestUtilities.h" + +int TestOSPRayScalarBar( int argc, char *argv[] ) +{ + vtkNew sphere; + sphere->SetThetaResolution(8); + sphere->SetPhiResolution(8); + vtkNew elev; + elev->SetInputConnection(sphere->GetOutputPort(0)); + + vtkNew sphereMapper; + sphereMapper->SetInputConnection(elev->GetOutputPort(0)); + vtkNew sphereActor; + sphereActor->SetMapper(sphereMapper.Get()); + + // Create the RenderWindow, Renderer and all Actors + vtkSmartPointer ren1 = + vtkSmartPointer::New(); + vtkSmartPointer renWin = + vtkSmartPointer::New(); + renWin->AddRenderer( ren1 ); + + vtkSmartPointer iren = + vtkSmartPointer::New(); + iren->SetRenderWindow( renWin ); + + vtkSmartPointer scalarBar1 = + vtkSmartPointer::New(); + vtkScalarsToColors* lut = sphereMapper->GetLookupTable(); + lut->SetAnnotation(0.0, "Zed"); + lut->SetAnnotation(1.0, "Uno"); + lut->SetAnnotation(0.1, "$\\frac{1}{10}$"); + lut->SetAnnotation(0.125, "$\\frac{1}{8}$"); + lut->SetAnnotation(0.5, "Half"); + scalarBar1->SetTitle("Density"); + scalarBar1->SetLookupTable(lut); + scalarBar1->DrawAnnotationsOn(); + scalarBar1->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); + scalarBar1->GetPositionCoordinate()->SetValue( .6, .05 ); + scalarBar1->SetWidth( 0.15 ); + scalarBar1->SetHeight( 0.5 ); + scalarBar1->SetTextPositionToPrecedeScalarBar(); + scalarBar1->GetTitleTextProperty()->SetColor( 0., 0., 1. ); + scalarBar1->GetLabelTextProperty()->SetColor( 0., 0., 1. ); + scalarBar1->SetDrawFrame( 1 ); + scalarBar1->GetFrameProperty()->SetColor( 0., 0., 0. ); + scalarBar1->SetDrawBackground( 1 ); + scalarBar1->GetBackgroundProperty()->SetColor( 1., 1., 1. ); + + // Add the actors to the renderer, set the background and size + // + ren1->AddActor( sphereActor.Get() ); + ren1->AddActor( scalarBar1 ); + ren1->GradientBackgroundOn(); + ren1->SetBackground( .5,.5,.5 ); + ren1->SetBackground2( .0,.0,.0 ); + + // render the image + renWin->SetWindowName( "VTK - Scalar Bar options" ); + renWin->SetSize( 600, 500 ); + renWin->SetMultiSamples( 0 ); + vtkSmartPointer ospray = vtkSmartPointer::New(); + ren1->SetPass(ospray); + + renWin->Render(); + + int retVal = vtkRegressionTestImage( renWin.GetPointer() ); + if ( retVal == vtkRegressionTester::DO_INTERACTOR ) + { + iren->Start(); + } + + return !retVal; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayTime.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayTime.cxx new file mode 100644 index 00000000000..4df26c7f4ca --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayTime.cxx @@ -0,0 +1,87 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayDynamicScene.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test verifies that time varying data works as expected in ospray +// +// The command line arguments are: +// -I => run in interactive mode; unless this is used, the program will +// not allow interaction and exit + +//TODO: test broken by pre SC15 ospray caching + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkDataSetSurfaceFilter.h" +#include "vtkInformation.h" +#include "vtkOSPRayPass.h" +#include "vtkPolyDataMapper.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkSmartPointer.h" +#include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkTimeSourceExample.h" + +int TestOSPRayTime(int vtkNotUsed(argc), char* vtkNotUsed(argv)[]) +{ + vtkSmartPointer iren = vtkSmartPointer::New(); + vtkSmartPointer renWin = vtkSmartPointer::New(); + iren->SetRenderWindow(renWin); + vtkSmartPointer renderer = vtkSmartPointer::New(); + renWin->AddRenderer(renderer); + renderer->SetBackground(0.0,0.0,0.0); + renWin->SetSize(400,400); + renWin->Render(); + + vtkSmartPointer ospray=vtkSmartPointer::New(); + renderer->SetPass(ospray); + + vtkSmartPointer timeywimey = vtkSmartPointer::New(); + timeywimey->GrowingOn(); + vtkSmartPointer dsf = vtkSmartPointer::New(); + dsf->SetInputConnection(timeywimey->GetOutputPort()); + + vtkSmartPointer mapper=vtkSmartPointer::New(); + mapper->SetInputConnection(dsf->GetOutputPort()); + vtkSmartPointer actor= vtkSmartPointer::New(); + renderer->AddActor(actor); + actor->SetMapper(mapper); + + renWin->Render(); + renderer->ResetCamera(); + double pos[3]; + vtkCamera *camera = renderer->GetActiveCamera(); + camera->SetFocalPoint(0.0,2.5,0.0); + camera->GetPosition(pos); + pos[0]= pos[0] + 6; + pos[1]= pos[1] + 6; + pos[2]= pos[2] + 6; + camera->SetPosition(pos); + renderer->ResetCameraClippingRange(); + renWin->Render(); + + for (int i = 0; i < 20; i++) + { + double updateTime = (double)(i%10)/10.0; + cerr << "t=" << updateTime << endl; + renderer->SetActiveCamera(camera); + vtkInformation* outInfo = dsf->GetExecutive()->GetOutputInformation(0); + outInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP(), updateTime); + renderer->ResetCameraClippingRange(); + renWin->Render(); + } + iren->Start(); + + return 0; +} diff --git a/Rendering/OSPRay/Testing/Cxx/TestOSPRayWindow.cxx b/Rendering/OSPRay/Testing/Cxx/TestOSPRayWindow.cxx new file mode 100644 index 00000000000..d35b8d68cde --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/TestOSPRayWindow.cxx @@ -0,0 +1,105 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestOSPRayScalarBar.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkSmartPointer.h" + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkLight.h" +#include "vtkPolyDataMapper.h" +#include "vtkProperty2D.h" +#include "vtkRegressionTestImage.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkTextProperty.h" +#include "vtkSphereSource.h" +#include "vtkNew.h" +#include "vtkElevationFilter.h" +#include "vtkOSPRayWindowNode.h" +#include "vtkImageActor.h" +#include "vtkImageData.h" +#include "vtkPointData.h" +#include "vtkImageMapper3D.h" + +#include "vtkTestUtilities.h" + +int TestOSPRayWindow( int argc, char *argv[] ) +{ + vtkNew sphere; + sphere->SetThetaResolution(8); + sphere->SetPhiResolution(8); + vtkNew elev; + elev->SetInputConnection(sphere->GetOutputPort(0)); + + vtkNew sphereMapper; + sphereMapper->SetInputConnection(elev->GetOutputPort(0)); + vtkNew sphereActor; + sphereActor->SetMapper(sphereMapper.Get()); + + vtkSmartPointer light1 = vtkSmartPointer::New(); + + // Create the RenderWindow, Renderer and all Actors + vtkSmartPointer ren1 = + vtkSmartPointer::New(); + ren1->AddLight(light1); + + vtkSmartPointer renWin = + vtkSmartPointer::New(); + renWin->AddRenderer( ren1 ); + + // Add the actors to the renderer, set the background and size + // + ren1->AddActor( sphereActor.Get() ); + ren1->SetBackground( .2,.3,.4 ); + + // render the image + renWin->SetWindowName( "VTK - Scalar Bar options" ); + renWin->SetSize( 600, 500 ); + + vtkNew owindow; + owindow->SetRenderable(renWin); + owindow->TraverseAllPasses(); + + // now get the result and display it + int *size = owindow->GetSize(); + vtkNew image; + image->SetDimensions(size[0], size[1], 1); + image->GetPointData()->SetScalars(owindow->GetColorBuffer()); + + // Create a new image actor and remove the geometry one + vtkNew imageActor; + imageActor->GetMapper()->SetInputData(image.Get()); + vtkNew renderer; + renderer->AddActor(imageActor.Get()); + + // Background color white to distinguish image boundary + renderer->SetBackground(1, 1, 1); + vtkNew renderWindow; + renderWindow->AddRenderer(renderer.Get()); + + vtkNew renderWindowInteractor; + renderWindowInteractor->SetRenderWindow(renderWindow.Get()); + renderWindow->Render(); + renderer->ResetCamera(); + renderWindow->Render(); + int retVal = vtkRegressionTestImage(renderWindow.Get()); + if (retVal == vtkRegressionTester::DO_INTERACTOR) + { + renderWindowInteractor->Start(); + } + + return !retVal; +} diff --git a/Rendering/OSPRay/Testing/Cxx/vtkOSPRayTestInteractor.cxx b/Rendering/OSPRay/Testing/Cxx/vtkOSPRayTestInteractor.cxx new file mode 100644 index 00000000000..d4a1739079f --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/vtkOSPRayTestInteractor.cxx @@ -0,0 +1,235 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayTestInteractor.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkOSPRayTestInteractor.h" +#include "vtkObjectFactory.h" + +#include "vtkLight.h" +#include "vtkLightCollection.h" +#include "vtkOpenGLRenderer.h" +#include "vtkOSPRayLightNode.h" +#include "vtkOSPRayRendererNode.h" +#include "vtkOSPRayPass.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" + +#include +#include + +namespace { + static std::vector ActorNames; +} + +//---------------------------------------------------------------------------- +vtkStandardNewMacro(vtkOSPRayTestInteractor); + +//---------------------------------------------------------------------------- +vtkOSPRayTestInteractor::vtkOSPRayTestInteractor() +{ + this->SetPipelineControlPoints(NULL,NULL,NULL); + this->VisibleActor = -1; + this->VisibleLight = -1; +} + +//---------------------------------------------------------------------------- +void vtkOSPRayTestInteractor::SetPipelineControlPoints + (vtkOpenGLRenderer *g, + vtkRenderPass *_O, + vtkRenderPass *_G) +{ + this->GLRenderer = g; + this->O = _O; + this->G = _G; +} + +//---------------------------------------------------------------------------- +void vtkOSPRayTestInteractor::OnKeyPress() +{ + if (this->GLRenderer == NULL) + { + return; + } + + // Get the keypress + vtkRenderWindowInteractor *rwi = this->Interactor; + std::string key = rwi->GetKeySym(); + + if(key == "c") + { + vtkRenderPass * current = this->GLRenderer->GetPass(); + if (current == this->G) + { + cerr << "OSPRAY rendering " << this->O << endl; + this->GLRenderer->SetPass(this->O); + this->GLRenderer->GetRenderWindow()->Render(); + } + else if (current == this->O) + { + cerr << "GL rendering " << this->G << endl; + this->GLRenderer->SetPass(this->G); + this->GLRenderer->GetRenderWindow()->Render(); + } + } + + if(key == "n") + { + vtkActorCollection * actors = this->GLRenderer->GetActors(); + + this->VisibleActor++; + cerr << "VISIBLE " << this->VisibleActor; + if (this->VisibleActor == actors->GetNumberOfItems()) + { + this->VisibleActor = -1; + } + for (int i = 0; i < actors->GetNumberOfItems(); i++) + { + if (this->VisibleActor == -1 || this->VisibleActor == i) + { + if (i < ActorNames.size()) + { + cerr << " : " << ActorNames[i] << " "; + } + vtkActor::SafeDownCast(actors->GetItemAsObject(i))-> + SetVisibility(1); + } + else + { + vtkActor::SafeDownCast(actors->GetItemAsObject(i))-> + SetVisibility(0); + } + } + cerr << endl; + this->GLRenderer->ResetCamera(); + this->GLRenderer->GetRenderWindow()->Render(); + } + + if(key == "l") + { + vtkLightCollection * lights = this->GLRenderer->GetLights(); + + this->VisibleLight++; + if (this->VisibleLight == lights->GetNumberOfItems()) + { + this->VisibleLight = -1; + } + cerr << "LIGHT " << this->VisibleLight << "/" << lights->GetNumberOfItems() << endl; + for (int i = 0; i < lights->GetNumberOfItems(); i++) + { + if (this->VisibleLight == -1 || this->VisibleLight == i) + { + vtkLight::SafeDownCast(lights->GetItemAsObject(i))-> + SwitchOn(); + } + else + { + vtkLight::SafeDownCast(lights->GetItemAsObject(i))-> + SwitchOff(); + } + } + this->GLRenderer->GetRenderWindow()->Render(); + } + + if(key == "P") + { + int maxframes = vtkOSPRayRendererNode::GetMaxFrames(this->GLRenderer) + 4; + if (maxframes>64) + { + maxframes=64; + } + vtkOSPRayRendererNode::SetMaxFrames(maxframes, this->GLRenderer); + cerr << "frames " << maxframes << endl; + this->GLRenderer->GetRenderWindow()->Render(); + } + + if(key == "p") + { + int maxframes = vtkOSPRayRendererNode::GetMaxFrames(this->GLRenderer); + if (maxframes>1) + { + maxframes=maxframes/2; + } + vtkOSPRayRendererNode::SetMaxFrames(maxframes, this->GLRenderer); + cerr << "frames " << maxframes << endl; + this->GLRenderer->GetRenderWindow()->Render(); + } + + if(key == "s") + { + bool shadows = !(this->GLRenderer->GetUseShadows()==0); + cerr << "shadows now " << (!shadows?"ON":"OFF") << endl; + this->GLRenderer->SetUseShadows(!shadows); + this->GLRenderer->GetRenderWindow()->Render(); + } + + if(key == "2") + { + int spp = vtkOSPRayRendererNode::GetSamplesPerPixel(this->GLRenderer); + cerr << "samples now " << spp+1 << endl; + vtkOSPRayRendererNode::SetSamplesPerPixel(spp+1, this->GLRenderer); + this->GLRenderer->GetRenderWindow()->Render(); + } + if(key == "1") + { + vtkOSPRayRendererNode::SetSamplesPerPixel(1, this->GLRenderer); + cerr << "samples now " << 1 << endl; + this->GLRenderer->GetRenderWindow()->Render(); + } + + if(key == "D") + { + int aoSamples = vtkOSPRayRendererNode::GetAmbientSamples(this->GLRenderer) + 2; + if (aoSamples>64) + { + aoSamples=64; + } + vtkOSPRayRendererNode::SetAmbientSamples(aoSamples, this->GLRenderer); + cerr << "aoSamples " << aoSamples << endl; + this->GLRenderer->GetRenderWindow()->Render(); + } + + if(key == "d") + { + int aosamples = vtkOSPRayRendererNode::GetAmbientSamples(this->GLRenderer); + aosamples=aosamples/2; + vtkOSPRayRendererNode::SetAmbientSamples(aosamples, this->GLRenderer); + cerr << "aoSamples " << aosamples << endl; + this->GLRenderer->GetRenderWindow()->Render(); + } + + if(key == "I") + { + double intens = vtkOSPRayLightNode::GetLightScale()*1.5; + vtkOSPRayLightNode::SetLightScale(intens); + cerr << "intensity " << intens << endl; + this->GLRenderer->GetRenderWindow()->Render(); + } + + if(key == "i") + { + double intens = vtkOSPRayLightNode::GetLightScale()/1.5; + vtkOSPRayLightNode::SetLightScale(intens); + cerr << "intensity " << intens << endl; + this->GLRenderer->GetRenderWindow()->Render(); + } + + // Forward events + vtkInteractorStyleTrackballCamera::OnKeyPress(); +} + +//------------------------------------------------------------------------------ +void vtkOSPRayTestInteractor::AddName(const char *name) +{ + ActorNames.push_back(std::string(name)); +} diff --git a/Rendering/OSPRay/Testing/Cxx/vtkOSPRayTestInteractor.h b/Rendering/OSPRay/Testing/Cxx/vtkOSPRayTestInteractor.h new file mode 100644 index 00000000000..74837daed24 --- /dev/null +++ b/Rendering/OSPRay/Testing/Cxx/vtkOSPRayTestInteractor.h @@ -0,0 +1,60 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayTestInteractor.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .SECTION Description +// A common interactor style for the ospray tests that understands +// the following key presses. +// c => switch between OSPRay and GL +// s => turn shadows on and off +// n => focuses view on the next actor and hides all others +// 2/1 => increase/decrease the number of samples per pixel +// P/p => increase/decrease the number of OSPRay rendering passes +// l => turns on each light in the scene in turn +// I/i => increase/decrease the global light intensity scale +// D/d => increase/decrease the number of ambient occlusion samples + +#ifndef vtkOSPRayTestInteractor_h +#define vtkOSPRayTestInteractor_h + +#include "vtkInteractorStyleTrackballCamera.h" + +#include +#include + +class vtkOpenGLRenderer; +class vtkRenderPass; + +// Define interaction style +class vtkOSPRayTestInteractor : public vtkInteractorStyleTrackballCamera +{ +private: + vtkOpenGLRenderer *GLRenderer; + vtkRenderPass *O; + vtkRenderPass *G; + int VisibleActor; + int VisibleLight; + +public: + static vtkOSPRayTestInteractor* New(); + vtkTypeMacro(vtkOSPRayTestInteractor, vtkInteractorStyleTrackballCamera); + vtkOSPRayTestInteractor(); + void SetPipelineControlPoints(vtkOpenGLRenderer *g, + vtkRenderPass *_O, + vtkRenderPass *_G); + virtual void OnKeyPress(); + + static void AddName(const char *name); +}; + +#endif diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayComposite.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayComposite.png.md5 new file mode 100644 index 00000000000..c163cdf5307 --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayComposite.png.md5 @@ -0,0 +1 @@ +7a65212255bde748c16def76c09f64e8 diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayCompositePolyDataMapper2.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayCompositePolyDataMapper2.png.md5 new file mode 100644 index 00000000000..0eb1a45340a --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayCompositePolyDataMapper2.png.md5 @@ -0,0 +1 @@ +3ecc7877aff6877410f0fa9ea9e561ec diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayDynamicObject.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayDynamicObject.png.md5 new file mode 100644 index 00000000000..632fe57e91d --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayDynamicObject.png.md5 @@ -0,0 +1 @@ +fef2bd7b6830d2365241f95a17da78d0 diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayDynamicScene.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayDynamicScene.png.md5 new file mode 100644 index 00000000000..d066eed28e7 --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayDynamicScene.png.md5 @@ -0,0 +1 @@ +ec67db0317b7291a106e69da58446f44 diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayImplicits.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayImplicits.png.md5 new file mode 100644 index 00000000000..3a0e3ad281b --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayImplicits.png.md5 @@ -0,0 +1 @@ +919fd2e934a3eb75dea586066860cb8b diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayLayers.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayLayers.png.md5 new file mode 100644 index 00000000000..9b576c80762 --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayLayers.png.md5 @@ -0,0 +1 @@ +ea272d2414c2b369ff4bb3fde1c11d73 diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayLights.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayLights.png.md5 new file mode 100644 index 00000000000..e829ce67d25 --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayLights.png.md5 @@ -0,0 +1 @@ +edbf5c0d5ca43b4f4c89ee40207ba729 diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayMultiBlock.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayMultiBlock.png.md5 new file mode 100644 index 00000000000..1e8cbe11e63 --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayMultiBlock.png.md5 @@ -0,0 +1 @@ +ecf21b72ed548899df817bbc36098818 diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayMultiBlockPartialArrayFieldData.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayMultiBlockPartialArrayFieldData.png.md5 new file mode 100644 index 00000000000..98687a2062a --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayMultiBlockPartialArrayFieldData.png.md5 @@ -0,0 +1 @@ +53a81fcb69c21330238f26b39ad9ff2b diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayPass.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayPass.png.md5 new file mode 100644 index 00000000000..e0d6a89e8c9 --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayPass.png.md5 @@ -0,0 +1 @@ +b6c16d0e9d777e40e5c96aa12b6165bb diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayRenderMesh.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayRenderMesh.png.md5 new file mode 100644 index 00000000000..7c5e158ac6a --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayRenderMesh.png.md5 @@ -0,0 +1 @@ +136fb5a9cb8a5c6d8a403c45a188f638 diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayScalarBar.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayScalarBar.png.md5 new file mode 100644 index 00000000000..36b79ec1c81 --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayScalarBar.png.md5 @@ -0,0 +1 @@ +6794fe9c4aeb2675fb2a1b35a5ab6bf3 diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayTime.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayTime.png.md5 new file mode 100644 index 00000000000..94989b511b5 --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayTime.png.md5 @@ -0,0 +1 @@ +1ed4ef4aa88e635ccd1198c8cdd0f069 diff --git a/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayWindow.png.md5 b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayWindow.png.md5 new file mode 100644 index 00000000000..b9b34c2bbd5 --- /dev/null +++ b/Rendering/OSPRay/Testing/Data/Baseline/TestOSPRayWindow.png.md5 @@ -0,0 +1 @@ +66962c978d1f29728abf9ff5708ffc9d diff --git a/Rendering/OSPRay/module.cmake b/Rendering/OSPRay/module.cmake new file mode 100644 index 00000000000..b0e1cbe7828 --- /dev/null +++ b/Rendering/OSPRay/module.cmake @@ -0,0 +1,22 @@ +set(optional_test_depends) +if("${Module_vtkRenderingParallel}" AND "${Module_vtkParallelMPI}") + set(optional_test_depends "vtkRenderingParallel;vtkParallelMPI") +endif() + +vtk_module(vtkRenderingOSPRay + DEPENDS + vtkRenderingSceneGraph + #todo promote compositedatadisplayattributes to rendering/core + vtkRendering${VTK_RENDERING_BACKEND} #only for comp.data.disp.attr. + TEST_DEPENDS + vtkFiltersTexture + vtkInteractionStyle + vtkIOGeometry + vtkIOPLY + vtkIOXML + vtkRenderingAnnotation + vtkTestingCore + vtkTestingRendering + ${optional_test_depends} + EXCLUDE_FROM_ALL + ) diff --git a/Rendering/OSPRay/vtkOSPRayActorNode.cxx b/Rendering/OSPRay/vtkOSPRayActorNode.cxx new file mode 100644 index 00000000000..bb124207128 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayActorNode.cxx @@ -0,0 +1,191 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayActorNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkOSPRayActorNode.h" + +#include "vtkActor.h" +#include "vtkCompositeDataIterator.h" +#include "vtkCompositeDataSet.h" +#include "vtkDataArray.h" +#include "vtkInformation.h" +#include "vtkInformationIntegerKey.h" +#include "vtkInformationObjectBaseKey.h" +#include "vtkInformationStringKey.h" +#include "vtkMapper.h" +#include "vtkObjectFactory.h" +#include "vtkPiecewiseFunction.h" +#include "vtkPolyData.h" +#include "vtkViewNodeCollection.h" + +#include "ospray/ospray.h" + +vtkInformationKeyMacro(vtkOSPRayActorNode, ENABLE_SCALING, Integer); +vtkInformationKeyMacro(vtkOSPRayActorNode, SCALE_ARRAY_NAME, String); +vtkInformationKeyMacro(vtkOSPRayActorNode, SCALE_FUNCTION, ObjectBase); + +//============================================================================ +vtkStandardNewMacro(vtkOSPRayActorNode); + +//---------------------------------------------------------------------------- +vtkOSPRayActorNode::vtkOSPRayActorNode() +{ +} + +//---------------------------------------------------------------------------- +vtkOSPRayActorNode::~vtkOSPRayActorNode() +{ +} + +//---------------------------------------------------------------------------- +void vtkOSPRayActorNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +void vtkOSPRayActorNode::SetEnableScaling(int value, vtkActor *actor) +{ + if (!actor) + { + return; + } + vtkMapper *mapper = actor->GetMapper(); + if (mapper) + { + vtkInformation *info = mapper->GetInformation(); + info->Set(vtkOSPRayActorNode::ENABLE_SCALING(), value); + } +} + +//---------------------------------------------------------------------------- +int vtkOSPRayActorNode::GetEnableScaling(vtkActor *actor) +{ + if (!actor) + { + return 0; + } + vtkMapper *mapper = actor->GetMapper(); + if (mapper) + { + vtkInformation *info = mapper->GetInformation(); + if (info && info->Has(vtkOSPRayActorNode::ENABLE_SCALING())) + { + return (info->Get(vtkOSPRayActorNode::ENABLE_SCALING())); + } + } + return 0; +} + +//---------------------------------------------------------------------------- +void vtkOSPRayActorNode::SetScaleArrayName + (const char *arrayName, vtkActor *actor) +{ + if (!actor) + { + return; + } + vtkMapper *mapper = actor->GetMapper(); + if (mapper) + { + vtkInformation *mapperInfo = mapper->GetInformation(); + mapperInfo->Set(vtkOSPRayActorNode::SCALE_ARRAY_NAME(), arrayName); + } +} + +//---------------------------------------------------------------------------- +void vtkOSPRayActorNode::SetScaleFunction(vtkPiecewiseFunction *scaleFunction, + vtkActor *actor) +{ + if (!actor) + { + return; + } + vtkMapper *mapper = actor->GetMapper(); + if (mapper) + { + vtkInformation *mapperInfo = mapper->GetInformation(); + mapperInfo->Set(vtkOSPRayActorNode::SCALE_FUNCTION(), scaleFunction); + } +} + +//---------------------------------------------------------------------------- +unsigned long vtkOSPRayActorNode::GetMTime() +{ + unsigned long mtime = this->Superclass::GetMTime(); + vtkActor *act = (vtkActor*)this->GetRenderable(); + if (act->GetMTime() > mtime) + { + mtime = act->GetMTime(); + } + vtkDataObject * dobj = NULL; + vtkPolyData *poly = NULL; + vtkMapper *mapper = act->GetMapper(); + if (mapper) + { + //if (act->GetRedrawMTime() > mtime) + // { + // mtime = act->GetRedrawMTime(); + // } + if (mapper->GetMTime() > mtime) + { + mtime = mapper->GetMTime(); + } + if (mapper->GetInformation()->GetMTime() > mtime) + { + mtime = mapper->GetInformation()->GetMTime(); + } + vtkPiecewiseFunction *pwf = vtkPiecewiseFunction::SafeDownCast + (mapper->GetInformation()->Get(vtkOSPRayActorNode::SCALE_FUNCTION())); + if (pwf) + { + if (pwf->GetMTime() > mtime) + { + mtime = pwf->GetMTime(); + } + } + dobj = mapper->GetInputDataObject(0, 0); + poly = vtkPolyData::SafeDownCast(dobj); + } + if (poly) + { + if (poly->GetMTime() > mtime) + { + mtime = poly->GetMTime(); + } + } + else if (dobj) + { + vtkCompositeDataSet *comp = vtkCompositeDataSet::SafeDownCast + (dobj); + if (comp) + { + vtkCompositeDataIterator*dit = comp->NewIterator(); + dit->SkipEmptyNodesOn(); + while(!dit->IsDoneWithTraversal()) + { + poly = vtkPolyData::SafeDownCast(comp->GetDataSet(dit)); + if (poly) + { + if (poly->GetMTime() > mtime) + { + mtime = poly->GetMTime(); + } + } + dit->GoToNextItem(); + } + dit->Delete(); + } + } + return mtime; +} diff --git a/Rendering/OSPRay/vtkOSPRayActorNode.h b/Rendering/OSPRay/vtkOSPRayActorNode.h new file mode 100644 index 00000000000..6daca1958a9 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayActorNode.h @@ -0,0 +1,85 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayActorNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkOSPRayActorNode - links vtkActor and vtkMapper to OSPRay +// .SECTION Description +// Translates vtkActor/Mapper state into OSPRay rendering calls + +#ifndef vtkOSPRayActorNode_h +#define vtkOSPRayActorNode_h + +#include "vtkRenderingOSPRayModule.h" // For export macro +#include "vtkActorNode.h" + +class vtkActor; +class vtkCompositeDataDisplayAttributes; +class vtkDataArray; +class vtkInformationIntegerKey; +class vtkInformationObjectBaseKey; +class vtkInformationStringKey; +class vtkPiecewiseFunction; +class vtkPolyData; + +class VTKRENDERINGOSPRAY_EXPORT vtkOSPRayActorNode : + public vtkActorNode +{ +public: + static vtkOSPRayActorNode* New(); + vtkTypeMacro(vtkOSPRayActorNode, vtkActorNode); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Overridden to take into account my renderables time, including + // mapper and data into mapper inclusive of composite input + virtual unsigned long GetMTime(); + + // Description: + // When added to the mapper, enables scale array and scale function. + static vtkInformationIntegerKey* ENABLE_SCALING(); + + // Description: + // Convenience method to set enabled scaling on my renderable. + static void SetEnableScaling(int value, vtkActor *); + static int GetEnableScaling(vtkActor *); + + // Description: + // Name of a point aligned, single component wide, double valued array that, + // when added to the mapper, will be used to scale each element in the + // sphere and cylinder representations individually. + // When not supplied the radius is constant across all elements and + // is a function of the Mapper's PointSize and LineWidth. + static vtkInformationStringKey* SCALE_ARRAY_NAME(); + + // Description: + // Convenience method to set a scale array on my renderable. + static void SetScaleArrayName(const char *scaleArrayName, vtkActor *); + + // Description: + // A piecewise function for values from the scale array that alters the resulting + // radii arbitrarily + static vtkInformationObjectBaseKey* SCALE_FUNCTION(); + + // Description: + // Convenience method to set a scale function on my renderable. + static void SetScaleFunction(vtkPiecewiseFunction *scaleFunction, vtkActor *); + +protected: + vtkOSPRayActorNode(); + ~vtkOSPRayActorNode(); + +private: + vtkOSPRayActorNode(const vtkOSPRayActorNode&); // Not implemented. + void operator=(const vtkOSPRayActorNode&); // Not implemented. +}; +#endif diff --git a/Rendering/OSPRay/vtkOSPRayCameraNode.cxx b/Rendering/OSPRay/vtkOSPRayCameraNode.cxx new file mode 100644 index 00000000000..3a8575821a9 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayCameraNode.cxx @@ -0,0 +1,77 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayCameraNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkOSPRayCameraNode.h" + +#include "vtkCamera.h" +#include "vtkCollectionIterator.h" +#include "vtkObjectFactory.h" +#include "vtkOSPRayRendererNode.h" +#include "vtkRenderer.h" +#include "vtkViewNodeCollection.h" + +#include "ospray/ospray.h" + +//============================================================================ +vtkStandardNewMacro(vtkOSPRayCameraNode); + +//---------------------------------------------------------------------------- +vtkOSPRayCameraNode::vtkOSPRayCameraNode() +{ +} + +//---------------------------------------------------------------------------- +vtkOSPRayCameraNode::~vtkOSPRayCameraNode() +{ +} + +//---------------------------------------------------------------------------- +void vtkOSPRayCameraNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +void vtkOSPRayCameraNode::Render(bool prepass) +{ + if (prepass) + { + vtkOSPRayRendererNode *orn = + static_cast( + this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); + + vtkRenderer *ren = vtkRenderer::SafeDownCast(orn->GetRenderable()); + int tiledSize[2]; + int tiledOrigin[2]; + ren->GetTiledSizeAndOrigin(&tiledSize[0], &tiledSize[1], + &tiledOrigin[0], &tiledOrigin[1]); + + + OSPCamera ospCamera = ospNewCamera("perspective"); + ospSetObject(orn->GetORenderer(),"camera", ospCamera); + + vtkCamera *cam = static_cast(this->Renderable); + ospSetf(ospCamera,"aspect", float(tiledSize[0])/float(tiledSize[1])); + ospSetf(ospCamera,"fovy",cam->GetViewAngle()); + double *pos = cam->GetPosition(); + ospSet3f(ospCamera,"pos",pos[0], pos[1], pos[2]); + ospSet3f(ospCamera,"up", + cam->GetViewUp()[0], cam->GetViewUp()[1], cam->GetViewUp()[2]); + double *dop = cam->GetDirectionOfProjection(); + ospSet3f(ospCamera,"dir", dop[0], dop[1], dop[2]); + + ospCommit(ospCamera); + ospRelease(ospCamera); + } +} diff --git a/Rendering/OSPRay/vtkOSPRayCameraNode.h b/Rendering/OSPRay/vtkOSPRayCameraNode.h new file mode 100644 index 00000000000..2d19a1d1aa2 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayCameraNode.h @@ -0,0 +1,46 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayCameraNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkOSPRayCameraNode - links vtkCamera to OSPRay +// .SECTION Description +// Translates vtkCamera state into OSPRay rendering calls + +#ifndef vtkOSPRayCameraNode_h +#define vtkOSPRayCameraNode_h + +#include "vtkRenderingOSPRayModule.h" // For export macro +#include "vtkCameraNode.h" + +class VTKRENDERINGOSPRAY_EXPORT vtkOSPRayCameraNode : + public vtkCameraNode +{ +public: + static vtkOSPRayCameraNode* New(); + vtkTypeMacro(vtkOSPRayCameraNode, vtkCameraNode); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //Make ospray calls to render me. + virtual void Render(bool prepass); + +protected: + vtkOSPRayCameraNode(); + ~vtkOSPRayCameraNode(); + +private: + vtkOSPRayCameraNode(const vtkOSPRayCameraNode&); // Not implemented. + void operator=(const vtkOSPRayCameraNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/OSPRay/vtkOSPRayCompositePolyDataMapper2Node.cxx b/Rendering/OSPRay/vtkOSPRayCompositePolyDataMapper2Node.cxx new file mode 100644 index 00000000000..94de0f7da45 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayCompositePolyDataMapper2Node.cxx @@ -0,0 +1,225 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayCompositePolyDataMapper2Node.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkOSPRayCompositePolyDataMapper2Node.h" + +#include "vtkActor.h" +#include "vtkOSPRayActorNode.h" +#include "vtkOSPRayRendererNode.h" +#include "vtkCompositeDataDisplayAttributes.h" +#include "vtkCompositeDataIterator.h" +#include "vtkCompositeDataSet.h" +#include "vtkCompositePolyDataMapper2.h" +#include "vtkDataArray.h" +#include "vtkFloatArray.h" +#include "vtkImageData.h" +#include "vtkInformation.h" +#include "vtkInformationDoubleKey.h" +#include "vtkInformationObjectBaseKey.h" +#include "vtkMapper.h" +#include "vtkObjectFactory.h" +#include "vtkPiecewiseFunction.h" +#include "vtkPointData.h" +#include "vtkPolyData.h" +#include "vtkProperty.h" +#include "vtkTexture.h" +#include "vtkSmartPointer.h" + +#include "vtkMultiBlockDataSet.h" +#include "vtkMultiPieceDataSet.h" + +#include "ospray/ospray.h" +#include "ospray/version.h" + +#include + + +//============================================================================ +vtkStandardNewMacro(vtkOSPRayCompositePolyDataMapper2Node); + +//---------------------------------------------------------------------------- +vtkOSPRayCompositePolyDataMapper2Node::vtkOSPRayCompositePolyDataMapper2Node() +{ +} + +//---------------------------------------------------------------------------- +vtkOSPRayCompositePolyDataMapper2Node::~vtkOSPRayCompositePolyDataMapper2Node() +{ +} + +//---------------------------------------------------------------------------- +void vtkOSPRayCompositePolyDataMapper2Node::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + + +//---------------------------------------------------------------------------- +void vtkOSPRayCompositePolyDataMapper2Node::Render(bool prepass) +{ + if (prepass) + { + // we use a lot of params from our parent + vtkOSPRayActorNode *aNode = vtkOSPRayActorNode::SafeDownCast(this->Parent); + vtkActor *act = vtkActor::SafeDownCast(aNode->GetRenderable()); + + if (act->GetVisibility() == false) + { + return; + } + + vtkOSPRayRendererNode *orn = + static_cast( + this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); + + //if there are no changes, just reuse last result + unsigned long inTime = aNode->GetMTime(); + if (this->RenderTime >= inTime) + { + this->AddMeshesToModel(orn->GetOModel()); + return; + } + + this->RenderTime = inTime; + + //something changed so make new meshes + this->CreateNewMeshes(); + + vtkProperty* prop = act->GetProperty(); + + // Push base-values on the state stack. + this->BlockState.Visibility.push(true); + this->BlockState.Opacity.push(prop->GetOpacity()); + this->BlockState.AmbientColor.push(vtkColor3d(prop->GetAmbientColor())); + this->BlockState.DiffuseColor.push(vtkColor3d(prop->GetDiffuseColor())); + this->BlockState.SpecularColor.push(vtkColor3d(prop->GetSpecularColor())); + + // render using the composite data attributes + unsigned int flat_index = 0; + vtkCompositePolyDataMapper2 *cpdm = + vtkCompositePolyDataMapper2::SafeDownCast(act->GetMapper()); + vtkDataObject * dobj = NULL; + if (cpdm) + { + dobj = cpdm->GetInputDataObject(0, 0); + if (dobj) + { + this->RenderBlock(orn, cpdm, act, dobj, flat_index); + } + } + + this->BlockState.Visibility.pop(); + this->BlockState.Opacity.pop(); + this->BlockState.AmbientColor.pop(); + this->BlockState.DiffuseColor.pop(); + this->BlockState.SpecularColor.pop(); + } +} + + + +//----------------------------------------------------------------------------- +void vtkOSPRayCompositePolyDataMapper2Node::RenderBlock( + vtkOSPRayRendererNode *orn, + vtkCompositePolyDataMapper2 *cpdm, + vtkActor *actor, + vtkDataObject *dobj, + unsigned int &flat_index) +{ + vtkCompositeDataDisplayAttributes* cda = cpdm->GetCompositeDataDisplayAttributes(); + + vtkProperty *prop = actor->GetProperty(); + // bool draw_surface_with_edges = + // (prop->GetEdgeVisibility() && prop->GetRepresentation() == VTK_SURFACE); + vtkColor3d ecolor(prop->GetEdgeColor()); + + bool overrides_visibility = (cda && cda->HasBlockVisibility(flat_index)); + if (overrides_visibility) + { + this->BlockState.Visibility.push(cda->GetBlockVisibility(flat_index)); + } + + bool overrides_opacity = (cda && cda->HasBlockOpacity(flat_index)); + if (overrides_opacity) + { + this->BlockState.Opacity.push(cda->GetBlockOpacity(flat_index)); + } + + bool overrides_color = (cda && cda->HasBlockColor(flat_index)); + if (overrides_color) + { + vtkColor3d color = cda->GetBlockColor(flat_index); + this->BlockState.AmbientColor.push(color); + this->BlockState.DiffuseColor.push(color); + this->BlockState.SpecularColor.push(color); + } + + // Advance flat-index. After this point, flat_index no longer points to this + // block. + flat_index++; + + vtkMultiBlockDataSet *mbds = vtkMultiBlockDataSet::SafeDownCast(dobj); + vtkMultiPieceDataSet *mpds = vtkMultiPieceDataSet::SafeDownCast(dobj); + if (mbds || mpds) + { + unsigned int numChildren = mbds? mbds->GetNumberOfBlocks() : + mpds->GetNumberOfPieces(); + for (unsigned int cc=0 ; cc < numChildren; cc++) + { + vtkDataObject* child = mbds ? mbds->GetBlock(cc) : mpds->GetPiece(cc); + if (child == NULL) + { + // speeds things up when dealing with NULL blocks (which is common with + // AMRs). + flat_index++; + continue; + } + this->RenderBlock(orn, cpdm, actor, child, flat_index); + } + } + else if (dobj && this->BlockState.Visibility.top() == true && this->BlockState.Opacity.top() > 0.0) + { + // do we have a entry for this dataset? + // make sure we have an entry for this dataset + vtkPolyData *ds = vtkPolyData::SafeDownCast(dobj); + if (ds) + { + vtkOSPRayActorNode *aNode = vtkOSPRayActorNode::SafeDownCast(this->Parent); + vtkColor3d &aColor = this->BlockState.AmbientColor.top(); + vtkColor3d &dColor = this->BlockState.DiffuseColor.top(); + cpdm->ClearColorArrays(); //prevents reuse of stale color arrays + this->ORenderPoly( + orn->GetORenderer(), orn->GetOModel(), + aNode, ds, + aColor.GetData(), + dColor.GetData(), + this->BlockState.Opacity.top()); + } + } + + if (overrides_color) + { + this->BlockState.AmbientColor.pop(); + this->BlockState.DiffuseColor.pop(); + this->BlockState.SpecularColor.pop(); + } + if (overrides_opacity) + { + this->BlockState.Opacity.pop(); + } + if (overrides_visibility) + { + this->BlockState.Visibility.pop(); + } +} diff --git a/Rendering/OSPRay/vtkOSPRayCompositePolyDataMapper2Node.h b/Rendering/OSPRay/vtkOSPRayCompositePolyDataMapper2Node.h new file mode 100644 index 00000000000..d1e89f1f5ce --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayCompositePolyDataMapper2Node.h @@ -0,0 +1,69 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayCompositePolyDataMapper2Node.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkOSPRayCompositePolyDataMapper2Node - links vtkActor and vtkMapper to OSPRay +// .SECTION Description +// Translates vtkActor/Mapper state into OSPRay rendering calls + +#ifndef vtkOSPRayCompositePolyDataMapper2Node_h +#define vtkOSPRayCompositePolyDataMapper2Node_h + +#include "vtkRenderingOSPRayModule.h" // For export macro +#include "vtkOSPRayPolyDataMapperNode.h" +#include "vtkColor.h" // used for ivars +#include // used for ivars + +class vtkDataObject; +class vtkCompositePolyDataMapper2; +class vtkOSPRayRendererNode; + +class VTKRENDERINGOSPRAY_EXPORT vtkOSPRayCompositePolyDataMapper2Node : + public vtkOSPRayPolyDataMapperNode +{ +public: + static vtkOSPRayCompositePolyDataMapper2Node* New(); + vtkTypeMacro(vtkOSPRayCompositePolyDataMapper2Node, vtkOSPRayPolyDataMapperNode); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //Make ospray calls to render me. + virtual void Render(bool prepass); + +protected: + vtkOSPRayCompositePolyDataMapper2Node(); + ~vtkOSPRayCompositePolyDataMapper2Node(); + + class RenderBlockState + { + public: + std::stack Visibility; + std::stack Opacity; + std::stack AmbientColor; + std::stack DiffuseColor; + std::stack SpecularColor; + }; + + RenderBlockState BlockState; + void RenderBlock(vtkOSPRayRendererNode *orn, + vtkCompositePolyDataMapper2 *cpdm, + vtkActor *actor, + vtkDataObject *dobj, + unsigned int &flat_index); + + +private: + vtkOSPRayCompositePolyDataMapper2Node(const vtkOSPRayCompositePolyDataMapper2Node&); // Not implemented. + void operator=(const vtkOSPRayCompositePolyDataMapper2Node&); // Not implemented. +}; +#endif diff --git a/Rendering/OSPRay/vtkOSPRayLightNode.cxx b/Rendering/OSPRay/vtkOSPRayLightNode.cxx new file mode 100644 index 00000000000..63cf0d334f1 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayLightNode.cxx @@ -0,0 +1,123 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayLightNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkOSPRayLightNode.h" + +#include "vtkCollectionIterator.h" +#include "vtkLight.h" +#include "vtkMath.h" +#include "vtkObjectFactory.h" +#include "vtkOSPRayRendererNode.h" + +#include "ospray/ospray.h" +#include + + +//============================================================================ +double vtkOSPRayLightNode::LightScale = 1.0; + +//---------------------------------------------------------------------------- +vtkStandardNewMacro(vtkOSPRayLightNode); + +//---------------------------------------------------------------------------- +vtkOSPRayLightNode::vtkOSPRayLightNode() +{ +} + +//---------------------------------------------------------------------------- +vtkOSPRayLightNode::~vtkOSPRayLightNode() +{ +} + +//---------------------------------------------------------------------------- +void vtkOSPRayLightNode::SetLightScale(double s) +{ + vtkOSPRayLightNode::LightScale = s; +} + +//---------------------------------------------------------------------------- +double vtkOSPRayLightNode::GetLightScale() +{ + return vtkOSPRayLightNode::LightScale; +} + +//---------------------------------------------------------------------------- +void vtkOSPRayLightNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +void vtkOSPRayLightNode::Render(bool prepass) +{ + if (prepass) + { + vtkOSPRayRendererNode *orn = + static_cast( + this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); + OSPRenderer oRenderer = orn->GetORenderer(); + + vtkLight *light = vtkLight::SafeDownCast(this->GetRenderable()); + + float color[3] = {0.0,0.0,0.0}; + if (light->GetSwitch()) + { + color[0] = static_cast(light->GetDiffuseColor()[0]); + color[1] = static_cast(light->GetDiffuseColor()[1]); + color[2] = static_cast(light->GetDiffuseColor()[2]); + } + if (light->GetPositional()) + { + OSPLight ospLight = ospNewLight(oRenderer, "PointLight"); + ospSet3f(ospLight, "color", + color[0], + color[1], + color[2]); + float fI = static_cast + (vtkOSPRayLightNode::LightScale* + light->GetIntensity()* + vtkMath::Pi() //since OSP 0.10.0 + ); + ospSet1f(ospLight, "intensity", fI); + ospSet3f(ospLight, "position", + light->GetPosition()[0], + light->GetPosition()[1], + light->GetPosition()[2]); + ospCommit(ospLight); + orn->AddLight(ospLight); + } + else + { + double direction[3]; + direction[0] = light->GetPosition()[0] - light->GetFocalPoint()[0]; + direction[1] = light->GetPosition()[1] - light->GetFocalPoint()[1]; + direction[2] = light->GetPosition()[2] - light->GetFocalPoint()[2]; + OSPLight ospLight = ospNewLight(oRenderer, "DirectionalLight"); + ospSet3f(ospLight, "color", + color[0], + color[1], + color[2]); + float fI = static_cast + (vtkOSPRayLightNode::LightScale* + light->GetIntensity()* + vtkMath::Pi()); //since OSP 0.10.0 + ospSet1f(ospLight, "intensity", fI); + vtkMath::Normalize(direction); + ospSet3f(ospLight, "direction", + -direction[0],-direction[1],-direction[2]); + ospCommit(ospLight); + orn->AddLight(ospLight); + } + } +} diff --git a/Rendering/OSPRay/vtkOSPRayLightNode.h b/Rendering/OSPRay/vtkOSPRayLightNode.h new file mode 100644 index 00000000000..23a5706dbe9 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayLightNode.h @@ -0,0 +1,54 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayLightNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkOSPRayLightNode - links vtkLights to OSPRay +// .SECTION Description +// Translates vtkLight state into OSPRay rendering calls + +#ifndef vtkOSPRayLightNode_h +#define vtkOSPRayLightNode_h + +#include "vtkRenderingOSPRayModule.h" // For export macro +#include "vtkLightNode.h" + +class VTKRENDERINGOSPRAY_EXPORT vtkOSPRayLightNode : + public vtkLightNode +{ +public: + static vtkOSPRayLightNode* New(); + vtkTypeMacro(vtkOSPRayLightNode, vtkLightNode); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //Make ospray calls to render me. + virtual void Render(bool prepass); + + //Description: + //A global multiplier to all ospray lights. + //default is 1.0 + static void SetLightScale(double s); + static double GetLightScale(); + +protected: + vtkOSPRayLightNode(); + ~vtkOSPRayLightNode(); + +private: + vtkOSPRayLightNode(const vtkOSPRayLightNode&); // Not implemented. + void operator=(const vtkOSPRayLightNode&); // Not implemented. + + static double LightScale; +}; + +#endif diff --git a/Rendering/OSPRay/vtkOSPRayPass.cxx b/Rendering/OSPRay/vtkOSPRayPass.cxx new file mode 100644 index 00000000000..96addac79fb --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayPass.cxx @@ -0,0 +1,228 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayPass.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkCameraPass.h" +#include "vtkLightsPass.h" +#include "vtkObjectFactory.h" +#include "vtkOSPRayPass.h" +#include "vtkOSPRayRendererNode.h" +#include "vtkOSPRayViewNodeFactory.h" +#include "vtkOverlayPass.h" +#include "vtkOpaquePass.h" +#include "vtkRenderPassCollection.h" +#include "vtkRenderState.h" +#include "vtkRenderWindow.h" +#include "vtkRenderer.h" +#include "vtkSequencePass.h" +#include "vtkSequencePass.h" +#include "vtkVolumetricPass.h" + +#include "ospray/ospray.h" + +#include + +class vtkOSPRayPassInternals : public vtkRenderPass +{ +public: + static vtkOSPRayPassInternals *New(); + vtkTypeMacro(vtkOSPRayPassInternals,vtkRenderPass); + vtkOSPRayPassInternals() + { + this->Factory = 0; + } + ~vtkOSPRayPassInternals() + { + this->Factory->Delete(); + } + void Render(const vtkRenderState *s) + { + this->Parent->RenderInternal(s); + } + + vtkOSPRayViewNodeFactory *Factory; + vtkOSPRayPass *Parent; +}; + +// ---------------------------------------------------------------------------- +vtkStandardNewMacro(vtkOSPRayPassInternals); + +// ---------------------------------------------------------------------------- +vtkStandardNewMacro(vtkOSPRayPass); + +// ---------------------------------------------------------------------------- +vtkOSPRayPass::vtkOSPRayPass() +{ + this->SceneGraph = NULL; + + int ac = 1; + const char* av[] = {"pvOSPRay\0"}; + try + { + ospInit(&ac, av); + } + catch (std::runtime_error &vtkNotUsed(e)) + { + //todo: request addition of ospFinalize() to ospray + //cerr << "warning: double init" << endl; + } + + vtkOSPRayViewNodeFactory *vnf = vtkOSPRayViewNodeFactory::New(); + this->Internal = vtkOSPRayPassInternals::New(); + this->Internal->Factory = vnf; + this->Internal->Parent = this; + + + this->CameraPass = vtkCameraPass::New(); + this->LightsPass = vtkLightsPass::New(); + this->SequencePass = vtkSequencePass::New(); + this->VolumetricPass = vtkVolumetricPass::New(); + this->OverlayPass = vtkOverlayPass::New(); + + this->RenderPassCollection = vtkRenderPassCollection::New(); + this->RenderPassCollection->AddItem(this->LightsPass); + this->RenderPassCollection->AddItem(this->Internal); +// this->RenderPassCollection->AddItem(vtkOpaquePass::New()); + this->RenderPassCollection->AddItem(this->VolumetricPass); + this->RenderPassCollection->AddItem(this->OverlayPass); + + this->SequencePass->SetPasses(this->RenderPassCollection); + this->CameraPass->SetDelegatePass(this->SequencePass); + +} + +// ---------------------------------------------------------------------------- +vtkOSPRayPass::~vtkOSPRayPass() +{ + this->SetSceneGraph(NULL); + this->Internal->Delete(); + this->Internal = 0; + if (this->CameraPass) + { + this->CameraPass->Delete(); + this->CameraPass = 0; + } + if (this->LightsPass) + { + this->LightsPass->Delete(); + this->LightsPass = 0; + } + if (this->SequencePass) + { + this->SequencePass->Delete(); + this->SequencePass = 0; + } + if (this->VolumetricPass) + { + this->VolumetricPass->Delete(); + this->VolumetricPass = 0; + } + if (this->OverlayPass) + { + this->OverlayPass->Delete(); + this->OverlayPass = 0; + } + if (this->RenderPassCollection) + { + this->RenderPassCollection->Delete(); + this->RenderPassCollection = 0; + } +} + +// ---------------------------------------------------------------------------- +void vtkOSPRayPass::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os,indent); +} + +// ---------------------------------------------------------------------------- +vtkCxxSetObjectMacro(vtkOSPRayPass, SceneGraph, vtkOSPRayRendererNode) + +// ---------------------------------------------------------------------------- +void vtkOSPRayPass::Render(const vtkRenderState *s) +{ + if (!this->SceneGraph) + { + vtkRenderer *ren = s->GetRenderer(); + if (ren) + { + this->SceneGraph = vtkOSPRayRendererNode::SafeDownCast + (this->Internal->Factory->CreateNode(ren)); + } + } + this->CameraPass->Render(s); +} + +// ---------------------------------------------------------------------------- +void vtkOSPRayPass::RenderInternal(const vtkRenderState *s) +{ + this->NumberOfRenderedProps=0; + + if (this->SceneGraph) + { + this->SceneGraph->TraverseAllPasses(); + + // copy the result to the window + vtkRenderer *ren = s->GetRenderer(); + vtkRenderWindow *rwin = + vtkRenderWindow::SafeDownCast(ren->GetVTKWindow()); + int viewportX, viewportY; + int viewportWidth, viewportHeight; + ren->GetTiledSizeAndOrigin(&viewportWidth,&viewportHeight, + &viewportX,&viewportY); + int layer = ren->GetLayer(); + if (layer == 0) + { + rwin->SetZbufferData( + viewportX, viewportY, + viewportX+viewportWidth-1, + viewportY+viewportHeight-1, + this->SceneGraph->GetZBuffer()); + rwin->SetRGBACharPixelData( + viewportX, viewportY, + viewportX+viewportWidth-1, + viewportY+viewportHeight-1, + this->SceneGraph->GetBuffer(), + 0, 0 ); + } + else + { + float *ontoZ = rwin->GetZbufferData + (viewportX, viewportY, + viewportX+viewportWidth-1, + viewportY+viewportHeight-1); + unsigned char *ontoRGBA = rwin->GetRGBACharPixelData + (viewportX, viewportY, + viewportX+viewportWidth-1, + viewportY+viewportHeight-1, + 0); + vtkOSPRayRendererNode* oren= vtkOSPRayRendererNode::SafeDownCast + (this->SceneGraph->GetViewNodeFor(ren)); + oren->WriteLayer(ontoRGBA, ontoZ, viewportWidth, viewportHeight, layer); + rwin->SetZbufferData( + viewportX, viewportY, + viewportX+viewportWidth-1, + viewportY+viewportHeight-1, + ontoZ); + rwin->SetRGBACharPixelData( + viewportX, viewportY, + viewportX+viewportWidth-1, + viewportY+viewportHeight-1, + ontoRGBA, + 0, 0 ); + delete[] ontoZ; + delete[] ontoRGBA; + } + } +} diff --git a/Rendering/OSPRay/vtkOSPRayPass.h b/Rendering/OSPRay/vtkOSPRayPass.h new file mode 100644 index 00000000000..99fb361d695 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayPass.h @@ -0,0 +1,81 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayPass.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkOSPRayPass - a render pass that uses OSPRay instead of GL +// .SECTION Description +// This is a render pass that can be put into a vtkRenderWindow which makes +// it use OSPRay instead of OpenGL to render. Adding/Removing the pass +// will swap back and forth between the two. + +#ifndef vtkOSPRayPass_h +#define vtkOSPRayPass_h + +#include "vtkRenderingOSPRayModule.h" // For export macro +#include "vtkRenderPass.h" + +class vtkOSPRayRendererNode; +class vtkCameraPass; +class vtkLightsPass; +class vtkOverlayPass; +class vtkRenderPassCollection; +class vtkSequencePass; +class vtkVolumetricPass; +class vtkOSPRayPassInternals; + +class VTKRENDERINGOSPRAY_EXPORT vtkOSPRayPass : public vtkRenderPass +{ +public: + static vtkOSPRayPass *New(); + vtkTypeMacro(vtkOSPRayPass,vtkRenderPass); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Perform rendering according to a render state s. + virtual void Render(const vtkRenderState *s); + + // Description: + // Tells the pass what it will render. + void SetSceneGraph(vtkOSPRayRendererNode *); + vtkGetObjectMacro(SceneGraph, vtkOSPRayRendererNode); + + // Description: + // Called by the internals of this class + virtual void RenderInternal(const vtkRenderState *s); + + protected: + // Description: + // Default constructor. + vtkOSPRayPass(); + + // Description: + // Destructor. + virtual ~vtkOSPRayPass(); + + vtkOSPRayRendererNode *SceneGraph; + vtkCameraPass *CameraPass; + vtkLightsPass *LightsPass; + vtkOverlayPass *OverlayPass; + vtkVolumetricPass *VolumetricPass; + vtkSequencePass *SequencePass; + vtkRenderPassCollection *RenderPassCollection; + + private: + vtkOSPRayPass(const vtkOSPRayPass&); // Not implemented. + void operator=(const vtkOSPRayPass&); // Not implemented. + + class Internals; + vtkOSPRayPassInternals *Internal; +}; + +#endif diff --git a/Rendering/OSPRay/vtkOSPRayPolyDataMapperNode.cxx b/Rendering/OSPRay/vtkOSPRayPolyDataMapperNode.cxx new file mode 100644 index 00000000000..1d9094e30ff --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayPolyDataMapperNode.cxx @@ -0,0 +1,973 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayPolyDataMapperNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkOSPRayPolyDataMapperNode.h" + +#include "vtkActor.h" +#include "vtkOSPRayActorNode.h" +#include "vtkOSPRayRendererNode.h" +#include "vtkDataArray.h" +#include "vtkFloatArray.h" +#include "vtkImageData.h" +#include "vtkInformation.h" +#include "vtkInformationDoubleKey.h" +#include "vtkInformationObjectBaseKey.h" +#include "vtkMapper.h" +#include "vtkObjectFactory.h" +#include "vtkPiecewiseFunction.h" +#include "vtkPointData.h" +#include "vtkPolyData.h" +#include "vtkProperty.h" +#include "vtkTexture.h" +#include "vtkSmartPointer.h" + +#include "ospray/ospray.h" +//#include "ospray/common/OSPCommon.h" +#include "ospray/version.h" + +#include + +//============================================================================ + +namespace vtkosp { + + //------------------------------------------------------------------------------ + class MyGeom { + //A cache for the ospray meshes we make for this actor. + //When something else in the scene changes but this actor doesn't we + //reuse instead of recreating. RendererNode has a higher level cache + //that prevent spatial sorting when nothing changes other than camera. + public: + std::vector geoms; + ~MyGeom() + { + std::vector::iterator it = geoms.begin(); + while (it != geoms.end()) + { + ospRelease((OSPGeometry)*it); + it++; + } + geoms.clear(); + } + void Add(OSPGeometry geo) + { + geoms.push_back(geo); + } + void AddMyselfTo(OSPModel oModel) + { + std::vector::iterator it = geoms.begin(); + while (it != geoms.end()) + { + ospAddGeometry(oModel, *it); + it++; + } + } + }; + + //------------------------------------------------------------------------------ + void VToOPointNormals( + vtkDataArray *vNormals, + osp::vec3f *&normals) + { + int numNormals = vNormals->GetNumberOfTuples(); + normals = new osp::vec3f[numNormals]; + for (int i = 0; i < numNormals; i++) + { + double *vNormal = vNormals->GetTuple(i); + normals[i] = osp::vec3f { + static_cast(vNormal[0]), + static_cast(vNormal[1]), + static_cast(vNormal[2]) + }; + } + } + + //------------------------------------------------------------------------------ + void CellColorMaterials( + vtkUnsignedCharArray *vColors, + OSPRenderer oRenderer, + std::vector &ospMaterials, + float *specColor, float specPower, + float opacity) + { + int numColors = vColors->GetNumberOfTuples(); + for (int i = 0; i < numColors; i++) + { + double *color = vColors->GetTuple(i); + OSPMaterial oMaterial; + oMaterial = ospNewMaterial(oRenderer,"RayTraceMaterial"); + float diffusef[] = + { + static_cast(color[0])/(255.0f), + static_cast(color[1])/(255.0f), + static_cast(color[2])/(255.0f) + }; + ospSet3fv(oMaterial,"Kd",diffusef); + float specAdjust = 2.0f/(2.0f+specPower); //since OSP 0.10.0 + float specularf[] = { + specColor[0]*specAdjust, + specColor[1]*specAdjust, + specColor[2]*specAdjust + }; + ospSet3fv(oMaterial,"Ks",specularf); + ospSet1f(oMaterial,"Ns",specPower); + ospSet1f(oMaterial,"d", opacity); + ospCommit(oMaterial); + ospMaterials.push_back(oMaterial); + } + } + + //---------------------------------------------------------------------------- + OSPMaterial VTKToOSPTexture(vtkImageData *vColorTextureMap, + OSPRenderer oRenderer) + { + int xsize = vColorTextureMap->GetExtent()[1]; + int ysize = vColorTextureMap->GetExtent()[3]; + unsigned char *ichars = + (unsigned char *)vColorTextureMap->GetScalarPointer(); + unsigned char *ochars = new unsigned char[(xsize+1)*(ysize+1)*3]; + unsigned char *oc = ochars; + int comps = vColorTextureMap->GetNumberOfScalarComponents(); + for (int i = 0; i <= xsize; i++) + { + for (int j = 0; j <= ysize; j++) + { + oc[0] = ichars[0]; + oc[1] = ichars[1]; + oc[2] = ichars[2]; + oc+=3; + ichars+=comps; + } + } + osp::Texture2D *t2d; + t2d = (osp::Texture2D*)ospNewTexture2D + ( + osp::vec2i{xsize+1, + ysize+1}, + OSP_TEXTURE_RGB8, + ochars, + OSP_TEXTURE_FILTER_NEAREST); + + OSPMaterial ospMaterial; + ospMaterial = ospNewMaterial(oRenderer,"RayTraceMaterial"); + ospSetObject(ospMaterial, "map_Kd", ((OSPTexture2D)(t2d))); + ospCommit(t2d); + ospCommit(ospMaterial); + return ospMaterial; + } + + float MapThroughPWF(double in, vtkPiecewiseFunction *scaleFunction) + { + double out = in; + if (!scaleFunction) + { + out = in; + } + else + { + out = scaleFunction->GetValue(in); + } + return static_cast(out); + } + + //---------------------------------------------------------------------------- + OSPGeometry RenderAsSpheres(osp::vec3fa *vertices, + std::vector &indexArray, + std::vector &rIndexArray, + double pointSize, + vtkDataArray* scaleArray, + vtkPiecewiseFunction *scaleFunction, + OSPMaterial actorMaterial, + int numCellMaterials, + OSPData CellMaterials, + int numPointColors, + osp::vec4f *PointColors, + OSPModel oModel + ) + { + OSPGeometry ospMesh = ospNewGeometry("spheres"); + int width=4; + int scaleOffset = -1; + if (scaleArray != NULL) + { + width = 5; + scaleOffset = 4*sizeof(float); + } + float *mdata = new float[width*indexArray.size()]; + int *idata = (int*)mdata; + for (size_t i = 0; i < indexArray.size(); i++) + { + mdata[i*width+0] = static_cast(vertices[indexArray[i]].x); + mdata[i*width+1] = static_cast(vertices[indexArray[i]].y); + mdata[i*width+2] = static_cast(vertices[indexArray[i]].z); + int mat = 0; + if (numCellMaterials) + { + mat = rIndexArray[i]; + } + else if (numPointColors) + { + mat = indexArray[i]; + } + idata[i*width+3] = mat; + if (scaleArray != NULL) + { + mdata[i*width+4] = MapThroughPWF + (*scaleArray->GetTuple(indexArray[i]), + scaleFunction); + } + } + OSPData _PointColors = NULL; + if (numPointColors) + { + _PointColors = ospNewData(numPointColors, OSP_FLOAT4, &PointColors[0]); + } + OSPData _mdata = ospNewData(indexArray.size()*width, OSP_FLOAT, mdata); + ospSetObject(ospMesh, "spheres", _mdata); + ospSet1i(ospMesh, "bytes_per_sphere", width*sizeof(float)); + ospSet1i(ospMesh, "offset_center", 0*sizeof(float)); + ospSet1f(ospMesh, "radius", pointSize); + ospSet1i(ospMesh, "offset_radius", scaleOffset); + + if (numCellMaterials) + { + //per cell color + ospSet1i(ospMesh, "offset_materialID", 3*sizeof(float)); + ospSetData(ospMesh, "materialList", CellMaterials); + } + else if (numPointColors) + { + //per point color + ospSet1i(ospMesh, "offset_colorID", 3*sizeof(float)); + ospSetData(ospMesh, "color", _PointColors); + } + else + { + //per actor color + ospSetMaterial(ospMesh, actorMaterial); + } + + ospAddGeometry(oModel, ospMesh); + ospCommit(ospMesh); + //ospCommit(oModel); //TODO: crashes without yet others don't, why? + ospRelease(_PointColors); + ospRelease(_mdata); + delete[] mdata; + + return ospMesh; + } + + //---------------------------------------------------------------------------- + OSPGeometry RenderAsCylinders(osp::vec3fa *vertices, + std::vector &indexArray, + std::vector &rIndexArray, + double lineWidth, + vtkDataArray *scaleArray, + vtkPiecewiseFunction *scaleFunction, + OSPMaterial actorMaterial, + int numCellMaterials, + OSPData CellMaterials, + int numPointColors, + osp::vec4f *PointColors, + OSPModel oModel) + { + OSPGeometry ospMesh = ospNewGeometry("cylinders"); + int width=7; + int scaleOffset = -1; + if (scaleArray != NULL) + { + width = 8; + scaleOffset = 7*sizeof(float); + } + float *mdata = new float[indexArray.size()/2*width]; + int *idata = (int*)mdata; + for (size_t i = 0; i < indexArray.size()/2; i++) + { + mdata[i*width+0] = static_cast(vertices[indexArray[i*2+0]].x); + mdata[i*width+1] = static_cast(vertices[indexArray[i*2+0]].y); + mdata[i*width+2] = static_cast(vertices[indexArray[i*2+0]].z); + mdata[i*width+3] = static_cast(vertices[indexArray[i*2+1]].x); + mdata[i*width+4] = static_cast(vertices[indexArray[i*2+1]].y); + mdata[i*width+5] = static_cast(vertices[indexArray[i*2+1]].z); + int mat = 0; + if (numCellMaterials) + { + mat = rIndexArray[i*2]; + } + else if (numPointColors) + { + mat = indexArray[i*2]; + } + idata[i*width+6] = mat; + if (scaleArray != NULL) + { + double avg = (*scaleArray->GetTuple(indexArray[i*2+0]) + + *scaleArray->GetTuple(indexArray[i*2+1]))*0.5; + mdata[i*width+7] = MapThroughPWF + (avg, + scaleFunction); + } + } + OSPData _PointColors = NULL; + if (numPointColors) + { + _PointColors = ospNewData(numPointColors, OSP_FLOAT4, &PointColors[0]); + } + OSPData _mdata = ospNewData(indexArray.size()/2*width, OSP_FLOAT, mdata); + ospSetData(ospMesh, "cylinders", _mdata); + ospSet1i(ospMesh, "bytes_per_cylinder", width*sizeof(float)); + ospSet1i(ospMesh, "offset_v0", 0); + ospSet1i(ospMesh, "offset_v1", 3*sizeof(float)); + ospSet1f(ospMesh, "radius", lineWidth); + ospSet1i(ospMesh, "offset_radius", scaleOffset); + + if (numCellMaterials) + { + //per cell color + ospSet1i(ospMesh, "offset_materialID", 6*sizeof(float)); + ospSetData(ospMesh, "materialList", CellMaterials); + } + else if (numPointColors) + { + //per point color + ospSet1i(ospMesh, "offset_colorID", 6*sizeof(float)); + ospSetData(ospMesh, "color", _PointColors); + } + else + { + //per actor color + ospSetMaterial(ospMesh, actorMaterial); + } + + ospAddGeometry(oModel, ospMesh); + ospCommit(ospMesh); + //ospCommit(oModel); //TODO: crashes without yet others don't, why? + ospRelease(_PointColors); + ospRelease(_mdata); + delete[] mdata; + + return ospMesh; + } + + //---------------------------------------------------------------------------- + OSPGeometry RenderAsTriangles(OSPData vertices, + std::vector &indexArray, + std::vector &rIndexArray, + OSPMaterial actorMaterial, + int numNormals, + osp::vec3f *normals, + vtkImageData *vColorTextureMap, + int numTextureCoordinates, + float *textureCoordinates, + int numCellMaterials, + OSPData CellMaterials, + int numPointColors, + osp::vec4f *PointColors, + int numPointValueTextureCoords, + float *pointValueTextureCoords, + OSPModel oModel, + OSPRenderer oRenderer + ) + { + OSPGeometry ospMesh = ospNewGeometry("trianglemesh"); + ospSetData(ospMesh, "position", vertices); + + size_t numTriangles = indexArray.size() / 3; + osp::vec3i *triangles = new osp::vec3i[numTriangles]; + for (size_t i = 0, mi = 0; i < numTriangles; i++, mi += 3) + { + triangles[i] = osp::vec3i{static_cast(indexArray[mi + 0]), + static_cast(indexArray[mi + 1]), + static_cast(indexArray[mi + 2])}; + } + OSPData index = ospNewData(numTriangles, OSP_INT3, &triangles[0]); + delete[] triangles; + ospSetData(ospMesh, "index", index); + + OSPData _normals = NULL; + if (numNormals) + { + _normals = ospNewData(numNormals, OSP_FLOAT3, &normals[0]); + ospSetData(ospMesh, "vertex.normal", _normals); + } + + //send the texture map and texture coordiantes over + bool _hastm = false; + osp::vec2f *tc = NULL; + if (numTextureCoordinates || numPointValueTextureCoords) + { + _hastm = true; + + if (numPointValueTextureCoords) + { + //using 1D texture for point value LUT + tc = new osp::vec2f[numPointValueTextureCoords]; + for (size_t i = 0; i < numPointValueTextureCoords; i++) + { + tc[i] = osp::vec2f{pointValueTextureCoords[i],0}; + } + OSPData tcs = ospNewData(numPointValueTextureCoords, OSP_FLOAT2, &tc[0]); + ospSetData(ospMesh, "vertex.texcoord", tcs); + } + else if (numTextureCoordinates) + { + //2d texture mapping + tc = new osp::vec2f[numTextureCoordinates/2]; + float *itc = textureCoordinates; + for (size_t i = 0; i < numTextureCoordinates; i+=2) + { + float t1,t2; + t1 = *itc; + itc++; + t2 = *itc; + itc++; + tc[i/2] = osp::vec2f{t1,t2}; + } + OSPData tcs = ospNewData(numTextureCoordinates/2, OSP_FLOAT2, &tc[0]); + ospSetData(ospMesh, "vertex.texcoord", tcs); + } + OSPMaterial ospMaterial = vtkosp::VTKToOSPTexture(vColorTextureMap,oRenderer); + ospSetMaterial(ospMesh, ospMaterial); + } + delete[] tc; + + //send over cell colors, point colors or whole actor color + OSPData _cmats = NULL; + OSPData _PointColors = NULL; + int *ids = NULL; + if (!_hastm) + { + if (numCellMaterials) + { + ids = new int[numTriangles]; + for (size_t i = 0; i < numTriangles; i++) + { + ids[i] = rIndexArray[i*3+0]; + } + _cmats = ospNewData(numTriangles, OSP_INT, &ids[0]); + ospSetData(ospMesh, "prim.materialID", _cmats); + ospSetData(ospMesh, "materialList", CellMaterials); + } + else if (numPointColors) + { + _PointColors = ospNewData(numPointColors, OSP_FLOAT4, &PointColors[0]); + ospSetData(ospMesh, "vertex.color", _PointColors); + } + else + { + ospSetMaterial(ospMesh, actorMaterial); + } + } + + ospAddGeometry(oModel, ospMesh); + ospCommit(ospMesh); + ospCommit(oModel); //TODO: crashes without yet others don't, why? + ospRelease(index); + ospRelease(_normals); + ospRelease(_PointColors); + ospRelease(_cmats); + delete[] ids; + return ospMesh; + } +} + +//============================================================================ +vtkStandardNewMacro(vtkOSPRayPolyDataMapperNode); + +//---------------------------------------------------------------------------- +vtkOSPRayPolyDataMapperNode::vtkOSPRayPolyDataMapperNode() +{ + this->OSPMeshes = NULL; +} + +//---------------------------------------------------------------------------- +vtkOSPRayPolyDataMapperNode::~vtkOSPRayPolyDataMapperNode() +{ + delete (vtkosp::MyGeom*)this->OSPMeshes; +} + +//---------------------------------------------------------------------------- +void vtkOSPRayPolyDataMapperNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +void vtkOSPRayPolyDataMapperNode::ORenderPoly( + void *renderer, void *model, + vtkOSPRayActorNode *aNode, vtkPolyData * poly, + double *ambientColor, + double *diffuseColor, + double opacity) +{ + OSPRenderer oRenderer = static_cast(renderer); + OSPModel oModel = static_cast(model); + vtkActor *act = vtkActor::SafeDownCast(aNode->GetRenderable()); + vtkProperty *property = act->GetProperty(); + vtkosp::MyGeom *myMeshes = (vtkosp::MyGeom*)this->OSPMeshes; + + //make geometry + std::vector _vertices; + vtkPolyDataMapperNode::TransformPoints(act, poly, _vertices); + size_t numPositions = _vertices.size()/3; + osp::vec3fa *vertices = new osp::vec3fa[numPositions]; + for (size_t i = 0; i < numPositions; i++) + { + vertices[i] = + osp::vec3fa{static_cast(_vertices[i*3+0]), + static_cast(_vertices[i*3+1]), + static_cast(_vertices[i*3+2])}; + } + OSPData position = ospNewData(numPositions, OSP_FLOAT3A, &vertices[0]); + ospCommit(position); + _vertices.clear(); + + //make connectivity + std::vector vertex_index; + std::vector vertex_reverse; + std::vector line_index; + std::vector line_reverse; + std::vector triangle_index; + std::vector triangle_reverse; + std::vector strip_index; + std::vector strip_reverse; + vtkPolyDataMapperNode::MakeConnectivity(poly, property->GetRepresentation(), + vertex_index, vertex_reverse, + line_index, line_reverse, + triangle_index, triangle_reverse, + strip_index, strip_reverse); + + //choose sphere and cylinder radii (for points and lines) that approximate pointsize and linewidth + //TODO: take into account camera so that size is roughly numpixels wide on screen? + vtkMapper *mapper = act->GetMapper(); + double length = 1.0; + if (mapper) + { + length = mapper->GetLength(); + } + double pointSize = length/1000.0 * property->GetPointSize(); + double lineWidth = length/1000.0 * property->GetLineWidth(); + //finer control over sphere and cylinders sizes + int enable_scaling = + vtkOSPRayActorNode::GetEnableScaling(act); + vtkDataArray *scaleArray = NULL; + vtkPiecewiseFunction *scaleFunction = NULL; + if (enable_scaling && mapper) + { + vtkInformation *mapInfo = mapper->GetInformation(); + char *scaleArrayName = (char *)mapInfo->Get + (vtkOSPRayActorNode::SCALE_ARRAY_NAME()); + scaleArray = poly->GetPointData()->GetArray(scaleArrayName); + scaleFunction = vtkPiecewiseFunction::SafeDownCast + (mapInfo->Get(vtkOSPRayActorNode::SCALE_FUNCTION())); + } + + //per actor material + OSPMaterial oMaterial; + oMaterial = ospNewMaterial(oRenderer,"RayTraceMaterial"); + float ambientf[] = + { + static_cast(ambientColor[0]*property->GetAmbient()), + static_cast(ambientColor[1]*property->GetAmbient()), + static_cast(ambientColor[2]*property->GetAmbient()) + }; + float diffusef[] = + { + static_cast(diffuseColor[0]*property->GetDiffuse()), + static_cast(diffuseColor[1]*property->GetDiffuse()), + static_cast(diffuseColor[2]*property->GetDiffuse()) + }; + float specPower = + static_cast(property->GetSpecularPower()); + float specAdjust = 2.0f/(2.0f+specPower); //since OSP 0.10.0 + float specularf[] = + { + static_cast(property->GetSpecularColor()[0]* + property->GetSpecular()* + specAdjust), + static_cast(property->GetSpecularColor()[1]* + property->GetSpecular()* + specAdjust), + static_cast(property->GetSpecularColor()[2]* + property->GetSpecular()* + specAdjust) + }; + + ospSet3fv(oMaterial,"Ka",ambientf); + double scale = property->GetDiffuse(); + if (property->GetDiffuse()==0.0) + { + //a workaround for ParaView, remove when ospray supports Ka + ospSet3fv(oMaterial,"Kd",ambientf); + } + else + { + ospSet3fv(oMaterial,"Kd",diffusef); + } + ospSet3fv(oMaterial,"Ks",specularf); + ospSet1f(oMaterial,"Ns",specPower); + ospSet1f(oMaterial,"d",float(opacity)); + ospCommit(oMaterial); + + //texture + vtkTexture *texture = act->GetTexture(); + int numTextureCoordinates = 0; + float *textureCoordinates = NULL; + vtkImageData* vColorTextureMap = NULL; + if (texture) + { + vtkDataArray *da = poly->GetPointData()->GetTCoords(); + numTextureCoordinates = da->GetNumberOfTuples(); + textureCoordinates = new float[numTextureCoordinates*2]; + float *tp = textureCoordinates; + for (int i=0; i(da->GetTuple(i)[0]); + tp++; + *tp = static_cast(da->GetTuple(i)[1]); + tp++; + } + vColorTextureMap = vtkImageData::SafeDownCast + (texture->GetInput()); + numTextureCoordinates = numTextureCoordinates*2; + } + + //colors from point and cell arrays + int numCellMaterials = 0; + OSPData cellMaterials = NULL; + int numPointColors = 0; + osp::vec4f *pointColors = NULL; + int numPointValueTextureCoords = 0; + float *pointValueTextureCoords = NULL; + // + //now ask mapper to do most of the work and provide use with + //colors per cell and colors or texture coordinates per point + vtkUnsignedCharArray *vColors = NULL; + vtkFloatArray *vColorCoordinates = NULL; + vtkImageData* pColorTextureMap = NULL; + int cellFlag = -1; //mapper tells us which + if (mapper) + { + mapper->MapScalars(poly, 1.0, cellFlag); + vColors = mapper->GetColorMapColors(); + vColorCoordinates = mapper->GetColorCoordinates(); + pColorTextureMap = mapper->GetColorTextureMap(); + } + if (vColors) + { + if (cellFlag==2 && mapper->GetFieldDataTupleId() > -1) + { + int numComp = vColors->GetNumberOfComponents(); + unsigned char *colorPtr = vColors->GetPointer(0); + colorPtr = colorPtr + mapper->GetFieldDataTupleId()*numComp; + // this setting (and all the other scalar colors) + // really depends on mapper->ScalarMaterialMode + // but I'm not sure Ka is working currently so leaving it on Kd + float fdiffusef[] = + { + static_cast(colorPtr[0]*property->GetDiffuse()/255.0f), + static_cast(colorPtr[1]*property->GetDiffuse()/255.0f), + static_cast(colorPtr[2]*property->GetDiffuse()/255.0f) + }; + ospSet3fv(oMaterial,"Kd",fdiffusef); + ospCommit(oMaterial); + } + else if (cellFlag==1) + { + //color on cell + std::vector cellColors; + vtkosp::CellColorMaterials(vColors, oRenderer, cellColors, specularf, + float(property->GetSpecularPower()), opacity); + numCellMaterials = cellColors.size(); + cellMaterials = ospNewData(cellColors.size(), OSP_OBJECT, &cellColors[0]); + ospCommit(cellMaterials); + cellColors.clear(); + } + else if (cellFlag==0) + { + //color on point interpolated RGB + numPointColors = vColors->GetNumberOfTuples(); + pointColors = new osp::vec4f[numPointColors]; + for (int i = 0; i < numPointColors; i++) + { + unsigned char *color = vColors->GetPointer(4 * i); + pointColors[i] = osp::vec4f{color[0] / 255.0f, + color[1] / 255.0f, + color[2] / 255.0f, + 1}; + } + } + } + else + { + if (vColorCoordinates && pColorTextureMap) + { + //color on point interpolated values (subsequently colormapped via 1D LUT) + numPointValueTextureCoords = vColorCoordinates->GetNumberOfTuples(); + pointValueTextureCoords = new float[numPointValueTextureCoords]; + float *tc = vColorCoordinates->GetPointer(0); + for (int i = 0; i < numPointValueTextureCoords; i++) + { + pointValueTextureCoords[i] = *tc; + tc+=2; + } + vColorTextureMap = pColorTextureMap; + } + + } + + //create an ospray mesh for the vertex cells + if (vertex_index.size()) + { + myMeshes + ->Add(vtkosp::RenderAsSpheres(vertices, + vertex_index, vertex_reverse, + pointSize, scaleArray, scaleFunction, + oMaterial, + numCellMaterials, cellMaterials, + numPointColors, pointColors, + oModel + )); + } + + + //create an ospray mesh for the line cells + if (line_index.size()) + { + //format depends on representation style + if (property->GetRepresentation() == VTK_POINTS) + { + myMeshes + ->Add(vtkosp::RenderAsSpheres(vertices, + line_index, line_reverse, + pointSize, scaleArray, scaleFunction, + oMaterial, + numCellMaterials, cellMaterials, + numPointColors, pointColors, + oModel + )); + } + else + { + myMeshes + ->Add(vtkosp::RenderAsCylinders(vertices, + line_index, line_reverse, + lineWidth, scaleArray, scaleFunction, + oMaterial, + numCellMaterials, cellMaterials, + numPointColors, pointColors, + oModel + )); + } + } + + //create an ospray mesh for the polygon cells + if (triangle_index.size()) + { + //format depends on representation style + switch (property->GetRepresentation()) + { + case VTK_POINTS: + { + myMeshes + ->Add(vtkosp::RenderAsSpheres(vertices, + triangle_index, triangle_reverse, + pointSize, scaleArray, scaleFunction, + oMaterial, + numCellMaterials, cellMaterials, + numPointColors, pointColors, + oModel + )); + break; + } + case VTK_WIREFRAME: + { + myMeshes + ->Add(vtkosp::RenderAsCylinders(vertices, + triangle_index, triangle_reverse, + lineWidth, scaleArray, scaleFunction, + oMaterial, + numCellMaterials, cellMaterials, + numPointColors, pointColors, + oModel + )); + break; + } + default: + { + osp::vec3f *normals = NULL; + int numNormals = 0; + if (property->GetInterpolation() != VTK_FLAT) + { + vtkDataArray *vNormals = poly->GetPointData()->GetNormals(); + if (vNormals) + { + vtkosp::VToOPointNormals + (vNormals, normals); + numNormals = vNormals->GetNumberOfTuples(); + } + } + myMeshes + ->Add(vtkosp::RenderAsTriangles(position, + triangle_index, triangle_reverse, + oMaterial, + numNormals, normals, + vColorTextureMap, + numTextureCoordinates, textureCoordinates, + numCellMaterials, cellMaterials, + numPointColors, pointColors, + numPointValueTextureCoords, pointValueTextureCoords, + oModel, oRenderer + )); + delete[] normals; + } + } + } + + if (strip_index.size()) + { + switch (property->GetRepresentation()) + { + case VTK_POINTS: + { + myMeshes + ->Add(vtkosp::RenderAsSpheres(vertices, + strip_index, strip_reverse, + pointSize, scaleArray, scaleFunction, + oMaterial, + numCellMaterials, cellMaterials, + numPointColors, pointColors, + oModel + )); + break; + } + case VTK_WIREFRAME: + { + myMeshes + ->Add(vtkosp::RenderAsCylinders(vertices, + strip_index, strip_reverse, + lineWidth, scaleArray, scaleFunction, + oMaterial, + numCellMaterials, cellMaterials, + numPointColors, pointColors, + oModel + )); + break; + } + default: + { + osp::vec3f *normals = NULL; + int numNormals = 0; + if (property->GetInterpolation() != VTK_FLAT) + { + vtkDataArray *vNormals = poly->GetPointData()->GetNormals(); + if (vNormals) + { + vtkosp::VToOPointNormals + (vNormals, normals); + numNormals = strip_index.size(); + } + } + myMeshes + ->Add(vtkosp::RenderAsTriangles(position, + strip_index, strip_reverse, + oMaterial, + numNormals, normals, + vColorTextureMap, + numTextureCoordinates, textureCoordinates, + numCellMaterials, cellMaterials, + numPointColors, pointColors, + numPointValueTextureCoords, pointValueTextureCoords, + oModel, oRenderer + )); + delete[] normals; + } + } + } + ospRelease(position); + delete[] vertices; + delete[] pointColors; + delete[] pointValueTextureCoords; +} + +void vtkOSPRayPolyDataMapperNode::AddMeshesToModel(void *arg) +{ + vtkosp::MyGeom *myMeshes = (vtkosp::MyGeom*)this->OSPMeshes; + OSPModel oModel = static_cast(arg); + myMeshes->AddMyselfTo(oModel); +} + +void vtkOSPRayPolyDataMapperNode::CreateNewMeshes() +{ + vtkosp::MyGeom *myMeshes = (vtkosp::MyGeom*)this->OSPMeshes; + delete myMeshes; + myMeshes = new vtkosp::MyGeom(); + this->OSPMeshes = myMeshes; +} + +//---------------------------------------------------------------------------- +void vtkOSPRayPolyDataMapperNode::Render(bool prepass) +{ + if (prepass) + { + // we use a lot of params from our parent + vtkOSPRayActorNode *aNode = vtkOSPRayActorNode::SafeDownCast(this->Parent); + vtkActor *act = vtkActor::SafeDownCast(aNode->GetRenderable()); + + if (act->GetVisibility() == false) + { + delete (vtkosp::MyGeom*)this->OSPMeshes; + this->OSPMeshes = NULL; + return; + } + + vtkOSPRayRendererNode *orn = + static_cast( + this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); + + //if there are no changes, just reuse last result + bool enable_cache = true; //turn off to force rebuilds for debugging + unsigned long inTime = aNode->GetMTime(); + if (enable_cache && this->RenderTime >= inTime) + { + OSPModel oModel = static_cast(orn->GetOModel()); + this->AddMeshesToModel(oModel); + return; + } + this->RenderTime = inTime; + + //something changed so make new meshes + this->CreateNewMeshes(); + + vtkPolyData *poly = NULL; + vtkMapper *mapper = act->GetMapper(); + if (mapper) + { + poly = (vtkPolyData*)(mapper->GetInput()); + } + if (poly) + { + vtkProperty * property = act->GetProperty(); + this->ORenderPoly( + orn->GetORenderer(), + orn->GetOModel(), + aNode, + poly, + property->GetAmbientColor(), + property->GetDiffuseColor(), + property->GetOpacity() + ); + } + } +} diff --git a/Rendering/OSPRay/vtkOSPRayPolyDataMapperNode.h b/Rendering/OSPRay/vtkOSPRayPolyDataMapperNode.h new file mode 100644 index 00000000000..de6b0c9d541 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayPolyDataMapperNode.h @@ -0,0 +1,58 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayPolyDataMapperNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkOSPRayPolyDataMapperNode - links vtkActor and vtkMapper to OSPRay +// .SECTION Description +// Translates vtkActor/Mapper state into OSPRay rendering calls + +#ifndef vtkOSPRayPolyDataMapperNode_h +#define vtkOSPRayPolyDataMapperNode_h + +#include "vtkRenderingOSPRayModule.h" // For export macro +#include "vtkPolyDataMapperNode.h" + +class vtkOSPRayActorNode; +class vtkPolyData; + +class VTKRENDERINGOSPRAY_EXPORT vtkOSPRayPolyDataMapperNode : + public vtkPolyDataMapperNode +{ +public: + static vtkOSPRayPolyDataMapperNode* New(); + vtkTypeMacro(vtkOSPRayPolyDataMapperNode, vtkPolyDataMapperNode); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //Make ospray calls to render me. + virtual void Render(bool prepass); + +protected: + vtkOSPRayPolyDataMapperNode(); + ~vtkOSPRayPolyDataMapperNode(); + + void ORenderPoly(void *renderer, void *model, + vtkOSPRayActorNode *aNode, vtkPolyData * poly, + double *ambientColor, + double *diffuseColor, + double opacity); + + void *OSPMeshes; + void CreateNewMeshes(); + void AddMeshesToModel(void *arg); + +private: + vtkOSPRayPolyDataMapperNode(const vtkOSPRayPolyDataMapperNode&); // Not implemented. + void operator=(const vtkOSPRayPolyDataMapperNode&); // Not implemented. +}; +#endif diff --git a/Rendering/OSPRay/vtkOSPRayRendererNode.cxx b/Rendering/OSPRay/vtkOSPRayRendererNode.cxx new file mode 100644 index 00000000000..42988ee66df --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayRendererNode.cxx @@ -0,0 +1,429 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayRendererNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkOSPRayRendererNode.h" + +#include "vtkCamera.h" +#include "vtkCollectionIterator.h" +#include "vtkInformation.h" +#include "vtkInformationIntegerKey.h" +#include "vtkObjectFactory.h" +#include "vtkOSPRayActorNode.h" +#include "vtkOSPRayCameraNode.h" +#include "vtkOSPRayLightNode.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkViewNodeCollection.h" + +#include "ospray/ospray.h" +#include "ospray/version.h" + +#include + +#if 0 +//debug includes +#include "vtkDataSetWriter.h" +#include "vtkImageImport.h" +#include "vtkSmartPointer.h" +#include "vtkWindowToImageFilter.h" +#include +#endif + +vtkInformationKeyMacro(vtkOSPRayRendererNode, SAMPLES_PER_PIXEL, Integer); +vtkInformationKeyMacro(vtkOSPRayRendererNode, MAX_FRAMES, Integer); +vtkInformationKeyMacro(vtkOSPRayRendererNode, AMBIENT_SAMPLES, Integer); + +//============================================================================ +vtkStandardNewMacro(vtkOSPRayRendererNode); + +//---------------------------------------------------------------------------- +vtkOSPRayRendererNode::vtkOSPRayRendererNode() +{ + this->Buffer = NULL; + this->ZBuffer = NULL; + this->OModel = NULL; + this->ORenderer = NULL; + this->NumActors = 0; +} + +//---------------------------------------------------------------------------- +vtkOSPRayRendererNode::~vtkOSPRayRendererNode() +{ + delete[] this->Buffer; + delete[] this->ZBuffer; + ospRelease((OSPModel)this->OModel); + ospRelease((OSPRenderer)this->ORenderer); +} + +//---------------------------------------------------------------------------- +void vtkOSPRayRendererNode::SetSamplesPerPixel(int value, vtkRenderer *renderer) +{ + if (!renderer) + { + return; + } + vtkInformation *info = renderer->GetInformation(); + info->Set(vtkOSPRayRendererNode::SAMPLES_PER_PIXEL(), value); +} + +//---------------------------------------------------------------------------- +int vtkOSPRayRendererNode::GetSamplesPerPixel(vtkRenderer *renderer) +{ + if (!renderer) + { + return 1; + } + vtkInformation *info = renderer->GetInformation(); + if (info && info->Has(vtkOSPRayRendererNode::SAMPLES_PER_PIXEL())) + { + return (info->Get(vtkOSPRayRendererNode::SAMPLES_PER_PIXEL())); + } + return 1; +} + +//---------------------------------------------------------------------------- +void vtkOSPRayRendererNode::SetMaxFrames(int value, vtkRenderer *renderer) +{ + if (!renderer) + { + return; + } + vtkInformation *info = renderer->GetInformation(); + info->Set(vtkOSPRayRendererNode::MAX_FRAMES(), value); +} + +//---------------------------------------------------------------------------- +int vtkOSPRayRendererNode::GetMaxFrames(vtkRenderer *renderer) +{ + if (!renderer) + { + return 1; + } + vtkInformation *info = renderer->GetInformation(); + if (info && info->Has(vtkOSPRayRendererNode::MAX_FRAMES())) + { + return (info->Get(vtkOSPRayRendererNode::MAX_FRAMES())); + } + return 1; +} + +//---------------------------------------------------------------------------- +void vtkOSPRayRendererNode::SetAmbientSamples(int value, vtkRenderer *renderer) +{ + if (!renderer) + { + return; + } + vtkInformation *info = renderer->GetInformation(); + info->Set(vtkOSPRayRendererNode::AMBIENT_SAMPLES(), value); +} + +//---------------------------------------------------------------------------- +int vtkOSPRayRendererNode::GetAmbientSamples(vtkRenderer *renderer) +{ + if (!renderer) + { + return 0; + } + vtkInformation *info = renderer->GetInformation(); + if (info && info->Has(vtkOSPRayRendererNode::AMBIENT_SAMPLES())) + { + return (info->Get(vtkOSPRayRendererNode::AMBIENT_SAMPLES())); + } + return 0; +} + +//---------------------------------------------------------------------------- +void vtkOSPRayRendererNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +void vtkOSPRayRendererNode::Traverse(int operation) +{ + // do not override other passes + if (operation != render) + { + this->Superclass::Traverse(operation); + return; + } + + this->Apply(operation,true); + + OSPRenderer oRenderer = (osp::Renderer*)this->ORenderer; + + //camera + //TODO: this repeated traversal to find things of particular types + //is bad, find something smarter + vtkViewNodeCollection *nodes = this->GetChildren(); + vtkCollectionIterator *it = nodes->NewIterator(); + it->InitTraversal(); + while (!it->IsDoneWithTraversal()) + { + vtkOSPRayCameraNode *child = + vtkOSPRayCameraNode::SafeDownCast(it->GetCurrentObject()); + if (child) + { + child->Traverse(operation); + break; + } + it->GoToNextItem(); + } + + //lights + this->Lights.clear(); + it->InitTraversal(); + while (!it->IsDoneWithTraversal()) + { + vtkOSPRayLightNode *child = + vtkOSPRayLightNode::SafeDownCast(it->GetCurrentObject()); + if (child) + { + child->Traverse(operation); + } + it->GoToNextItem(); + } + OSPData lightArray = ospNewData(this->Lights.size(), OSP_OBJECT, + (this->Lights.size()?&this->Lights[0]:NULL), 0); + ospSetData(oRenderer, "lights", lightArray); + + //actors + OSPModel oModel=NULL; + it->InitTraversal(); + //since we have to spatially sort everything + //let's see if we can avoid that in the common case when + //the objects have not changed. Note we also cache in actornodes + //to reuse already created ospray meshes + unsigned int recent = 0; + int numAct = 0; //catches removed actors + while (!it->IsDoneWithTraversal()) + { + vtkOSPRayActorNode *child = + vtkOSPRayActorNode::SafeDownCast(it->GetCurrentObject()); + if (child) + { + numAct++; + unsigned int mtime = child->GetMTime(); + if (mtime > recent) + { + recent = mtime; + } + } + it->GoToNextItem(); + } + + bool enable_cache = true; //turn off to force rebuilds for debugging + if (!this->OModel || + !enable_cache || + (recent > this->RenderTime) || + (numAct != this->NumActors)) + { + this->NumActors = numAct; + ospRelease((OSPModel)this->OModel); + oModel = ospNewModel(); + this->OModel = oModel; + it->InitTraversal(); + while (!it->IsDoneWithTraversal()) + { + vtkOSPRayActorNode *child = + vtkOSPRayActorNode::SafeDownCast(it->GetCurrentObject()); + if (child) + { + child->Traverse(operation); + } + it->GoToNextItem(); + } + this->RenderTime = recent; + ospSetObject(oRenderer,"model", oModel); + ospCommit(oModel); + } + else + { + oModel = (OSPModel)this->OModel; + } + it->Delete(); + + this->Apply(operation,false); +} + +//---------------------------------------------------------------------------- +void vtkOSPRayRendererNode::Build(bool prepass) +{ + if (prepass) + { + vtkRenderer *aren = vtkRenderer::SafeDownCast(this->Renderable); + // make sure we have a camera + if ( !aren->IsActiveCameraCreated() ) + { + aren->ResetCamera(); + } + } + this->Superclass::Build(prepass); +} + +//---------------------------------------------------------------------------- +void vtkOSPRayRendererNode::Render(bool prepass) +{ + if (prepass) + { + OSPRenderer oRenderer = NULL; + if (!this->ORenderer) + { + ospRelease((osp::Renderer*)this->ORenderer); + oRenderer = (osp::Renderer*)ospNewRenderer("scivis"); + this->ORenderer = oRenderer; + } + else + { + oRenderer = (osp::Renderer*)this->ORenderer; + } + + vtkRenderer *ren = vtkRenderer::SafeDownCast(this->GetRenderable()); + int *tmp = ren->GetSize(); + this->Size[0] = tmp[0]; + this->Size[1] = tmp[1]; + if (ren->GetUseShadows()) + { + ospSet1i(oRenderer,"shadowsEnabled",1); + } + else + { + ospSet1i(oRenderer,"shadowsEnabled",0); + } + ospSet1i(oRenderer,"aoSamples", + this->GetAmbientSamples(static_cast(this->Renderable))); + ospSet1i(oRenderer,"spp", + this->GetSamplesPerPixel(static_cast(this->Renderable))); + + double *bg = ren->GetBackground(); + ospSet3f(oRenderer,"bgColor", bg[0], bg[1], bg[2]); + } + else + { + OSPRenderer oRenderer = (osp::Renderer*)this->ORenderer; + ospCommit(oRenderer); + + osp::vec2i isize = {this->Size[0], this->Size[1]}; + OSPFrameBuffer osp_framebuffer = ospNewFrameBuffer + (isize, + #if OSPRAY_VERSION_MAJOR < 1 && OSPRAY_VERSION_MINOR < 10 && OSPRAY_VERSION_PATCH < 2 + OSP_RGBA_I8, OSP_FB_COLOR | OSP_FB_DEPTH | OSP_FB_ACCUM); + #else + OSP_FB_RGBA8, OSP_FB_COLOR | OSP_FB_DEPTH | OSP_FB_ACCUM); + #endif + ospSet1f(osp_framebuffer, "gamma", 1.0f); + ospCommit(osp_framebuffer); + ospFrameBufferClear(osp_framebuffer, OSP_FB_COLOR|OSP_FB_DEPTH|OSP_FB_ACCUM); + for (int i = 0; i < this->GetMaxFrames(static_cast(this->Renderable)); i++) + { + ospRenderFrame(osp_framebuffer, oRenderer, + OSP_FB_COLOR|OSP_FB_DEPTH|OSP_FB_ACCUM); + } + const void* rgba = ospMapFrameBuffer(osp_framebuffer, OSP_FB_COLOR); + delete[] this->Buffer; + this->Buffer = new unsigned char[this->Size[0]*this->Size[1]*4]; + memcpy((void*)this->Buffer, rgba, this->Size[0]*this->Size[1]*sizeof(char)*4); + ospUnmapFrameBuffer(rgba, osp_framebuffer); + + vtkCamera *cam = vtkRenderer::SafeDownCast(this->Renderable)-> + GetActiveCamera(); + double *clipValues = cam->GetClippingRange(); + double clipMin = clipValues[0]; + double clipMax = clipValues[1]; + double clipDiv = 1.0 / (clipMax - clipMin); + + const void *Z = ospMapFrameBuffer(osp_framebuffer, OSP_FB_DEPTH); + delete[] this->ZBuffer; + this->ZBuffer = new float[this->Size[0]*this->Size[1]]; + float *s = (float *)Z; + float *d = this->ZBuffer; + /* + float minS = 1000.0; + float maxS = -1000.0; + float minD = 1000.0; + float maxD = -10000.0; + */ + for (int i = 0; i < (this->Size[0]*this->Size[1]); i++, s++, d++) + { + *d = (*s maxD) maxD = *d; + if (*s < minS) minS = *s; + if (*s > maxS) maxS = *s; + */ + } + /* + cerr << "CmM" << clipMin << "," << clipMax << "\t"; + cerr << "SmM " << minS << "," << maxS << "\t"; + cerr << "DmM " << minD << "," << maxD << endl; + */ + ospUnmapFrameBuffer(Z, osp_framebuffer); + + ospRelease(osp_framebuffer); + } +} + +//---------------------------------------------------------------------------- +void vtkOSPRayRendererNode::WriteLayer(unsigned char *buffer, float *Z, + int buffx, int buffy, int layer) +{ + if (layer == 0) + { + for (int j = 0; j < buffy && j < this->Size[1]; j++) + { + unsigned char *iptr = this->Buffer + j*this->Size[0]*4; + float *zptr = this->ZBuffer + j*this->Size[0]; + unsigned char *optr = buffer + j*buffx*4; + float *ozptr = Z + j*buffx; + for (int i = 0; i < buffx && i < this->Size[0]; i++) + { + *optr++ = *iptr++; + *optr++ = *iptr++; + *optr++ = *iptr++; + *optr++ = *iptr++; + *ozptr++ = *zptr; + zptr++; + } + } + } + else + { + for (int j = 0; j < buffy && j < this->Size[1]; j++) + { + unsigned char *iptr = this->Buffer + j*this->Size[0]*4; + float *zptr = this->ZBuffer + j*this->Size[0]; + unsigned char *optr = buffer + j*buffx*4; + float *ozptr = Z + j*buffx; + for (int i = 0; i < buffx && i < this->Size[0]; i++) + { + if (*zptr<1.0) + { + *optr++ = *iptr++; + *optr++ = *iptr++; + *optr++ = *iptr++; + *optr++ = *iptr++; + *ozptr = *zptr; + } + else + { + optr+=4; + iptr+=4; + } + ozptr++; + zptr++; + } + } + } +} diff --git a/Rendering/OSPRay/vtkOSPRayRendererNode.h b/Rendering/OSPRay/vtkOSPRayRendererNode.h new file mode 100644 index 00000000000..25963d3e96b --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayRendererNode.h @@ -0,0 +1,130 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayRendererNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkOSPRayRendererNode - links vtkRenderers to OSPRay +// .SECTION Description +// Translates vtkRenderer state into OSPRay rendering calls + +#ifndef vtkOSPRayRendererNode_h +#define vtkOSPRayRendererNode_h + +#include "vtkRenderingOSPRayModule.h" // For export macro +#include "vtkRendererNode.h" + +#include // for ivars + +class vtkRenderer; +class vtkInformationIntegerKey; +// ospray forward decs so that someone does not need to include ospray.h +namespace osp { +struct Model; +struct Renderer; +struct Light; +} +typedef osp::Model *OSPModel; +typedef osp::Renderer *OSPRenderer; +typedef osp::Light *OSPLight; + +class VTKRENDERINGOSPRAY_EXPORT vtkOSPRayRendererNode : + public vtkRendererNode +{ +public: + static vtkOSPRayRendererNode* New(); + vtkTypeMacro(vtkOSPRayRendererNode, vtkRendererNode); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //Builds myself. + virtual void Build(bool prepass); + + //Description: + //Traverse graph in ospray's prefered order and render + virtual void Render(bool prepass); + + //Description: + //Put my results into the correct place in the provided pixel buffer. + virtual void WriteLayer(unsigned char *buffer, float *zbuffer, + int buffx, int buffy, int layer); + + //state beyond rendering core... + + //Description: + //When present on renderer, controls the number of primary rays + //shot per pixel + //default is 1 + static vtkInformationIntegerKey* SAMPLES_PER_PIXEL(); + + //Description: + //Convenience method to set/get SAMPLES_PER_PIXEL on a vtkRenderer. + static void SetSamplesPerPixel(int, vtkRenderer *renderer); + static int GetSamplesPerPixel(vtkRenderer *renderer); + + //Description: + //When present on renderer, controls the number of ospray render calls + //for each refresh. + //default is 1 + static vtkInformationIntegerKey* MAX_FRAMES(); + static void SetMaxFrames(int, vtkRenderer *renderer); + static int GetMaxFrames(vtkRenderer *renderer); + + //Description: + //When present on renderer, controls the number of ambient occlusion + //samples shot per hit. + //default is 4 + static vtkInformationIntegerKey* AMBIENT_SAMPLES(); + //Description: + //Convenience method to set/get SAMPLES_PER_PIXEL on a vtkRenderer. + static void SetAmbientSamples(int, vtkRenderer *renderer); + static int GetAmbientSamples(vtkRenderer *renderer); + + // Description: + // Methods for other nodes to access + OSPModel GetOModel() { return this->OModel; } + OSPRenderer GetORenderer() { return this->ORenderer; } + void AddLight(OSPLight light) { + this->Lights.push_back(light); } + + // Description: + // Get the last rendered ColorBuffer + virtual unsigned char *GetBuffer() { + return this->Buffer; } + + // Description: + // Get the last rendered ZBuffer + virtual float *GetZBuffer() { + return this->ZBuffer; } + + // if you want to traverse your children in a specific order + // or way override this method + virtual void Traverse(int operation); + +protected: + vtkOSPRayRendererNode(); + ~vtkOSPRayRendererNode(); + + //internal structures + unsigned char *Buffer; + float *ZBuffer; + + OSPModel OModel; + OSPRenderer ORenderer; + std::vector Lights; + + int NumActors; +private: + vtkOSPRayRendererNode(const vtkOSPRayRendererNode&); // Not implemented. + void operator=(const vtkOSPRayRendererNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/OSPRay/vtkOSPRayViewNodeFactory.cxx b/Rendering/OSPRay/vtkOSPRayViewNodeFactory.cxx new file mode 100644 index 00000000000..12e74ada6e1 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayViewNodeFactory.cxx @@ -0,0 +1,87 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayViewNodeFactory.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkOSPRayViewNodeFactory.h" +#include "vtkObjectFactory.h" + +#include "vtkOSPRayActorNode.h" +#include "vtkOSPRayCameraNode.h" +#include "vtkOSPRayCompositePolyDataMapper2Node.h" +#include "vtkOSPRayLightNode.h" +#include "vtkOSPRayRendererNode.h" +#include "vtkOSPRayPolyDataMapperNode.h" + +vtkViewNode *ren_maker() +{ + vtkOSPRayRendererNode *vn = vtkOSPRayRendererNode::New(); + return vn; +} + +vtkViewNode *act_maker() +{ + vtkOSPRayActorNode *vn = vtkOSPRayActorNode::New(); + return vn; +} + +vtkViewNode *cam_maker() +{ + vtkOSPRayCameraNode *vn = vtkOSPRayCameraNode::New(); + return vn; +} + +vtkViewNode *light_maker() +{ + vtkOSPRayLightNode *vn = vtkOSPRayLightNode::New(); + return vn; +} + +vtkViewNode *pd_maker() +{ + vtkOSPRayPolyDataMapperNode *vn = vtkOSPRayPolyDataMapperNode::New(); + return vn; +} + +vtkViewNode *cpd_maker() +{ + vtkOSPRayCompositePolyDataMapper2Node *vn = vtkOSPRayCompositePolyDataMapper2Node::New(); + return vn; +} + +//============================================================================ +vtkStandardNewMacro(vtkOSPRayViewNodeFactory); + +//---------------------------------------------------------------------------- +vtkOSPRayViewNodeFactory::vtkOSPRayViewNodeFactory() +{ + //see vtkRenderWindow::GetRenderLibrary + this->RegisterOverride("vtkOpenGLRenderer", ren_maker); + this->RegisterOverride("vtkOpenGLActor", act_maker); + this->RegisterOverride("vtkPVLODActor", act_maker); + this->RegisterOverride("vtkOpenGLCamera", cam_maker); + this->RegisterOverride("vtkOpenGLLight", light_maker); + this->RegisterOverride("vtkPainterPolyDataMapper", pd_maker); + this->RegisterOverride("vtkOpenGLPolyDataMapper", pd_maker); + this->RegisterOverride("vtkCompositePolyDataMapper2", cpd_maker); +} + +//---------------------------------------------------------------------------- +vtkOSPRayViewNodeFactory::~vtkOSPRayViewNodeFactory() +{ +} + +//---------------------------------------------------------------------------- +void vtkOSPRayViewNodeFactory::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/Rendering/OSPRay/vtkOSPRayViewNodeFactory.h b/Rendering/OSPRay/vtkOSPRayViewNodeFactory.h new file mode 100644 index 00000000000..308ae385983 --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayViewNodeFactory.h @@ -0,0 +1,44 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayViewNodeFactory.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkOSPRayViewNodeFactory - matches vtk rendering classes to +// specific ospray ViewNode classes +// .SECTION Description +// Ensures that vtkOSPRayPass makes ospray specific translator instances +// for every VTK rendering pipeline class instance it encounters. + +#ifndef vtkOSPRayViewNodeFactory_h +#define vtkOSPRayViewNodeFactory_h + +#include "vtkRenderingOSPRayModule.h" // For export macro +#include "vtkViewNodeFactory.h" + +class VTKRENDERINGOSPRAY_EXPORT vtkOSPRayViewNodeFactory : + public vtkViewNodeFactory +{ +public: + static vtkOSPRayViewNodeFactory* New(); + vtkTypeMacro(vtkOSPRayViewNodeFactory, vtkViewNodeFactory); + void PrintSelf(ostream& os, vtkIndent indent); + +protected: + vtkOSPRayViewNodeFactory(); + ~vtkOSPRayViewNodeFactory(); + +private: + vtkOSPRayViewNodeFactory(const vtkOSPRayViewNodeFactory&); // Not implemented. + void operator=(const vtkOSPRayViewNodeFactory&); // Not implemented. +}; + +#endif diff --git a/Rendering/OSPRay/vtkOSPRayWindowNode.cxx b/Rendering/OSPRay/vtkOSPRayWindowNode.cxx new file mode 100644 index 00000000000..f9db02ac1fd --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayWindowNode.cxx @@ -0,0 +1,104 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayWindowNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkOSPRayWindowNode.h" + +#include "vtkCollectionIterator.h" +#include "vtkFloatArray.h" +#include "vtkObjectFactory.h" +#include "vtkOSPRayRendererNode.h" +#include "vtkOSPRayViewNodeFactory.h" +#include "vtkRendererCollection.h" +#include "vtkRenderWindow.h" +#include "vtkUnsignedCharArray.h" +#include "vtkViewNodeCollection.h" + +#include "ospray/ospray.h" +#include + +//============================================================================ +vtkStandardNewMacro(vtkOSPRayWindowNode); + +//---------------------------------------------------------------------------- +vtkOSPRayWindowNode::vtkOSPRayWindowNode() +{ + int ac = 1; + const char* av[] = {"pvOSPRay\0"}; + try + { + ospInit(&ac, av); + } + catch (std::runtime_error &vtkNotUsed(e)) + { + //todo: request addition of ospFinalize() to ospray + //cerr << "warning: double init" << endl; + } + vtkOSPRayViewNodeFactory *fac = vtkOSPRayViewNodeFactory::New(); + this->SetMyFactory(fac); + fac->Delete(); +} + +//---------------------------------------------------------------------------- +vtkOSPRayWindowNode::~vtkOSPRayWindowNode() +{ +} + +//---------------------------------------------------------------------------- +void vtkOSPRayWindowNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +void vtkOSPRayWindowNode::Render(bool prepass) +{ + if (!prepass) + { + //composite all renderers framebuffers together + this->ColorBuffer->SetNumberOfComponents(4); + this->ColorBuffer->SetNumberOfTuples(this->Size[0]*this->Size[1]); + unsigned char *rgba = static_cast + (this->ColorBuffer->GetVoidPointer(0)); + + this->ZBuffer->SetNumberOfComponents(1); + this->ZBuffer->SetNumberOfTuples(this->Size[0]*this->Size[1]); + float *z = static_cast + (this->ZBuffer->GetVoidPointer(0)); + + vtkViewNodeCollection *renderers = this->GetChildren(); + vtkCollectionIterator *it = renderers->NewIterator(); + it->InitTraversal(); + + int layer = 0; + int count = 0; + while (count < renderers->GetNumberOfItems()) + { + it->InitTraversal(); + while (!it->IsDoneWithTraversal()) + { + vtkOSPRayRendererNode *child = + vtkOSPRayRendererNode::SafeDownCast(it->GetCurrentObject()); + vtkRenderer *ren = vtkRenderer::SafeDownCast(child->GetRenderable()); + if (ren->GetLayer() == layer) + { + child->WriteLayer(rgba, z, this->Size[0], this->Size[1], layer); + count++; + } + it->GoToNextItem(); + } + layer++; + } + it->Delete(); + } +} diff --git a/Rendering/OSPRay/vtkOSPRayWindowNode.h b/Rendering/OSPRay/vtkOSPRayWindowNode.h new file mode 100644 index 00000000000..5cb72130e3e --- /dev/null +++ b/Rendering/OSPRay/vtkOSPRayWindowNode.h @@ -0,0 +1,46 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOSPRayWindowNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkOSPRayWindowNode - links vtkRendererWindows to OSPRay +// .SECTION Description +// Translates vtkRenderWindow state into OSPRay rendering calls + +#ifndef vtkOSPRayWindowNode_h +#define vtkOSPRayWindowNode_h + +#include "vtkRenderingOSPRayModule.h" // For export macro +#include "vtkWindowNode.h" + +class VTKRENDERINGOSPRAY_EXPORT vtkOSPRayWindowNode : + public vtkWindowNode +{ +public: + static vtkOSPRayWindowNode* New(); + vtkTypeMacro(vtkOSPRayWindowNode, vtkWindowNode); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //Make ospray calls to render me. + virtual void Render(bool prepass); + +protected: + vtkOSPRayWindowNode(); + ~vtkOSPRayWindowNode(); + +private: + vtkOSPRayWindowNode(const vtkOSPRayWindowNode&); // Not implemented. + void operator=(const vtkOSPRayWindowNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/OpenGL/CMakeLists.txt b/Rendering/OpenGL/CMakeLists.txt index f1faf2223a0..14d284abab7 100644 --- a/Rendering/OpenGL/CMakeLists.txt +++ b/Rendering/OpenGL/CMakeLists.txt @@ -77,9 +77,7 @@ set(Module_SRCS vtkPolyDataPainter.cxx vtkPolygonsPainter.cxx vtkPrimitivePainter.cxx - vtkRenderPass.cxx vtkRenderPassCollection.cxx - vtkRenderState.cxx vtkRenderbuffer.cxx vtkRepresentationPainter.cxx vtkScalarsToColorsPainter.cxx @@ -138,8 +136,6 @@ set(${vtk-module}_HDRS set_source_files_properties( vtkImageProcessingPass vtkOpenGLRenderWindow - vtkRenderPass - vtkRenderState vtkPainter vtkPolyDataPainter vtkPrimitivePainter @@ -148,7 +144,6 @@ set_source_files_properties( set_source_files_properties( vtkLightingHelper - vtkRenderState vtkOpenGLState vtkOpenGLGL2PSHelper vtkShader2 diff --git a/Rendering/OpenGL/Testing/Cxx/TestRenderToImage.cxx b/Rendering/OpenGL/Testing/Cxx/TestRenderToImage.cxx index 7511aa2e700..1b60aedf775 100644 --- a/Rendering/OpenGL/Testing/Cxx/TestRenderToImage.cxx +++ b/Rendering/OpenGL/Testing/Cxx/TestRenderToImage.cxx @@ -62,7 +62,7 @@ int TestRenderToImage(int argc, char* argv[]) image->SetDimensions(size[0], size[1], 1); image->AllocateScalars(VTK_UNSIGNED_CHAR, 3); renderWindow->GetPixelData(0, 0, size[0] - 1, size[1] - 1, 0, - vtkUnsignedCharArray::SafeDownCast(image->GetPointData()->GetScalars())); + vtkArrayDownCast(image->GetPointData()->GetScalars())); glRenderWindow->SetUseOffScreenBuffers(false); // Now add the actor @@ -74,7 +74,7 @@ int TestRenderToImage(int argc, char* argv[]) renderWindow->Render(); // Capture the framebuffer to the image, again renderWindow->GetPixelData(0, 0, size[0]-1, size[1]-1, 0, - vtkUnsignedCharArray::SafeDownCast(image->GetPointData()->GetScalars())); + vtkArrayDownCast(image->GetPointData()->GetScalars())); glRenderWindow->SetUseOffScreenBuffers(false); // Create a new image actor and remove the geometry one diff --git a/Rendering/OpenGL/Testing/Cxx/TestValuePainter.cxx b/Rendering/OpenGL/Testing/Cxx/TestValuePainter.cxx index 403fe883d43..dc493b459f9 100644 --- a/Rendering/OpenGL/Testing/Cxx/TestValuePainter.cxx +++ b/Rendering/OpenGL/Testing/Cxx/TestValuePainter.cxx @@ -254,7 +254,7 @@ int TestValuePainter(int argc, char* argv[]) vtkImageData *id = grabber->GetOutput(); //id->PrintSelf(cerr, vtkIndent(0)); - vtkUnsignedCharArray *ar = vtkUnsignedCharArray::SafeDownCast(id->GetPointData()->GetArray("ImageScalars")); + vtkUnsignedCharArray *ar = vtkArrayDownCast(id->GetPointData()->GetArray("ImageScalars")); unsigned char *ptr = static_cast(ar->GetVoidPointer(0)); std::set found; double value; diff --git a/Rendering/OpenGL/vtkCameraPass.cxx b/Rendering/OpenGL/vtkCameraPass.cxx index fb5aabc1489..0a58507f427 100644 --- a/Rendering/OpenGL/vtkCameraPass.cxx +++ b/Rendering/OpenGL/vtkCameraPass.cxx @@ -23,7 +23,7 @@ #include "vtkMatrix4x4.h" #include "vtkgluPickMatrix.h" #include "vtkCamera.h" -#include "vtkFrameBufferObject.h" +#include "vtkFrameBufferObjectBase.h" #include "vtkOpenGLError.h" vtkStandardNewMacro(vtkCameraPass); @@ -108,7 +108,7 @@ void vtkCameraPass::Render(const vtkRenderState *s) int vsize; vtkMatrix4x4 *matrix=vtkMatrix4x4::New(); - vtkFrameBufferObject *fbo=s->GetFrameBuffer(); + vtkFrameBufferObjectBase *fbo=s->GetFrameBuffer(); if(fbo==0) { diff --git a/Rendering/OpenGL/vtkCameraPass.h b/Rendering/OpenGL/vtkCameraPass.h index 203267199ec..e74a5f3428b 100644 --- a/Rendering/OpenGL/vtkCameraPass.h +++ b/Rendering/OpenGL/vtkCameraPass.h @@ -39,12 +39,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkCameraPass : public vtkRenderPass vtkTypeMacro(vtkCameraPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL/vtkChooserPainter.cxx b/Rendering/OpenGL/vtkChooserPainter.cxx index 30dc45ddb1d..79c9da5a3fa 100644 --- a/Rendering/OpenGL/vtkChooserPainter.cxx +++ b/Rendering/OpenGL/vtkChooserPainter.cxx @@ -44,14 +44,6 @@ vtkChooserPainter::vtkChooserPainter() this->PolyPainter = NULL; this->StripPainter = NULL; this->LastRenderer = NULL; - this->UseLinesPainterForWireframes = 0; -#if defined(__APPLE__) && defined(VTK_USE_COCOA) - /* - * On some Macs, glPolygonMode(*,GL_LINE) does not render anything - * for polys. To fix this, we use the GL_LINE_LOOP to render the polygons. - */ -// this->UseLinesPainterForWireframes = 1; -#endif } //----------------------------------------------------------------------------- @@ -333,23 +325,9 @@ void vtkChooserPainter::RenderInternal(vtkRenderer* renderer, vtkActor* actor, { //cout << this << "Polys" << endl; this->ProgressScaleFactor = static_cast(numPolys)/total_cells; - if ( this->UseLinesPainterForWireframes - && (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME) - && !actor->GetProperty()->GetBackfaceCulling() - && !actor->GetProperty()->GetFrontfaceCulling() - && !this->GetInputAsPolyData()->GetPointData()->GetAttribute( - vtkDataSetAttributes::EDGEFLAG) ) - { - this->LinePainter->Render(renderer, actor, vtkPainter::POLYS, - forceCompileOnly); - this->TimeToDraw += this->LinePainter->GetTimeToDraw(); - } - else - { - this->PolyPainter->Render(renderer, actor, vtkPainter::POLYS, - forceCompileOnly); - this->TimeToDraw += this->PolyPainter->GetTimeToDraw(); - } + this->PolyPainter->Render(renderer, actor, vtkPainter::POLYS, + forceCompileOnly); + this->TimeToDraw += this->PolyPainter->GetTimeToDraw(); this->ProgressOffset += this->ProgressScaleFactor; } @@ -373,6 +351,4 @@ void vtkChooserPainter::PrintSelf(ostream &os, vtkIndent indent) os << indent << "LinePainter: " << this->LinePainter << endl; os << indent << "PolyPainter: " << this->PolyPainter << endl; os << indent << "StripPainter: " << this->StripPainter << endl; - os << indent << "UseLinesPainterForWireframes: " - << this->UseLinesPainterForWireframes << endl; } diff --git a/Rendering/OpenGL/vtkChooserPainter.h b/Rendering/OpenGL/vtkChooserPainter.h index b3dddef06e6..8c126a26e38 100644 --- a/Rendering/OpenGL/vtkChooserPainter.h +++ b/Rendering/OpenGL/vtkChooserPainter.h @@ -41,13 +41,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkChooserPainter : public vtkPolyDataPainter void SetPolyPainter(vtkPolyDataPainter*); void SetStripPainter(vtkPolyDataPainter*); - // Description: - // When set, the lines painter is used for drawing wireframes (off by - // default, except on Mac, where it's on by default). - vtkSetMacro(UseLinesPainterForWireframes, int); - vtkGetMacro(UseLinesPainterForWireframes, int); - vtkBooleanMacro(UseLinesPainterForWireframes, int); - // Description: // Release any graphics resources that are being consumed by this mapper. // The parameter window could be used to determine which graphic @@ -111,7 +104,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkChooserPainter : public vtkPolyDataPainter vtkRenderer *LastRenderer; vtkTimeStamp PaintersChoiceTime; - int UseLinesPainterForWireframes; private: vtkChooserPainter(const vtkChooserPainter &); // Not implemented void operator=(const vtkChooserPainter &); // Not implemented diff --git a/Rendering/OpenGL/vtkClearZPass.h b/Rendering/OpenGL/vtkClearZPass.h index cfaeaee7f3f..6f76351f26a 100644 --- a/Rendering/OpenGL/vtkClearZPass.h +++ b/Rendering/OpenGL/vtkClearZPass.h @@ -34,12 +34,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkClearZPass : public vtkRenderPass vtkTypeMacro(vtkClearZPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Set/Get the depth value. Initial value is 1.0 (farest). diff --git a/Rendering/OpenGL/vtkCocoaMacOSXSDKCompatibility.h b/Rendering/OpenGL/vtkCocoaMacOSXSDKCompatibility.h index 864c5b4ac62..2e9bb9de8c5 100644 --- a/Rendering/OpenGL/vtkCocoaMacOSXSDKCompatibility.h +++ b/Rendering/OpenGL/vtkCocoaMacOSXSDKCompatibility.h @@ -25,8 +25,8 @@ PURPOSE. See the above copyright notice for more information. #error VTK requires the Mac OS X 10.6 SDK or later #endif -#if MAC_OS_X_VERSION_MIN_REQUIRED < 1060 - #error VTK requires a deployment target of Mac OS X 10.6 or later +#if MAC_OS_X_VERSION_MIN_REQUIRED < 1068 + #error VTK requires a deployment target of Mac OS X 10.6.8 or later #endif // __has_feature is new in the 10.7 SDK, define it here if it's not yet defined. diff --git a/Rendering/OpenGL/vtkCocoaRenderWindow.mm b/Rendering/OpenGL/vtkCocoaRenderWindow.mm index e2aab89cb15..4f444989fb1 100644 --- a/Rendering/OpenGL/vtkCocoaRenderWindow.mm +++ b/Rendering/OpenGL/vtkCocoaRenderWindow.mm @@ -737,7 +737,6 @@ - (void)viewFrameDidChange:(NSNotification *)aNotification NSWindow* theWindow = nil; -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 NSScreen *screen = [NSScreen mainScreen]; if (this->FullScreen && screen) { @@ -757,7 +756,6 @@ - (void)viewFrameDidChange:(NSNotification *)aNotification //[theWindow setLevel:NSFloatingWindowLevel]; } else -#endif { if ((this->Size[0]+this->Size[1]) == 0) { diff --git a/Rendering/OpenGL/vtkColorMaterialHelper.h b/Rendering/OpenGL/vtkColorMaterialHelper.h index fad6a647186..283d803ab64 100644 --- a/Rendering/OpenGL/vtkColorMaterialHelper.h +++ b/Rendering/OpenGL/vtkColorMaterialHelper.h @@ -38,10 +38,8 @@ class VTKRENDERINGOPENGL_EXPORT vtkColorMaterialHelper : public vtkObject vtkTypeMacro(vtkColorMaterialHelper, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); - //BTX void Initialize(vtkShaderProgram2*); vtkGetObjectMacro(Shader, vtkShaderProgram2); - //ETX // Description: // Capture current OpenGL state and initialize uniform variables @@ -60,7 +58,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkColorMaterialHelper : public vtkObject // DEPRECATED: Use SetUnformVariables instead. void Render(); -//BTX protected: vtkColorMaterialHelper(); ~vtkColorMaterialHelper(); @@ -82,7 +79,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkColorMaterialHelper : public vtkObject private: vtkColorMaterialHelper(const vtkColorMaterialHelper&); // Not implemented. void operator=(const vtkColorMaterialHelper&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkCompositePainter.h b/Rendering/OpenGL/vtkCompositePainter.h index e27f7392f92..219491eff5f 100644 --- a/Rendering/OpenGL/vtkCompositePainter.h +++ b/Rendering/OpenGL/vtkCompositePainter.h @@ -56,7 +56,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkCompositePainter : public vtkPainter void SetCompositeDataDisplayAttributes(vtkCompositeDataDisplayAttributes *attributes); vtkGetObjectMacro(CompositeDataDisplayAttributes, vtkCompositeDataDisplayAttributes) -//BTX protected: vtkCompositePainter(); ~vtkCompositePainter(); @@ -112,7 +111,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkCompositePainter : public vtkPainter private: vtkCompositePainter(const vtkCompositePainter&); // Not implemented. void operator=(const vtkCompositePainter&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkCompositePolyDataMapper2.h b/Rendering/OpenGL/vtkCompositePolyDataMapper2.h index 5eb04246e16..11f2bce32e3 100644 --- a/Rendering/OpenGL/vtkCompositePolyDataMapper2.h +++ b/Rendering/OpenGL/vtkCompositePolyDataMapper2.h @@ -77,7 +77,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkCompositePolyDataMapper2 : public vtkPainterP void RemoveBlockOpacity(unsigned int index); void RemoveBlockOpacities(); -//BTX protected: vtkCompositePolyDataMapper2(); ~vtkCompositePolyDataMapper2(); @@ -118,7 +117,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkCompositePolyDataMapper2 : public vtkPainterP private: vtkCompositePolyDataMapper2(const vtkCompositePolyDataMapper2&); // Not implemented. void operator=(const vtkCompositePolyDataMapper2&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkDataTransferHelper.cxx b/Rendering/OpenGL/vtkDataTransferHelper.cxx index 77a96641b8e..24b5f7d0dc8 100644 --- a/Rendering/OpenGL/vtkDataTransferHelper.cxx +++ b/Rendering/OpenGL/vtkDataTransferHelper.cxx @@ -165,7 +165,6 @@ void vtkDataTransferHelper::SetContext(vtkRenderWindow* renWin) // \pre valid_gpu_extent: this->GetGPUExtentIsValid() // \pre gpu_extent_in_cpu_extent: CPUExtent[0]<=GPUExtent[0] && GPUExtent[1]<=CPUExtent[1] && CPUExtent[2]<=GPUExtent[2] && GPUExtent[3]<=CPUExtent[3] && CPUExtent[4]<=GPUExtent[4] && GPUExtent[5]<=CPUExtent[5] // \pre gpu_texture_size: !this->GetTextureExtentIsValid() || (GPUExtent[1]-GPUExtent[0]+1)*(GPUExtent[3]-GPUExtent[2]+1)*(GPUExtent[5]-GPUExtent[4]+1)==(TextureExtent[1]-TextureExtent[0]+1)*(TextureExtent[3]-TextureExtent[2]+1)*(TextureExtent[5]-TextureExtent[4]+1) - // \pre texture_can_exist_or_not: texture==0 || texture!=0 // \pre valid_components: (components==0 && componentList==0 && array->GetNumberOfComponents()<=4) || (components>=1 && components<=array->GetNumberOfComponents() && components<=4 && componentList!=0) bool vtkDataTransferHelper::Upload(int components, int *componentList) @@ -194,8 +193,6 @@ bool vtkDataTransferHelper::Upload(int components, (this->TextureExtent[1]-this->TextureExtent[0]+1)* (this->TextureExtent[3]-this->TextureExtent[2]+1)* (this->TextureExtent[5]-this->TextureExtent[4]+1)))); - assert("pre: texture_can_exist_or_not" && (this->Texture==0 || - this->Texture!=0)); assert("pre: valid_components" && ((components==0 && componentList==0 && this->Array->GetNumberOfComponents()<=4) || @@ -460,8 +457,6 @@ bool vtkDataTransferHelper::DownloadAsync1() (this->TextureExtent[1]-this->TextureExtent[0]+1)* (this->TextureExtent[3]-this->TextureExtent[2]+1)* (this->TextureExtent[5]-this->TextureExtent[4]+1)))); - assert("pre: texture_can_exist_or_not" && (this->Texture==0 || - this->Texture!=0)); assert("pre: valid_components" && (this->Array==0 || this->Array->GetNumberOfComponents()<=4)); assert("pre: components_match" && (this->Array==0 || diff --git a/Rendering/OpenGL/vtkDataTransferHelper.h b/Rendering/OpenGL/vtkDataTransferHelper.h index e932810b40b..345f929697f 100644 --- a/Rendering/OpenGL/vtkDataTransferHelper.h +++ b/Rendering/OpenGL/vtkDataTransferHelper.h @@ -187,7 +187,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkDataTransferHelper : public vtkObject // Description: // Returns if the context supports the required extensions. static bool IsSupported(vtkRenderWindow* renWin); -//BTX + protected: vtkDataTransferHelper(); ~vtkDataTransferHelper(); @@ -215,7 +215,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkDataTransferHelper : public vtkObject private: vtkDataTransferHelper(const vtkDataTransferHelper&); // Not implemented. void operator=(const vtkDataTransferHelper&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkDefaultPass.h b/Rendering/OpenGL/vtkDefaultPass.h index b302cb99e99..90bbbaa1747 100644 --- a/Rendering/OpenGL/vtkDefaultPass.h +++ b/Rendering/OpenGL/vtkDefaultPass.h @@ -44,14 +44,12 @@ class VTKRENDERINGOPENGL_EXPORT vtkDefaultPass : public vtkRenderPass vtkTypeMacro(vtkDefaultPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // Call RenderOpaqueGeometry(), RenderTranslucentPolygonalGeometry(), // RenderVolumetricGeometry(), RenderOverlay() // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL/vtkDepthPeelingPass.cxx b/Rendering/OpenGL/vtkDepthPeelingPass.cxx index 59d570d06b3..9996e939f76 100644 --- a/Rendering/OpenGL/vtkDepthPeelingPass.cxx +++ b/Rendering/OpenGL/vtkDepthPeelingPass.cxx @@ -605,7 +605,7 @@ void vtkDepthPeelingPass::CheckSupport(vtkOpenGLRenderWindow *w) // os mesa 9.1.4 some tests fail // ATI Radeon HD XXXXX on Windows chokes on PROXY_TEXTURE_RECTANGLE_ARB // memory querries however if those are not used all the tests pass. - // ATI Radeon HD on Mac OSX PROXY_TEXTURE_RECTANGLE_ARB are fine but + // ATI Radeon HD on Mac OS X PROXY_TEXTURE_RECTANGLE_ARB are fine but // TestTranslucentLUTDepthPeeling fails. So leave it disabled on Apple int driver_support = (!(extensions->DriverIsATI() diff --git a/Rendering/OpenGL/vtkDepthPeelingPass.h b/Rendering/OpenGL/vtkDepthPeelingPass.h index af8ec5cc51a..6ef3acb40ad 100644 --- a/Rendering/OpenGL/vtkDepthPeelingPass.h +++ b/Rendering/OpenGL/vtkDepthPeelingPass.h @@ -51,12 +51,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkDepthPeelingPass : public vtkRenderPass vtkTypeMacro(vtkDepthPeelingPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL/vtkFrameBufferObject.h b/Rendering/OpenGL/vtkFrameBufferObject.h index 546b6acf92f..5b28c328d1a 100644 --- a/Rendering/OpenGL/vtkFrameBufferObject.h +++ b/Rendering/OpenGL/vtkFrameBufferObject.h @@ -25,13 +25,12 @@ #ifndef vtkFrameBufferObject_h #define vtkFrameBufferObject_h -#include "vtkObject.h" +#include "vtkFrameBufferObjectBase.h" #include "vtkRenderingOpenGLModule.h" // For export macro #include "vtkSmartPointer.h" // needed for vtkSmartPointer. #include "vtkWeakPointer.h" // needed for vtkWeakPointer. -//BTX + #include // for the lists of logical buffers. -//ETX class vtkRenderWindow; class vtkTextureObject; @@ -40,11 +39,11 @@ class vtkPixelBufferObject; class vtkOpenGLExtensionManager; class vtkOpenGLRenderWindow; -class VTKRENDERINGOPENGL_EXPORT vtkFrameBufferObject : public vtkObject +class VTKRENDERINGOPENGL_EXPORT vtkFrameBufferObject : public vtkFrameBufferObjectBase { public: static vtkFrameBufferObject* New(); - vtkTypeMacro(vtkFrameBufferObject, vtkObject); + vtkTypeMacro(vtkFrameBufferObject, vtkFrameBufferObjectBase); void PrintSelf(ostream& os, vtkIndent indent); // Description: @@ -167,7 +166,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkFrameBufferObject : public vtkObject // prints detected errors to vtkErrorMacro. int CheckFrameBufferStatus(unsigned int mode); -//BTX protected: // Description: // Load all necessary extensions. @@ -244,7 +242,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkFrameBufferObject : public vtkObject private: vtkFrameBufferObject(const vtkFrameBufferObject&); // Not implemented. void operator=(const vtkFrameBufferObject&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkFrameBufferObject2.h b/Rendering/OpenGL/vtkFrameBufferObject2.h index 7830d1dbb65..d31c114ffef 100644 --- a/Rendering/OpenGL/vtkFrameBufferObject2.h +++ b/Rendering/OpenGL/vtkFrameBufferObject2.h @@ -275,7 +275,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkFrameBufferObject2 : public vtkObject int oglFormat, vtkPixelBufferObject *pbo); -//BTX protected: // Description: // Load all necessary extensions. @@ -310,7 +309,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkFrameBufferObject2 : public vtkObject void operator=(const vtkFrameBufferObject2&); // Not implemented. friend class vtkRenderbuffer; // needs access to LoadRequiredExtentsions -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkGLSLShaderDeviceAdapter2.h b/Rendering/OpenGL/vtkGLSLShaderDeviceAdapter2.h index afb0333a213..8de3c2e4e9e 100644 --- a/Rendering/OpenGL/vtkGLSLShaderDeviceAdapter2.h +++ b/Rendering/OpenGL/vtkGLSLShaderDeviceAdapter2.h @@ -59,7 +59,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkGLSLShaderDeviceAdapter2 const void *attribute, unsigned long offset=0); -//BTX protected: vtkGLSLShaderDeviceAdapter2(); ~vtkGLSLShaderDeviceAdapter2(); @@ -74,7 +73,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkGLSLShaderDeviceAdapter2 class vtkInternal; vtkInternal* Internal; -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkGaussianBlurPass.h b/Rendering/OpenGL/vtkGaussianBlurPass.h index 911492da25a..cda2ee8863f 100644 --- a/Rendering/OpenGL/vtkGaussianBlurPass.h +++ b/Rendering/OpenGL/vtkGaussianBlurPass.h @@ -63,12 +63,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkGaussianBlurPass : public vtkImageProcessingP vtkTypeMacro(vtkGaussianBlurPass,vtkImageProcessingPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL/vtkHardwareSelectionPolyDataPainter.cxx b/Rendering/OpenGL/vtkHardwareSelectionPolyDataPainter.cxx index 955a8f412a9..9c2a86d7125 100644 --- a/Rendering/OpenGL/vtkHardwareSelectionPolyDataPainter.cxx +++ b/Rendering/OpenGL/vtkHardwareSelectionPolyDataPainter.cxx @@ -174,17 +174,17 @@ void vtkHardwareSelectionPolyDataPainter::DrawCells( vtkIdType npts, *pts; vtkIdType cellId = startCellId; vtkUnsignedIntArray* procIdsArray = this->ProcessIdArrayName? - vtkUnsignedIntArray::SafeDownCast( + vtkArrayDownCast( pd->GetPointData()->GetArray(this->ProcessIdArrayName)) : NULL; - vtkIdTypeArray* pidArray = this->PointIdArrayName? vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* pidArray = this->PointIdArrayName? vtkArrayDownCast( pd->GetPointData()->GetArray(this->PointIdArrayName)) : NULL; - vtkIdTypeArray* cidArray = this->CellIdArrayName? vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray* cidArray = this->CellIdArrayName? vtkArrayDownCast( pd->GetCellData()->GetArray(this->CellIdArrayName)) : NULL; vtkUnsignedIntArray* compositeIdArray = this->CompositeIdArrayName? - vtkUnsignedIntArray::SafeDownCast( + vtkArrayDownCast( pd->GetCellData()->GetArray(this->CompositeIdArrayName)) : NULL; int pointtype = p->GetDataType(); diff --git a/Rendering/OpenGL/vtkHardwareSelectionPolyDataPainter.h b/Rendering/OpenGL/vtkHardwareSelectionPolyDataPainter.h index 0eb1f7377e0..52ff87410bd 100644 --- a/Rendering/OpenGL/vtkHardwareSelectionPolyDataPainter.h +++ b/Rendering/OpenGL/vtkHardwareSelectionPolyDataPainter.h @@ -69,7 +69,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkHardwareSelectionPolyDataPainter : vtkSetStringMacro(CompositeIdArrayName); vtkGetStringMacro(CompositeIdArrayName); -//BTX protected: vtkHardwareSelectionPolyDataPainter(); ~vtkHardwareSelectionPolyDataPainter(); @@ -93,7 +92,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkHardwareSelectionPolyDataPainter : private: vtkHardwareSelectionPolyDataPainter(const vtkHardwareSelectionPolyDataPainter&); // Not implemented. void operator=(const vtkHardwareSelectionPolyDataPainter&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkLightingHelper.h b/Rendering/OpenGL/vtkLightingHelper.h index 317de431b68..90a29003db7 100644 --- a/Rendering/OpenGL/vtkLightingHelper.h +++ b/Rendering/OpenGL/vtkLightingHelper.h @@ -56,7 +56,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkLightingHelper : public vtkObject void EncodeLightState(){ this->PrepareForRendering(); } void PrepareForRendering(); -//BTX protected: vtkLightingHelper(); ~vtkLightingHelper(); @@ -67,7 +66,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkLightingHelper : public vtkObject private: vtkLightingHelper(const vtkLightingHelper&); // Not implemented. void operator=(const vtkLightingHelper&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkLightsPass.h b/Rendering/OpenGL/vtkLightsPass.h index 0f07105c9ba..6ea0e1e5eee 100644 --- a/Rendering/OpenGL/vtkLightsPass.h +++ b/Rendering/OpenGL/vtkLightsPass.h @@ -38,12 +38,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkLightsPass : public vtkRenderPass vtkTypeMacro(vtkLightsPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL/vtkOpaquePass.h b/Rendering/OpenGL/vtkOpaquePass.h index fc512a051b0..8e59264d72e 100644 --- a/Rendering/OpenGL/vtkOpaquePass.h +++ b/Rendering/OpenGL/vtkOpaquePass.h @@ -38,12 +38,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpaquePass : public vtkDefaultPass vtkTypeMacro(vtkOpaquePass,vtkDefaultPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL/vtkOpenGLDisplayListPainter.h b/Rendering/OpenGL/vtkOpenGLDisplayListPainter.h index 1dbc57e9f77..243553757d1 100644 --- a/Rendering/OpenGL/vtkOpenGLDisplayListPainter.h +++ b/Rendering/OpenGL/vtkOpenGLDisplayListPainter.h @@ -39,7 +39,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLDisplayListPainter : public vtkDisplayL virtual void ReleaseGraphicsResources(vtkWindow *); protected: -//BTX + vtkOpenGLDisplayListPainter(); ~vtkOpenGLDisplayListPainter(); @@ -56,7 +56,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLDisplayListPainter : public vtkDisplayL class vtkInternals; vtkInternals* Internals; -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkOpenGLExtensionManager.cxx b/Rendering/OpenGL/vtkOpenGLExtensionManager.cxx index 302ded28a7a..0d48943f1b3 100644 --- a/Rendering/OpenGL/vtkOpenGLExtensionManager.cxx +++ b/Rendering/OpenGL/vtkOpenGLExtensionManager.cxx @@ -870,7 +870,7 @@ void vtkOpenGLExtensionManager::ReadOpenGLExtensions() extensions_string += glu_extensions; } -#if defined(WIN32) +#if defined(_WIN32) // Don't use this->LoadExtension or we will go into an infinite loop. vtkgl::LoadExtension("WGL_ARB_extensions_string", this); if (vtkwgl::GetExtensionsStringARB) diff --git a/Rendering/OpenGL/vtkOpenGLExtensionManager.h b/Rendering/OpenGL/vtkOpenGLExtensionManager.h index 95e062930cf..ed0f44333fc 100644 --- a/Rendering/OpenGL/vtkOpenGLExtensionManager.h +++ b/Rendering/OpenGL/vtkOpenGLExtensionManager.h @@ -128,7 +128,6 @@ class vtkRenderWindow; -//BTX extern "C" { #ifdef _WIN32 #include "vtkOpenGL.h" // Needed for WINAPI @@ -137,7 +136,6 @@ extern "C" { typedef void (*vtkOpenGLExtensionManagerFunctionPointer)(void); #endif } -//ETX class VTKRENDERINGOPENGL_EXPORT vtkOpenGLExtensionManager : public vtkObject { @@ -165,13 +163,11 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLExtensionManager : public vtkObject // Returns true if the extension is supported, false otherwise. virtual int ExtensionSupported(const char *name); -//BTX // Description: // Returns a function pointer to the OpenGL extension function with the // given name. Returns NULL if the function could not be retrieved. virtual vtkOpenGLExtensionManagerFunctionPointer GetProcAddress( const char *fname); -//ETX // Description: // Loads all the functions associated with the given extension into the @@ -342,7 +338,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLExtensionManager : public vtkObject vtkSetMacro(IgnoreDriverBugs, bool); vtkBooleanMacro(IgnoreDriverBugs, bool); -//BTX protected: vtkOpenGLExtensionManager(); virtual ~vtkOpenGLExtensionManager(); @@ -390,7 +385,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLExtensionManager : public vtkObject void operator=(const vtkOpenGLExtensionManager&); // Not implemented vtkWeakPointer RenderWindow; -//ETX + }; #endif // vtkOpenGLExtensionManager_h diff --git a/Rendering/OpenGL/vtkOpenGLGlyph3DMapper.cxx b/Rendering/OpenGL/vtkOpenGLGlyph3DMapper.cxx index 0c2c0ae44a1..b7c93d9602b 100644 --- a/Rendering/OpenGL/vtkOpenGLGlyph3DMapper.cxx +++ b/Rendering/OpenGL/vtkOpenGLGlyph3DMapper.cxx @@ -399,7 +399,7 @@ void vtkOpenGLGlyph3DMapper::Render( if (this->Masking) { - maskArray = vtkBitArray::SafeDownCast(this->GetMaskArray(dataset)); + maskArray = vtkArrayDownCast(this->GetMaskArray(dataset)); if (maskArray == 0) { vtkDebugMacro(<<"masking is enabled but there is no mask array. Ignore masking."); @@ -588,7 +588,7 @@ void vtkOpenGLGlyph3DMapper::Render( else if (colors) { unsigned char rgba[4]; - colors->GetTupleValue(inPtId, rgba); + colors->GetTypedTuple(inPtId, rgba); glColor4ub(rgba[0], rgba[1], rgba[2], rgba[3]); } //glFinish(); // for debug diff --git a/Rendering/OpenGL/vtkOpenGLGlyph3DMapper.h b/Rendering/OpenGL/vtkOpenGLGlyph3DMapper.h index 98e2d0d8e7a..b0b80e133df 100644 --- a/Rendering/OpenGL/vtkOpenGLGlyph3DMapper.h +++ b/Rendering/OpenGL/vtkOpenGLGlyph3DMapper.h @@ -55,13 +55,13 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLGlyph3DMapper : public vtkGlyph3DMapper virtual void ReleaseGraphicsResources(vtkWindow *window); protected: - //BTX + vtkOpenGLGlyph3DMapper(); ~vtkOpenGLGlyph3DMapper(); // Description: // Take part in garbage collection. - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; // Description: // Send mapper ivars to sub-mapper. @@ -92,7 +92,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLGlyph3DMapper : public vtkGlyph3DMapper void operator=(const vtkOpenGLGlyph3DMapper&); // Not implemented. virtual void Render(vtkRenderer*, vtkActor*, vtkDataSet*); - //ETX + }; #endif diff --git a/Rendering/OpenGL/vtkOpenGLLightMonitor.h b/Rendering/OpenGL/vtkOpenGLLightMonitor.h index c813ca97a7b..c3657e2b1de 100644 --- a/Rendering/OpenGL/vtkOpenGLLightMonitor.h +++ b/Rendering/OpenGL/vtkOpenGLLightMonitor.h @@ -58,7 +58,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLLightMonitor : public vtkObject // this is done automatically in SateChanged. void Update(); - //BTX // Description: // Setters for internal state. void SetEnabled(int val); @@ -70,7 +69,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLLightMonitor : public vtkObject void SetSpotExponent(float val); void SetSpotCutoff(float val); void SetAttenuation(float *val); - //ETX private: vtkOpenGLLightMonitor(int lightId) : LightId(lightId), UpTime(0) diff --git a/Rendering/OpenGL/vtkOpenGLModelViewProjectionMonitor.h b/Rendering/OpenGL/vtkOpenGLModelViewProjectionMonitor.h index 6d8877fa504..94c22fd82f3 100644 --- a/Rendering/OpenGL/vtkOpenGLModelViewProjectionMonitor.h +++ b/Rendering/OpenGL/vtkOpenGLModelViewProjectionMonitor.h @@ -51,12 +51,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLModelViewProjectionMonitor : public vtk // this is done automatically in SateChanged. void Update(); - //BTX // Description: // Set the matrix data. void SetProjection(float *val); void SetModelView(float *val); - //ETX protected: vtkOpenGLModelViewProjectionMonitor() : UpTime(0) diff --git a/Rendering/OpenGL/vtkOpenGLProperty.h b/Rendering/OpenGL/vtkOpenGLProperty.h index 2f6247c3855..4fd5c261ce9 100644 --- a/Rendering/OpenGL/vtkOpenGLProperty.h +++ b/Rendering/OpenGL/vtkOpenGLProperty.h @@ -46,7 +46,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLProperty : public vtkProperty // Implement base class method. void BackfaceRender(vtkActor *a, vtkRenderer *ren); - //BTX // Description: // This method is called after the actor has been rendered. // Don't call this directly. This method cleans up @@ -73,7 +72,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLProperty : public vtkProperty // Description: // Get the vtkShaderProgram2 object in use. vtkGetObjectMacro(CurrentShaderProgram2, vtkShaderProgram2); - //ETX // Description: // Provide values to initialize shader variables. diff --git a/Rendering/OpenGL/vtkOpenGLRenderWindow.cxx b/Rendering/OpenGL/vtkOpenGLRenderWindow.cxx index 321ebbb4682..d3d84510fdf 100644 --- a/Rendering/OpenGL/vtkOpenGLRenderWindow.cxx +++ b/Rendering/OpenGL/vtkOpenGLRenderWindow.cxx @@ -1595,6 +1595,10 @@ int vtkOpenGLRenderWindow::SetZbufferData( int x1, int y1, int x2, int y2, glDisable( GL_ALPHA_TEST ); glDisable( GL_SCISSOR_TEST ); + int gldepth; + glGetIntegerv(GL_DEPTH_FUNC, &gldepth); + glDepthFunc(GL_ALWAYS); + // Turn of texturing in case it is on - some drivers have a problem // getting / setting pixels with texturing enabled. glDisable( GL_TEXTURE_2D ); @@ -1605,6 +1609,8 @@ int vtkOpenGLRenderWindow::SetZbufferData( int x1, int y1, int x2, int y2, // This seems to be necessary for the image to show up glFlush(); + glDepthFunc(gldepth); + if (glGetError() != GL_NO_ERROR) { return VTK_ERROR; diff --git a/Rendering/OpenGL/vtkOpenGLRenderWindow.h b/Rendering/OpenGL/vtkOpenGLRenderWindow.h index 504b56924ee..073bb561efa 100644 --- a/Rendering/OpenGL/vtkOpenGLRenderWindow.h +++ b/Rendering/OpenGL/vtkOpenGLRenderWindow.h @@ -182,12 +182,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLRenderWindow : public vtkRenderWindow // hasn't already been set up. vtkOpenGLHardwareSupport* GetHardwareSupport(); - //BTX // Description: // Returns its texture unit manager object. A new one will be created if one // hasn't already been set up. vtkTextureUnitManager *GetTextureUnitManager(); - //ETX // Description: // Block the thread until the actual rendering is finished(). diff --git a/Rendering/OpenGL/vtkOpenGLRenderer.cxx b/Rendering/OpenGL/vtkOpenGLRenderer.cxx index ac96d1cd094..33a0cb4f647 100644 --- a/Rendering/OpenGL/vtkOpenGLRenderer.cxx +++ b/Rendering/OpenGL/vtkOpenGLRenderer.cxx @@ -51,7 +51,6 @@ class vtkGLPickInfo vtkStandardNewMacro(vtkOpenGLRenderer); vtkCxxSetObjectMacro(vtkOpenGLRenderer,ShaderProgram,vtkShaderProgram2); -vtkCxxSetObjectMacro(vtkOpenGLRenderer, Pass, vtkRenderPass); #define VTK_MAX_LIGHTS 8 @@ -84,7 +83,6 @@ vtkOpenGLRenderer::vtkOpenGLRenderer() this->ShaderProgram=0; this->BackgroundTexture = 0; - this->Pass = 0; } // Internal method temporarily removes lights before reloading them @@ -392,7 +390,7 @@ void vtkOpenGLRenderer::DeviceRenderTranslucentPolygonalGeometry() // Mesa 8 with GMA945 renderer supports depth peeling // ATI Radeon HD XXXXX on Windows chokes on PROXY_TEXTURE_RECTANGLE_ARB // memory querries however if those are not used all the tests pass. - // ATI Radeon HD on Mac OSX PROXY_TEXTURE_RECTANGLE_ARB are fine but + // ATI Radeon HD on Mac OS X PROXY_TEXTURE_RECTANGLE_ARB are fine but // TestTranslucentLUTDepthPeeling fails. So leave it disabled on Apple int driver_support = (!(extensions->DriverIsATI() @@ -1086,15 +1084,6 @@ void vtkOpenGLRenderer::PrintSelf(ostream& os, vtkIndent indent) os << indent << "PickedId" << this->PickInfo->PickedId<< "\n"; os << indent << "NumPicked" << this->PickInfo->NumPicked<< "\n"; os << indent << "PickedZ " << this->PickedZ << "\n"; - os << indent << "Pass:"; - if(this->Pass!=0) - { - os << "exists" << endl; - } - else - { - os << "null" << endl; - } } @@ -1228,9 +1217,13 @@ void vtkOpenGLRenderer::StartPick(unsigned int pickFromSize) void vtkOpenGLRenderer::ReleaseGraphicsResources(vtkWindow *w) { - if (w && this->Pass) + if (w) { - this->Pass->ReleaseGraphicsResources(w); + vtkRenderer::ReleaseGraphicsResources(w); + if (this->Pass) + { + this->Pass->ReleaseGraphicsResources(w); + } } } diff --git a/Rendering/OpenGL/vtkOpenGLRenderer.h b/Rendering/OpenGL/vtkOpenGLRenderer.h index 81dea2343b9..298c2813295 100644 --- a/Rendering/OpenGL/vtkOpenGLRenderer.h +++ b/Rendering/OpenGL/vtkOpenGLRenderer.h @@ -48,7 +48,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLRenderer : public vtkRenderer // Description: // Internal method temporarily removes lights before reloading them // into graphics pipeline. - void ClearLights(void); + virtual void ClearLights(void); virtual void Clear(void); @@ -63,18 +63,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLRenderer : public vtkRenderer // (Used by vtkOpenGLProperty or vtkOpenGLTexture) int GetDepthPeelingHigherLayer(); - //BTX // Description: // vtkGetObjectMacro(ShaderProgram, vtkShaderProgram2); virtual void SetShaderProgram(vtkShaderProgram2 *program); - //ETX - - // Description: - // Set/Get a custom render pass. - // Initial value is NULL. - void SetPass(vtkRenderPass *p); - vtkGetObjectMacro(Pass, vtkRenderPass); protected: vtkOpenGLRenderer(); @@ -87,7 +79,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLRenderer : public vtkRenderer // Internal method to release graphics resources in any derived renderers. virtual void ReleaseGraphicsResources(vtkWindow *w); - //BTX // Picking functions to be implemented by sub-classes virtual void DevicePickRender(); virtual void StartPick(unsigned int pickFromSize); @@ -100,7 +91,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLRenderer : public vtkRenderer // Ivars used in picking class vtkGLPickInfo* PickInfo; - //ETX double PickedZ; @@ -112,12 +102,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLRenderer : public vtkRenderer // \pre positive_layer: layer>=0 int RenderPeel(int layer); - //BTX friend class vtkOpenGLProperty; friend class vtkOpenGLTexture; friend class vtkOpenGLImageSliceMapper; friend class vtkOpenGLImageResliceMapper; - //ETX // Description: // Access to the OpenGL program shader uniform variable "useTexture" from the @@ -168,7 +156,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLRenderer : public vtkRenderer vtkShaderProgram2 *ShaderProgram; friend class vtkRenderPass; - vtkRenderPass *Pass; private: vtkOpenGLRenderer(const vtkOpenGLRenderer&); // Not implemented. diff --git a/Rendering/OpenGL/vtkOpenGLTexture.h b/Rendering/OpenGL/vtkOpenGLTexture.h index b3fb764eb0a..9409000194a 100644 --- a/Rendering/OpenGL/vtkOpenGLTexture.h +++ b/Rendering/OpenGL/vtkOpenGLTexture.h @@ -22,9 +22,8 @@ #include "vtkRenderingOpenGLModule.h" // For export macro #include "vtkTexture.h" -//BTX + #include "vtkWeakPointer.h" // needed for vtkWeakPointer. -//ETX class vtkWindow; class vtkOpenGLRenderer; @@ -59,7 +58,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLTexture : public vtkTexture vtkGetMacro(Index, long); protected: -//BTX + vtkOpenGLTexture(); ~vtkOpenGLTexture(); @@ -82,7 +81,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkOpenGLTexture : public vtkTexture // Handle loading in extension support virtual void Initialize(vtkRenderer * ren); -//ETX }; #endif diff --git a/Rendering/OpenGL/vtkOverlayPass.h b/Rendering/OpenGL/vtkOverlayPass.h index dcd9155e3d1..615552b7515 100644 --- a/Rendering/OpenGL/vtkOverlayPass.h +++ b/Rendering/OpenGL/vtkOverlayPass.h @@ -38,12 +38,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkOverlayPass : public vtkDefaultPass vtkTypeMacro(vtkOverlayPass,vtkDefaultPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL/vtkPainter.h b/Rendering/OpenGL/vtkPainter.h index bad3ef921da..80758ee7153 100644 --- a/Rendering/OpenGL/vtkPainter.h +++ b/Rendering/OpenGL/vtkPainter.h @@ -96,14 +96,12 @@ class VTKRENDERINGOPENGL_EXPORT vtkPainter : public vtkObject virtual void Register(vtkObjectBase *o); virtual void UnRegister(vtkObjectBase *o); - //BTX enum { VERTS = 0x1, LINES = 0x2, POLYS = 0x4, STRIPS = 0x8 }; - //ETX // Description: // Generates rendering primitives of appropriate type(s). Multiple types @@ -150,7 +148,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkPainter : public vtkObject virtual vtkDataObject* GetOutput() { return this->Input; } -//BTX protected: vtkPainter(); ~vtkPainter(); @@ -246,7 +243,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkPainter : public vtkObject void operator=(const vtkPainter &); // Not implemented. vtkDataObject* Input; -//ETX + }; #endif //vtkPainter_h diff --git a/Rendering/OpenGL/vtkPixelBufferObject.h b/Rendering/OpenGL/vtkPixelBufferObject.h index c24e89caea2..2567aae65b9 100644 --- a/Rendering/OpenGL/vtkPixelBufferObject.h +++ b/Rendering/OpenGL/vtkPixelBufferObject.h @@ -41,7 +41,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkPixelBufferObject : public vtkObject { public: - //BTX // Usage values. enum { @@ -56,7 +55,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkPixelBufferObject : public vtkObject DynamicCopy, NumberOfUsages }; - //ETX static vtkPixelBufferObject* New(); vtkTypeMacro(vtkPixelBufferObject, vtkObject); @@ -259,7 +257,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkPixelBufferObject : public vtkObject void UnmapPackedBuffer() { this->UnmapBuffer(PACKED_BUFFER); } -//BTX // PACKED_BUFFER for download APP<-PBO // UNPACKED_BUFFER for upload APP->PBO enum BufferType{ @@ -308,8 +305,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkPixelBufferObject : public vtkObject // Extension will be loaded when the conetxt is set. static bool IsSupported(vtkRenderWindow* renWin); -//ETX -//BTX protected: vtkPixelBufferObject(); ~vtkPixelBufferObject(); @@ -337,7 +332,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkPixelBufferObject : public vtkObject private: vtkPixelBufferObject(const vtkPixelBufferObject&); // Not implemented. void operator=(const vtkPixelBufferObject&); // Not implemented. - //ETX + }; #endif diff --git a/Rendering/OpenGL/vtkPolygonsPainter.cxx b/Rendering/OpenGL/vtkPolygonsPainter.cxx index 1247eb7ee7a..ee79e59c2f2 100644 --- a/Rendering/OpenGL/vtkPolygonsPainter.cxx +++ b/Rendering/OpenGL/vtkPolygonsPainter.cxx @@ -180,7 +180,7 @@ int vtkPolygonsPainter::RenderPrimitive(unsigned long idx, vtkDataArray* n, pd->GetLines()->GetNumberOfCells(); vtkIdType cellNumStart = cellNum; vtkIdType totalCells = ca->GetNumberOfCells(); - vtkUnsignedCharArray *ef = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray *ef = vtkArrayDownCast( pd->GetPointData()->GetAttribute(vtkDataSetAttributes::EDGEFLAG)); vtkPainterDeviceAdapter* device = ren->GetRenderWindow()-> diff --git a/Rendering/OpenGL/vtkPrimitivePainter.cxx b/Rendering/OpenGL/vtkPrimitivePainter.cxx index 06809b1cb19..a39c3dc5ea5 100644 --- a/Rendering/OpenGL/vtkPrimitivePainter.cxx +++ b/Rendering/OpenGL/vtkPrimitivePainter.cxx @@ -180,16 +180,16 @@ void vtkPrimitivePainter::RenderInternal(vtkRenderer* renderer, if (!this->DisableScalarColor) { // are they cell or point scalars - c = vtkUnsignedCharArray::SafeDownCast(input->GetPointData()->GetScalars()); + c = vtkArrayDownCast(input->GetPointData()->GetScalars()); if (!c) { - c = vtkUnsignedCharArray::SafeDownCast(input->GetCellData()->GetScalars()); + c = vtkArrayDownCast(input->GetCellData()->GetScalars()); cellScalars = 1; } if (!c) { - c = vtkUnsignedCharArray::SafeDownCast(input->GetFieldData()-> + c = vtkArrayDownCast(input->GetFieldData()-> GetArray("Color")); fieldScalars = 1; // note when fieldScalars == 1, also cellScalars == 1. // this ensures that primitive painters that do not distinguish between diff --git a/Rendering/OpenGL/vtkPrimitivePainter.h b/Rendering/OpenGL/vtkPrimitivePainter.h index 68fc3b354ce..405e5980003 100644 --- a/Rendering/OpenGL/vtkPrimitivePainter.h +++ b/Rendering/OpenGL/vtkPrimitivePainter.h @@ -48,7 +48,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkPrimitivePainter : public vtkPolyDataPainter vtkPrimitivePainter(); ~vtkPrimitivePainter(); - //BTX enum { VTK_PDM_NORMALS = 0x001, VTK_PDM_COLORS = 0x002, @@ -60,7 +59,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkPrimitivePainter : public vtkPolyDataPainter VTK_PDM_EDGEFLAGS = 0x080, VTK_PDM_GENERIC_VERTEX_ATTRIBUTES = 0x100 }; - //ETX // Description: // Some subclasses may need to do some preprocessing diff --git a/Rendering/OpenGL/vtkRenderPassCollection.h b/Rendering/OpenGL/vtkRenderPassCollection.h index c443664b448..c5b15cf5a26 100644 --- a/Rendering/OpenGL/vtkRenderPassCollection.h +++ b/Rendering/OpenGL/vtkRenderPassCollection.h @@ -48,12 +48,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkRenderPassCollection : public vtkCollection // Get the last RenderPass in the list. vtkRenderPass *GetLastRenderPass(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkRenderPass *GetNextRenderPass(vtkCollectionSimpleIterator &cookie); - //ETX protected: vtkRenderPassCollection(); diff --git a/Rendering/OpenGL/vtkRenderState.cxx b/Rendering/OpenGL/vtkRenderState.cxx deleted file mode 100644 index d0e1788c745..00000000000 --- a/Rendering/OpenGL/vtkRenderState.cxx +++ /dev/null @@ -1,151 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkRenderState.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkRenderState.h" -#include -#include "vtkRenderer.h" -#include "vtkFrameBufferObject.h" - -// ---------------------------------------------------------------------------- -// Description: -// Constructor. All values are initialized to 0 or NULL. -// \pre renderer_exists: renderer!=0 -// \post renderer_is_set: GetRenderer()==renderer. -// \post valid_state: IsValid() -vtkRenderState::vtkRenderState(vtkRenderer *renderer) -{ - assert("pre: renderer_exists" && renderer!=0); - this->Renderer = renderer; - this->FrameBuffer = 0; - this->PropArray = 0; - this->PropArrayCount = 0; - this->RequiredKeys = 0; - - assert("post: renderer_is_set" && this->GetRenderer() == renderer); - assert("post: is_valid" && this->IsValid()); -} - -// ---------------------------------------------------------------------------- -// Description: -// Destructor. As a vtkRenderState does not own any of its variables, -// the destructor does nothing. -vtkRenderState::~vtkRenderState() -{ -} - -// ---------------------------------------------------------------------------- -// Description: -// Tells if the RenderState is a valid one (Renderer is not null). -bool vtkRenderState::IsValid() const -{ - return this->Renderer != 0; -} - -// ---------------------------------------------------------------------------- -// Description: -// Return the Renderer. -// \post result_exists: result!=0 -vtkRenderer *vtkRenderState::GetRenderer() const -{ - assert("post: valid_result" && this->Renderer != 0); - return this->Renderer; -} - -// ---------------------------------------------------------------------------- -// Description: -// Return the FrameBuffer. -vtkFrameBufferObject *vtkRenderState::GetFrameBuffer() const -{ - return this->FrameBuffer; -} - -// ---------------------------------------------------------------------------- -// Description: -// Set the FrameBuffer. -// \post is_set: GetFrameBuffer()==fbo -void vtkRenderState::SetFrameBuffer(vtkFrameBufferObject *fbo) -{ - this->FrameBuffer = fbo; - assert("post: is_set" && this->GetFrameBuffer() == fbo); -} - -// ---------------------------------------------------------------------------- -// Description: -// Get the window size of the state. -void vtkRenderState::GetWindowSize(int size[2]) const -{ - if (this->FrameBuffer==0) - { - this->Renderer->GetTiledSize(&size[0], &size[1]); - } - else - { - this->FrameBuffer->GetLastSize(size); - } -} - -// ---------------------------------------------------------------------------- -// Description: -// Return the array of filtered props -vtkProp **vtkRenderState::GetPropArray() const -{ - return this->PropArray; -} - -// ---------------------------------------------------------------------------- -// Description: -// Return the size of the array of filtered props. -// \post positive_result: result>=0 -int vtkRenderState::GetPropArrayCount() const -{ - assert("post: positive_result" && this->PropArrayCount >= 0); - return this->PropArrayCount; -} - -// ---------------------------------------------------------------------------- -// Description: -// Set the array of of filtered props and its size. -// \pre positive_size: propArrayCount>=0 -// \pre valid_null_array: propArray!=0 || propArrayCount==0 -// \post is_set: GetPropArray()==propArray && GetPropArrayCount()==propArrayCount -void vtkRenderState::SetPropArrayAndCount(vtkProp **propArray, - int propArrayCount) -{ - assert("pre: positive_size" && propArrayCount >= 0); - assert("pre: valid_null_array" && (propArray != 0 || propArrayCount == 0)); - - this->PropArray = propArray; - this->PropArrayCount = propArrayCount; - - assert("post: is_set" && this->GetPropArray() == propArray - && this->GetPropArrayCount() == propArrayCount); -} - -// ---------------------------------------------------------------------------- -// Description: -// Return the required property keys for the props. -vtkInformation *vtkRenderState::GetRequiredKeys() const -{ - return this->RequiredKeys; -} - -// ---------------------------------------------------------------------------- -// Description: -// Set the required property keys for the props. -// \post is_set: GetRequiredKeys()==keys -void vtkRenderState::SetRequiredKeys(vtkInformation *keys) -{ - this->RequiredKeys = keys; - assert("post: is_set" && this->GetRequiredKeys() == keys); -} diff --git a/Rendering/OpenGL/vtkScalarsToColorsPainter.cxx b/Rendering/OpenGL/vtkScalarsToColorsPainter.cxx index c56c90a0548..91b9468c31b 100644 --- a/Rendering/OpenGL/vtkScalarsToColorsPainter.cxx +++ b/Rendering/OpenGL/vtkScalarsToColorsPainter.cxx @@ -46,7 +46,7 @@ //----------------------------------------------------------------------------- static inline void vtkMultiplyColorsWithAlpha(vtkDataArray* array) { - vtkUnsignedCharArray* colors = vtkUnsignedCharArray::SafeDownCast(array); + vtkUnsignedCharArray* colors = vtkArrayDownCast(array); if (!colors || colors->GetNumberOfComponents() != 4) { return; @@ -385,7 +385,7 @@ int vtkScalarsToColorsPainter::CanUseTextureMapForColoring(vtkDataObject* input) } if ((this->ColorMode == VTK_COLOR_MODE_DEFAULT && - vtkUnsignedCharArray::SafeDownCast(scalars)) || + vtkArrayDownCast(scalars)) || this->ColorMode == VTK_COLOR_MODE_DIRECT_SCALARS) { // Don't use texture is direct coloring using RGB unsigned chars is @@ -566,7 +566,7 @@ void vtkScalarsToColorsPainter::MapScalars(vtkDataSet* output, return; } - vtkDataArray* scalars = vtkDataArray::SafeDownCast(abstractScalars); + vtkDataArray* scalars = vtkArrayDownCast(abstractScalars); // Let subclasses know that scalar coloring was employed in the current pass. this->UsingScalarColoring = 1; @@ -678,7 +678,7 @@ void vtkScalarsToColorsPainter::MapScalars(vtkDataSet* output, { // Use only the requested tuple's color unsigned char color[4]; - scalarColors->GetTupleValue(this->FieldDataTupleId, color); + scalarColors->GetTypedTuple(this->FieldDataTupleId, color); vtkUnsignedCharArray* newColors = vtkUnsignedCharArray::New(); newColors->SetNumberOfComponents(4); @@ -686,7 +686,7 @@ void vtkScalarsToColorsPainter::MapScalars(vtkDataSet* output, newColors->SetName("Color"); for (vtkIdType i = 0; i < input->GetNumberOfCells(); ++i) { - newColors->SetTupleValue(i, color); + newColors->SetTypedTuple(i, color); } opfd->AddArray(newColors); diff --git a/Rendering/OpenGL/vtkScalarsToColorsPainter.h b/Rendering/OpenGL/vtkScalarsToColorsPainter.h index 7dee3692b66..6f3a76acbad 100644 --- a/Rendering/OpenGL/vtkScalarsToColorsPainter.h +++ b/Rendering/OpenGL/vtkScalarsToColorsPainter.h @@ -126,7 +126,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkScalarsToColorsPainter : public vtkPainter // hardcoded to 1024. virtual vtkIdType GetTextureSizeLimit(); -//BTX protected: vtkScalarsToColorsPainter(); virtual ~vtkScalarsToColorsPainter(); @@ -226,7 +225,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkScalarsToColorsPainter : public vtkPainter private: vtkScalarsToColorsPainter(const vtkScalarsToColorsPainter&); // Not implemented. void operator=(const vtkScalarsToColorsPainter&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkSequencePass.h b/Rendering/OpenGL/vtkSequencePass.h index 2c1d53f70fe..b1958de0092 100644 --- a/Rendering/OpenGL/vtkSequencePass.h +++ b/Rendering/OpenGL/vtkSequencePass.h @@ -39,12 +39,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkSequencePass : public vtkRenderPass vtkTypeMacro(vtkSequencePass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL/vtkShader2Collection.h b/Rendering/OpenGL/vtkShader2Collection.h index 91a3aa6376d..ce335840dd1 100644 --- a/Rendering/OpenGL/vtkShader2Collection.h +++ b/Rendering/OpenGL/vtkShader2Collection.h @@ -53,12 +53,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkShader2Collection : public vtkCollection // Get the last shader in the list. vtkShader2 *GetLastShader(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkShader2 *GetNextShader(vtkCollectionSimpleIterator &cookie); - //ETX // Description: // Add the elements of `other' to the end of `this'. diff --git a/Rendering/OpenGL/vtkShaderProgram2.h b/Rendering/OpenGL/vtkShaderProgram2.h index f166c478730..1469fd92afb 100644 --- a/Rendering/OpenGL/vtkShaderProgram2.h +++ b/Rendering/OpenGL/vtkShaderProgram2.h @@ -415,7 +415,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkShaderProgram2 : public vtkObject }; // ---------------------------------------------------------------------------- -//BTX + #define vtkShaderProgram2SetUniformCopyCastMacro(toLetter, toType, num) \ template \ void vtkShaderProgram2::SetUniform##num##toLetter##t(const char *name, fromType *fvalues) \ @@ -446,7 +446,5 @@ vtkShaderProgram2SetUniformCopyCastMacro(i, int, 1) vtkShaderProgram2SetUniformCopyCastMacro(i, int, 2) vtkShaderProgram2SetUniformCopyCastMacro(i, int, 3) vtkShaderProgram2SetUniformCopyCastMacro(i, int, 4) -//ETX - #endif diff --git a/Rendering/OpenGL/vtkShadowMapBakerPass.h b/Rendering/OpenGL/vtkShadowMapBakerPass.h index dd1ac34aa7d..8a0daf6f2d7 100644 --- a/Rendering/OpenGL/vtkShadowMapBakerPass.h +++ b/Rendering/OpenGL/vtkShadowMapBakerPass.h @@ -69,12 +69,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkShadowMapBakerPass : public vtkRenderPass // OCCLUDER() key. static vtkInformationIntegerKey *RECEIVER(); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own @@ -150,7 +148,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkShadowMapBakerPass : public vtkRenderPass // \pre l_exists: l!=0 bool LightCreatesShadow(vtkLight *l); -//BTX // Description: // INTERNAL USE ONLY // Internally used by vtkShadowMapBakerPass and vtkShadowMapPass. @@ -164,7 +161,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkShadowMapBakerPass : public vtkRenderPass // // Give access the cameras builds from the ligths. vtkShadowMapBakerPassLightCameras *GetLightCameras(); -//ETX // Description: // INTERNAL USE ONLY. @@ -215,7 +211,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkShadowMapBakerPass : public vtkRenderPass double &mNear, double &mFar); - //BTX // Description: // Build a camera from spot light parameters. // \pre light_exists: light!=0 @@ -223,7 +218,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkShadowMapBakerPass : public vtkRenderPass void BuildCameraLight(vtkLight *light, double *boundingBox, vtkCamera *lcamera); - //ETX // Description: // Check if shadow mapping is supported by the current OpenGL context. diff --git a/Rendering/OpenGL/vtkShadowMapPass.h b/Rendering/OpenGL/vtkShadowMapPass.h index 7da76375bc0..60fff78402d 100644 --- a/Rendering/OpenGL/vtkShadowMapPass.h +++ b/Rendering/OpenGL/vtkShadowMapPass.h @@ -62,12 +62,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkShadowMapPass : public vtkRenderPass vtkTypeMacro(vtkShadowMapPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL/vtkSobelGradientMagnitudePass.h b/Rendering/OpenGL/vtkSobelGradientMagnitudePass.h index 5969486eefa..0d584eaeaa1 100644 --- a/Rendering/OpenGL/vtkSobelGradientMagnitudePass.h +++ b/Rendering/OpenGL/vtkSobelGradientMagnitudePass.h @@ -73,12 +73,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkSobelGradientMagnitudePass : public vtkImageP vtkTypeMacro(vtkSobelGradientMagnitudePass,vtkImageProcessingPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL/vtkStandardPolyDataPainter.cxx b/Rendering/OpenGL/vtkStandardPolyDataPainter.cxx index eacf3c46213..def66160ed6 100644 --- a/Rendering/OpenGL/vtkStandardPolyDataPainter.cxx +++ b/Rendering/OpenGL/vtkStandardPolyDataPainter.cxx @@ -291,7 +291,7 @@ void vtkStandardPolyDataPainter::DrawCells( vtkCellData* cellData = pd->GetCellData(); vtkPointData* pointData = pd->GetPointData(); - vtkUnsignedCharArray* fieldColors = vtkUnsignedCharArray::SafeDownCast( + vtkUnsignedCharArray* fieldColors = vtkArrayDownCast( pd->GetFieldData()->GetArray("Color")); int disable_scalar_color = 0; diff --git a/Rendering/OpenGL/vtkStandardPolyDataPainter.h b/Rendering/OpenGL/vtkStandardPolyDataPainter.h index 603aef059e1..dafbbe2fd54 100644 --- a/Rendering/OpenGL/vtkStandardPolyDataPainter.h +++ b/Rendering/OpenGL/vtkStandardPolyDataPainter.h @@ -55,7 +55,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkStandardPolyDataPainter : public vtkPolyDataP static vtkStandardPolyDataPainter *New(); void AddMultiTextureCoordsArray(vtkDataArray * array); -//BTX + protected: vtkStandardPolyDataPainter(); ~vtkStandardPolyDataPainter(); @@ -86,7 +86,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkStandardPolyDataPainter : public vtkPolyDataP class vtkInternal; vtkInternal* Internal; -//ETX + }; #endif //vtkStandardPolyDataPainter_h diff --git a/Rendering/OpenGL/vtkTDxInteractorStyleGeo.h b/Rendering/OpenGL/vtkTDxInteractorStyleGeo.h index fb76c618aa1..4768fcb9cbb 100644 --- a/Rendering/OpenGL/vtkTDxInteractorStyleGeo.h +++ b/Rendering/OpenGL/vtkTDxInteractorStyleGeo.h @@ -37,12 +37,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkTDxInteractorStyleGeo : public vtkTDxInteract vtkTypeMacro(vtkTDxInteractorStyleGeo,vtkTDxInteractorStyle); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Action on motion event. // \pre: motionInfo_exist: motionInfo!=0 virtual void OnMotionEvent(vtkTDxMotionEventInfo *motionInfo); - //ETX protected: vtkTDxInteractorStyleGeo(); diff --git a/Rendering/OpenGL/vtkTextureObject.h b/Rendering/OpenGL/vtkTextureObject.h index e058f942585..31a47558718 100644 --- a/Rendering/OpenGL/vtkTextureObject.h +++ b/Rendering/OpenGL/vtkTextureObject.h @@ -37,7 +37,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkTextureObject : public vtkObject { public: - //BTX // DepthTextureCompareFunction values. enum { @@ -95,8 +94,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkTextureObject : public vtkObject NumberOfDepthFormats }; - //ETX - static vtkTextureObject* New(); vtkTypeMacro(vtkTextureObject, vtkObject); void PrintSelf(ostream& os, vtkIndent indent); @@ -511,9 +508,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkTextureObject : public vtkObject int width, int height); - - -//BTX protected: vtkTextureObject(); ~vtkTextureObject(); @@ -576,7 +570,7 @@ class VTKRENDERINGOPENGL_EXPORT vtkTextureObject : public vtkObject private: vtkTextureObject(const vtkTextureObject&); // Not implemented. void operator=(const vtkTextureObject&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL/vtkTranslucentPass.h b/Rendering/OpenGL/vtkTranslucentPass.h index 186c2c7a702..0ee391daa8d 100644 --- a/Rendering/OpenGL/vtkTranslucentPass.h +++ b/Rendering/OpenGL/vtkTranslucentPass.h @@ -38,12 +38,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkTranslucentPass : public vtkDefaultPass vtkTypeMacro(vtkTranslucentPass,vtkDefaultPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL/vtkUniformVariables.h b/Rendering/OpenGL/vtkUniformVariables.h index 4899db086d5..4a5485adb13 100644 --- a/Rendering/OpenGL/vtkUniformVariables.h +++ b/Rendering/OpenGL/vtkUniformVariables.h @@ -45,7 +45,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkUniformVariables : public vtkObject int numberOfComponents, int *value); - //BTX template void SetUniformit(const char *name, int numberOfComponents, @@ -54,7 +53,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkUniformVariables : public vtkObject template void SetUniformit(const char *name, T value) { this->SetUniformit(name, 1, &value); } - //ETX // Description: // Set an float uniform variable. @@ -65,7 +63,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkUniformVariables : public vtkObject int numberOfComponents, float *value); - //BTX template void SetUniformft(const char *name, int numberOfComponents, @@ -74,7 +71,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkUniformVariables : public vtkObject template void SetUniformft(const char *name, T value) { this->SetUniformft(name, 1, &value); } - //ETX // Description: // Set an array of integer uniform variables. @@ -172,7 +168,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkUniformVariables : public vtkObject vtkUniformVariablesMap *Map; }; -//BTX // ---------------------------------------------------------------------------- template void vtkUniformVariables::SetUniformit(const char *name, @@ -200,6 +195,5 @@ void vtkUniformVariables::SetUniformft(const char *name, } this->SetUniformf(name, numberOfComponents, fvalues); } -//ETX #endif diff --git a/Rendering/OpenGL/vtkVolumetricPass.h b/Rendering/OpenGL/vtkVolumetricPass.h index b433fe17100..53cea5d4fd0 100644 --- a/Rendering/OpenGL/vtkVolumetricPass.h +++ b/Rendering/OpenGL/vtkVolumetricPass.h @@ -38,12 +38,10 @@ class VTKRENDERINGOPENGL_EXPORT vtkVolumetricPass : public vtkDefaultPass vtkTypeMacro(vtkVolumetricPass,vtkDefaultPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL/vtkWin32OpenGLRenderWindow.h b/Rendering/OpenGL/vtkWin32OpenGLRenderWindow.h index f8d0878b5db..b5f72df8a09 100644 --- a/Rendering/OpenGL/vtkWin32OpenGLRenderWindow.h +++ b/Rendering/OpenGL/vtkWin32OpenGLRenderWindow.h @@ -109,7 +109,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkWin32OpenGLRenderWindow : public vtkOpenGLRen // Sets the HWND id of the window that WILL BE created. void SetParentInfo(char*); - //BTX virtual void *GetGenericDisplayId() { return (void*)this->ContextId; } virtual void *GetGenericWindowId() { return (void*)this->WindowId; } virtual void *GetGenericParentId() { return (void*)this->ParentId; } @@ -154,8 +153,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkWin32OpenGLRenderWindow : public vtkOpenGLRen // parent. virtual void SetNextWindowId(void *arg); - //ETX - // Description: // Prescribe that the window be created in a stereo-capable mode. This // method must be called before the window is realized. This method @@ -259,14 +256,13 @@ class VTKRENDERINGOPENGL_EXPORT vtkWin32OpenGLRenderWindow : public vtkOpenGLRen int CreatingOffScreenWindow; // to avoid recursion (and memory leaks...) - //BTX // message handler virtual LRESULT MessageProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); static LRESULT APIENTRY WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); - //ETX + int CursorHidden; int ForceMakeCurrent; diff --git a/Rendering/OpenGL/vtkWin32RenderWindowInteractor.h b/Rendering/OpenGL/vtkWin32RenderWindowInteractor.h index 9b71d2bfdff..b1a9e4f5b7c 100644 --- a/Rendering/OpenGL/vtkWin32RenderWindowInteractor.h +++ b/Rendering/OpenGL/vtkWin32RenderWindowInteractor.h @@ -75,7 +75,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkWin32RenderWindowInteractor : public vtkRende // ExitMethod for alternative behavior (i.e. suppression of keyboard exit) void TerminateApp(void); - //BTX friend VTKRENDERINGOPENGL_EXPORT LRESULT CALLBACK vtkHandleMessage(HWND hwnd,UINT uMsg, WPARAM w, LPARAM l); friend VTKRENDERINGOPENGL_EXPORT LRESULT CALLBACK vtkHandleMessage2(HWND hwnd,UINT uMsg, WPARAM w, LPARAM l, vtkWin32RenderWindowInteractor *me); @@ -99,7 +98,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkWin32RenderWindowInteractor : public vtkRende virtual int OnMouseWheelBackward(HWND wnd, UINT nFlags, int X, int Y); virtual int OnFocus(HWND wnd, UINT nFlags); virtual int OnKillFocus(HWND wnd, UINT nFlags); - //ETX // Description: // Methods to set the default exit method for the class. This method is @@ -124,7 +122,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkWin32RenderWindowInteractor : public vtkRende int MouseInWindow; int StartedMessageLoop; - //BTX // Description: // Class variables so an exit method can be defined for this class // (used to set different exit methods for various language bindings, @@ -132,7 +129,6 @@ class VTKRENDERINGOPENGL_EXPORT vtkWin32RenderWindowInteractor : public vtkRende static void (*ClassExitMethod)(void *); static void (*ClassExitMethodArgDelete)(void *); static void *ClassExitMethodArg; - //ETX // Description: // Win32-specific internal timer methods. See the superclass for detailed diff --git a/Rendering/OpenGL/vtkXOpenGLRenderWindow.cxx b/Rendering/OpenGL/vtkXOpenGLRenderWindow.cxx index 564624bfa13..042dfff5b50 100644 --- a/Rendering/OpenGL/vtkXOpenGLRenderWindow.cxx +++ b/Rendering/OpenGL/vtkXOpenGLRenderWindow.cxx @@ -930,7 +930,7 @@ void vtkXOpenGLRenderWindow::CreateOffScreenWindow(int width, int height) } } // if not hardware offscreen } - this->Mapped = 0; + this->Mapped = 1; this->Size[0] = width; this->Size[1] = height; @@ -997,6 +997,7 @@ void vtkXOpenGLRenderWindow::DestroyOffScreenWindow() } } } + this->Mapped = 0; } void vtkXOpenGLRenderWindow::ResizeOffScreenWindow(int width, int height) @@ -1100,7 +1101,7 @@ void vtkXOpenGLRenderWindow::SetFullScreen(int arg) if (this->FullScreen == arg) return; - if (!this->Mapped) + if (!this->Mapped || this->OffScreenRendering) { this->PrefFullScreen(); return; @@ -1209,7 +1210,7 @@ void vtkXOpenGLRenderWindow::SetSize(int width,int height) { this->ResizeOffScreenWindow(width,height); } - else if(this->WindowId && this->Mapped) + else if(this->WindowId && this->Mapped && ! this->OffScreenRendering) { XResizeWindow(this->DisplayId,this->WindowId, static_cast(width), @@ -1496,7 +1497,7 @@ int *vtkXOpenGLRenderWindow::GetPosition(void) Window child; // if we aren't mapped then just return the ivar - if (!this->Mapped) + if (!this->Mapped || this->OffScreenRendering) { return this->Position; } @@ -1540,7 +1541,7 @@ Window vtkXOpenGLRenderWindow::GetWindowId() void vtkXOpenGLRenderWindow::SetPosition(int x, int y) { // if we aren't mapped then just set the ivars - if (!this->Mapped) + if (!this->Mapped || this->OffScreenRendering) { if ((this->Position[0] != x)||(this->Position[1] != y)) { @@ -1769,7 +1770,7 @@ void vtkXOpenGLRenderWindow::SetWindowName(const char * cname) this->vtkOpenGLRenderWindow::SetWindowName( name ); - if (this->Mapped) + if (this->Mapped && ! this->OffScreenRendering) { if( XStringListToTextProperty( &name, 1, &win_name_text_prop ) == 0 ) { @@ -1824,7 +1825,7 @@ void vtkXOpenGLRenderWindow::Render() // To avoid the expensive XGetWindowAttributes call, // compute size at the start of a render and use // the ivar other times. - if (this->Mapped) + if (this->Mapped && ! this->OffScreenRendering) { // Find the current window size XGetWindowAttributes(this->DisplayId, diff --git a/Rendering/OpenGL/vtkXRenderWindowInteractor.h b/Rendering/OpenGL/vtkXRenderWindowInteractor.h index 9bd0959fe0b..505cfd2548c 100644 --- a/Rendering/OpenGL/vtkXRenderWindowInteractor.h +++ b/Rendering/OpenGL/vtkXRenderWindowInteractor.h @@ -41,11 +41,9 @@ class vtkCallbackCommand; class vtkXRenderWindowInteractorInternals; -//BTX // Forward declare internal friend functions. void VTKRENDERINGOPENGL_EXPORT vtkXRenderWindowInteractorCallback(Widget,XtPointer, XEvent *,Boolean *); void VTKRENDERINGOPENGL_EXPORT vtkXRenderWindowInteractorTimer(XtPointer,XtIntervalId *); -//ETX class VTKRENDERINGOPENGL_EXPORT vtkXRenderWindowInteractor : public vtkRenderWindowInteractor { diff --git a/Rendering/OpenGL2/CMakeLists.txt b/Rendering/OpenGL2/CMakeLists.txt index 90b2e3b6273..0675beb80d6 100644 --- a/Rendering/OpenGL2/CMakeLists.txt +++ b/Rendering/OpenGL2/CMakeLists.txt @@ -47,8 +47,9 @@ set(Module_SRCS vtkOpenGLPolyDataMapper.cxx vtkOpenGLPolyDataMapper2D.cxx vtkOpenGLProperty.cxx - vtkOpenGLRenderWindow.cxx + vtkOpenGLRenderPass.cxx vtkOpenGLRenderUtilities.cxx + vtkOpenGLRenderWindow.cxx vtkOpenGLRenderer.cxx vtkOpenGLShaderCache.cxx vtkOpenGLTextActor.cxx @@ -59,9 +60,7 @@ set(Module_SRCS vtkOpenGLVertexBufferObject.cxx vtkOverlayPass.cxx vtkPointFillPass.cxx - vtkRenderPass.cxx vtkRenderPassCollection.cxx - vtkRenderState.cxx vtkRenderStepsPass.cxx vtkSSAAPass.cxx vtkSequencePass.cxx @@ -81,6 +80,7 @@ set(Module_SRCS if (NOT DEFINED OPENGL_ES_VERSION) set(Module_SRCS ${Module_SRCS} vtkDataTransferHelper.cxx + vtkDualDepthPeelingPass.cxx # Needs GL_MAX vtkFrameBufferObject2.cxx vtkPixelBufferObject.cxx vtkRenderbuffer.cxx @@ -88,6 +88,7 @@ if (NOT DEFINED OPENGL_ES_VERSION) else() if (${OPENGL_ES_VERSION} MATCHES 3.0) set(Module_SRCS ${Module_SRCS} + vtkDualDepthPeelingPass.cxx # Needs GL_MAX vtkFrameBufferObject2.cxx vtkPixelBufferObject.cxx vtkRenderbuffer.cxx @@ -115,7 +116,6 @@ set_source_files_properties( vtkOpenGLVertexArrayObject vtkOpenGLVertexBufferObject vtkPixelBufferObject - vtkRenderState vtkRenderbuffer vtkTextureObject vtkTextureUnitManager @@ -132,8 +132,6 @@ set_source_files_properties( set_source_files_properties( vtkOpenGLGL2PSHelper vtkOpenGLRenderWindow - vtkRenderPass - vtkRenderState ABSTRACT ) diff --git a/Rendering/OpenGL2/Testing/Cxx/CMakeLists.txt b/Rendering/OpenGL2/Testing/Cxx/CMakeLists.txt index e7adbaaffd2..2e94d344637 100644 --- a/Rendering/OpenGL2/Testing/Cxx/CMakeLists.txt +++ b/Rendering/OpenGL2/Testing/Cxx/CMakeLists.txt @@ -1,6 +1,7 @@ vtk_add_test_cxx(${vtk-module}CxxTests tests TestAppleBug.cxx TestDepthOfFieldPass.cxx + TestDepthPeelingPass.cxx TestLightingMapLuminancePass.cxx TestLightingMapNormalsPass.cxx TestPointGaussianMapper.cxx diff --git a/Rendering/OpenGL2/Testing/Cxx/TestAppleBug.cxx b/Rendering/OpenGL2/Testing/Cxx/TestAppleBug.cxx index 6039dd495ed..75b9281c82b 100644 --- a/Rendering/OpenGL2/Testing/Cxx/TestAppleBug.cxx +++ b/Rendering/OpenGL2/Testing/Cxx/TestAppleBug.cxx @@ -116,7 +116,7 @@ int TestAppleBug(int argc, char* argv[]) int offRetVal = vtkRegressionTestImage(renderWindow.Get()); if (offRetVal == vtkRegressionTester::PASSED) { - cerr << "FIX!!!! This system is using the apple bug but does not need it\n\n"; + cerr << "FIX!!!! This system is using the AppleBug (rdar://20747550) code but does not need it\n\n"; return !vtkRegressionTester::FAILED; } } @@ -130,7 +130,7 @@ int TestAppleBug(int argc, char* argv[]) retVal = vtkRegressionTestImage(renderWindow.Get()); if (retVal == vtkRegressionTester::PASSED) { - cerr << "FIX!!! This system needs the AppleBug Code but doesn't have it\n\n"; + cerr << "FIX!!! This system needs the AppleBug (rdar://20747550) code but doesn't have it\n\n"; return !vtkRegressionTester::FAILED; } } diff --git a/Rendering/OpenGL2/Testing/Cxx/TestDepthPeelingPass.cxx b/Rendering/OpenGL2/Testing/Cxx/TestDepthPeelingPass.cxx new file mode 100644 index 00000000000..f7c8c33a359 --- /dev/null +++ b/Rendering/OpenGL2/Testing/Cxx/TestDepthPeelingPass.cxx @@ -0,0 +1,108 @@ +/*========================================================================= + + Program: Visualization Toolkit + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkActor.h" +#include "vtkCamera.h" +#include "vtkCellArray.h" +#include "vtkNew.h" +#include "vtkOpenGLRenderer.h" +#include "vtkPLYReader.h" +#include "vtkPolyDataMapper.h" +#include "vtkProperty.h" +#include "vtkRegressionTestImage.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkTestUtilities.h" +#include "vtkTimerLog.h" + +int TestDepthPeelingPass(int argc, char* argv[]) +{ + vtkNew iren; + vtkNew renWin; + renWin->SetMultiSamples(0); + renWin->SetAlphaBitPlanes(1); + iren->SetRenderWindow(renWin.Get()); + vtkNew renderer; + renWin->AddRenderer(renderer.Get()); + + vtkNew mapper; + const char* fileName = + vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/dragon.ply"); + vtkNew reader; + reader->SetFileName(fileName); + reader->Update(); + + mapper->SetInputConnection(reader->GetOutputPort()); + + // create three dragons + { + vtkNew actor; + actor->SetMapper(mapper.Get()); + actor->GetProperty()->SetAmbientColor(1.0, 0.0, 0.0); + actor->GetProperty()->SetDiffuseColor(1.0, 0.8, 0.3); + actor->GetProperty()->SetSpecular(0.0); + actor->GetProperty()->SetDiffuse(0.5); + actor->GetProperty()->SetAmbient(0.3); + actor->GetProperty()->SetOpacity(0.35); + actor->SetPosition(-0.1, 0.0, -0.1); + renderer->AddActor(actor.Get()); + } + + { + vtkNew actor; + actor->SetMapper(mapper.Get()); + actor->GetProperty()->SetAmbientColor(0.2, 0.2, 1.0); + actor->GetProperty()->SetDiffuseColor(0.2, 1.0, 0.8); + actor->GetProperty()->SetSpecularColor(1.0, 1.0, 1.0); + actor->GetProperty()->SetSpecular(0.2); + actor->GetProperty()->SetDiffuse(0.9); + actor->GetProperty()->SetAmbient(0.1); + actor->GetProperty()->SetSpecularPower(10.0); + actor->GetProperty()->SetOpacity(0.20); + renderer->AddActor(actor.Get()); + } + + { + vtkNew actor; + actor->SetMapper(mapper.Get()); + actor->GetProperty()->SetDiffuseColor(0.5, 0.65, 1.0); + actor->GetProperty()->SetSpecularColor(1.0, 1.0, 1.0); + actor->GetProperty()->SetSpecular(0.7); + actor->GetProperty()->SetDiffuse(0.4); + actor->GetProperty()->SetSpecularPower(60.0); + actor->GetProperty()->SetOpacity(0.35); + actor->SetPosition(0.1, 0.0, 0.1); + renderer->AddActor(actor.Get()); + } + + renderer->SetUseDepthPeeling(1); + renderer->SetOcclusionRatio(0.0); + renderer->SetMaximumNumberOfPeels(20); + + renWin->SetSize(500,500); + renderer->SetBackground(8., 7., 1.); + renderer->SetBackground2(.3, .1, .2); + renderer->GradientBackgroundOn(); + renderer->GetActiveCamera()->SetPosition(0,0,1); + renderer->GetActiveCamera()->SetFocalPoint(0,0,0); + renderer->GetActiveCamera()->SetViewUp(0,1,0); + renderer->ResetCamera(); + renderer->GetActiveCamera()->Azimuth(15.0); + renderer->GetActiveCamera()->Zoom(1.8); + + renWin->Render(); + iren->Start(); + + return EXIT_SUCCESS; +} diff --git a/Rendering/OpenGL2/Testing/Cxx/TestPointFillPass.cxx b/Rendering/OpenGL2/Testing/Cxx/TestPointFillPass.cxx index 1e40c696113..d2ec85ab499 100644 --- a/Rendering/OpenGL2/Testing/Cxx/TestPointFillPass.cxx +++ b/Rendering/OpenGL2/Testing/Cxx/TestPointFillPass.cxx @@ -20,6 +20,7 @@ #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" +#include "vtkCameraPass.h" #include "vtkNew.h" #include "vtkPLYReader.h" #include "vtkProperty.h" @@ -111,7 +112,9 @@ int TestPointFillPass(int argc, char* argv[]) vtkNew pfp; pfp->SetDelegatePass(basicPasses.Get()); // tell the renderer to use our render pass pipeline - glrenderer->SetPass(pfp.Get()); + vtkNew camPass; + camPass->SetDelegatePass(pfp.Get()); + glrenderer->SetPass(camPass.Get()); renWin->SetSize(500,500); diff --git a/Rendering/OpenGL2/Testing/Cxx/TestRenderToImage.cxx b/Rendering/OpenGL2/Testing/Cxx/TestRenderToImage.cxx index dbb0c6629a4..966b657f5b4 100644 --- a/Rendering/OpenGL2/Testing/Cxx/TestRenderToImage.cxx +++ b/Rendering/OpenGL2/Testing/Cxx/TestRenderToImage.cxx @@ -62,7 +62,7 @@ int TestRenderToImage(int argc, char* argv[]) image->SetDimensions(size[0], size[1], 1); image->AllocateScalars(VTK_UNSIGNED_CHAR, 3); renderWindow->GetPixelData(0, 0, size[0] - 1, size[1] - 1, 0, - vtkUnsignedCharArray::SafeDownCast(image->GetPointData()->GetScalars())); + vtkArrayDownCast(image->GetPointData()->GetScalars())); glRenderWindow->SetUseOffScreenBuffers(false); // Now add the actor @@ -74,7 +74,7 @@ int TestRenderToImage(int argc, char* argv[]) renderWindow->Render(); // Capture the framebuffer to the image, again renderWindow->GetPixelData(0, 0, size[0]-1, size[1]-1, 0, - vtkUnsignedCharArray::SafeDownCast(image->GetPointData()->GetScalars())); + vtkArrayDownCast(image->GetPointData()->GetScalars())); glRenderWindow->SetUseOffScreenBuffers(false); // Create a new image actor and remove the geometry one diff --git a/Rendering/OpenGL2/Testing/Cxx/TestValuePass2.cxx b/Rendering/OpenGL2/Testing/Cxx/TestValuePass2.cxx index 97bd019b122..6757ebf1e40 100644 --- a/Rendering/OpenGL2/Testing/Cxx/TestValuePass2.cxx +++ b/Rendering/OpenGL2/Testing/Cxx/TestValuePass2.cxx @@ -292,7 +292,7 @@ int TestValuePass2(int argc, char* argv[]) //id->PrintSelf(cerr, vtkIndent(0)); vtkUnsignedCharArray *ar = - vtkUnsignedCharArray::SafeDownCast(id->GetPointData()->GetArray("ImageScalars")); + vtkArrayDownCast(id->GetPointData()->GetArray("ImageScalars")); unsigned char *ptr = static_cast(ar->GetVoidPointer(0)); std::set found; double value; diff --git a/Rendering/OpenGL2/Testing/Data/Baseline/TestDepthPeelingPass.png.md5 b/Rendering/OpenGL2/Testing/Data/Baseline/TestDepthPeelingPass.png.md5 new file mode 100644 index 00000000000..5fbf01dfccc --- /dev/null +++ b/Rendering/OpenGL2/Testing/Data/Baseline/TestDepthPeelingPass.png.md5 @@ -0,0 +1 @@ +fbc5ffa92f448945f8a2a04d3f2e7a56 diff --git a/Rendering/OpenGL2/glsl/vtkPointFillPassFS.glsl b/Rendering/OpenGL2/glsl/vtkPointFillPassFS.glsl index 210314d685f..1d1e3a368c6 100644 --- a/Rendering/OpenGL2/glsl/vtkPointFillPassFS.glsl +++ b/Rendering/OpenGL2/glsl/vtkPointFillPassFS.glsl @@ -37,7 +37,7 @@ void main(void) vec4 fbcolor = texture2D(source,tcoordVC); vec4 closestColor = vec4(0.0,0.0,0.0,0.0); - float closestDepth = fbdepth; + float closestDepth = 0.0; int count = 0; // we track the theta range twice @@ -56,8 +56,8 @@ void main(void) for (int j = -3; j <= 3; j++) { float adepth = texture2D(depth,tcoordVC + pixelToTCoord*vec2(i,j)).r; - adepth = 2.0*nearC/(farC + nearC -adepth*(farC - nearC)); - if (adepth < fbdepth*CandidatePointRatio && (i != 0 || j != 0)) + float mdepth = 2.0*nearC/(farC + nearC -adepth*(farC - nearC)); + if (mdepth < fbdepth*CandidatePointRatio && (i != 0 || j != 0)) { float theta = atan(float(j),float(i)); minTheta = min(minTheta,theta); @@ -74,6 +74,7 @@ void main(void) maxTheta2 = max(maxTheta2,theta); count = count + 1; closestColor += texture2D(source,tcoordVC + pixelToTCoord*vec2(i,j)); + closestDepth += adepth; } } } @@ -82,9 +83,11 @@ void main(void) if (min(maxTheta-minTheta, maxTheta2-minTheta2) > MinimumCandidateAngle) { gl_FragData[0] = closestColor/count; + gl_FragDepth = closestDepth/count; } else { gl_FragData[0] = fbcolor; + gl_FragDepth = fbdepth; } } diff --git a/Rendering/OpenGL2/glsl/vtkPolyData2DFS.glsl b/Rendering/OpenGL2/glsl/vtkPolyData2DFS.glsl index b568c814485..e46e9d494ca 100644 --- a/Rendering/OpenGL2/glsl/vtkPolyData2DFS.glsl +++ b/Rendering/OpenGL2/glsl/vtkPolyData2DFS.glsl @@ -26,6 +26,9 @@ uniform int PrimitiveIDOffset; // Depth Peeling //VTK::DepthPeeling::Dec +// picking support +//VTK::Picking::Dec + // the output of this shader //VTK::Output::Dec @@ -40,4 +43,5 @@ void main() //VTK::Color::Impl //VTK::TCoord::Impl //VTK::DepthPeeling::Impl + //VTK::Picking::Impl } diff --git a/Rendering/OpenGL2/glsl/vtkPolyDataFS.glsl b/Rendering/OpenGL2/glsl/vtkPolyDataFS.glsl index 9f58185236a..8db9e1695ad 100644 --- a/Rendering/OpenGL2/glsl/vtkPolyDataFS.glsl +++ b/Rendering/OpenGL2/glsl/vtkPolyDataFS.glsl @@ -53,6 +53,15 @@ uniform int PrimitiveIDOffset; void main() { + // VC position of this fragment. This should not branch/return/discard. + //VTK::PositionVC::Impl + + // Place any calls that require uniform flow (e.g. dFdx) here. + //VTK::UniformFlow::Impl + + // Early depth peeling abort: + //VTK::DepthPeeling::PreColor + // Apple Bug //VTK::PrimID::Impl @@ -60,9 +69,6 @@ void main() //VTK::Color::Impl - // VC position of this fragment - //VTK::PositionVC::Impl - // Generate the normal if we are not passed in one //VTK::Normal::Impl diff --git a/Rendering/OpenGL2/vtkAndroidRenderWindowInteractor.cxx b/Rendering/OpenGL2/vtkAndroidRenderWindowInteractor.cxx index 973814a07d6..dac879f0524 100644 --- a/Rendering/OpenGL2/vtkAndroidRenderWindowInteractor.cxx +++ b/Rendering/OpenGL2/vtkAndroidRenderWindowInteractor.cxx @@ -442,7 +442,7 @@ void vtkAndroidRenderWindowInteractor::HandleMotionEvent( if (index > -1) { this->SetPointerIndex(index); - this->InvokeEvent(vtkCommand::LeftButtonPressEvent,NULL); + this->LeftButtonPressEvent(); } } return; @@ -455,7 +455,7 @@ void vtkAndroidRenderWindowInteractor::HandleMotionEvent( if (this->IsPointerIndexSet(i)) { this->SetPointerIndex(i); - this->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL); + this->LeftButtonReleaseEvent(); this->ClearPointerIndex(i); } } @@ -468,13 +468,13 @@ void vtkAndroidRenderWindowInteractor::HandleMotionEvent( if (i > -1) { this->SetPointerIndex(i); - this->InvokeEvent(vtkCommand::LeftButtonReleaseEvent,NULL); + this->LeftButtonReleaseEvent(); this->ClearContact(actionId); } } return; case AMOTION_EVENT_ACTION_MOVE: - this->InvokeEvent(vtkCommand::MouseMoveEvent, NULL); + this->MouseMoveEvent(); return; } // end switch action } diff --git a/Rendering/OpenGL2/vtkCameraPass.cxx b/Rendering/OpenGL2/vtkCameraPass.cxx index e88bbe90b12..c64fe465c12 100644 --- a/Rendering/OpenGL2/vtkCameraPass.cxx +++ b/Rendering/OpenGL2/vtkCameraPass.cxx @@ -104,7 +104,7 @@ void vtkCameraPass::Render(const vtkRenderState *s) int lowerLeft[2]; int usize; int vsize; - vtkFrameBufferObject *fbo=s->GetFrameBuffer(); + vtkFrameBufferObject *fbo=vtkFrameBufferObject::SafeDownCast(s->GetFrameBuffer()); vtkOpenGLRenderWindow *win=vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()); win->MakeCurrent(); diff --git a/Rendering/OpenGL2/vtkCameraPass.h b/Rendering/OpenGL2/vtkCameraPass.h index b09f57b1639..002b0a55605 100644 --- a/Rendering/OpenGL2/vtkCameraPass.h +++ b/Rendering/OpenGL2/vtkCameraPass.h @@ -39,12 +39,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkCameraPass : public vtkRenderPass vtkTypeMacro(vtkCameraPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL2/vtkClearZPass.h b/Rendering/OpenGL2/vtkClearZPass.h index c9a97d8ef5f..ff67f34ba4b 100644 --- a/Rendering/OpenGL2/vtkClearZPass.h +++ b/Rendering/OpenGL2/vtkClearZPass.h @@ -34,12 +34,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkClearZPass : public vtkRenderPass vtkTypeMacro(vtkClearZPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Set/Get the depth value. Initial value is 1.0 (farest). diff --git a/Rendering/OpenGL2/vtkCocoaMacOSXSDKCompatibility.h b/Rendering/OpenGL2/vtkCocoaMacOSXSDKCompatibility.h index 864c5b4ac62..2e9bb9de8c5 100644 --- a/Rendering/OpenGL2/vtkCocoaMacOSXSDKCompatibility.h +++ b/Rendering/OpenGL2/vtkCocoaMacOSXSDKCompatibility.h @@ -25,8 +25,8 @@ PURPOSE. See the above copyright notice for more information. #error VTK requires the Mac OS X 10.6 SDK or later #endif -#if MAC_OS_X_VERSION_MIN_REQUIRED < 1060 - #error VTK requires a deployment target of Mac OS X 10.6 or later +#if MAC_OS_X_VERSION_MIN_REQUIRED < 1068 + #error VTK requires a deployment target of Mac OS X 10.6.8 or later #endif // __has_feature is new in the 10.7 SDK, define it here if it's not yet defined. diff --git a/Rendering/OpenGL2/vtkCocoaRenderWindow.mm b/Rendering/OpenGL2/vtkCocoaRenderWindow.mm index 416e0bb3960..0681c2633b0 100644 --- a/Rendering/OpenGL2/vtkCocoaRenderWindow.mm +++ b/Rendering/OpenGL2/vtkCocoaRenderWindow.mm @@ -705,7 +705,6 @@ - (void)viewFrameDidChange:(NSNotification *)aNotification NSWindow* theWindow = nil; -#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060 NSScreen *screen = [NSScreen mainScreen]; if (this->FullScreen && screen) { @@ -725,7 +724,6 @@ - (void)viewFrameDidChange:(NSNotification *)aNotification //[theWindow setLevel:NSFloatingWindowLevel]; } else -#endif { if ((this->Size[0]+this->Size[1]) == 0) { @@ -873,11 +871,11 @@ - (void)viewFrameDidChange:(NSNotification *)aNotification int i = 0; NSOpenGLPixelFormatAttribute attribs[20]; -#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 +#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 attribs[i++] = NSOpenGLPFAOpenGLProfile; attribs[i++] = NSOpenGLProfileVersion3_2Core; #endif - // OSX always preferrs an accelerated context + // OS X always prefers an accelerated context // attribs[i++] = NSOpenGLPFAAccelerated; attribs[i++] = NSOpenGLPFADepthSize; attribs[i++] = (NSOpenGLPixelFormatAttribute)32; @@ -928,7 +926,7 @@ - (void)viewFrameDidChange:(NSNotification *)aNotification } else { -#if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_6 +#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 this->SetContextSupportsOpenGL32(true); #else this->SetContextSupportsOpenGL32(false); diff --git a/Rendering/OpenGL2/vtkCompositePolyDataMapper2.cxx b/Rendering/OpenGL2/vtkCompositePolyDataMapper2.cxx index 0bef5036c84..e9042ae19e4 100644 --- a/Rendering/OpenGL2/vtkCompositePolyDataMapper2.cxx +++ b/Rendering/OpenGL2/vtkCompositePolyDataMapper2.cxx @@ -625,7 +625,7 @@ int vtkCompositePolyDataMapper2::CanUseTextureMapForColoring(vtkDataObject*) this->CanUseTextureMapForColoringValue = 0; } if ((this->ColorMode == VTK_COLOR_MODE_DEFAULT && - vtkUnsignedCharArray::SafeDownCast(scalars)) || + vtkArrayDownCast(scalars)) || this->ColorMode == VTK_COLOR_MODE_DIRECT_SCALARS) { // Don't use texture is direct coloring using RGB unsigned chars is diff --git a/Rendering/OpenGL2/vtkDataTransferHelper.cxx b/Rendering/OpenGL2/vtkDataTransferHelper.cxx index 7c9c0aea6ca..c775dc2f46f 100644 --- a/Rendering/OpenGL2/vtkDataTransferHelper.cxx +++ b/Rendering/OpenGL2/vtkDataTransferHelper.cxx @@ -153,7 +153,6 @@ void vtkDataTransferHelper::SetContext(vtkRenderWindow* renWin) // \pre valid_gpu_extent: this->GetGPUExtentIsValid() // \pre gpu_extent_in_cpu_extent: CPUExtent[0]<=GPUExtent[0] && GPUExtent[1]<=CPUExtent[1] && CPUExtent[2]<=GPUExtent[2] && GPUExtent[3]<=CPUExtent[3] && CPUExtent[4]<=GPUExtent[4] && GPUExtent[5]<=CPUExtent[5] // \pre gpu_texture_size: !this->GetTextureExtentIsValid() || (GPUExtent[1]-GPUExtent[0]+1)*(GPUExtent[3]-GPUExtent[2]+1)*(GPUExtent[5]-GPUExtent[4]+1)==(TextureExtent[1]-TextureExtent[0]+1)*(TextureExtent[3]-TextureExtent[2]+1)*(TextureExtent[5]-TextureExtent[4]+1) - // \pre texture_can_exist_or_not: texture==0 || texture!=0 // \pre valid_components: (components==0 && componentList==0 && array->GetNumberOfComponents()<=4) || (components>=1 && components<=array->GetNumberOfComponents() && components<=4 && componentList!=0) bool vtkDataTransferHelper::Upload(int components, int *componentList) @@ -182,8 +181,6 @@ bool vtkDataTransferHelper::Upload(int components, (this->TextureExtent[1]-this->TextureExtent[0]+1)* (this->TextureExtent[3]-this->TextureExtent[2]+1)* (this->TextureExtent[5]-this->TextureExtent[4]+1)))); - assert("pre: texture_can_exist_or_not" && (this->Texture==0 || - this->Texture!=0)); assert("pre: valid_components" && ((components==0 && componentList==0 && this->Array->GetNumberOfComponents()<=4) || @@ -448,8 +445,6 @@ bool vtkDataTransferHelper::DownloadAsync1() (this->TextureExtent[1]-this->TextureExtent[0]+1)* (this->TextureExtent[3]-this->TextureExtent[2]+1)* (this->TextureExtent[5]-this->TextureExtent[4]+1)))); - assert("pre: texture_can_exist_or_not" && (this->Texture==0 || - this->Texture!=0)); assert("pre: valid_components" && (this->Array==0 || this->Array->GetNumberOfComponents()<=4)); assert("pre: components_match" && (this->Array==0 || diff --git a/Rendering/OpenGL2/vtkDataTransferHelper.h b/Rendering/OpenGL2/vtkDataTransferHelper.h index e0c4c9ad9d9..3ad96c49c69 100644 --- a/Rendering/OpenGL2/vtkDataTransferHelper.h +++ b/Rendering/OpenGL2/vtkDataTransferHelper.h @@ -186,7 +186,7 @@ class VTKRENDERINGOPENGL2_EXPORT vtkDataTransferHelper : public vtkObject // Description: // Returns if the context supports the required extensions. static bool IsSupported(vtkRenderWindow* renWin); -//BTX + protected: vtkDataTransferHelper(); ~vtkDataTransferHelper(); @@ -210,7 +210,7 @@ class VTKRENDERINGOPENGL2_EXPORT vtkDataTransferHelper : public vtkObject private: vtkDataTransferHelper(const vtkDataTransferHelper&); // Not implemented. void operator=(const vtkDataTransferHelper&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL2/vtkDefaultPass.h b/Rendering/OpenGL2/vtkDefaultPass.h index 0e30a34b63a..b30d9e12af5 100644 --- a/Rendering/OpenGL2/vtkDefaultPass.h +++ b/Rendering/OpenGL2/vtkDefaultPass.h @@ -44,14 +44,12 @@ class VTKRENDERINGOPENGL2_EXPORT vtkDefaultPass : public vtkRenderPass vtkTypeMacro(vtkDefaultPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // Call RenderOpaqueGeometry(), RenderTranslucentPolygonalGeometry(), // RenderVolumetricGeometry(), RenderOverlay() // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL2/vtkDepthImageProcessingPass.cxx b/Rendering/OpenGL2/vtkDepthImageProcessingPass.cxx index a0e699f9fe3..deaa7ccda4c 100644 --- a/Rendering/OpenGL2/vtkDepthImageProcessingPass.cxx +++ b/Rendering/OpenGL2/vtkDepthImageProcessingPass.cxx @@ -184,7 +184,8 @@ void vtkDepthImageProcessingPass::ReadWindowSize(const vtkRenderState* s) { assert("pre: s_exists" && s!=0); - vtkFrameBufferObject *fbo=s->GetFrameBuffer(); + vtkFrameBufferObject *fbo=vtkFrameBufferObject::SafeDownCast + (s->GetFrameBuffer()); vtkRenderer *r = s->GetRenderer(); if(fbo==0) { diff --git a/Rendering/OpenGL2/vtkDepthOfFieldPass.h b/Rendering/OpenGL2/vtkDepthOfFieldPass.h index 74c7253b439..245ba5382c1 100644 --- a/Rendering/OpenGL2/vtkDepthOfFieldPass.h +++ b/Rendering/OpenGL2/vtkDepthOfFieldPass.h @@ -58,12 +58,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkDepthOfFieldPass : public vtkDepthImageProce vtkGetMacro(AutomaticFocalDistance,bool); vtkBooleanMacro(AutomaticFocalDistance,bool); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL2/vtkDepthPeelingPass.cxx b/Rendering/OpenGL2/vtkDepthPeelingPass.cxx index 0d560f9fa07..36d0a07612f 100644 --- a/Rendering/OpenGL2/vtkDepthPeelingPass.cxx +++ b/Rendering/OpenGL2/vtkDepthPeelingPass.cxx @@ -15,9 +15,8 @@ PURPOSE. See the above copyright notice for more information. #include "vtkDepthPeelingPass.h" #include "vtkInformation.h" -#include "vtkInformationIntegerKey.h" -#include "vtkInformationIntegerVectorKey.h" #include "vtkObjectFactory.h" +#include "vtkOpenGLActor.h" #include "vtkOpenGLError.h" #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLRenderer.h" @@ -40,10 +39,6 @@ PURPOSE. See the above copyright notice for more information. vtkStandardNewMacro(vtkDepthPeelingPass); vtkCxxSetObjectMacro(vtkDepthPeelingPass,TranslucentPass,vtkRenderPass); -vtkInformationKeyMacro(vtkDepthPeelingPass,OpaqueZTextureUnit,Integer); -vtkInformationKeyMacro(vtkDepthPeelingPass,TranslucentZTextureUnit,Integer); -vtkInformationKeyMacro(vtkDepthPeelingPass,DestinationSize,IntegerVector); - // ---------------------------------------------------------------------------- vtkDepthPeelingPass::vtkDepthPeelingPass() { @@ -413,27 +408,23 @@ void vtkDepthPeelingPass::Render(const vtkRenderState *s) this->TranslucentZTexture->Activate(); this->OpaqueZTexture->Activate(); - // set the required keys on the props for the txture units - int destSize[2]; - destSize[0] = this->ViewportWidth; - destSize[1] = this->ViewportHeight; + // Setup property keys for actors: + this->PreRender(s); - int c = s->GetPropArrayCount(); - for (i = 0; i < c; i++) + // Enable the depth buffer (otherwise it's disabled for translucent geometry) + assert("Render state valid." && s); + int numProps = s->GetPropArrayCount(); + for (int j = 0; j < numProps; ++j) { - vtkProp *p=s->GetPropArray()[i]; - vtkInformation *info = p->GetPropertyKeys(); + vtkProp *prop = s->GetPropArray()[j]; + vtkInformation *info = prop->GetPropertyKeys(); if (!info) { info = vtkInformation::New(); - p->SetPropertyKeys(info); - info->Delete(); + prop->SetPropertyKeys(info); + info->FastDelete(); } - info->Set(vtkDepthPeelingPass::OpaqueZTextureUnit(), - this->OpaqueZTexture->GetTextureUnit()); - info->Set(vtkDepthPeelingPass::TranslucentZTextureUnit(), - this->TranslucentZTexture->GetTextureUnit()); - info->Set(vtkDepthPeelingPass::DestinationSize(),destSize,2); + info->Set(vtkOpenGLActor::GLDepthMaskOverride(), 1); } // Do render loop until complete @@ -518,6 +509,8 @@ void vtkDepthPeelingPass::Render(const vtkRenderState *s) } } +// std::cout << "Number of peels: " << peelCount << "\n"; + // unload the textures we are done with this->CurrentRGBATexture->Deactivate(); this->TranslucentZTexture->UnRegister(this); @@ -541,17 +534,70 @@ void vtkDepthPeelingPass::Render(const vtkRenderState *s) // restore blending glEnable(GL_BLEND); - c = s->GetPropArrayCount(); - for (i = 0; i < c; i++) + this->PostRender(s); + for (int j = 0; j < numProps; ++j) { - vtkProp *p=s->GetPropArray()[i]; - vtkInformation *info = p->GetPropertyKeys(); - info->Remove(vtkDepthPeelingPass::OpaqueZTextureUnit()); - info->Remove(vtkDepthPeelingPass::TranslucentZTextureUnit()); - info->Remove(vtkDepthPeelingPass::DestinationSize()); + vtkProp *prop = s->GetPropArray()[j]; + vtkInformation *info = prop->GetPropertyKeys(); + if (info) + { + info->Remove(vtkOpenGLActor::GLDepthMaskOverride()); + } } this->NumberOfRenderedProps = this->TranslucentPass->GetNumberOfRenderedProps(); vtkOpenGLCheckErrorMacro("failed after Render"); } + +//------------------------------------------------------------------------------ +bool vtkDepthPeelingPass::ReplaceShaderValues(std::string &, + std::string &, + std::string &fragmentShader, + vtkAbstractMapper *, + vtkProp *) +{ + vtkShaderProgram::Substitute( + fragmentShader, "//VTK::DepthPeeling::Dec", + "uniform vec2 screenSize;\n" + "uniform sampler2D opaqueZTexture;\n" + "uniform sampler2D translucentZTexture;\n" + ); + + // the .0000001 below is an epsilon. It turns out that + // graphics cards can render the same polygon two times + // in a row with different z values. I suspect it has to + // do with how rasterization of the polygon is broken up. + // A different breakup across fragment shaders can result in + // very slightly different z values for some of the pixels. + // The end result is that with depth peeling, you can end up + // counting/accumulating pixels of the same surface twice + // simply due to this randomness in z values. So we introduce + // an epsilon into the transparent test to require some + // minimal z seperation between pixels + vtkShaderProgram::Substitute( + fragmentShader, "//VTK::DepthPeeling::Impl", + "float odepth = texture2D(opaqueZTexture, gl_FragCoord.xy/screenSize).r;\n" + " if (gl_FragCoord.z >= odepth) { discard; }\n" + " float tdepth = texture2D(translucentZTexture, gl_FragCoord.xy/screenSize).r;\n" + " if (gl_FragCoord.z <= tdepth + .0000001) { discard; }\n" + ); + + return true; +} + +//------------------------------------------------------------------------------ +bool vtkDepthPeelingPass::SetShaderParameters(vtkShaderProgram *program, + vtkAbstractMapper*, vtkProp*) +{ + program->SetUniformi("opaqueZTexture", + this->OpaqueZTexture->GetTextureUnit()); + program->SetUniformi("translucentZTexture", + this->TranslucentZTexture->GetTextureUnit()); + + float screenSize[2] = { static_cast(this->ViewportWidth), + static_cast(this->ViewportHeight) }; + program->SetUniform2f("screenSize", screenSize); + + return true; +} diff --git a/Rendering/OpenGL2/vtkDepthPeelingPass.h b/Rendering/OpenGL2/vtkDepthPeelingPass.h index aba376caa4f..851975b5b4d 100644 --- a/Rendering/OpenGL2/vtkDepthPeelingPass.h +++ b/Rendering/OpenGL2/vtkDepthPeelingPass.h @@ -15,6 +15,11 @@ // .NAME vtkDepthPeelingPass - Implement an Order Independent Transparency // render pass. // .SECTION Description +// +// Note that this implementation is only used as a fallback for drivers that +// don't support floating point textures. Most renderings will use the subclass +// vtkDualDepthPeelingPass instead. +// // Render the translucent polygonal geometry of a scene without sorting // polygons in the view direction. // @@ -37,28 +42,25 @@ #define vtkDepthPeelingPass_h #include "vtkRenderingOpenGL2Module.h" // For export macro -#include "vtkRenderPass.h" +#include "vtkOpenGLRenderPass.h" #include // STL Header class vtkTextureObject; class vtkOpenGLRenderWindow; -class vtkInformationIntegerKey; -class vtkInformationIntegerVectorKey; class vtkOpenGLHelper; -class VTKRENDERINGOPENGL2_EXPORT vtkDepthPeelingPass : public vtkRenderPass +class VTKRENDERINGOPENGL2_EXPORT vtkDepthPeelingPass + : public vtkOpenGLRenderPass { public: static vtkDepthPeelingPass *New(); - vtkTypeMacro(vtkDepthPeelingPass,vtkRenderPass); + vtkTypeMacro(vtkDepthPeelingPass,vtkOpenGLRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own @@ -99,17 +101,14 @@ class VTKRENDERINGOPENGL2_EXPORT vtkDepthPeelingPass : public vtkRenderPass // (Used by vtkOpenGLProperty or vtkOpenGLTexture) // int GetDepthPeelingHigherLayer(); - // Description: - // Required Key Indicating the texture unit for the opaque z texture unit - static vtkInformationIntegerKey *OpaqueZTextureUnit(); - - // Description: - // Required Key Indicating the texture unit for the translucent z texture unit - static vtkInformationIntegerKey *TranslucentZTextureUnit(); - - // Description: - // Required Key Indicating the size of the destination - static vtkInformationIntegerVectorKey *DestinationSize(); + // vtkOpenGLRenderPass virtuals: + virtual bool ReplaceShaderValues(std::string &vertexShader, + std::string &geometryShader, + std::string &fragmentShader, + vtkAbstractMapper *mapper, + vtkProp *prop); + virtual bool SetShaderParameters(vtkShaderProgram *program, + vtkAbstractMapper *mapper, vtkProp *prop); protected: // Description: diff --git a/Rendering/OpenGL2/vtkDualDepthPeelingPass.cxx b/Rendering/OpenGL2/vtkDualDepthPeelingPass.cxx new file mode 100644 index 00000000000..ce9a51ce269 --- /dev/null +++ b/Rendering/OpenGL2/vtkDualDepthPeelingPass.cxx @@ -0,0 +1,970 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkDualDepthPeelingPass.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkDualDepthPeelingPass.h" + +#include "vtkFrameBufferObject2.h" +#include "vtkInformation.h" +#include "vtkInformationKey.h" +#include "vtkNew.h" +#include "vtkObjectFactory.h" +#include "vtkOpenGLActor.h" +#include "vtkOpenGLBufferObject.h" +#include "vtkOpenGLError.h" +#include "vtkOpenGLRenderUtilities.h" +#include "vtkOpenGLRenderWindow.h" +#include "vtkOpenGLShaderCache.h" +#include "vtkOpenGLVertexArrayObject.h" +#include "vtkRenderer.h" +#include "vtkRenderState.h" +#include "vtkShaderProgram.h" +#include "vtkTextureObject.h" +#include "vtkTypeTraits.h" + +#include + +// Define to print debug statements to the OpenGL CS stream (useful for e.g. +// apitrace debugging): +//#define ANNOTATE_STREAM + +// Define to output details about each peel: +//#define DEBUG_PEEL + +// Define to output details about each frame: +//#define DEBUG_FRAME + +vtkStandardNewMacro(vtkDualDepthPeelingPass) + +namespace +{ +void annotate(const std::string &str) +{ +#ifdef ANNOTATE_STREAM + vtkOpenGLStaticCheckErrorMacro("Error before glDebug.") + glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER, + GL_DEBUG_SEVERITY_NOTIFICATION, + 0, str.size(), str.c_str()); + vtkOpenGLClearErrorMacro(); +#else // ANNOTATE_STREAM + (void)str; +#endif // ANNOTATE_STREAM +} +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::PrintSelf(std::ostream &os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::Render(const vtkRenderState *s) +{ + // Setup vtkOpenGLRenderPass + this->PreRender(s); + + this->Initialize(s); + this->Prepare(); + + while (!this->PeelingDone()) + { + this->Peel(); + } + + this->Finalize(); + + this->PostRender(s); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::ReleaseGraphicsResources(vtkWindow *) +{ + this->FreeGLObjects(); +} + +//------------------------------------------------------------------------------ +bool vtkDualDepthPeelingPass::ReplaceShaderValues(std::string &, + std::string &, + std::string &fragmentShader, + vtkAbstractMapper *, + vtkProp *) +{ + switch (this->CurrentStage) + { + case vtkDualDepthPeelingPass::InitializingDepth: + vtkShaderProgram::Substitute( + fragmentShader, "//VTK::DepthPeeling::Dec", + "uniform sampler2D opaqueDepth;\n"); + vtkShaderProgram::Substitute( + fragmentShader, "//VTK::DepthPeeling::PreColor", + "ivec2 pixel = ivec2(gl_FragCoord.xy);\n" + " float oDepth = texelFetch(opaqueDepth, pixel, 0).y;\n" + " if (oDepth != -1. && gl_FragCoord.z > oDepth)\n" + " { // Ignore fragments that are occluded by opaque geometry:\n" + " gl_FragData[1].xy = vec2(-1., oDepth);\n" + " return;\n" + " }\n" + " else\n" + " {\n" + " gl_FragData[1].xy = vec2(-gl_FragCoord.z, gl_FragCoord.z);\n" + " return;\n" + " }\n" + ); + break; + + case vtkDualDepthPeelingPass::Peeling: + vtkShaderProgram::Substitute( + fragmentShader, "//VTK::DepthPeeling::Dec", + "uniform sampler2D lastFrontPeel;\n" + "uniform sampler2D lastDepthPeel;\n"); + vtkShaderProgram::Substitute( + fragmentShader, "//VTK::DepthPeeling::PreColor", + "float depth = gl_FragCoord.z;\n" + " ivec2 pixelCoord = ivec2(gl_FragCoord.xy);\n" + " vec4 front = texelFetch(lastFrontPeel, pixelCoord, 0);\n" + " vec2 minMaxDepth = texelFetch(lastDepthPeel, pixelCoord, 0).xy;\n" + " float minDepth = -minMaxDepth.x;\n" + " float maxDepth = minMaxDepth.y;\n" + "\n" + " // Default outputs (no data/change):\n" + " gl_FragData[0] = vec4(0.);\n" + " gl_FragData[1] = front;\n" + " gl_FragData[2].xy = vec2(-1.);\n" + "\n" + " // Is this fragment outside the current peels?\n" + " if (depth < minDepth || depth > maxDepth)\n" + " {\n" + " return;\n" + " }\n" + "\n" + " // Is this fragment inside the current peels?\n" + " if (depth > minDepth && depth < maxDepth)\n" + " {\n" + " // Write out depth so this frag will be peeled later:\n" + " gl_FragData[2].xy = vec2(-depth, depth);\n" + " return;\n" + " }\n" + "\n" + " // Continue processing for fragments on the current peel:\n" + ); + vtkShaderProgram::Substitute( + fragmentShader, "//VTK::DepthPeeling::Impl", + "vec4 frag = gl_FragData[0];\n" + " // Default outputs (no data/change):\n" + "\n" + " // This fragment is on a current peel:\n" + " if (depth == minDepth)\n" + " { // Front peel:\n" + " // Clear the back color:\n" + " gl_FragData[0] = vec4(0.);\n" + "\n" + " // We store the front alpha value as (1-alpha) to allow MAX\n" + " // blending. This also means it is really initialized to 1,\n" + " // as it should be for under-blending.\n" + " front.a = 1. - front.a;\n" + "\n" + " // Use under-blending to combine fragment with front color:\n" + " gl_FragData[1].rgb = front.a * frag.a * frag.rgb + front.rgb;\n" + " // Write out (1-alpha):\n" + " gl_FragData[1].a = 1. - (front.a * (1. - frag.a));\n" + " return;\n" + " }\n" + " else // (depth == maxDepth)\n" + " { // Back peel:\n" + " // Dump premultiplied fragment, it will be blended later:\n" + " frag.rgb *= frag.a;\n" + " gl_FragData[0] = frag;\n" + " return;\n" + " }\n" + ); + break; + + case vtkDualDepthPeelingPass::AlphaBlending: + vtkShaderProgram::Substitute( + fragmentShader, "//VTK::DepthPeeling::Dec", + "uniform sampler2D lastDepthPeel;\n"); + vtkShaderProgram::Substitute( + fragmentShader, "//VTK::DepthPeeling::PreColor", + "float depth = gl_FragCoord.z;\n" + " ivec2 pixelCoord = ivec2(gl_FragCoord.xy);\n" + " vec2 minMaxDepth = texelFetch(lastDepthPeel, pixelCoord, 0).xy;\n" + " float minDepth = -minMaxDepth.x;\n" + " float maxDepth = minMaxDepth.y;\n" + "\n" + " // Discard all fragments outside of the last set of peels:\n" + " if (depth < minDepth || depth > maxDepth)\n" + " {\n" + " discard;\n" + " }\n" + ); + vtkShaderProgram::Substitute( + fragmentShader, "//VTK::DepthPeeling::Impl", + "\n" + " // Pre-multiply alpha for depth peeling:\n" + " gl_FragData[0].rgb *= gl_FragData[0].a;\n" + ); + break; + + default: + break; + } + + return true; +} + +//------------------------------------------------------------------------------ +bool vtkDualDepthPeelingPass::SetShaderParameters(vtkShaderProgram *program, + vtkAbstractMapper *, + vtkProp *) +{ + switch (this->CurrentStage) + { + case vtkDualDepthPeelingPass::InitializingDepth: + program->SetUniformi( + "opaqueDepth", + this->Textures[this->DepthDestination]->GetTextureUnit()); + break; + + case vtkDualDepthPeelingPass::Peeling: + program->SetUniformi( + "lastDepthPeel", + this->Textures[this->DepthSource]->GetTextureUnit()); + program->SetUniformi( + "frontDepthPeel", + this->Textures[this->FrontSource]->GetTextureUnit()); + break; + + case vtkDualDepthPeelingPass::AlphaBlending: + program->SetUniformi( + "lastDepthPeel", + this->Textures[this->DepthSource]->GetTextureUnit()); + break; + + default: + break; + } + + return true; +} + +//------------------------------------------------------------------------------ +unsigned long vtkDualDepthPeelingPass::GetShaderStageMTime() +{ + return this->CurrentStageTimeStamp.GetMTime(); +} + +//------------------------------------------------------------------------------ +vtkDualDepthPeelingPass::vtkDualDepthPeelingPass() + : RenderState(NULL), + CopyDepthProgram(NULL), + CopyDepthVAO(NULL), + BackBlendProgram(NULL), + BackBlendVAO(NULL), + BlendProgram(NULL), + BlendVAO(NULL), + Framebuffer(NULL), + FrontSource(FrontA), + FrontDestination(FrontB), + DepthSource(DepthA), + DepthDestination(DepthB), + CurrentStage(Inactive), + CurrentPeel(0), + OcclusionQueryId(0), + WrittenPixels(0), + OcclusionThreshold(0), + RenderCount(0) +{ + std::fill(this->Textures, this->Textures + static_cast(NumberOfTextures), + static_cast(NULL)); +} + +//------------------------------------------------------------------------------ +vtkDualDepthPeelingPass::~vtkDualDepthPeelingPass() +{ + this->FreeGLObjects(); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::SetCurrentStage(ShaderStage stage) +{ + if (stage != this->CurrentStage) + { + this->CurrentStage = stage; + this->CurrentStageTimeStamp.Modified(); + } +} + +//------------------------------------------------------------------------------ +// Delete the vtkObject subclass pointed at by ptr if it is set. +namespace { +template void DeleteHelper(T *& ptr) +{ + if (ptr) + { + ptr->Delete(); + ptr = NULL; + } +} +} // end anon namespace + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::FreeGLObjects() +{ + if (this->Framebuffer) + { + this->Framebuffer->Delete(); + this->Framebuffer = NULL; + + for (int i = 0; i < static_cast(NumberOfTextures); ++i) + { + this->Textures[i]->Delete(); + this->Textures[i] = NULL; + } + } + + DeleteHelper(this->CopyDepthVAO); + DeleteHelper(this->BackBlendVAO); + DeleteHelper(this->BlendVAO); + + // don't delete the shader programs -- let the cache clean them up. +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::RenderTranslucentPass() +{ + this->TranslucentPass->Render(this->RenderState); + ++this->RenderCount; +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::Initialize(const vtkRenderState *s) +{ + this->RenderState = s; + + // Get current viewport size: + vtkRenderer *r=s->GetRenderer(); + if(s->GetFrameBuffer()==0) + { + // get the viewport dimensions + r->GetTiledSizeAndOrigin(&this->ViewportWidth, &this->ViewportHeight, + &this->ViewportX, &this->ViewportY); + } + else + { + int size[2]; + s->GetWindowSize(size); + this->ViewportWidth = size[0]; + this->ViewportHeight = size[1]; + this->ViewportX =0 ; + this->ViewportY = 0; + } + + // See if we can reuse existing textures: + if (this->Textures[Back] && + (static_cast(this->Textures[Back]->GetHeight()) != + this->ViewportHeight || + static_cast(this->Textures[Back]->GetWidth()) != + this->ViewportWidth)) + { + this->FreeGLObjects(); + } + + // Allocate new textures if needed: + if (!this->Framebuffer) + { + this->Framebuffer = vtkFrameBufferObject2::New(); + + std::generate(this->Textures, + this->Textures + static_cast(NumberOfTextures), + &vtkTextureObject::New); + + this->InitColorTexture(this->Textures[BackTemp], s); + this->InitColorTexture(this->Textures[Back], s); + this->InitColorTexture(this->Textures[FrontA], s); + this->InitColorTexture(this->Textures[FrontB], s); + this->InitDepthTexture(this->Textures[DepthA], s); + this->InitDepthTexture(this->Textures[DepthB], s); + this->InitOpaqueDepthTexture(this->Textures[OpaqueDepth], s); + + this->InitFramebuffer(s); + } +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::InitColorTexture(vtkTextureObject *tex, + const vtkRenderState *s) +{ + tex->SetContext(static_cast( + s->GetRenderer()->GetRenderWindow())); + tex->SetFormat(GL_RGBA); + tex->SetInternalFormat(GL_RGBA8); + tex->Allocate2D(this->ViewportWidth, this->ViewportHeight, 4, + vtkTypeTraits::VTK_TYPE_ID); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::InitDepthTexture(vtkTextureObject *tex, + const vtkRenderState *s) +{ + tex->SetContext(static_cast( + s->GetRenderer()->GetRenderWindow())); + tex->SetFormat(GL_RG); + tex->SetInternalFormat(GL_RG32F); + tex->Allocate2D(this->ViewportWidth, this->ViewportHeight, 2, + vtkTypeTraits::VTK_TYPE_ID); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::InitOpaqueDepthTexture(vtkTextureObject *tex, + const vtkRenderState *s) +{ + tex->SetContext(static_cast( + s->GetRenderer()->GetRenderWindow())); + tex->AllocateDepth(this->ViewportWidth, this->ViewportHeight, + vtkTextureObject::Float32); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::InitFramebuffer(const vtkRenderState *s) +{ + this->Framebuffer->SetContext(static_cast( + s->GetRenderer()->GetRenderWindow())); + + // Save the current FBO bindings to restore them later. + this->Framebuffer->SaveCurrentBindings(); + this->Framebuffer->Bind(GL_DRAW_FRAMEBUFFER); + + this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, BackTemp, + this->Textures[BackTemp]); + this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, Back, + this->Textures[Back]); + + this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, FrontA, + this->Textures[FrontA]); + this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, FrontB, + this->Textures[FrontB]); + + // The depth has to be treated like a color attachment, since it's a 2 + // component min-max texture. + this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, DepthA, + this->Textures[DepthA]); + this->Framebuffer->AddColorAttachment(GL_DRAW_FRAMEBUFFER, DepthB, + this->Textures[DepthB]); + + this->Framebuffer->UnBind(GL_DRAW_FRAMEBUFFER); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::Prepare() +{ + // Prevent vtkOpenGLActor from messing with the depth mask: + size_t numProps = this->RenderState->GetPropArrayCount(); + for (size_t i = 0; i < numProps; ++i) + { + vtkProp *prop = this->RenderState->GetPropArray()[i]; + vtkInformation *info = prop->GetPropertyKeys(); + if (!info) + { + info = vtkInformation::New(); + prop->SetPropertyKeys(info); + info->FastDelete(); + } + info->Set(vtkOpenGLActor::GLDepthMaskOverride(), -1); + } + + // Setup GL state: + glDisable(GL_DEPTH_TEST); + this->InitializeOcclusionQuery(); + this->CurrentPeel = 0; + this->RenderCount = 0; + + // Save the current FBO bindings to restore them later. + this->Framebuffer->SaveCurrentBindings(); + this->Framebuffer->Bind(GL_DRAW_FRAMEBUFFER); + + // The source front buffer must be initialized, since it simply uses additive + // blending. + // The back-blending may discard fragments, so the back peel accumulator needs + // initialization as well. + unsigned int targets[2] = { Back, this->FrontSource }; + this->Framebuffer->ActivateDrawBuffers(targets, 2); + glClearColor(0.f, 0.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT); + + // Fill both depth buffers with -1, -1. This lets us discard fragments in + // CopyOpaqueDepthBuffers, which gives a moderate performance boost. + targets[0] = this->DepthSource; + targets[1] = this->DepthDestination; + this->Framebuffer->ActivateDrawBuffers(targets, 2); + glClearColor(-1, -1, 0, 0); + glClear(GL_COLOR_BUFFER_BIT); + + // Pre-fill the depth buffer with opaque pass data: + this->CopyOpaqueDepthBuffer(); + + // Initialize the transparent depths for the peeling algorithm: + this->InitializeDepth(); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::InitializeOcclusionQuery() +{ + glGenQueries(1, &this->OcclusionQueryId); + + int numPixels = this->ViewportHeight * this->ViewportWidth; + this->OcclusionThreshold = numPixels * this->OcclusionRatio; + this->WrittenPixels = this->OcclusionThreshold + 1; +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::CopyOpaqueDepthBuffer() +{ + // Initialize the peeling depth buffer using the existing opaque depth buffer. + // Note that the min component is stored as -depth, allowing + // glBlendEquation = GL_MAX to be used during peeling. + + // Copy from the current (default) framebuffer's depth buffer into a texture: + this->Framebuffer->UnBind(GL_DRAW_FRAMEBUFFER); + this->Textures[OpaqueDepth]->CopyFromFrameBuffer( + this->ViewportX, this->ViewportY, 0, 0, + this->ViewportWidth, this->ViewportHeight); + this->Framebuffer->Bind(GL_DRAW_FRAMEBUFFER); + + // Fill both depth buffers with the opaque fragment depths. InitializeDepth + // will compare translucent fragment depths with values in DepthDestination + // and write to DepthSource using MAX blending, so we need both to have opaque + // fragments (src/dst seem reversed because they're named for their usage in + // PeelRender). + unsigned int targets[2] = { this->DepthSource, this->DepthDestination }; + this->Framebuffer->ActivateDrawBuffers(targets, 2); + this->Textures[OpaqueDepth]->Activate(); + + glDisable(GL_BLEND); + + typedef vtkOpenGLRenderUtilities GLUtil; + + vtkOpenGLRenderWindow *renWin = static_cast( + this->RenderState->GetRenderer()->GetRenderWindow()); + if (!this->CopyDepthProgram) + { + std::string fragShader = GLUtil::GetFullScreenQuadFragmentShaderTemplate(); + vtkShaderProgram::Substitute( + fragShader, "//VTK::FSQ::Decl", + "uniform float clearValue;\n" + "uniform sampler2D oDepth;\n"); + vtkShaderProgram::Substitute( + fragShader, "//VTK::FSQ::Impl", + " float d = texture2D(oDepth, texCoord).x;\n" + " if (d == clearValue)\n" + " { // If no depth value has been written, discard the frag:\n" + " discard;\n" + " }\n" + " gl_FragData[0] = gl_FragData[1] = vec4(-1, d, 0., 0.);\n" + ); + this->CopyDepthProgram = renWin->GetShaderCache()->ReadyShaderProgram( + GLUtil::GetFullScreenQuadVertexShader().c_str(), + fragShader.c_str(), + GLUtil::GetFullScreenQuadGeometryShader().c_str()); + } + else + { + renWin->GetShaderCache()->ReadyShaderProgram(this->CopyDepthProgram); + } + + if (!this->CopyDepthVAO) + { + this->CopyDepthVAO = vtkOpenGLVertexArrayObject::New(); + GLUtil::PrepFullScreenVAO(this->CopyDepthVAO, this->CopyDepthProgram); + } + + // Get the clear value. We don't set this, so it should still be what the + // opaque pass uses: + GLfloat clearValue = 1.f; + glGetFloatv(GL_DEPTH_CLEAR_VALUE, &clearValue); + this->CopyDepthProgram->SetUniformf("clearValue", clearValue); + this->CopyDepthProgram->SetUniformi( + "oDepth", this->Textures[OpaqueDepth]->GetTextureUnit()); + + this->CopyDepthVAO->Bind(); + + annotate("Copying opaque depth!"); + GLUtil::DrawFullScreenQuad(); + annotate("Opaque depth copied!"); + + this->CopyDepthVAO->Release(); + + this->Textures[OpaqueDepth]->Deactivate(); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::InitializeDepth() +{ + // Add the translucent geometry to our depth peeling buffer: + + // We bind the front destination buffer as render target 0 -- the data we + // write to it isn't used, but this makes it easier to work with the existing + // polydata shaders as they expect gl_FragData[0] to be RGBA. The front + // destination buffer is cleared prior to peeling, so it's just a dummy + // buffer at this point. + unsigned int targets[2] = { this->FrontDestination, this->DepthSource }; + this->Framebuffer->ActivateDrawBuffers(targets, 2); + + this->SetCurrentStage(InitializingDepth); + this->Textures[this->DepthDestination]->Activate(); + + glEnable(GL_BLEND); + glBlendEquation(GL_MAX); + annotate("Initializing depth."); + this->RenderTranslucentPass(); + annotate("Depth initialized"); + + this->Textures[this->DepthDestination]->Deactivate(); +} + +//------------------------------------------------------------------------------ +bool vtkDualDepthPeelingPass::PeelingDone() +{ + return this->CurrentPeel >= this->MaximumNumberOfPeels || + this->WrittenPixels <= this->OcclusionThreshold; +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::Peel() +{ + this->InitializeTargets(); + this->PeelRender(); + this->BlendBackBuffer(); + this->SwapTargets(); + ++this->CurrentPeel; + +#ifdef DEBUG_PEEL + std::cout << "Peel " << this->CurrentPeel << ": Pixels written: " + << this->WrittenPixels << " (threshold: " + << this->OcclusionThreshold << ")\n"; +#endif // DEBUG_PEEL +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::InitializeTargets() +{ + // Initialize destination buffers to their minima, since we're MAX blending, + // this ensures that valid outputs are captured. + unsigned int destColorBuffers[2] = { this->FrontDestination, BackTemp }; + this->Framebuffer->ActivateDrawBuffers(destColorBuffers, 2); + glClearColor(0.f, 0.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT); + + this->Framebuffer->ActivateDrawBuffer(this->DepthDestination); + glClearColor(-1.f, -1.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::PeelRender() +{ + // Enable the destination targets: + unsigned int targets[3] = { BackTemp, this->FrontDestination, + this->DepthDestination }; + this->Framebuffer->ActivateDrawBuffers(targets, 3); + + // Use MAX blending to capture peels: + glEnable(GL_BLEND); + glBlendEquation(GL_MAX); + + this->SetCurrentStage(Peeling); + this->Textures[this->FrontSource]->Activate(); + this->Textures[this->DepthSource]->Activate(); + + annotate("Start peeling!"); + this->RenderTranslucentPass(); + annotate("Peeling done!"); + + this->Textures[this->FrontSource]->Deactivate(); + this->Textures[this->DepthSource]->Deactivate(); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::BlendBackBuffer() +{ + this->Framebuffer->ActivateDrawBuffer(Back); + this->Textures[BackTemp]->Activate(); + + /* For this step, we blend the last peel's back fragments into a back- + * accumulation buffer. The full over-blending equations are: + * + * (f = front frag (incoming peel); b = back frag (current accum. buffer)) + * + * a = f.a + (1. - f.a) * b.a + * + * if a == 0, C == (0, 0, 0). Otherwise, + * + * C = ( f.a * f.rgb + (1. - f.a) * b.a * b.rgb ) / a + * + * We use premultiplied alphas to save on computations, resulting in: + * + * [a * C] = [f.a * f.rgb] + (1 - f.a) * [ b.a * b.rgb ] + * a = f.a + (1. - f.a) * b.a + */ + + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + + typedef vtkOpenGLRenderUtilities GLUtil; + + vtkOpenGLRenderWindow *renWin = static_cast( + this->RenderState->GetRenderer()->GetRenderWindow()); + if (!this->BackBlendProgram) + { + std::string fragShader = GLUtil::GetFullScreenQuadFragmentShaderTemplate(); + vtkShaderProgram::Substitute( + fragShader, "//VTK::FSQ::Decl", + "uniform sampler2D newPeel;\n" + ); + vtkShaderProgram::Substitute( + fragShader, "//VTK::FSQ::Impl", + " vec4 f = texture2D(newPeel, texCoord); // new frag\n" + " if (f.a == 0.)\n" + " {\n" + " discard;\n" + " }\n" + "\n" + " gl_FragData[0] = f;\n" + ); + this->BackBlendProgram = renWin->GetShaderCache()->ReadyShaderProgram( + GLUtil::GetFullScreenQuadVertexShader().c_str(), + fragShader.c_str(), + GLUtil::GetFullScreenQuadGeometryShader().c_str()); + } + else + { + renWin->GetShaderCache()->ReadyShaderProgram(this->BackBlendProgram); + } + + if (!this->BackBlendVAO) + { + this->BackBlendVAO = vtkOpenGLVertexArrayObject::New(); + GLUtil::PrepFullScreenVAO(this->BackBlendVAO, this->BackBlendProgram); + } + + this->BackBlendProgram->SetUniformi( + "newPeel", this->Textures[BackTemp]->GetTextureUnit()); + + this->BackBlendVAO->Bind(); + + this->StartOcclusionQuery(); + annotate("Start blending back!"); + GLUtil::DrawFullScreenQuad(); + annotate("Back blended!"); + this->EndOcclusionQuery(); + + this->BackBlendVAO->Release(); + + this->Textures[BackTemp]->Deactivate(); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::StartOcclusionQuery() +{ + // ES 3.0 only supports checking if *any* samples passed. We'll just use + // that query to stop peeling once all frags are processed, and ignore the + // requested occlusion ratio. +#if GL_ES_VERSION_3_0 == 1 + glBeginQuery(GL_ANY_SAMPLES_PASSED, this->OcclusionQueryId); +#else // GL ES 3.0 + glBeginQuery(GL_SAMPLES_PASSED, this->OcclusionQueryId); +#endif // GL ES 3.0 +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::EndOcclusionQuery() +{ +#if GL_ES_VERSION_3_0 == 1 + glEndQuery(GL_ANY_SAMPLES_PASSED); + GLuint anySamplesPassed; + glGetQueryObjectuiv(this->OcclusionQueryId, GL_QUERY_RESULT, + &anySamplesPassed); + this->WrittenPixels = anySamplesPassed ? this->OcclusionThreshold + 1 + : 0; +#else // GL ES 3.0 + glEndQuery(GL_SAMPLES_PASSED); + glGetQueryObjectuiv(this->OcclusionQueryId, GL_QUERY_RESULT, + &this->WrittenPixels); +#endif // GL ES 3.0 +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::SwapTargets() +{ + std::swap(this->FrontSource, this->FrontDestination); + std::swap(this->DepthSource, this->DepthDestination); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::Finalize() +{ + // Mop up any unrendered fragments using simple alpha blending into the back + // buffer. + if (this->WrittenPixels > 0) + { + this->AlphaBlendRender(); + } + + this->NumberOfRenderedProps = + this->TranslucentPass->GetNumberOfRenderedProps(); + + this->Framebuffer->UnBind(GL_DRAW_FRAMEBUFFER); + this->BlendFinalImage(); + + // Restore blending parameters: + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + size_t numProps = this->RenderState->GetPropArrayCount(); + for (size_t i = 0; i < numProps; ++i) + { + vtkProp *prop = this->RenderState->GetPropArray()[i]; + vtkInformation *info = prop->GetPropertyKeys(); + if (info) + { + info->Remove(vtkOpenGLActor::GLDepthMaskOverride()); + } + } + + this->RenderState = NULL; + this->DeleteOcclusionQueryId(); + this->SetCurrentStage(Inactive); + +#ifdef DEBUG_FRAME + std::cout << "Depth peel done:\n" + << " - Number of peels: " << this->CurrentPeel << "\n" + << " - Number of geometry passes: " << this->RenderCount << "\n" + << " - Occlusion Ratio: " + << static_cast(this->WrittenPixels) / + static_cast(this->ViewportWidth * this->ViewportHeight) + << " (target: " << this->OcclusionRatio << ")\n"; +#endif // DEBUG_FRAME +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::AlphaBlendRender() +{ + /* This pass is mopping up the remaining fragments when we exceed the max + * number of peels or hit the occlusion limit. We'll simply render all of the + * remaining fragments into the back destination buffer using the + * premultiplied-alpha over-blending equations: + * + * aC = f.a * f.rgb + (1 - f.a) * b.a * b.rgb + * a = f.a + (1 - f.a) * b.a + */ + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + + this->SetCurrentStage(AlphaBlending); + this->Framebuffer->ActivateDrawBuffer(Back); + this->Textures[this->DepthSource]->Activate(); + + annotate("Alpha blend render start"); + this->RenderTranslucentPass(); + annotate("Alpha blend render end"); + + this->Textures[this->DepthSource]->Deactivate(); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::BlendFinalImage() +{ + this->Textures[this->FrontSource]->Activate(); + this->Textures[Back]->Activate(); + + /* The final pixel (including the opaque layer is: + * + * C = (1 - b.a) * f.a * o.a * o.rgb + f.a * (b.a * b.rgb) + f.rgb + * + * ( C = final color; o = opaque frag; b = back frag; f = front frag ) + * + * This is obtained from repeatedly applying the underblend equations: + * + * C = f.a * b.a * b.rgb + f.rgb + * a = (1 - b.a) * f.a + * + * These blending parameters and fragment shader perform this work. + * Note that the opaque fragments are assumed to have premultiplied alpha + * in this implementation. */ + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_ONE, GL_SRC_ALPHA); + + typedef vtkOpenGLRenderUtilities GLUtil; + + vtkOpenGLRenderWindow *renWin = static_cast( + this->RenderState->GetRenderer()->GetRenderWindow()); + if (!this->BlendProgram) + { + std::string fragShader = GLUtil::GetFullScreenQuadFragmentShaderTemplate(); + vtkShaderProgram::Substitute( + fragShader, "//VTK::FSQ::Decl", + "uniform sampler2D frontTexture;\n" + "uniform sampler2D backTexture;\n" + ); + vtkShaderProgram::Substitute( + fragShader, "//VTK::FSQ::Impl", + " vec4 front = texture2D(frontTexture, texCoord);\n" + " vec4 back = texture2D(backTexture, texCoord);\n" + " front.a = 1. - front.a; // stored as (1 - alpha)\n" + " // Underblend. Back color is premultiplied:\n" + " gl_FragData[0].rgb = (front.rgb + back.rgb * front.a);\n" + " gl_FragData[0].a = front.a * (1 - back.a);\n" + ); + this->BlendProgram = renWin->GetShaderCache()->ReadyShaderProgram( + GLUtil::GetFullScreenQuadVertexShader().c_str(), + fragShader.c_str(), + GLUtil::GetFullScreenQuadGeometryShader().c_str()); + } + else + { + renWin->GetShaderCache()->ReadyShaderProgram(this->BlendProgram); + } + + if (!this->BlendVAO) + { + this->BlendVAO = vtkOpenGLVertexArrayObject::New(); + GLUtil::PrepFullScreenVAO(this->BlendVAO, this->BlendProgram); + } + + this->BlendProgram->SetUniformi( + "frontTexture", this->Textures[this->FrontSource]->GetTextureUnit()); + this->BlendProgram->SetUniformi( + "backTexture", this->Textures[Back]->GetTextureUnit()); + + this->BlendVAO->Bind(); + + annotate("blending final!"); + GLUtil::DrawFullScreenQuad(); + annotate("final blended!"); + + this->BlendVAO->Release(); + + this->Textures[this->FrontSource]->Deactivate(); + this->Textures[Back]->Deactivate(); +} + +//------------------------------------------------------------------------------ +void vtkDualDepthPeelingPass::DeleteOcclusionQueryId() +{ + glDeleteQueries(1, &this->OcclusionQueryId); +} diff --git a/Rendering/OpenGL2/vtkDualDepthPeelingPass.h b/Rendering/OpenGL2/vtkDualDepthPeelingPass.h new file mode 100644 index 00000000000..7e65152e134 --- /dev/null +++ b/Rendering/OpenGL2/vtkDualDepthPeelingPass.h @@ -0,0 +1,196 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkDualDepthPeelingPass.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +// .NAME vtkDualDepthPeelingPass - Implements the dual depth peeling algorithm. +// +// .SECTION Description +// Dual depth peeling is an augmentatation of the standard depth peeling +// algorithm that peels two layers (front and back) for each render pass. The +// technique is described in "Order independent transparency with dual depth +// peeling" (February 2008) by L. Bavoil, K. Myers. +// +// The pass occurs in several stages: +// +// 1. Copy the current (opaque geometry) depth buffer into a texture. +// 2. Initialize the min-max depth buffer from the opaque depth texture and the +// translucent geometry. +// 3. Peel the nearest and farthest fragments: +// 3a. Blend fragments that match the nearest depth of the min-max depth buffer +// into the front buffer. +// 3b. Write the far depth fragments into a temporary buffer. +// 3c. Extract the next set of min/max depth values for the next peel. +// 3d. Blend the temporary far fragment texture (3b) into an accumulation +// texture. +// 3e. Go back to 3a and repeat until the maximum number of peels is met, or +// the desired occlusion ratio is satisfied. +// 4. If the occlusion ratio != 0 (i.e. we hit the maximum number of peels +// before finishing), alpha blend the remaining fragments in-between the +// near and far accumulation textures. +// 5. Blend all accumulation buffers over the opaque color buffer to produce the +// final image. + + +#ifndef vtkDualDepthPeelingPass_h +#define vtkDualDepthPeelingPass_h + +#include "vtkRenderingOpenGL2Module.h" // For export macro +#include "vtkDepthPeelingPass.h" + +class vtkFrameBufferObject2; +class vtkOpenGLBufferObject; +class vtkOpenGLVertexArrayObject; +class vtkShaderProgram; +class vtkTextureObject; + +class VTKRENDERINGOPENGL2_EXPORT vtkDualDepthPeelingPass: + public vtkDepthPeelingPass +{ +public: + static vtkDualDepthPeelingPass* New(); + vtkTypeMacro(vtkDualDepthPeelingPass, vtkDepthPeelingPass) + virtual void PrintSelf(ostream &os, vtkIndent indent); + + virtual void Render(const vtkRenderState *s); + virtual void ReleaseGraphicsResources(vtkWindow *w); + + // vtkOpenGLRenderPass virtuals: + virtual bool ReplaceShaderValues(std::string &vertexShader, + std::string &geometryShader, + std::string &fragmentShader, + vtkAbstractMapper *mapper, + vtkProp *prop); + virtual bool SetShaderParameters(vtkShaderProgram *program, + vtkAbstractMapper *mapper, vtkProp *prop); + virtual unsigned long int GetShaderStageMTime(); + +protected: + + // Name the textures used by this render pass. These are indexes into + // this->Textures + enum TextureName + { + BackTemp = 0, // RGBA8 back-to-front peeling buffer + Back, // RGBA8 back-to-front accumulation buffer + FrontA, // RGBA8 front-to-back accumulation buffer + FrontB, // RGBA8 front-to-back accumulation buffer + DepthA, // RG32F min-max depth buffer + DepthB, // RG32F min-max depth buffer + OpaqueDepth, // Stores the depth map from the opaque passes + + NumberOfTextures + }; + + // The stages of this multipass render pass: + enum ShaderStage + { + InitializingDepth, + Peeling, + AlphaBlending, + + NumberOfPasses, + Inactive = -1, + }; + + vtkDualDepthPeelingPass(); + ~vtkDualDepthPeelingPass(); + + void SetCurrentStage(ShaderStage stage); + + // Description: + // Release all FBOs and textures. + void FreeGLObjects(); + + // Description: + // Render the translucent pass geometry, counting number of render calls. + void RenderTranslucentPass(); + + // Description: + // Allocate and configure FBOs and textures. + void Initialize(const vtkRenderState *s); + + // Description: + // Initialize helpers. + void InitColorTexture(vtkTextureObject *tex, const vtkRenderState *s); + void InitDepthTexture(vtkTextureObject *tex, const vtkRenderState *s); + void InitOpaqueDepthTexture(vtkTextureObject *tex, const vtkRenderState *s); + void InitFramebuffer(const vtkRenderState *s); + + // Description: + // Fill textures with initial values, bind the framebuffer. + void Prepare(); + void InitializeOcclusionQuery(); + void CopyOpaqueDepthBuffer(); + void InitializeDepth(); + + bool PeelingDone(); + + // Description: + // Render the scene to produce the next set of peels. + void Peel(); + + void InitializeTargets(); + + void PeelRender(); + + void BlendBackBuffer(); + void StartOcclusionQuery(); + void EndOcclusionQuery(); + + // Description: + // Swap the src/dest render targets: + void SwapTargets(); + + void Finalize(); + + void AlphaBlendRender(); + + void BlendFinalImage(); + void DeleteOcclusionQueryId(); + + const vtkRenderState *RenderState; + + vtkShaderProgram *CopyDepthProgram; + vtkOpenGLVertexArrayObject *CopyDepthVAO; + + vtkShaderProgram *BackBlendProgram; + vtkOpenGLVertexArrayObject *BackBlendVAO; + + vtkShaderProgram *BlendProgram; + vtkOpenGLVertexArrayObject *BlendVAO; + + vtkFrameBufferObject2 *Framebuffer; + vtkTextureObject *Textures[NumberOfTextures]; + + TextureName FrontSource; // The current front source buffer + TextureName FrontDestination; // The current front destination buffer + TextureName DepthSource; // The current depth source buffer + TextureName DepthDestination; // The current depth destination buffer + + ShaderStage CurrentStage; + vtkTimeStamp CurrentStageTimeStamp; + + int CurrentPeel; + unsigned int OcclusionQueryId; + unsigned int WrittenPixels; + unsigned int OcclusionThreshold; + + int RenderCount; // Debug info, counts number of geometry passes. + +private: + vtkDualDepthPeelingPass(const vtkDualDepthPeelingPass&); // Not implemented + void operator=(const vtkDualDepthPeelingPass&); // Not implemented +}; + +#endif // vtkDualDepthPeelingPass_h diff --git a/Rendering/OpenGL2/vtkEDLShading.cxx b/Rendering/OpenGL2/vtkEDLShading.cxx index 3bd7059c81c..d94a88d4e75 100644 --- a/Rendering/OpenGL2/vtkEDLShading.cxx +++ b/Rendering/OpenGL2/vtkEDLShading.cxx @@ -733,7 +733,7 @@ void vtkEDLShading::Render(const vtkRenderState *s) // if(s->GetFrameBuffer() != NULL) { - s->GetFrameBuffer()->Bind(); + vtkFrameBufferObject::SafeDownCast(s->GetFrameBuffer())->Bind(); } #if GL_ES_VERSION_2_0 != 1 glDrawBuffer(static_cast(savedCurrentDrawBuffer)); diff --git a/Rendering/OpenGL2/vtkEDLShading.h b/Rendering/OpenGL2/vtkEDLShading.h index 2a129241f6c..baab890bfe5 100644 --- a/Rendering/OpenGL2/vtkEDLShading.h +++ b/Rendering/OpenGL2/vtkEDLShading.h @@ -73,12 +73,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkEDLShading : public vtkDepthImageProcessingP vtkTypeMacro(vtkEDLShading,vtkDepthImageProcessingPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL2/vtkEGLRenderWindow.cxx b/Rendering/OpenGL2/vtkEGLRenderWindow.cxx index b5432245557..c76a38ffc9e 100644 --- a/Rendering/OpenGL2/vtkEGLRenderWindow.cxx +++ b/Rendering/OpenGL2/vtkEGLRenderWindow.cxx @@ -29,6 +29,9 @@ #include #include +#if ANDROID +#include +#endif namespace @@ -513,7 +516,7 @@ void vtkEGLRenderWindow::MakeCurrent() { if (eglMakeCurrent(impl->Display, impl->Surface, impl->Surface, impl->Context) == EGL_FALSE) { - vtkErrorMacro("Unable to eglMakeCurrent"); + vtkWarningMacro("Unable to eglMakeCurrent: " << eglGetError()); return; } } diff --git a/Rendering/OpenGL2/vtkFrameBufferObject.h b/Rendering/OpenGL2/vtkFrameBufferObject.h index de1e42bdec6..f3c66da4b0e 100644 --- a/Rendering/OpenGL2/vtkFrameBufferObject.h +++ b/Rendering/OpenGL2/vtkFrameBufferObject.h @@ -25,7 +25,7 @@ #ifndef vtkFrameBufferObject_h #define vtkFrameBufferObject_h -#include "vtkObject.h" +#include "vtkFrameBufferObjectBase.h" #include "vtkRenderingOpenGL2Module.h" // For export macro #include "vtkSmartPointer.h" // needed for vtkSmartPointer. #include "vtkWeakPointer.h" // needed for vtkWeakPointer. @@ -39,11 +39,11 @@ class vtkOpenGLRenderWindow; class vtkShaderProgram; class vtkOpenGLVertexArrayObject; -class VTKRENDERINGOPENGL2_EXPORT vtkFrameBufferObject : public vtkObject +class VTKRENDERINGOPENGL2_EXPORT vtkFrameBufferObject : public vtkFrameBufferObjectBase { public: static vtkFrameBufferObject* New(); - vtkTypeMacro(vtkFrameBufferObject, vtkObject); + vtkTypeMacro(vtkFrameBufferObject, vtkFrameBufferObjectBase); void PrintSelf(ostream& os, vtkIndent indent); // Description: diff --git a/Rendering/OpenGL2/vtkFrameBufferObject2.h b/Rendering/OpenGL2/vtkFrameBufferObject2.h index 4bb173cef1e..f103d3c1da1 100644 --- a/Rendering/OpenGL2/vtkFrameBufferObject2.h +++ b/Rendering/OpenGL2/vtkFrameBufferObject2.h @@ -274,7 +274,6 @@ class VTKRENDERINGOPENGL2_EXPORT vtkFrameBufferObject2 : public vtkObject int oglFormat, vtkPixelBufferObject *pbo); -//BTX protected: // Description: // Load all necessary extensions. @@ -308,7 +307,7 @@ class VTKRENDERINGOPENGL2_EXPORT vtkFrameBufferObject2 : public vtkObject void operator=(const vtkFrameBufferObject2&); // Not implemented. friend class vtkRenderbuffer; // needs access to LoadRequiredExtentsions -//ETX + }; #endif diff --git a/Rendering/OpenGL2/vtkGaussianBlurPass.h b/Rendering/OpenGL2/vtkGaussianBlurPass.h index 1636557a5df..a9653c2c5fa 100644 --- a/Rendering/OpenGL2/vtkGaussianBlurPass.h +++ b/Rendering/OpenGL2/vtkGaussianBlurPass.h @@ -62,12 +62,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkGaussianBlurPass : public vtkImageProcessing vtkTypeMacro(vtkGaussianBlurPass,vtkImageProcessingPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL2/vtkGenericCompositePolyDataMapper2.cxx b/Rendering/OpenGL2/vtkGenericCompositePolyDataMapper2.cxx index 567a9a3305e..db853ef97f9 100644 --- a/Rendering/OpenGL2/vtkGenericCompositePolyDataMapper2.cxx +++ b/Rendering/OpenGL2/vtkGenericCompositePolyDataMapper2.cxx @@ -620,7 +620,7 @@ void vtkGenericCompositePolyDataMapper2::RenderBlock(vtkRenderer *renderer, { if (selector && selector->GetCurrentPass() == vtkHardwareSelector::COMPOSITE_INDEX_PASS && (!this->CompositeIdArrayName || !ds->GetCellData() || - vtkUnsignedIntArray::SafeDownCast( + vtkArrayDownCast( ds->GetCellData()->GetArray(this->CompositeIdArrayName)) == NULL)) { helper->SetPopulateSelectionSettings(0); diff --git a/Rendering/OpenGL2/vtkGenericCompositePolyDataMapper2.h b/Rendering/OpenGL2/vtkGenericCompositePolyDataMapper2.h index b49b359cba4..84890b96c04 100644 --- a/Rendering/OpenGL2/vtkGenericCompositePolyDataMapper2.h +++ b/Rendering/OpenGL2/vtkGenericCompositePolyDataMapper2.h @@ -88,7 +88,6 @@ class VTKRENDERINGOPENGL2_EXPORT vtkGenericCompositePolyDataMapper2 : public vtk // resources to release. void ReleaseGraphicsResources(vtkWindow *); -//BTX protected: vtkGenericCompositePolyDataMapper2(); ~vtkGenericCompositePolyDataMapper2(); @@ -160,7 +159,7 @@ class VTKRENDERINGOPENGL2_EXPORT vtkGenericCompositePolyDataMapper2 : public vtk vtkGenericCompositePolyDataMapper2(const vtkGenericCompositePolyDataMapper2&); // Not implemented. void operator=(const vtkGenericCompositePolyDataMapper2&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/OpenGL2/vtkLightingMapPass.h b/Rendering/OpenGL2/vtkLightingMapPass.h index 388810d116f..96466695aa4 100644 --- a/Rendering/OpenGL2/vtkLightingMapPass.h +++ b/Rendering/OpenGL2/vtkLightingMapPass.h @@ -58,12 +58,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkLightingMapPass : public vtkDefaultPass // the RENDER_LUMINANCE key. static vtkInformationIntegerKey *RENDER_NORMALS(); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL2/vtkLightsPass.h b/Rendering/OpenGL2/vtkLightsPass.h index 9492da7a2ea..9b6c4746c7c 100644 --- a/Rendering/OpenGL2/vtkLightsPass.h +++ b/Rendering/OpenGL2/vtkLightsPass.h @@ -38,12 +38,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkLightsPass : public vtkRenderPass vtkTypeMacro(vtkLightsPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL2/vtkOpaquePass.h b/Rendering/OpenGL2/vtkOpaquePass.h index 58055064fd0..8d2bf33ed15 100644 --- a/Rendering/OpenGL2/vtkOpaquePass.h +++ b/Rendering/OpenGL2/vtkOpaquePass.h @@ -38,12 +38,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpaquePass : public vtkDefaultPass vtkTypeMacro(vtkOpaquePass,vtkDefaultPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL2/vtkOpenGLActor.cxx b/Rendering/OpenGL2/vtkOpenGLActor.cxx index 7becdc5a64a..3a617eb6d7a 100644 --- a/Rendering/OpenGL2/vtkOpenGLActor.cxx +++ b/Rendering/OpenGL2/vtkOpenGLActor.cxx @@ -15,7 +15,9 @@ #include "vtkOpenGLActor.h" #include "vtkDepthPeelingPass.h" +#include "vtkDualDepthPeelingPass.h" #include "vtkInformation.h" +#include "vtkInformationIntegerKey.h" #include "vtkMapper.h" #include "vtkMatrix3x3.h" #include "vtkMatrix4x4.h" @@ -31,6 +33,8 @@ vtkStandardNewMacro(vtkOpenGLActor); +vtkInformationKeyMacro(vtkOpenGLActor, GLDepthMaskOverride, Integer) + vtkOpenGLActor::vtkOpenGLActor() { this->MCWCMatrix = vtkMatrix4x4::New(); @@ -69,9 +73,21 @@ void vtkOpenGLActor::Render(vtkRenderer *ren, vtkMapper *mapper) { // check for deptgh peeling vtkInformation *info = this->GetPropertyKeys(); - if (info && info->Has(vtkDepthPeelingPass::OpaqueZTextureUnit())) + if (info && info->Has(vtkOpenGLActor::GLDepthMaskOverride())) { - glDepthMask(GL_TRUE); // transparency with depth peeling + int override = info->Get(vtkOpenGLActor::GLDepthMaskOverride()); + switch (override) + { + case 0: + glDepthMask(GL_FALSE); + break; + case 1: + glDepthMask(GL_TRUE); + break; + default: + // Do nothing. + break; + } } else { diff --git a/Rendering/OpenGL2/vtkOpenGLActor.h b/Rendering/OpenGL2/vtkOpenGLActor.h index 556babff27f..e0b77e2e2b0 100644 --- a/Rendering/OpenGL2/vtkOpenGLActor.h +++ b/Rendering/OpenGL2/vtkOpenGLActor.h @@ -23,6 +23,7 @@ #include "vtkRenderingOpenGL2Module.h" // For export macro #include "vtkActor.h" +class vtkInformationIntegerKey; class vtkOpenGLRenderer; class vtkMatrix4x4; class vtkMatrix3x3; @@ -40,6 +41,21 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLActor : public vtkActor void GetKeyMatrices(vtkMatrix4x4 *&WCVCMatrix, vtkMatrix3x3 *&normalMatrix); + // Description: + // If this key is set in GetPropertyKeys(), the glDepthMask will be adjusted + // prior to rendering translucent objects. This is useful for e.g. depth + // peeling. + // + // If GetIsOpaque() == true, the depth mask is always enabled, regardless of + // this key. Otherwise, the depth mask is disabled for default alpha blending + // unless this key is set. + // + // If this key is set, the integer value has the following meanings: + // 0: glDepthMask(GL_FALSE) + // 1: glDepthMask(GL_TRUE) + // Anything else: No change to depth mask. + static vtkInformationIntegerKey* GLDepthMaskOverride(); + protected: vtkOpenGLActor(); ~vtkOpenGLActor(); diff --git a/Rendering/OpenGL2/vtkOpenGLCamera.h b/Rendering/OpenGL2/vtkOpenGLCamera.h index af962d32d1a..29371745ed3 100644 --- a/Rendering/OpenGL2/vtkOpenGLCamera.h +++ b/Rendering/OpenGL2/vtkOpenGLCamera.h @@ -35,11 +35,11 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLCamera : public vtkCamera // Description: // Implement base class method. - void Render(vtkRenderer *ren); + virtual void Render(vtkRenderer *ren); - void UpdateViewport(vtkRenderer *ren); + virtual void UpdateViewport(vtkRenderer *ren); - void GetKeyMatrices(vtkRenderer *ren, vtkMatrix4x4 *&WCVCMatrix, + virtual void GetKeyMatrices(vtkRenderer *ren, vtkMatrix4x4 *&WCVCMatrix, vtkMatrix3x3 *&normalMatrix, vtkMatrix4x4 *&VCDCMatrix, vtkMatrix4x4 *&WCDCMatrix); protected: diff --git a/Rendering/OpenGL2/vtkOpenGLGlyph3DMapper.cxx b/Rendering/OpenGL2/vtkOpenGLGlyph3DMapper.cxx index 494edc4c626..e397236be64 100644 --- a/Rendering/OpenGL2/vtkOpenGLGlyph3DMapper.cxx +++ b/Rendering/OpenGL2/vtkOpenGLGlyph3DMapper.cxx @@ -323,7 +323,7 @@ void vtkOpenGLGlyph3DMapper::Render( vtkBitArray *maskArray = 0; if (this->Masking) { - maskArray = vtkBitArray::SafeDownCast(this->GetMaskArray(dataset)); + maskArray = vtkArrayDownCast(this->GetMaskArray(dataset)); if (maskArray == 0) { vtkDebugMacro(<<"masking is enabled but there is no mask array. Ignore masking."); @@ -664,7 +664,7 @@ void vtkOpenGLGlyph3DMapper::RebuildStructures( if (colors) { - colors->GetTupleValue(inPtId, &(entry->Colors[entry->NumberOfPoints*4])); + colors->GetTypedTuple(inPtId, &(entry->Colors[entry->NumberOfPoints*4])); } // scale data if appropriate diff --git a/Rendering/OpenGL2/vtkOpenGLImageSliceMapper.cxx b/Rendering/OpenGL2/vtkOpenGLImageSliceMapper.cxx index 2c073cf2da9..9af7f31a716 100644 --- a/Rendering/OpenGL2/vtkOpenGLImageSliceMapper.cxx +++ b/Rendering/OpenGL2/vtkOpenGLImageSliceMapper.cxx @@ -461,6 +461,7 @@ void vtkOpenGLImageSliceMapper::RenderPolygon( { actor->GetTexture()->Render(ren); } + actor->GetMapper()->SetClippingPlanes(this->GetClippingPlanes()); actor->GetMapper()->Render(ren, actor); if (textured) { @@ -587,6 +588,7 @@ void vtkOpenGLImageSliceMapper::RenderBackground( } } + actor->GetMapper()->SetClippingPlanes(this->GetClippingPlanes()); actor->GetMapper()->Render(ren, actor); vtkOpenGLCheckErrorMacro("failed after RenderBackground"); diff --git a/Rendering/OpenGL2/vtkOpenGLIndexBufferObject.cxx b/Rendering/OpenGL2/vtkOpenGLIndexBufferObject.cxx index 3efc5227e28..87277ccd5b8 100644 --- a/Rendering/OpenGL2/vtkOpenGLIndexBufferObject.cxx +++ b/Rendering/OpenGL2/vtkOpenGLIndexBufferObject.cxx @@ -163,6 +163,7 @@ size_t vtkOpenGLIndexBufferObject::CreateTriangleIndexBuffer( { if (!cells->GetNumberOfCells()) { + this->IndexCount = 0; return 0; } std::vector indexArray; @@ -206,6 +207,7 @@ size_t vtkOpenGLIndexBufferObject::CreatePointIndexBuffer(vtkCellArray *cells) { if (!cells->GetNumberOfCells()) { + this->IndexCount = 0; return 0; } std::vector indexArray; @@ -259,6 +261,7 @@ size_t vtkOpenGLIndexBufferObject::CreateTriangleLineIndexBuffer( { if (!cells->GetNumberOfCells()) { + this->IndexCount = 0; return 0; } std::vector indexArray; @@ -312,6 +315,7 @@ size_t vtkOpenGLIndexBufferObject::CreateLineIndexBuffer(vtkCellArray *cells) { if (!cells->GetNumberOfCells()) { + this->IndexCount = 0; return 0; } std::vector indexArray; @@ -328,6 +332,7 @@ size_t vtkOpenGLIndexBufferObject::CreateStripIndexBuffer( { if (!cells->GetNumberOfCells()) { + this->IndexCount = 0; return 0; } vtkIdType *pts = 0; @@ -493,13 +498,14 @@ size_t vtkOpenGLIndexBufferObject::CreateEdgeFlagIndexBuffer( { if (!cells->GetNumberOfCells()) { + this->IndexCount = 0; return 0; } vtkIdType *pts = 0; vtkIdType npts = 0; std::vector indexArray; unsigned char *ucef = NULL; - ucef = vtkUnsignedCharArray::SafeDownCast(ef)->GetPointer(0); + ucef = vtkArrayDownCast(ef)->GetPointer(0); indexArray.reserve(cells->GetData()->GetSize()*2); for (cells->InitTraversal(); cells->GetNextCell(npts,pts); ) { diff --git a/Rendering/OpenGL2/vtkOpenGLPointGaussianMapper.cxx b/Rendering/OpenGL2/vtkOpenGLPointGaussianMapper.cxx index d7975d038b7..617a76c4eb9 100644 --- a/Rendering/OpenGL2/vtkOpenGLPointGaussianMapper.cxx +++ b/Rendering/OpenGL2/vtkOpenGLPointGaussianMapper.cxx @@ -219,6 +219,8 @@ bool vtkOpenGLPointGaussianMapperHelper::GetNeedToRebuildShaders( this->LastSelectionState = picking; } + unsigned long int renderPassMTime = this->GetRenderPassStageMTime(actor); + // has something changed that would require us to recreate the shader? // candidates are // property modified (representation interpolation and lighting) @@ -229,7 +231,7 @@ bool vtkOpenGLPointGaussianMapperHelper::GetNeedToRebuildShaders( cellBO.ShaderSourceTime < actor->GetMTime() || cellBO.ShaderSourceTime < this->CurrentInput->GetMTime() || cellBO.ShaderSourceTime < this->SelectionStateChanged || - cellBO.ShaderSourceTime < this->DepthPeelingChanged) + cellBO.ShaderSourceTime < renderPassMTime) { return true; } @@ -648,7 +650,7 @@ void vtkOpenGLPointGaussianMapperHelper::BuildBufferObjects( this->VBO->NormalOffset = 0; this->VBO->TCoordOffset = 0; this->VBO->TCoordComponents = 0; - this->VBO->ColorComponents = 4; + this->VBO->ColorComponents = (this->Colors == NULL)? 0 : 4; this->VBO->ColorOffset = sizeof(float) * blockSize; ++blockSize; // color diff --git a/Rendering/OpenGL2/vtkOpenGLPolyDataMapper.cxx b/Rendering/OpenGL2/vtkOpenGLPolyDataMapper.cxx index 0460ee6a2b8..10f64ad3671 100644 --- a/Rendering/OpenGL2/vtkOpenGLPolyDataMapper.cxx +++ b/Rendering/OpenGL2/vtkOpenGLPolyDataMapper.cxx @@ -17,7 +17,6 @@ #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkCommand.h" -#include "vtkDepthPeelingPass.h" #include "vtkFloatArray.h" #include "vtkHardwareSelector.h" #include "vtkImageData.h" @@ -28,7 +27,6 @@ #include "vtkMath.h" #include "vtkMatrix3x3.h" #include "vtkMatrix4x4.h" -#include "vtkNew.h" #include "vtkObjectFactory.h" #include "vtkOpenGLActor.h" #include "vtkOpenGLBufferObject.h" @@ -36,6 +34,7 @@ #include "vtkOpenGLError.h" #include "vtkOpenGLHelper.h" #include "vtkOpenGLIndexBufferObject.h" +#include "vtkOpenGLRenderPass.h" #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLRenderer.h" #include "vtkOpenGLShaderCache.h" @@ -73,7 +72,6 @@ vtkOpenGLPolyDataMapper::vtkOpenGLPolyDataMapper() this->InternalColorTexture = 0; this->PopulateSelectionSettings = 1; this->LastSelectionState = vtkHardwareSelector::MIN_KNOWN_PASS - 1; - this->LastDepthPeeling = 0; this->CurrentInput = 0; this->TempMatrix4 = vtkMatrix4x4::New(); this->TempMatrix3 = vtkMatrix3x3::New(); @@ -201,6 +199,13 @@ void vtkOpenGLPolyDataMapper::ReleaseGraphicsResources(vtkWindow* win) { this->AppleBugPrimIDBuffer->ReleaseGraphicsResources(); } + if (this->TimerQuery) + { +#if GL_ES_VERSION_2_0 != 1 && GL_ES_VERSION_3_0 != 1 + glDeleteQueries(1, &this->TimerQuery); +#endif + this->TimerQuery = 0; + } this->VBOBuildString = ""; this->IBOBuildString = ""; this->Modified(); @@ -310,6 +315,70 @@ bool vtkOpenGLPolyDataMapper::HaveWideLines( return false; } +//----------------------------------------------------------------------------- +unsigned long vtkOpenGLPolyDataMapper::GetRenderPassStageMTime(vtkActor *actor) +{ + vtkInformation *info = actor->GetPropertyKeys(); + unsigned long int renderPassMTime = 0; + + int curRenderPasses = 0; + if (info && info->Has(vtkOpenGLRenderPass::RenderPasses())) + { + curRenderPasses = info->Length(vtkOpenGLRenderPass::RenderPasses()); + } + + int lastRenderPasses = 0; + if (this->LastRenderPassInfo->Has(vtkOpenGLRenderPass::RenderPasses())) + { + lastRenderPasses = + this->LastRenderPassInfo->Length(vtkOpenGLRenderPass::RenderPasses()); + } + + // Determine the last time a render pass changed stages: + if (curRenderPasses != lastRenderPasses) + { + // Number of passes changed, definitely need to update. + // Fake the time to force an update: + renderPassMTime = VTK_UNSIGNED_LONG_MAX; + } + else + { + // Compare the current to the previous render passes: + for (int i = 0; i < curRenderPasses; ++i) + { + vtkObjectBase *curRP = info->Get(vtkOpenGLRenderPass::RenderPasses(), i); + vtkObjectBase *lastRP = + this->LastRenderPassInfo->Get(vtkOpenGLRenderPass::RenderPasses(), i); + + if (curRP != lastRP) + { + // Render passes have changed. Force update: + renderPassMTime = VTK_UNSIGNED_LONG_MAX; + break; + } + else + { + // Render passes have not changed -- check MTime. + vtkOpenGLRenderPass *rp = static_cast(curRP); + renderPassMTime = std::max(renderPassMTime, rp->GetShaderStageMTime()); + } + } + } + + // Cache the current set of render passes for next time: + if (info) + { + this->LastRenderPassInfo->CopyEntry(info, + vtkOpenGLRenderPass::RenderPasses()); + } + else + { + this->LastRenderPassInfo->Clear(); + } + + return renderPassMTime; +} + //----------------------------------------------------------------------------- void vtkOpenGLPolyDataMapper::GetShaderTemplate( std::map shaders, @@ -350,6 +419,37 @@ void vtkOpenGLPolyDataMapper::GetShaderTemplate( } } +//------------------------------------------------------------------------------ +void vtkOpenGLPolyDataMapper::ReplaceShaderRenderPass( + std::map shaders, vtkRenderer *, + vtkActor *act) +{ + std::string VSSource = shaders[vtkShader::Vertex]->GetSource(); + std::string GSSource = shaders[vtkShader::Geometry]->GetSource(); + std::string FSSource = shaders[vtkShader::Fragment]->GetSource(); + + vtkInformation *info = act->GetPropertyKeys(); + if (info && info->Has(vtkOpenGLRenderPass::RenderPasses())) + { + int numRenderPasses = info->Length(vtkOpenGLRenderPass::RenderPasses()); + for (int i = 0; i < numRenderPasses; ++i) + { + vtkObjectBase *rpBase = info->Get(vtkOpenGLRenderPass::RenderPasses(), i); + vtkOpenGLRenderPass *rp = static_cast(rpBase); + if (!rp->ReplaceShaderValues(VSSource, GSSource, FSSource, this, act)) + { + vtkErrorMacro("vtkOpenGLRenderPass::ReplaceShaderValues failed for " + << rp->GetClassName()); + } + } + } + + shaders[vtkShader::Vertex]->SetSource(VSSource); + shaders[vtkShader::Geometry]->SetSource(GSSource); + shaders[vtkShader::Fragment]->SetSource(FSSource); +} + +//------------------------------------------------------------------------------ void vtkOpenGLPolyDataMapper::ReplaceShaderColor( std::map shaders, vtkRenderer *, vtkActor *actor) @@ -953,42 +1053,6 @@ void vtkOpenGLPolyDataMapper::ReplaceShaderPicking( shaders[vtkShader::Fragment]->SetSource(FSSource); } -void vtkOpenGLPolyDataMapper::ReplaceShaderDepthPeeling( - std::map shaders, - vtkRenderer *, vtkActor *actor) -{ - std::string FSSource = shaders[vtkShader::Fragment]->GetSource(); - - // are we using depth peeling? - vtkInformation *info = actor->GetPropertyKeys(); - if (info && info->Has(vtkDepthPeelingPass::OpaqueZTextureUnit())) - { - vtkShaderProgram::Substitute(FSSource, "//VTK::DepthPeeling::Dec", - "uniform vec2 screenSize;\n" - "uniform sampler2D opaqueZTexture;\n" - "uniform sampler2D translucentZTexture;\n"); - // the .0000001 below is an epsilon. It turns out that - // graphics cards can render the same polygon two times - // in a row with different z values. I suspect it has to - // do with how rasterization of the polygon is broken up. - // A different breakup across fragment shaders can result in - // very slightly different z values for some of the pixels. - // The end result is that with depth peeling, you can end up - // counting/accumulating pixels of the same surface twice - // simply due to this randomness in z values. So we introduce - // an epsilon into the transparent test to require some - // minimal z seperation between pixels - vtkShaderProgram::Substitute(FSSource, "//VTK::DepthPeeling::Impl", - "float odepth = texture2D(opaqueZTexture, gl_FragCoord.xy/screenSize).r;\n" - " if (gl_FragCoord.z >= odepth) { discard; }\n" - " float tdepth = texture2D(translucentZTexture, gl_FragCoord.xy/screenSize).r;\n" - " if (gl_FragCoord.z <= tdepth + .0000001) { discard; }\n" - // "gl_FragData[0] = vec4(odepth*odepth,tdepth*tdepth,gl_FragCoord.z*gl_FragCoord.z,1.0);" - ); - } - shaders[vtkShader::Fragment]->SetSource(FSSource); -} - void vtkOpenGLPolyDataMapper::ReplaceShaderClip( std::map shaders, vtkRenderer *, vtkActor *) @@ -1097,10 +1161,16 @@ void vtkOpenGLPolyDataMapper::ReplaceShaderNormal( // view are probably not orthogonal. Which is why when we cross result that with // the line gradient again we get a reasonable normal. It will be othogonal to // the line (which is a plane but maximally aligned with the camera view. + vtkShaderProgram::Substitute( + FSSource,"//VTK::UniformFlow::Impl", + " vec3 fdx = vec3(dFdx(vertexVC.x),dFdx(vertexVC.y),dFdx(vertexVC.z));\n" + " vec3 fdy = vec3(dFdy(vertexVC.x),dFdy(vertexVC.y),dFdy(vertexVC.z));\n" + " //VTK::UniformFlow::Impl\n" // For further replacements + ); vtkShaderProgram::Substitute(FSSource,"//VTK::Normal::Impl", "vec3 normalVCVSOutput;\n" - " vec3 fdx = normalize(vec3(dFdx(vertexVC.x),dFdx(vertexVC.y),dFdx(vertexVC.z)));\n" - " vec3 fdy = normalize(vec3(dFdy(vertexVC.x),dFdy(vertexVC.y),dFdy(vertexVC.z)));\n" + " fdx = normalize(fdx);\n" + " fdy = normalize(fdy);\n" " if (abs(fdx.x) > 0.0)\n" " { normalVCVSOutput = normalize(cross(vec3(fdx.y, -fdx.x, 0.0), fdx)); }\n" " else { normalVCVSOutput = normalize(cross(vec3(fdy.y, -fdy.x, 0.0), fdy));}" @@ -1112,9 +1182,15 @@ void vtkOpenGLPolyDataMapper::ReplaceShaderNormal( "//VTK::Normal::Dec", "uniform int cameraParallel;"); + vtkShaderProgram::Substitute( + FSSource,"//VTK::UniformFlow::Impl", + "vec3 fdx = vec3(dFdx(vertexVC.x),dFdx(vertexVC.y),dFdx(vertexVC.z));\n" + " vec3 fdy = vec3(dFdy(vertexVC.x),dFdy(vertexVC.y),dFdy(vertexVC.z));\n" + " //VTK::UniformFlow::Impl\n" // For further replacements + ); vtkShaderProgram::Substitute(FSSource,"//VTK::Normal::Impl", - "vec3 fdx = normalize(vec3(dFdx(vertexVC.x),dFdx(vertexVC.y),dFdx(vertexVC.z)));\n" - " vec3 fdy = normalize(vec3(dFdy(vertexVC.x),dFdy(vertexVC.y),dFdy(vertexVC.z)));\n" + " fdx = normalize(fdx);\n" + " fdy = normalize(fdy);\n" " vec3 normalVCVSOutput = normalize(cross(fdx,fdy));\n" // the code below is faster, but does not work on some devices //"vec3 normalVC = normalize(cross(dFdx(vertexVC.xyz), dFdy(vertexVC.xyz)));\n" @@ -1248,9 +1324,10 @@ void vtkOpenGLPolyDataMapper::ReplaceShaderCoincidentOffset( if (factor != 0.0) { vtkShaderProgram::Substitute(FSSource, - "//VTK::Coincident::Impl", + "//VTK::UniformFlow::Impl", "float cscale = length(vec2(dFdx(gl_FragCoord.z),dFdy(gl_FragCoord.z)));\n" " gl_FragDepth = gl_FragCoord.z + cfactor*cscale + 0.000016*coffset;\n" + " //VTK::UniformFlow::Impl\n" // for other replacements ); } else @@ -1268,12 +1345,12 @@ void vtkOpenGLPolyDataMapper::ReplaceShaderValues( std::map shaders, vtkRenderer *ren, vtkActor *actor) { + this->ReplaceShaderRenderPass(shaders, ren, actor); this->ReplaceShaderColor(shaders, ren, actor); this->ReplaceShaderNormal(shaders, ren, actor); this->ReplaceShaderLight(shaders, ren, actor); this->ReplaceShaderTCoord(shaders, ren, actor); this->ReplaceShaderPicking(shaders, ren, actor); - this->ReplaceShaderDepthPeeling(shaders, ren, actor); this->ReplaceShaderClip(shaders, ren, actor); this->ReplaceShaderPrimID(shaders, ren, actor); this->ReplaceShaderPositionVC(shaders, ren, actor); @@ -1353,15 +1430,8 @@ bool vtkOpenGLPolyDataMapper::GetNeedToRebuildShaders( this->LastLightComplexity[&cellBO] = lightComplexity; } - // check for prop keys - vtkInformation *info = actor->GetPropertyKeys(); - int dp = (info && info->Has(vtkDepthPeelingPass::OpaqueZTextureUnit())) ? 1 : 0; - - if (this->LastDepthPeeling != dp) - { - this->DepthPeelingChanged.Modified(); - this->LastDepthPeeling = dp; - } + // Have the renderpasses changed? + unsigned long int renderPassMTime = this->GetRenderPassStageMTime(actor); // has something changed that would require us to recreate the shader? // candidates are @@ -1373,7 +1443,7 @@ bool vtkOpenGLPolyDataMapper::GetNeedToRebuildShaders( cellBO.ShaderSourceTime < actor->GetMTime() || cellBO.ShaderSourceTime < this->CurrentInput->GetMTime() || cellBO.ShaderSourceTime < this->SelectionStateChanged || - cellBO.ShaderSourceTime < this->DepthPeelingChanged || + cellBO.ShaderSourceTime < renderPassMTime || cellBO.ShaderSourceTime < this->LightComplexityChanged[&cellBO]) { return true; @@ -1453,13 +1523,18 @@ void vtkOpenGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, cellBO.ShaderSourceTime > cellBO.AttributeUpdateTime)) { cellBO.VAO->Bind(); - if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, - "vertexMC", this->VBO->VertexOffset, - this->VBO->Stride, VTK_FLOAT, 3, false)) + if (cellBO.Program->IsAttributeUsed("vertexMC")) { - vtkErrorMacro(<< "Error setting 'vertexMC' in shader VAO."); + if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, + "vertexMC", this->VBO->VertexOffset, + this->VBO->Stride, VTK_FLOAT, 3, + false)) + { + vtkErrorMacro(<< "Error setting 'vertexMC' in shader VAO."); + } } - if (this->VBO->NormalOffset && this->LastLightComplexity[&cellBO] > 0) + if (this->VBO->NormalOffset && this->LastLightComplexity[&cellBO] > 0 && + cellBO.Program->IsAttributeUsed("normalMC")) { if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, "normalMC", this->VBO->NormalOffset, @@ -1468,7 +1543,8 @@ void vtkOpenGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, vtkErrorMacro(<< "Error setting 'normalMC' in shader VAO."); } } - if (this->VBO->TCoordComponents && !this->DrawingEdges) + if (this->VBO->TCoordComponents && !this->DrawingEdges && + cellBO.Program->IsAttributeUsed("tcoordMC")) { if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, "tcoordMC", this->VBO->TCoordOffset, @@ -1477,7 +1553,8 @@ void vtkOpenGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, vtkErrorMacro(<< "Error setting 'tcoordMC' in shader VAO."); } } - if (this->VBO->ColorComponents != 0 && !this->DrawingEdges) + if (this->VBO->ColorComponents != 0 && !this->DrawingEdges && + cellBO.Program->IsAttributeUsed("scalarColor")) { if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, "scalarColor", this->VBO->ColorOffset, @@ -1487,7 +1564,8 @@ void vtkOpenGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, vtkErrorMacro(<< "Error setting 'scalarColor' in shader VAO."); } } - if (this->AppleBugPrimIDs.size()) + if (this->AppleBugPrimIDs.size() && + cellBO.Program->IsAttributeUsed("appleBugPrimID")) { if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->AppleBugPrimIDBuffer, @@ -1511,7 +1589,7 @@ void vtkOpenGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, { texture = actor->GetProperty()->GetTexture(0); } - if (texture) + if (texture && cellBO.Program->IsUniformUsed("texture1")) { int tunit = vtkOpenGLTexture::SafeDownCast(texture)->GetTextureUnit(); cellBO.Program->SetUniformi("texture1", tunit); @@ -1519,7 +1597,8 @@ void vtkOpenGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, // check for tcoord transform matrix vtkInformation *info = actor->GetPropertyKeys(); vtkOpenGLCheckErrorMacro("failed after Render"); - if (info && info->Has(vtkProp::GeneralTextureTransform())) + if (info && info->Has(vtkProp::GeneralTextureTransform()) && + cellBO.Program->IsUniformUsed("tcMatrix")) { double *dmatrix = info->Get(vtkProp::GeneralTextureTransform()); float fmatrix[16]; @@ -1535,38 +1614,39 @@ void vtkOpenGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, } } - if (this->HaveCellScalars || this->HavePickScalars) + if ((this->HaveCellScalars || this->HavePickScalars) && + cellBO.Program->IsUniformUsed("textureC")) { int tunit = this->CellScalarTexture->GetTextureUnit(); cellBO.Program->SetUniformi("textureC", tunit); } - if (this->HaveCellNormals) + if (this->HaveCellNormals && cellBO.Program->IsUniformUsed("textureN")) { int tunit = this->CellNormalTexture->GetTextureUnit(); cellBO.Program->SetUniformi("textureN", tunit); } - // if depth peeling set the required uniforms + // Handle render pass setup: vtkInformation *info = actor->GetPropertyKeys(); - if (info && info->Has(vtkDepthPeelingPass::OpaqueZTextureUnit()) && - info->Has(vtkDepthPeelingPass::TranslucentZTextureUnit())) + if (info && info->Has(vtkOpenGLRenderPass::RenderPasses())) { - int otunit = info->Get(vtkDepthPeelingPass::OpaqueZTextureUnit()); - int ttunit = info->Get(vtkDepthPeelingPass::TranslucentZTextureUnit()); - cellBO.Program->SetUniformi("opaqueZTexture", otunit); - cellBO.Program->SetUniformi("translucentZTexture", ttunit); - - int *renSize = info->Get(vtkDepthPeelingPass::DestinationSize()); - float screenSize[2]; - screenSize[0] = renSize[0]; - screenSize[1] = renSize[1]; - cellBO.Program->SetUniform2f("screenSize", screenSize); + int numRenderPasses = info->Length(vtkOpenGLRenderPass::RenderPasses()); + for (int i = 0; i < numRenderPasses; ++i) + { + vtkObjectBase *rpBase = info->Get(vtkOpenGLRenderPass::RenderPasses(), i); + vtkOpenGLRenderPass *rp = static_cast(rpBase); + if (!rp->SetShaderParameters(cellBO.Program, this, actor)) + { + vtkErrorMacro("RenderPass::SetShaderParameters failed for renderpass: " + << rp->GetClassName()); + } + } } vtkHardwareSelector* selector = ren->GetSelector(); bool picking = (ren->GetRenderWindow()->GetIsPicking() || selector != NULL); - if (picking) + if (picking && cellBO.Program->IsUniformUsed("mapperIndex")) { if (selector) { @@ -1584,7 +1664,9 @@ void vtkOpenGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, } } - if (this->GetNumberOfClippingPlanes()) + if (this->GetNumberOfClippingPlanes() && + cellBO.Program->IsUniformUsed("numClipPlanes") && + cellBO.Program->IsUniformUsed("clipPlanes")) { // add all the clipping planes int numClipPlanes = this->GetNumberOfClippingPlanes(); @@ -1609,7 +1691,8 @@ void vtkOpenGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, } // handle wide lines - if (this->HaveWideLines(ren, actor)) + if (this->HaveWideLines(ren, actor) && + cellBO.Program->IsUniformUsed("lineWidthNVC")) { int vp[4]; glGetIntegerv(GL_VIEWPORT, vp); @@ -1625,7 +1708,11 @@ void vtkOpenGLPolyDataMapper::SetMapperShaderParameters(vtkOpenGLHelper &cellBO, float factor, offset; this->GetCoincidentParameters(actor,factor,offset); cellBO.Program->SetUniformf("coffset",offset); - cellBO.Program->SetUniformf("cfactor",factor); + // cfactor isn't always used when coffset is. + if (cellBO.Program->IsUniformUsed("cfactor")) + { + cellBO.Program->SetUniformf("cfactor", factor); + } } } @@ -1766,40 +1853,82 @@ void vtkOpenGLPolyDataMapper::SetCameraShaderParameters(vtkOpenGLHelper &cellBO, vtkOpenGLCamera *cam = (vtkOpenGLCamera *)(ren->GetActiveCamera()); - vtkMatrix4x4 *wcdc; - vtkMatrix4x4 *wcvc; - vtkMatrix3x3 *norms; - vtkMatrix4x4 *vcdc; - cam->GetKeyMatrices(ren,wcvc,norms,vcdc,wcdc); - - if (!actor->GetIsIdentity()) - { - vtkMatrix4x4 *mcwc; - vtkMatrix3x3 *anorms; - ((vtkOpenGLActor *)actor)->GetKeyMatrices(mcwc,anorms); - vtkMatrix4x4::Multiply4x4(mcwc, wcdc, this->TempMatrix4); - program->SetUniformMatrix("MCDCMatrix", this->TempMatrix4); - if (program->IsUniformUsed("MCVCMatrix")) - { - vtkMatrix4x4::Multiply4x4(mcwc, wcvc, this->TempMatrix4); - program->SetUniformMatrix("MCVCMatrix", this->TempMatrix4); + // [WMVD]C == {world, model, view, display} coordinates + // E.g., WCDC == world to display coordinate transformation + vtkMatrix4x4* wcdc; + vtkMatrix4x4* wcvc; + vtkMatrix3x3* norms; + vtkMatrix4x4* vcdc; + cam->GetKeyMatrices(ren, wcvc, norms, vcdc, wcdc); + + if (this->VBO->GetCoordShiftAndScaleEnabled()) + { + if (!actor->GetIsIdentity()) + { + vtkMatrix4x4* mcwc; + vtkMatrix3x3* anorms; + ((vtkOpenGLActor*)actor)->GetKeyMatrices(mcwc,anorms); + vtkMatrix4x4::Multiply4x4(this->VBOShiftScale.GetPointer(), mcwc, this->TempMatrix4); + vtkMatrix4x4::Multiply4x4(this->TempMatrix4, wcdc, this->TempMatrix4); + program->SetUniformMatrix("MCDCMatrix", this->TempMatrix4); + if (program->IsUniformUsed("MCVCMatrix")) + { + vtkMatrix4x4::Multiply4x4(this->VBOShiftScale.GetPointer(), mcwc, this->TempMatrix4); + vtkMatrix4x4::Multiply4x4(this->TempMatrix4, wcvc, this->TempMatrix4); + program->SetUniformMatrix("MCVCMatrix", this->TempMatrix4); + } + if (program->IsUniformUsed("normalMatrix")) + { + vtkMatrix3x3::Multiply3x3(anorms, norms, this->TempMatrix3); + program->SetUniformMatrix("normalMatrix", this->TempMatrix3); + } } - if (program->IsUniformUsed("normalMatrix")) + else { - vtkMatrix3x3::Multiply3x3(anorms, norms, this->TempMatrix3); - program->SetUniformMatrix("normalMatrix", this->TempMatrix3); + vtkMatrix4x4::Multiply4x4(this->VBOShiftScale.GetPointer(), wcdc, this->TempMatrix4); + program->SetUniformMatrix("MCDCMatrix", this->TempMatrix4); + if (program->IsUniformUsed("MCVCMatrix")) + { + vtkMatrix4x4::Multiply4x4(this->VBOShiftScale.GetPointer(), wcvc, this->TempMatrix4); + program->SetUniformMatrix("MCVCMatrix", this->TempMatrix4); + } + if (program->IsUniformUsed("normalMatrix")) + { + program->SetUniformMatrix("normalMatrix", norms); + } } } else { - program->SetUniformMatrix("MCDCMatrix", wcdc); - if (program->IsUniformUsed("MCVCMatrix")) + if (!actor->GetIsIdentity()) { - program->SetUniformMatrix("MCVCMatrix", wcvc); + vtkMatrix4x4 *mcwc; + vtkMatrix3x3 *anorms; + ((vtkOpenGLActor *)actor)->GetKeyMatrices(mcwc,anorms); + vtkMatrix4x4::Multiply4x4(mcwc, wcdc, this->TempMatrix4); + program->SetUniformMatrix("MCDCMatrix", this->TempMatrix4); + if (program->IsUniformUsed("MCVCMatrix")) + { + vtkMatrix4x4::Multiply4x4(mcwc, wcvc, this->TempMatrix4); + program->SetUniformMatrix("MCVCMatrix", this->TempMatrix4); + } + if (program->IsUniformUsed("normalMatrix")) + { + vtkMatrix3x3::Multiply3x3(anorms, norms, this->TempMatrix3); + program->SetUniformMatrix("normalMatrix", this->TempMatrix3); + } } - if (program->IsUniformUsed("normalMatrix")) + else { - program->SetUniformMatrix("normalMatrix", norms); + program->SetUniformMatrix("MCDCMatrix", wcdc); + if (program->IsUniformUsed("MCVCMatrix")) + { + program->SetUniformMatrix("MCVCMatrix", wcvc); + } + if (program->IsUniformUsed("normalMatrix")) + { + program->SetUniformMatrix("normalMatrix", norms); + } } } @@ -2434,13 +2563,13 @@ void vtkOpenGLPolyDataMapper::AppendCellTextures( if (selector->GetUseProcessIdFromData()) { mapArray = this->ProcessIdArrayName ? - vtkUnsignedIntArray::SafeDownCast( + vtkArrayDownCast( pd->GetArray(this->ProcessIdArrayName)) : NULL; } break; case vtkHardwareSelector::COMPOSITE_INDEX_PASS: mapArray = this->CompositeIdArrayName ? - vtkUnsignedIntArray::SafeDownCast( + vtkArrayDownCast( cd->GetArray(this->CompositeIdArrayName)) : NULL; break; case vtkHardwareSelector::ID_LOW24: @@ -2449,13 +2578,13 @@ void vtkOpenGLPolyDataMapper::AppendCellTextures( vtkDataObject::FIELD_ASSOCIATION_POINTS) { mapArrayId = this->PointIdArrayName ? - vtkIdTypeArray::SafeDownCast( + vtkArrayDownCast( pd->GetArray(this->PointIdArrayName)) : NULL; } else { mapArrayId = this->CellIdArrayName ? - vtkIdTypeArray::SafeDownCast( + vtkArrayDownCast( cd->GetArray(this->CellIdArrayName)) : NULL; } break; @@ -2888,6 +3017,7 @@ void vtkOpenGLPolyDataMapper::BuildBufferObjects(vtkRenderer *ren, vtkActor *act this->AppleBugPrimIDs, vtkOpenGLBufferObject::ArrayBuffer); this->AppleBugPrimIDBuffer->Release(); +#ifndef NDEBUG static bool warnedAboutBrokenAppleDriver = false; if (!warnedAboutBrokenAppleDriver) { @@ -2897,6 +3027,7 @@ void vtkOpenGLPolyDataMapper::BuildBufferObjects(vtkRenderer *ren, vtkActor *act << (const char *)glGetString(GL_VERSION)); warnedAboutBrokenAppleDriver = true; } +#endif if (n) { n = (act->GetProperty()->GetInterpolation() != VTK_FLAT) ? @@ -2954,6 +3085,19 @@ void vtkOpenGLPolyDataMapper::BuildBufferObjects(vtkRenderer *ren, vtkActor *act c ? (unsigned char *)c->GetVoidPointer(0) : NULL, c ? c->GetNumberOfComponents() : 0); + // If the VBO coordinates were shifted and scaled, prepare the inverse transform + // for application to the model->view matrix: + if (this->VBO->GetCoordShiftAndScaleEnabled()) + { + double shift[3]; + double scale[3]; + this->VBO->GetCoordShift(shift); + this->VBO->GetCoordScale(scale); + this->VBOInverseTransform->Identity(); + this->VBOInverseTransform->Translate(shift[0], shift[1], shift[2]); + this->VBOInverseTransform->Scale(1.0/scale[0], 1.0/scale[1], 1.0/scale[2]); + this->VBOInverseTransform->GetTranspose(this->VBOShiftScale.GetPointer()); + } this->VBOBuildTime.Modified(); this->VBOBuildString = toString.str(); } @@ -3153,6 +3297,12 @@ void vtkOpenGLPolyDataMapper::ShallowCopy(vtkAbstractMapper *mapper) this->vtkPolyDataMapper::ShallowCopy(mapper); } +void vtkOpenGLPolyDataMapper::SetVBOShiftScaleMethod(int m) +{ + this->VBO->SetCoordShiftAndScaleMethod( + static_cast(m)); +} + //----------------------------------------------------------------------------- void vtkOpenGLPolyDataMapper::PrintSelf(ostream& os, vtkIndent indent) { diff --git a/Rendering/OpenGL2/vtkOpenGLPolyDataMapper.h b/Rendering/OpenGL2/vtkOpenGLPolyDataMapper.h index df8028f192f..b1adf8b9689 100644 --- a/Rendering/OpenGL2/vtkOpenGLPolyDataMapper.h +++ b/Rendering/OpenGL2/vtkOpenGLPolyDataMapper.h @@ -18,10 +18,13 @@ #ifndef vtkOpenGLPolyDataMapper_h #define vtkOpenGLPolyDataMapper_h +#include "vtkNew.h" // For vtkNew #include "vtkRenderingOpenGL2Module.h" // For export macro +#include "vtkNew.h" // for ivars #include "vtkPolyDataMapper.h" #include "vtkShader.h" // for methods #include "vtkOpenGLHelper.h" // used for ivars + #include //for ivars #include //for methods @@ -32,6 +35,7 @@ class vtkOpenGLTexture; class vtkOpenGLBufferObject; class vtkOpenGLVertexBufferObject; class vtkTextureObject; +class vtkTransform; class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLPolyDataMapper : public vtkPolyDataMapper { @@ -170,6 +174,13 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLPolyDataMapper : public vtkPolyDataMap // Get the value of HaveAppleBug bool GetHaveAppleBug() { return this->HaveAppleBug; } + /// Return the mapper's vertex buffer object. + vtkGetObjectMacro(VBO,vtkOpenGLVertexBufferObject); + + /**\brief A convenience method for enabling/disabling + * the VBO's shift+scale transform. + */ + void SetVBOShiftScaleMethod(int m); protected: vtkOpenGLPolyDataMapper(); ~vtkOpenGLPolyDataMapper(); @@ -225,6 +236,9 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLPolyDataMapper : public vtkPolyDataMap // Description: // Perform string replacments on the shader templates, called from // ReplaceShaderValues + virtual void ReplaceShaderRenderPass( + std::map shaders, + vtkRenderer *ren, vtkActor *act); virtual void ReplaceShaderColor( std::map shaders, vtkRenderer *ren, vtkActor *act); @@ -237,9 +251,6 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLPolyDataMapper : public vtkPolyDataMap virtual void ReplaceShaderPicking( std::map shaders, vtkRenderer *ren, vtkActor *act); - virtual void ReplaceShaderDepthPeeling( - std::map shaders, - vtkRenderer *ren, vtkActor *act); virtual void ReplaceShaderPrimID( std::map shaders, vtkRenderer *ren, vtkActor *act); @@ -311,8 +322,14 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLPolyDataMapper : public vtkPolyDataMap int LastSelectionState; vtkTimeStamp SelectionStateChanged; - int LastDepthPeeling; - vtkTimeStamp DepthPeelingChanged; + // Caches the vtkOpenGLRenderPass::RenderPasses() information. + // Note: Do not dereference the pointers held by this object. There is no + // guarantee that they are still valid! + vtkNew LastRenderPassInfo; + + // Check the renderpasses in actor's property keys to see if they've changed + // render stages: + unsigned long GetRenderPassStageMTime(vtkActor *actor); bool UsingScalarColoring; vtkTimeStamp VBOBuildTime; // When was the OpenGL VBO updated? @@ -323,8 +340,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLPolyDataMapper : public vtkPolyDataMap int PopulateSelectionSettings; int PrimitiveIDOffset; - vtkMatrix4x4 *TempMatrix4; - vtkMatrix3x3 *TempMatrix3; + vtkMatrix4x4* TempMatrix4; + vtkMatrix3x3* TempMatrix3; + vtkNew VBOInverseTransform; + vtkNew VBOShiftScale; // if set to true, tcoords will be passed to the // VBO even if the mapper knows of no texture maps diff --git a/Rendering/OpenGL2/vtkOpenGLPolyDataMapper2D.cxx b/Rendering/OpenGL2/vtkOpenGLPolyDataMapper2D.cxx index 43cd34f7e78..d20c581457a 100644 --- a/Rendering/OpenGL2/vtkOpenGLPolyDataMapper2D.cxx +++ b/Rendering/OpenGL2/vtkOpenGLPolyDataMapper2D.cxx @@ -18,6 +18,7 @@ #include "vtkActor2D.h" #include "vtkCellArray.h" +#include "vtkHardwareSelector.h" #include "vtkInformation.h" #include "vtkMath.h" #include "vtkMatrix4x4.h" @@ -38,6 +39,7 @@ #include "vtkProperty.h" #include "vtkShaderProgram.h" #include "vtkTextureObject.h" +#include "vtkTransform.h" #include "vtkUnsignedCharArray.h" #include "vtkViewport.h" @@ -61,6 +63,7 @@ vtkOpenGLPolyDataMapper2D::vtkOpenGLPolyDataMapper2D() this->LastBoundBO = 0; this->HaveCellScalars = false; this->PrimitiveIDOffset = 0; + this->LastPickState = 0; } //----------------------------------------------------------------------------- @@ -127,7 +130,8 @@ bool vtkOpenGLPolyDataMapper2D::GetNeedToRebuildShaders( if (cellBO.Program == 0 || cellBO.ShaderSourceTime < this->GetMTime() || cellBO.ShaderSourceTime < actor->GetMTime() || - cellBO.ShaderSourceTime < this->GetInput()->GetMTime()) + cellBO.ShaderSourceTime < this->GetInput()->GetMTime() || + cellBO.ShaderSourceTime < this->PickStateChanged) { return true; } @@ -276,6 +280,12 @@ void vtkOpenGLPolyDataMapper2D::BuildShaders( "gl_PrimitiveID = gl_PrimitiveIDIn;"); } } + + vtkRenderer* ren = vtkRenderer::SafeDownCast(viewport); + if (ren && ren->GetRenderWindow()->GetIsPicking()) + { + this->ReplaceShaderPicking(FSSource, ren, actor); + } } //----------------------------------------------------------------------------- @@ -332,7 +342,7 @@ void vtkOpenGLPolyDataMapper2D::SetMapperShaderParameters( { vtkErrorMacro(<< "Error setting 'vertexWC' in shader program."); } - if (this->VBO->TCoordComponents) + if (this->VBO->TCoordComponents && cellBO.Program->IsAttributeUsed("tcoordMC")) { if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, "tcoordMC", this->VBO->TCoordOffset, @@ -341,7 +351,7 @@ void vtkOpenGLPolyDataMapper2D::SetMapperShaderParameters( vtkErrorMacro(<< "Error setting 'tcoordMC' in shader VAO."); } } - if (this->VBO->ColorComponents != 0) + if (this->VBO->ColorComponents && cellBO.Program->IsAttributeUsed("diffuseColor")) { if (!cellBO.VAO->AddAttributeArray(cellBO.Program, this->VBO, "diffuseColor", this->VBO->ColorOffset, @@ -393,6 +403,16 @@ void vtkOpenGLPolyDataMapper2D::SetMapperShaderParameters( lineWidth[1] = 2.0*actor->GetProperty()->GetLineWidth()/vp[3]; cellBO.Program->SetUniform2f("lineWidthNVC",lineWidth); } + + vtkRenderer* ren = vtkRenderer::SafeDownCast(viewport); + bool picking = ren && ren->GetRenderWindow()->GetIsPicking(); + if (picking && cellBO.Program->IsUniformUsed("mapperIndex")) + { + unsigned int idx = ren->GetCurrentPickId(); + float color[3]; + vtkHardwareSelector::Convert(idx, color); + cellBO.Program->SetUniform3f("mapperIndex", color); + } } //----------------------------------------------------------------------------- @@ -415,6 +435,18 @@ void vtkOpenGLPolyDataMapper2D::SetPropertyShaderParameters( } } +//----------------------------------------------------------------------------- +void vtkOpenGLPolyDataMapper2D::ReplaceShaderPicking( + std::string & fssource, + vtkRenderer *, vtkActor2D *) +{ + vtkShaderProgram::Substitute(fssource, "//VTK::Picking::Dec", + "uniform vec3 mapperIndex;"); + vtkShaderProgram::Substitute(fssource, + "//VTK::Picking::Impl", + "gl_FragData[0] = vec4(mapperIndex,1.0);\n"); +} + //----------------------------------------------------------------------------- void vtkOpenGLPolyDataMapper2D::SetCameraShaderParameters( vtkOpenGLHelper &cellBO, vtkViewport* viewport, vtkActor2D *actor) @@ -501,6 +533,14 @@ void vtkOpenGLPolyDataMapper2D::SetCameraShaderParameters( // XXX(cppcheck): possible division by zero tmpMat->SetElement(2,3,-1.0*(farV+nearV)/(farV-nearV)); tmpMat->Transpose(); + if (this->VBO->GetCoordShiftAndScaleEnabled()) + { + this->VBOTransformInverse->GetTranspose(this->VBOShiftScale.GetPointer()); + // Pre-multiply the inverse of the VBO's transform: + vtkMatrix4x4::Multiply4x4( + this->VBOShiftScale.GetPointer(), tmpMat, tmpMat); + } + program->SetUniformMatrix("WCVCMatrix", tmpMat); tmpMat->Delete(); @@ -556,6 +596,7 @@ void vtkOpenGLPolyDataMapper2D::UpdateVBO(vtkActor2D *act, vtkViewport *viewport this->AppleBugPrimIDs, vtkOpenGLBufferObject::ArrayBuffer); this->AppleBugPrimIDBuffer->Release(); +#ifndef NDEBUG static bool warnAppleBugOnce = true; if (warnAppleBugOnce) { @@ -564,7 +605,7 @@ void vtkOpenGLPolyDataMapper2D::UpdateVBO(vtkActor2D *act, vtkViewport *viewport << (const char *)glGetString(GL_RENDERER)); warnAppleBugOnce = false; } - +#endif } // if we have cell scalars then we have to @@ -666,6 +707,20 @@ void vtkOpenGLPolyDataMapper2D::UpdateVBO(vtkActor2D *act, vtkViewport *viewport c ? (unsigned char *) c->GetVoidPointer(0) : NULL, c ? c->GetNumberOfComponents() : 0); + if (this->VBO->GetCoordShiftAndScaleEnabled()) + { + // The poly points are far from the origin relative to their + // variations so the VBO removed their mean coordinate and scaled... + // Generate an inverse of the VBO's transform: + double shift[3]; + double scale[3]; + this->VBO->GetCoordShift(shift); + this->VBO->GetCoordScale(scale); + this->VBOTransformInverse->Identity(); + this->VBOTransformInverse->Translate(shift[0], shift[1], shift[2]); + this->VBOTransformInverse->Scale(1.0/scale[0], 1.0/scale[1], 1.0/scale[2]); + } + this->Points.IBO->IndexCount = this->Points.IBO->CreatePointIndexBuffer(prims[0]); this->Lines.IBO->IndexCount = @@ -732,6 +787,14 @@ void vtkOpenGLPolyDataMapper2D::RenderOverlay(vtkViewport* viewport, this->CreateDefaultLookupTable(); } + vtkRenderWindow *renWin = vtkRenderWindow::SafeDownCast(viewport->GetVTKWindow()); + int picking = renWin->GetIsPicking(); + if (picking != this->LastPickState) + { + this->LastPickState = picking; + this->PickStateChanged.Modified(); + } + // Assume we want to do Zbuffering for now. // we may turn this off later glDepthMask(GL_TRUE); diff --git a/Rendering/OpenGL2/vtkOpenGLPolyDataMapper2D.h b/Rendering/OpenGL2/vtkOpenGLPolyDataMapper2D.h index 2e62fd811e1..4aef6692c42 100644 --- a/Rendering/OpenGL2/vtkOpenGLPolyDataMapper2D.h +++ b/Rendering/OpenGL2/vtkOpenGLPolyDataMapper2D.h @@ -26,16 +26,20 @@ #include "vtkRenderingOpenGL2Module.h" // For export macro #include "vtkPolyDataMapper2D.h" +#include "vtkNew.h" // used for ivars #include "vtkOpenGLHelper.h" // used for ivars #include // For API. #include //for ivars +class vtkActor2D; +class vtkMatrix4x4; class vtkOpenGLBufferObject; class vtkOpenGLHelper; class vtkOpenGLVertexBufferObject; class vtkPoints; class vtkRenderer; class vtkTextureObject; +class vtkTransform; class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLPolyDataMapper2D : public vtkPolyDataMapper2D { @@ -54,6 +58,9 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLPolyDataMapper2D : public vtkPolyDataM // resources to release. void ReleaseGraphicsResources(vtkWindow *); + /// Return the mapper's vertex buffer object. + vtkGetObjectMacro(VBO,vtkOpenGLVertexBufferObject); + protected: vtkOpenGLPolyDataMapper2D(); ~vtkOpenGLPolyDataMapper2D(); @@ -96,6 +103,13 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLPolyDataMapper2D : public vtkPolyDataM // Set the shader parameteres related to the property void SetPropertyShaderParameters(vtkOpenGLHelper &cellBO, vtkViewport *viewport, vtkActor2D *act); + // Description: + // Perform string replacments on the shader templates, called from + // ReplaceShaderValues + virtual void ReplaceShaderPicking( + std::string & fssource, + vtkRenderer *ren, vtkActor2D *act); + // Description: // Update the scene when necessary. void UpdateVBO(vtkActor2D *act, vtkViewport *viewport); @@ -117,6 +131,11 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLPolyDataMapper2D : public vtkPolyDataM vtkTimeStamp VBOUpdateTime; // When was the VBO updated? vtkPoints *TransformedPoints; + vtkNew VBOTransformInverse; + vtkNew VBOShiftScale; + + int LastPickState; + vtkTimeStamp PickStateChanged; // do we have wide lines that require special handling virtual bool HaveWideLines(vtkViewport *, vtkActor2D *); diff --git a/Rendering/OpenGL2/vtkOpenGLRenderPass.cxx b/Rendering/OpenGL2/vtkOpenGLRenderPass.cxx new file mode 100644 index 00000000000..801149d1cbc --- /dev/null +++ b/Rendering/OpenGL2/vtkOpenGLRenderPass.cxx @@ -0,0 +1,102 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOpenGLRenderPass.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkOpenGLRenderPass.h" + +#include "vtkInformation.h" +#include "vtkInformationObjectBaseVectorKey.h" +#include "vtkObjectFactory.h" +#include "vtkProp.h" +#include "vtkRenderState.h" + +#include + +vtkInformationKeyMacro(vtkOpenGLRenderPass, RenderPasses, ObjectBaseVector) + +//------------------------------------------------------------------------------ +void vtkOpenGLRenderPass::PrintSelf(std::ostream &os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//------------------------------------------------------------------------------ +bool vtkOpenGLRenderPass::ReplaceShaderValues(std::string &, std::string &, + std::string &, + vtkAbstractMapper *, vtkProp *) +{ + return true; +} + +//------------------------------------------------------------------------------ +bool vtkOpenGLRenderPass::SetShaderParameters(vtkShaderProgram *, + vtkAbstractMapper *, vtkProp *) +{ + return true; +} + +//------------------------------------------------------------------------------ +unsigned long int vtkOpenGLRenderPass::GetShaderStageMTime() +{ + return 0; +} + +//------------------------------------------------------------------------------ +vtkOpenGLRenderPass::vtkOpenGLRenderPass() +{ +} + +//------------------------------------------------------------------------------ +vtkOpenGLRenderPass::~vtkOpenGLRenderPass() +{ +} + +//------------------------------------------------------------------------------ +void vtkOpenGLRenderPass::PreRender(const vtkRenderState *s) +{ + assert("Render state valid." && s); + size_t numProps = s->GetPropArrayCount(); + for (size_t i = 0; i < numProps; ++i) + { + vtkProp *prop = s->GetPropArray()[i]; + vtkInformation *info = prop->GetPropertyKeys(); + if (!info) + { + info = vtkInformation::New(); + prop->SetPropertyKeys(info); + info->FastDelete(); + } + info->Append(vtkOpenGLRenderPass::RenderPasses(), this); + } +} + +//------------------------------------------------------------------------------ +void vtkOpenGLRenderPass::PostRender(const vtkRenderState *s) +{ + assert("Render state valid." && s); + size_t numProps = s->GetPropArrayCount(); + for (size_t i = 0; i < numProps; ++i) + { + vtkProp *prop = s->GetPropArray()[i]; + vtkInformation *info = prop->GetPropertyKeys(); + if (info) + { + info->Remove(vtkOpenGLRenderPass::RenderPasses(), this); + if (info->Length(vtkOpenGLRenderPass::RenderPasses()) == 0) + { + info->Remove(vtkOpenGLRenderPass::RenderPasses()); + } + } + } +} diff --git a/Rendering/OpenGL2/vtkOpenGLRenderPass.h b/Rendering/OpenGL2/vtkOpenGLRenderPass.h new file mode 100644 index 00000000000..1fda5dea1d9 --- /dev/null +++ b/Rendering/OpenGL2/vtkOpenGLRenderPass.h @@ -0,0 +1,84 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkOpenGLRenderPass.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +// .NAME vtkOpenGLRenderPass - Abstract render pass with shader modifications. +// +// .SECTION Description +// Allows a render pass to update shader code using a new virtual API. + +#ifndef vtkOpenGLRenderPass_h +#define vtkOpenGLRenderPass_h + +#include "vtkRenderingOpenGL2Module.h" // For export macro +#include "vtkRenderPass.h" + +#include // For std::string + +class vtkAbstractMapper; +class vtkInformationObjectBaseVectorKey; +class vtkProp; +class vtkShaderProgram; + +class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLRenderPass: public vtkRenderPass +{ +public: + vtkTypeMacro(vtkOpenGLRenderPass, vtkRenderPass) + virtual void PrintSelf(ostream &os, vtkIndent indent); + + // Description: + // Use vtkShaderProgram::Substitute to replace //VTK::XXX:YYY declarations in + // the shader sources. + // Return false on error. + virtual bool ReplaceShaderValues(std::string &vertexShader, + std::string &geometryShader, + std::string &fragmentShader, + vtkAbstractMapper *mapper, vtkProp *prop); + + // Description: + // Update the uniforms of the shader program. + // Return false on error. + virtual bool SetShaderParameters(vtkShaderProgram *program, + vtkAbstractMapper *mapper, vtkProp *prop); + + // Description: + // For multi-stage render passes that need to change shader code during a + // single pass, use this method to notify a mapper that the shader needs to be + // rebuilt (rather than reuse the last cached shader. This method should + // return the last time that the shader stage changed, or 0 if the shader + // is single-stage. + virtual unsigned long int GetShaderStageMTime(); + + // Description: + // Key containing information about the current pass. + static vtkInformationObjectBaseVectorKey *RenderPasses(); + +protected: + vtkOpenGLRenderPass(); + ~vtkOpenGLRenderPass(); + + // Description: + // Call before rendering to update the actors' information keys. + void PreRender(const vtkRenderState *s); + + // Description: + // Call after rendering to clean up the actors' information keys. + void PostRender(const vtkRenderState *s); + +private: + vtkOpenGLRenderPass(const vtkOpenGLRenderPass&); // Not implemented + void operator=(const vtkOpenGLRenderPass&); // Not implemented +}; + +#endif // vtkOpenGLRenderPass_h diff --git a/Rendering/OpenGL2/vtkOpenGLRenderUtilities.cxx b/Rendering/OpenGL2/vtkOpenGLRenderUtilities.cxx index e91b2b13fba..649564e5834 100644 --- a/Rendering/OpenGL2/vtkOpenGLRenderUtilities.cxx +++ b/Rendering/OpenGL2/vtkOpenGLRenderUtilities.cxx @@ -19,6 +19,21 @@ #include "vtkOpenGLBufferObject.h" #include "vtkOpenGLVertexArrayObject.h" +// Static initializion: +vtkOpenGLBufferObject *vtkOpenGLRenderUtilities::FullScreenQuadVerts = NULL; +struct vtkOpenGLRenderUtilities::FSQVertsCleanUp +{ + ~FSQVertsCleanUp() + { + if (vtkOpenGLRenderUtilities::FullScreenQuadVerts) + { + vtkOpenGLRenderUtilities::FullScreenQuadVerts->Delete(); + vtkOpenGLRenderUtilities::FullScreenQuadVerts = NULL; + } + } +}; +vtkOpenGLRenderUtilities::FSQVertsCleanUp vtkFSQVertsCleanUp; + // ---------------------------------------------------------------------------- vtkOpenGLRenderUtilities::vtkOpenGLRenderUtilities() { @@ -102,3 +117,96 @@ void vtkOpenGLRenderUtilities::RenderTriangles( tvbo->ReleaseGraphicsResources(); } } + +//------------------------------------------------------------------------------ +std::string vtkOpenGLRenderUtilities::GetFullScreenQuadVertexShader() +{ + // Pass through: + return "//VTK::System::Dec\n" + "attribute vec4 ndCoordIn;\n" + "attribute vec2 texCoordIn;\n" + "varying vec2 texCoord;\n" + "void main()\n" + "{\n" + " gl_Position = ndCoordIn;\n" + " texCoord = texCoordIn;\n" + "}\n"; +} + +//------------------------------------------------------------------------------ +std::string vtkOpenGLRenderUtilities::GetFullScreenQuadFragmentShaderTemplate() +{ + return "//VTK::System::Dec\n" + "//VTK::Output::Dec\n" + "in vec2 texCoord;\n" + "//VTK::FSQ::Decl\n" + "void main()\n" + "{\n" + "//VTK::FSQ::Impl\n" + "}\n"; +} + +//------------------------------------------------------------------------------ +std::string vtkOpenGLRenderUtilities::GetFullScreenQuadGeometryShader() +{ + return ""; +} + +//------------------------------------------------------------------------------ +bool vtkOpenGLRenderUtilities::PrepFullScreenVAO(vtkOpenGLVertexArrayObject *vao, + vtkShaderProgram *prog) +{ + bool res; + typedef vtkOpenGLRenderUtilities GLUtil; + + if (!GLUtil::FullScreenQuadVerts) + { + GLUtil::FullScreenQuadVerts = vtkOpenGLBufferObject::New(); + + // ndCoord_x, ndCoord_y, texCoord_x, texCoord_y + float verts[4][4] = { { 1.f, 1.f, 1.f, 1.f }, + {-1.f, 1.f, 0.f, 1.f }, + { 1.f,-1.f, 1.f, 0.f }, + {-1.f,-1.f, 0.f, 0.f } }; + + GLUtil::FullScreenQuadVerts->SetType(vtkOpenGLBufferObject::ArrayBuffer); + res = GLUtil::FullScreenQuadVerts->Upload( + verts, 16, vtkOpenGLBufferObject::ArrayBuffer); + if (!res) + { + vtkGenericWarningMacro("Error uploading fullscreen quad vertex data."); + return false; + } + } + + vao->Bind(); + + res = vao->AddAttributeArray(prog, GLUtil::FullScreenQuadVerts, "ndCoordIn", + 0, 4 * sizeof(float), + VTK_FLOAT, 2, false); + if (!res) + { + vao->Release(); + vtkGenericWarningMacro("Error binding ndCoords to VAO."); + return false; + } + + res = vao->AddAttributeArray(prog, GLUtil::FullScreenQuadVerts, "texCoordIn", + 2 * sizeof(float), 4 * sizeof(float), + VTK_FLOAT, 2, false); + if (!res) + { + vao->Release(); + vtkGenericWarningMacro("Error binding texCoords to VAO."); + return false; + } + + vao->Release(); + return true; +} + +//------------------------------------------------------------------------------ +void vtkOpenGLRenderUtilities::DrawFullScreenQuad() +{ + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); +} diff --git a/Rendering/OpenGL2/vtkOpenGLRenderUtilities.h b/Rendering/OpenGL2/vtkOpenGLRenderUtilities.h index 9af4690846d..32540c741a5 100644 --- a/Rendering/OpenGL2/vtkOpenGLRenderUtilities.h +++ b/Rendering/OpenGL2/vtkOpenGLRenderUtilities.h @@ -23,7 +23,9 @@ #include "vtkObject.h" #include "vtk_glew.h" // Needed for GLuint. +#include // for std::string +class vtkOpenGLBufferObject; class vtkOpenGLVertexArrayObject; class vtkShaderProgram; @@ -47,10 +49,66 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLRenderUtilities : public vtkObject float *tcoords, vtkShaderProgram *program, vtkOpenGLVertexArrayObject *vao); + // Description: + // Draw a full-screen quad: + // * VertexShader and GeometryShader should be used as-is when building the + // ShaderProgram. + // * FragmentShaderTemplate supports the replacements //VTK::FSQ::Decl and + // //VTK::FSQ::Impl for declaring variables and the shader body, + // respectively. + // * The varying texCoord is available to the fragment shader for texture + // lookups into full-screen textures, ie. texture2D(textureName, texCoord). + // * PrepFullScreenVAO initializes a new VAO for drawing a quad. + // * DrawFullScreenQuad actually draws the quad. + // + // Example usage: + // @code + // typedef vtkOpenGLRenderUtilities GLUtil; + // + // // Prep fragment shader source: + // std::string fragShader = GLUtil::GetFullScreenQuadFragmentShaderTemplate(); + // vtkShaderProgram::Substitute(fragShader, "//VTK::FSQ::Decl", + // "uniform sampler2D aTexture;"); + // vtkShaderProgram::Substitute(fragShader, "//VTK::FSQ::Impl", + // "gl_FragData[0] = texture2D(aTexture, texCoord);"); + // + // // Create shader program: + // vtkShaderProgram *prog = shaderCache->ReadyShaderProgram( + // GLUtil::GetFullScreenQuadVertexShader().c_str(), + // fragShader.c_str(), + // GLUtil::GetFullScreenQuadGeometryShader().c_str()); + // + // // Initialize new VAO: + // vtkNew vao; + // GLUtil::PrepFullScreenVAO(vao.Get(), prog); + // + // // Setup shader program to sample vtkTextureObject aTexture: + // aTexture->Activate(); + // prog->SetUniformi("aTexture", aTexture->GetTextureUnit()); + // + // // Render the full-screen quad: + // vao->Bind(); + // GLUtil::DrawFullScreenQuad(); + // vao->Release(); + // aTexture->Deactivate(); + // @endcode + static std::string GetFullScreenQuadVertexShader(); + static std::string GetFullScreenQuadFragmentShaderTemplate(); + static std::string GetFullScreenQuadGeometryShader(); + static bool PrepFullScreenVAO(vtkOpenGLVertexArrayObject *vao, + vtkShaderProgram *prog); + static void DrawFullScreenQuad(); + + // Description: + // Implementation detail -- do not use. + struct FSQVertsCleanUp; + protected: vtkOpenGLRenderUtilities(); ~vtkOpenGLRenderUtilities(); + static vtkOpenGLBufferObject *FullScreenQuadVerts; + private: vtkOpenGLRenderUtilities(const vtkOpenGLRenderUtilities&); // Not implemented. void operator=(const vtkOpenGLRenderUtilities&); // Not implemented. diff --git a/Rendering/OpenGL2/vtkOpenGLRenderWindow.cxx b/Rendering/OpenGL2/vtkOpenGLRenderWindow.cxx index 8cc739f3dec..259598bd507 100644 --- a/Rendering/OpenGL2/vtkOpenGLRenderWindow.cxx +++ b/Rendering/OpenGL2/vtkOpenGLRenderWindow.cxx @@ -598,9 +598,9 @@ void vtkOpenGLRenderWindow::OpenGLInitContext() return; } - if (!GLEW_VERSION_3_2) + if (!GLEW_VERSION_3_2 && !GLEW_VERSION_3_1) { - if (!GLEW_VERSION_2_1 || !GLEW_EXT_gpu_shader4) + if (!GLEW_EXT_gpu_shader4) { vtkErrorMacro("GL version 2.1 with the gpu_shader4 extension is not " "supported by your graphics driver but is required for the new " @@ -612,8 +612,8 @@ void vtkOpenGLRenderWindow::OpenGLInitContext() vtkWarningMacro( "VTK is designed to work with OpenGL version 3.2 but it appears " "it has been given a context that does not support 3.2. VTK will " - "run in a compatibility mode designed to work with OpenGL 2.1 but " - "some features may not work."); + "run in a compatibility mode designed to work with earlier versions " + "of OpenGL but some features may not work."); } else { @@ -2275,11 +2275,11 @@ int vtkOpenGLRenderWindow::SupportsOpenGL() #ifdef GLEW_OK - else if (GLEW_VERSION_3_2 || (GLEW_VERSION_2_1 && GLEW_EXT_gpu_shader4)) + else if (GLEW_VERSION_3_2 || GLEW_VERSION_3_1 || GLEW_EXT_gpu_shader4) { this->OpenGLSupportResult = 1; this->OpenGLSupportMessage = - "The system appears to support OpenGL 3.2 or has 2.1 with the required extension"; + "The system appears to support OpenGL 3.2/3.1 or has 2.1 with the required extension"; } #endif diff --git a/Rendering/OpenGL2/vtkOpenGLRenderer.cxx b/Rendering/OpenGL2/vtkOpenGLRenderer.cxx index 4d15c8f4975..5a0d08fe40d 100644 --- a/Rendering/OpenGL2/vtkOpenGLRenderer.cxx +++ b/Rendering/OpenGL2/vtkOpenGLRenderer.cxx @@ -43,9 +43,15 @@ PURPOSE. See the above copyright notice for more information. #include "vtkTrivialProducer.h" #include "vtkUnsignedCharArray.h" +// Dual depth peeling requires GL_MAX blending, which is unavailable on ES2. +#if GL_ES_VERSION_2_0 != 1 +#include "vtkDualDepthPeelingPass.h" +#endif + #include #include #include +#include class vtkGLPickInfo { @@ -58,8 +64,6 @@ class vtkGLPickInfo vtkStandardNewMacro(vtkOpenGLRenderer); -vtkCxxSetObjectMacro(vtkOpenGLRenderer, Pass, vtkRenderPass); - vtkOpenGLRenderer::vtkOpenGLRenderer() { this->PickInfo = new vtkGLPickInfo; @@ -72,8 +76,6 @@ vtkOpenGLRenderer::vtkOpenGLRenderer() this->DepthPeelingHigherLayer=0; this->BackgroundTexture = 0; - this->Pass = 0; - this->HaveApplePrimitiveIdBugValue = false; this->HaveApplePrimitiveIdBugChecked = false; } @@ -281,7 +283,55 @@ void vtkOpenGLRenderer::DeviceRenderTranslucentPolygonalGeometry() { if (!this->DepthPeelingPass) { - this->DepthPeelingPass = vtkDepthPeelingPass::New(); + // Dual depth peeling requires: + // - float textures (ARB_texture_float) + // - RG textures (ARB_texture_rg) + // - MAX blending (not available in ES2, but added in ES3). + bool dualDepthPeelingSupported = false; +#if GL_ES_VERSION_2_0 != 1 + dualDepthPeelingSupported = context->GetContextSupportsOpenGL32() || + (GLEW_ARB_texture_float && GLEW_ARB_texture_rg); +#elif GL_ES_VERSION_3_0 == 1 + // ES3 is supported: + dualDepthPeelingSupported = true; +#endif + + // There's a bug on current mesa master that prevents dual depth peeling + // from functioning properly, something in the texture sampler is causing + // all lookups to return NaN. See discussion on + // https://bugs.freedesktop.org/show_bug.cgi?id=94955 + // We'll always fallback to regular depth peeling until this is fixed. + // Only disable for mesa + llvmpipe/SWR, since those are the drivers that + // seem to be affected by this. + std::string glVersion = + reinterpret_cast(glGetString(GL_VERSION)); + if (glVersion.find("Mesa") != std::string::npos) + { + std::string glRenderer = + reinterpret_cast(glGetString(GL_RENDERER)); + if (glRenderer.find("llvmpipe") != std::string::npos || + glRenderer.find("SWR") != std::string::npos) + { + vtkDebugMacro("Disabling dual depth peeling -- mesa bug detected. " + "GL_VERSION = '" << glVersion << "'; " + "GL_RENDERER = '" << glRenderer << "'."); + dualDepthPeelingSupported = false; + } + } + + if (dualDepthPeelingSupported) + { +#if GL_ES_VERSION_2_0 != 1 // vtkDualDepthPeelingPass is not built on ES2 + vtkDebugMacro("Using dual depth peeling."); + this->DepthPeelingPass = vtkDualDepthPeelingPass::New(); +#endif + } + else + { + vtkDebugMacro("Using standard depth peeling (dual depth peeling not " + "supported by the graphics card/driver)."); + this->DepthPeelingPass = vtkDepthPeelingPass::New(); + } vtkTranslucentPass *tp = vtkTranslucentPass::New(); this->DepthPeelingPass->SetTranslucentPass(tp); tp->Delete(); @@ -307,15 +357,6 @@ void vtkOpenGLRenderer::PrintSelf(ostream& os, vtkIndent indent) os << indent << "PickedId" << this->PickInfo->PickedId<< "\n"; os << indent << "NumPicked" << this->PickInfo->NumPicked<< "\n"; os << indent << "PickedZ " << this->PickedZ << "\n"; - os << indent << "Pass:"; - if(this->Pass!=0) - { - os << "exists" << endl; - } - else - { - os << "null" << endl; - } } @@ -661,20 +702,30 @@ bool vtkOpenGLRenderer::HaveApplePrimitiveIdBug() } #ifdef __APPLE__ - // working AMD APPLE systems + // Known working Apple+AMD systems: // OpenGL vendor string: ATI Technologies Inc. // OpenGL version string: 4.1 ATI-1.38.3 // OpenGL version string: 4.1 ATI-1.40.15 // OpenGL renderer string: AMD Radeon R9 M370X OpenGL Engine + // OpenGL version string: 4.1 ATI-1.40.16 // OpenGL renderer string: AMD Radeon HD - FirePro D500 OpenGL Engine // OpenGL renderer string: AMD Radeon HD 5770 OpenGL Engine + // OpenGL renderer string: AMD Radeon R9 M395 OpenGL Engine - // known bad APPLE AMD systems + // OpenGL vendor string: ATI Technologies Inc. + // OpenGL renderer string: ATI Radeon HD 5770 OpenGL Engine + // OpenGL version string: 4.1 ATI-1.42.6 + + // Known buggy Apple+AMD systems: // OpenGL vendor string: ATI Technologies Inc. // OpenGL version string: 3.3 ATI-10.0.40 // OpenGL renderer string: ATI Radeon HD 2600 PRO OpenGL Engine + // OpenGL vendor string: ATI Technologies Inc. + // OpenGL renderer string: AMD Radeon HD - FirePro D300 OpenGL Engine + // OpenGL version string: 4.1 ATI-1.24.39 + std::string vendor = (const char *)glGetString(GL_VENDOR); if (vendor.find("ATI") != std::string::npos || vendor.find("AMD") != std::string::npos || @@ -686,14 +737,26 @@ bool vtkOpenGLRenderer::HaveApplePrimitiveIdBug() // but exclude systems we know do not have it std::string renderer = (const char *)glGetString(GL_RENDERER); std::string version = (const char *)glGetString(GL_VERSION); + int minorVersion = 0; + int patchVersion = 0; + // try to extract some minor version numbers + if (version.find("4.1 ATI-1.") == 0) + { + std::string minorVer = version.substr(strlen("4.1 ATI-1."),std::string::npos); + if (minorVer.find(".") == 2) + { + minorVersion = atoi(minorVer.substr(0,2).c_str()); + patchVersion = atoi(minorVer.substr(3,std::string::npos).c_str()); + } + } if ( ((version.find("4.1 ATI-1.38.3") != std::string::npos || version.find("4.1 ATI-1.40.15") != std::string::npos) && (renderer.find("AMD Radeon R9 M370X OpenGL Engine") != std::string::npos)) || - (version.find("4.1 ATI-1.40.16") != std::string::npos && - (renderer.find("ATI Radeon HD 5770 OpenGL Engine") != std::string::npos || - renderer.find("AMD Radeon HD - FirePro D500 OpenGL Engine") != std::string::npos)) - ) + // assume anything with 1.40.16 or later is good? + minorVersion > 40 || + (minorVersion == 40 && patchVersion >= 16) + ) { this->HaveApplePrimitiveIdBugValue = false; } diff --git a/Rendering/OpenGL2/vtkOpenGLRenderer.h b/Rendering/OpenGL2/vtkOpenGLRenderer.h index c65ba884b00..e6a4877a40a 100644 --- a/Rendering/OpenGL2/vtkOpenGLRenderer.h +++ b/Rendering/OpenGL2/vtkOpenGLRenderer.h @@ -61,12 +61,6 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLRenderer : public vtkRenderer // (Used by vtkOpenGLProperty or vtkOpenGLTexture) int GetDepthPeelingHigherLayer(); - // Description: - // Set/Get a custom render pass. - // Initial value is NULL. - void SetPass(vtkRenderPass *p); - vtkGetObjectMacro(Pass, vtkRenderPass); - // Description: // Indicate if this system is subject to the apple/amd bug // of not having a working glPrimitiveId @@ -124,7 +118,6 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLRenderer : public vtkRenderer int DepthPeelingHigherLayer; friend class vtkRenderPass; - vtkRenderPass *Pass; bool HaveApplePrimitiveIdBugValue; bool HaveApplePrimitiveIdBugChecked; diff --git a/Rendering/OpenGL2/vtkOpenGLShaderCache.cxx b/Rendering/OpenGL2/vtkOpenGLShaderCache.cxx index f2b79844843..59b40bcdfab 100644 --- a/Rendering/OpenGL2/vtkOpenGLShaderCache.cxx +++ b/Rendering/OpenGL2/vtkOpenGLShaderCache.cxx @@ -123,85 +123,57 @@ unsigned int vtkOpenGLShaderCache::ReplaceShaderValues( vtkShaderProgram::Substitute(FSSource,"VSOut","GSOut"); } + std::string version = "#version 120\n"; + bool needFragDecls = false; #if GL_ES_VERSION_2_0 != 1 - unsigned int count = 0; - if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32()) + int glMajorVersion = 2; + int glMinorVersion = 0; + glGetIntegerv(GL_MAJOR_VERSION, & glMajorVersion); + glGetIntegerv(GL_MINOR_VERSION, & glMinorVersion); + if (glMajorVersion >= 3) { - vtkShaderProgram::Substitute(VSSource,"//VTK::System::Dec", - "#version 150\n" - "#define attribute in\n" - "#define varying out\n" - "#define highp\n" - "#define mediump\n" - "#define lowp"); - vtkShaderProgram::Substitute(FSSource,"//VTK::System::Dec", - "#version 150\n" - "#define varying in\n" - "#define highp\n" - "#define mediump\n" - "#define lowp\n" - "#define texelFetchBuffer texelFetch\n" - "#define texture1D texture\n" - "#define texture2D texture\n" - "#define texture3D texture\n" - ); - vtkShaderProgram::Substitute(GSSource,"//VTK::System::Dec", - "#version 150\n" - "#define highp\n" - "#define mediump\n" - "#define lowp" - ); - std::string fragDecls; - bool done = false; - while (!done) + version = "#version 150\n"; + if (glMajorVersion == 3 && glMinorVersion == 1) { - std::ostringstream src; - std::ostringstream dst; - src << "gl_FragData[" << count << "]"; - // this naming has to match the bindings - // in vtkOpenGLShaderProgram.cxx - dst << "fragOutput" << count; - done = !vtkShaderProgram::Substitute(FSSource, src.str(),dst.str()); - if (!done) - { - fragDecls += "out vec4 " + dst.str() + ";\n"; - count++; - } + version = "#version 140\n"; + } + else + { + needFragDecls = true; } - vtkShaderProgram::Substitute(FSSource,"//VTK::Output::Dec",fragDecls); - } - else - { - vtkShaderProgram::Substitute(VSSource,"//VTK::System::Dec", - "#version 120\n" - "#define highp\n" - "#define mediump\n" - "#define lowp"); - vtkShaderProgram::Substitute(FSSource,"//VTK::System::Dec", - "#version 120\n" - "#extension GL_EXT_gpu_shader4 : require\n" - "#define highp\n" - "#define mediump\n" - "#define lowp"); - vtkShaderProgram::Substitute(GSSource,"//VTK::System::Dec", - "#version 120\n" - "#define highp\n" - "#define mediump\n" - "#define lowp"); } - return count; #else #if GL_ES_VERSION_3_0 == 1 - unsigned int count = 0; + version = "#version 300 es\n"; + needFragDecls = true; +#else + version = "#version 100\n"; +#endif +#endif + vtkShaderProgram::Substitute(VSSource,"//VTK::System::Dec", - "#version 300 es\n" + version + + "#ifdef GL_ES\n" + "#if __VERSION__ == 300\n" + "#define attribute in\n" + "#define varying out\n"\ + "#endif // 300\n" + "#else // GL_ES\n" + "#define highp\n" + "#define mediump\n" + "#define lowp\n" + "#if __VERSION__ == 150\n" "#define attribute in\n" "#define varying out\n" + "#endif\n" + "#endif // GL_ES\n" ); + vtkShaderProgram::Substitute(FSSource,"//VTK::System::Dec", - "#version 300 es\n" - "#define varying in\n" + version + "#ifdef GL_ES\n" + "#if __VERSION__ == 300\n" + "#define varying in\n" "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" "precision highp float;\n" "precision highp sampler2D;\n" @@ -211,53 +183,81 @@ unsigned int vtkOpenGLShaderCache::ReplaceShaderValues( "precision mediump sampler2D;\n" "precision mediump sampler3D;\n" "#endif\n" + "#define texelFetchBuffer texelFetch\n" + "#define texture1D texture\n" + "#define texture2D texture\n" + "#define texture3D texture\n" + "#endif // 300\n" + "#if __VERSION__ == 100\n" + "#extension GL_OES_standard_derivatives : enable\n" + "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" + "precision highp float;\n" + "#else\n" + "precision mediump float;\n" "#endif\n" + "#endif // 100\n" + "#else // GL_ES\n" + "#define highp\n" + "#define mediump\n" + "#define lowp\n" + "#if __VERSION__ == 150\n" + "#define varying in\n" "#define texelFetchBuffer texelFetch\n" "#define texture1D texture\n" "#define texture2D texture\n" "#define texture3D texture\n" + "#endif\n" + "#if __VERSION__ == 120\n" + "#extension GL_EXT_gpu_shader4 : require\n" + "#endif\n" + "#endif // GL_ES\n" ); + vtkShaderProgram::Substitute(GSSource,"//VTK::System::Dec", - "#version 300 es\n" + version + "#ifdef GL_ES\n" "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" "precision highp float;\n" "#else\n" "precision mediump float;\n" "#endif\n" + "#else // GL_ES\n" + "#define highp\n" + "#define mediump\n" + "#define lowp\n" + "#if __VERSION__ == 150\n" + "#define attribute in\n" + "#define varying out\n" "#endif\n" + "#endif // GL_ES\n" ); - std::string fragDecls; - bool done = false; - while (!done) + + + if (needFragDecls) { - std::ostringstream src; - std::ostringstream dst; - src << "gl_FragData[" << count << "]"; - // this naming has to match the bindings - // in vtkOpenGLShaderProgram.cxx - dst << "fragOutput" << count; - done = !vtkShaderProgram::Substitute(FSSource, src.str(),dst.str()); - if (!done) + unsigned int count = 0; + std::string fragDecls; + bool done = false; + while (!done) { - fragDecls += "out vec4 " + dst.str() + ";\n"; - count++; + std::ostringstream src; + std::ostringstream dst; + src << "gl_FragData[" << count << "]"; + // this naming has to match the bindings + // in vtkOpenGLShaderProgram.cxx + dst << "fragOutput" << count; + done = !vtkShaderProgram::Substitute(FSSource, src.str(),dst.str()); + if (!done) + { + fragDecls += "out vec4 " + dst.str() + ";\n"; + count++; + } } + vtkShaderProgram::Substitute(FSSource,"//VTK::Output::Dec",fragDecls); + return count; } - vtkShaderProgram::Substitute(FSSource,"//VTK::Output::Dec",fragDecls); -#else - vtkShaderProgram::Substitute(FSSource,"//VTK::System::Dec", - "#ifdef GL_ES\n" - "#extension GL_OES_standard_derivatives : enable\n" - "#ifdef GL_FRAGMENT_PRECISION_HIGH\n" - "precision highp float;\n" - "#else\n" - "precision mediump float;\n" - "#endif\n" - "#endif\n"); -#endif + return 0; -#endif } vtkShaderProgram *vtkOpenGLShaderCache::ReadyShaderProgram( diff --git a/Rendering/OpenGL2/vtkOpenGLVertexBufferObject.cxx b/Rendering/OpenGL2/vtkOpenGLVertexBufferObject.cxx index 7d7979233a4..8e7fc3e52ca 100644 --- a/Rendering/OpenGL2/vtkOpenGLVertexBufferObject.cxx +++ b/Rendering/OpenGL2/vtkOpenGLVertexBufferObject.cxx @@ -31,6 +31,13 @@ vtkOpenGLVertexBufferObject::vtkOpenGLVertexBufferObject() this->ColorOffset = 0; // Offset of the color this->ColorComponents = 0; // Number of color components this->SetType(vtkOpenGLBufferObject::ArrayBuffer); + this->CoordShiftAndScaleMethod = AUTO_SHIFT_SCALE; + this->CoordShiftAndScaleEnabled = false; + for (int i = 0; i < 3; ++i) + { + this->CoordShift[i] = 0.; + this->CoordScale[i] = 1.; + } } vtkOpenGLVertexBufferObject::~vtkOpenGLVertexBufferObject() @@ -133,6 +140,96 @@ void TemplatedAppendVBO3(vtkOpenGLVertexBufferObject *self, self->VertexCount += numPts; } +// internal function called by AppendVBO +template +void TemplatedAppendVBOShiftScale3(vtkOpenGLVertexBufferObject *self, + T* points, T2* normals, vtkIdType numPts, + T3* tcoords, int textureComponents, + unsigned char* colors, int colorComponents, + const double* shift, const double* scale) +{ + // Figure out how big each block will be, currently 6 or 7 floats. + int blockSize = 3; + self->VertexOffset = 0; + self->NormalOffset = 0; + self->TCoordOffset = 0; + self->TCoordComponents = 0; + self->ColorComponents = 0; + self->ColorOffset = 0; + if (normals) + { + self->NormalOffset = sizeof(float) * blockSize; + blockSize += 3; + } + if (tcoords) + { + self->TCoordOffset = sizeof(float) * blockSize; + self->TCoordComponents = textureComponents; + blockSize += textureComponents; + } + if (colors) + { + self->ColorComponents = colorComponents; + self->ColorOffset = sizeof(float) * blockSize; + ++blockSize; + } + self->Stride = sizeof(float) * blockSize; + + // Create a buffer, and copy the data over. + self->PackedVBO.resize(blockSize * (numPts + self->VertexCount)); + std::vector::iterator it = self->PackedVBO.begin() + + (self->VertexCount*self->Stride/sizeof(float)); + + T *pointPtr; + T2 *normalPtr; + T3 *tcoordPtr; + unsigned char *colorPtr; + + // TODO: optimize this somehow, lots of if statements in here + for (vtkIdType i = 0; i < numPts; ++i) + { + pointPtr = points + i*3; + normalPtr = normals + i*3; + tcoordPtr = tcoords + i*textureComponents; + colorPtr = colors + i*colorComponents; + + // Vertices + *(it++) = (*(pointPtr++) - shift[0]) * scale[0]; + *(it++) = (*(pointPtr++) - shift[1]) * scale[1]; + *(it++) = (*(pointPtr++) - shift[2]) * scale[2]; + if (normals) + { + *(it++) = *(normalPtr++); + *(it++) = *(normalPtr++); + *(it++) = *(normalPtr++); + } + if (tcoords) + { + for (int j = 0; j < textureComponents; ++j) + { + *(it++) = *(tcoordPtr++); + } + } + if (colors) + { + if (colorComponents == 4) + { + *(it++) = *reinterpret_cast(colorPtr); + } + else + { + vtkucfloat c; + c.c[0] = *(colorPtr++); + c.c[1] = *(colorPtr++); + c.c[2] = *(colorPtr); + c.c[3] = 255; + *(it++) = c.f; + } + } + } + self->VertexCount += numPts; +} + //---------------------------------------------------------------------------- template void TemplatedAppendVBO2(vtkOpenGLVertexBufferObject *self, @@ -160,11 +257,41 @@ void TemplatedAppendVBO2(vtkOpenGLVertexBufferObject *self, } } +//---------------------------------------------------------------------------- +template +void TemplatedAppendVBOShiftScale2(vtkOpenGLVertexBufferObject* self, + T* points, T2* normals, vtkIdType numPts, + vtkDataArray* tcoords, + unsigned char* colors, int colorComponents, + const double* shift, const double* scale) +{ + if (tcoords) + { + switch(tcoords->GetDataType()) + { + vtkFloatDoubleTemplateMacro( + TemplatedAppendVBOShiftScale3(self, points, normals, + numPts, + static_cast(tcoords->GetVoidPointer(0)), + tcoords->GetNumberOfComponents(), + colors, colorComponents, + shift, scale)); + } + } + else + { + TemplatedAppendVBOShiftScale3(self, points, normals, + numPts, (float *)NULL, 0, + colors, colorComponents, + shift, scale); + } +} + //---------------------------------------------------------------------------- template -void TemplatedAppendVBO(vtkOpenGLVertexBufferObject *self, - T* points, vtkDataArray *normals, vtkIdType numPts, - vtkDataArray *tcoords, +void TemplatedAppendVBO(vtkOpenGLVertexBufferObject* self, + T* points, vtkDataArray* normals, vtkIdType numPts, + vtkDataArray* tcoords, unsigned char *colors, int colorComponents) { if (normals) @@ -185,8 +312,106 @@ void TemplatedAppendVBO(vtkOpenGLVertexBufferObject *self, } } +//---------------------------------------------------------------------------- +template +void TemplatedAppendVBOShiftScale(vtkOpenGLVertexBufferObject* self, + T* points, vtkDataArray* normals, vtkIdType numPts, + vtkDataArray* tcoords, + unsigned char *colors, int colorComponents, + const double* shift, const double* scale) +{ + if (normals) + { + switch(normals->GetDataType()) + { + vtkFloatDoubleTemplateMacro( + TemplatedAppendVBOShiftScale2(self, points, + static_cast(normals->GetVoidPointer(0)), + numPts, tcoords, colors, colorComponents, shift, scale)); + } + } + else + { + TemplatedAppendVBOShiftScale2(self, points, + (float *)NULL, + numPts, tcoords, colors, colorComponents, shift, scale); + } +} + } // end anonymous namespace +void vtkOpenGLVertexBufferObject::SetCoordShiftAndScaleMethod(ShiftScaleMethod meth) +{ + vtkDebugMacro( + << this->GetClassName() << " (" << this + << "): setting CoordShiftAndScaleMethod to " << meth); + if (this->CoordShiftAndScaleMethod != meth) + { + if (!this->PackedVBO.empty()) + { + vtkErrorMacro("SetCoordShiftAndScaleMethod() called with non-empty VBO! Ignoring."); + return; + } + + this->CoordShiftAndScaleMethod = meth; + this->Modified(); + } +} + +void vtkOpenGLVertexBufferObject::SetCoordShift(double sx, double sy, double sz) +{ + vtkDebugMacro( + << this->GetClassName() << " (" << this + << "): setting CoordShift to (" << sx << "," << sy << "," << sz << ")"); + if ((this->CoordShift[0] != sx) || (this->CoordShift[1] != sy) || (this->CoordShift[2] != sz)) + { + if (!this->PackedVBO.empty()) + { + vtkErrorMacro("SetCoordShift() called with non-empty VBO! Ignoring."); + return; + } + this->CoordShift[0] = sx; + this->CoordShift[1] = sy; + this->CoordShift[2] = sz; + this->CoordShiftAndScaleEnabled = + this->CoordShift[0] != 0.0 || this->CoordShift[1] != 0.0 || this->CoordShift[2] != 0.0 || + this->CoordScale[0] != 1.0 || this->CoordScale[1] != 1.0 || this->CoordScale[2] != 1.0; + this->Modified(); + } +} + +void vtkOpenGLVertexBufferObject::SetCoordShift(const double s[3]) +{ + this->SetCoordShift(s[0], s[1], s[2]); +} + +void vtkOpenGLVertexBufferObject::SetCoordScale(double sx, double sy, double sz) +{ + vtkDebugMacro( + << this->GetClassName() << " (" << this + << "): setting CoordScale to (" << sx << "," << sy << "," << sz << ")"); + if ((this->CoordScale[0] != sx) || (this->CoordScale[1] != sy) || (this->CoordScale[2] != sz)) + { + if (!this->PackedVBO.empty()) + { + vtkErrorMacro("SetCoordScale() called with non-empty VBO! Ignoring."); + return; + } + + this->CoordScale[0] = sx; + this->CoordScale[1] = sy; + this->CoordScale[2] = sz; + this->CoordShiftAndScaleEnabled = + this->CoordShift[0] != 0.0 || this->CoordShift[1] != 0.0 || this->CoordShift[2] != 0.0 || + this->CoordScale[0] != 1.0 || this->CoordScale[1] != 1.0 || this->CoordScale[2] != 1.0; + this->Modified(); + } +} + +void vtkOpenGLVertexBufferObject::SetCoordScale(const double s[3]) +{ + this->SetCoordScale(s[0], s[1], s[2]); +} // Take the points, and pack them into the VBO object supplied. This currently // takes whatever the input type might be and packs them into a VBO using @@ -198,11 +423,26 @@ void vtkOpenGLVertexBufferObject::AppendVBO( vtkDataArray *tcoords, unsigned char *colors, int colorComponents) { - switch(points->GetDataType()) + if (this->CoordShiftAndScaleEnabled) { - vtkTemplateMacro( - TemplatedAppendVBO(this, static_cast(points->GetVoidPointer(0)), - normals, numPts, tcoords, colors, colorComponents)); + switch(points->GetDataType()) + { + vtkTemplateMacro( + TemplatedAppendVBOShiftScale( + this, static_cast(points->GetVoidPointer(0)), + normals, numPts, tcoords, colors, colorComponents, + this->CoordShift, this->CoordScale)); + } + } + else + { + switch(points->GetDataType()) + { + vtkTemplateMacro( + TemplatedAppendVBO( + this, static_cast(points->GetVoidPointer(0)), + normals, numPts, tcoords, colors, colorComponents)); + } } } @@ -213,8 +453,37 @@ void vtkOpenGLVertexBufferObject::CreateVBO( vtkDataArray *tcoords, unsigned char *colors, int colorComponents) { + if (this->CoordShiftAndScaleMethod == AUTO_SHIFT_SCALE) + { + double bds[6]; + double shift[3]; + double scale[3]; + points->GetBounds(bds); + bool needed = false; + for (int i = 0; i < 3; ++i) + { + shift[i] = bds[2 * i]; //-0.5 * (bds[2 * i + 1] + bds[2 * i]); + double delta = bds[2 * i + 1] - bds[2 * i]; + if (delta > 0.0 && fabs(shift[i]) / delta > 1.0e4) + { + needed = true; + scale[i] = 1.0 / delta; + } + else + { + scale[i] = 1.0; + } + } + if (needed) + { + this->SetCoordShift(shift); + this->SetCoordScale(scale); + } + } // fast path - if (!tcoords && !normals && !colors && points->GetDataType() == VTK_FLOAT) + if ( + !this->CoordShiftAndScaleEnabled && !tcoords && !normals && + !colors && points->GetDataType() == VTK_FLOAT) { int blockSize = 3; this->VertexOffset = 0; @@ -232,7 +501,7 @@ void vtkOpenGLVertexBufferObject::CreateVBO( // slower path this->VertexCount = 0; - this->AppendVBO(points,numPts,normals,tcoords,colors,colorComponents); + this->AppendVBO(points, numPts, normals, tcoords, colors, colorComponents); this->Upload(this->PackedVBO, vtkOpenGLBufferObject::ArrayBuffer); this->PackedVBO.resize(0); return; diff --git a/Rendering/OpenGL2/vtkOpenGLVertexBufferObject.h b/Rendering/OpenGL2/vtkOpenGLVertexBufferObject.h index 7558eae4d97..f1f1d8c45fc 100644 --- a/Rendering/OpenGL2/vtkOpenGLVertexBufferObject.h +++ b/Rendering/OpenGL2/vtkOpenGLVertexBufferObject.h @@ -55,6 +55,70 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLVertexBufferObject : vtkDataArray *tcoords, unsigned char *colors, int colorComponents); + /**\brief Methods for VBO coordinate shift+scale-computation. + * + * By default, shift and scale vectors are enabled + * whenever CreateVBO is called with points whose + * bounds are many bbox-lengths away from the origin. + * + * Shifting and scaling may be completely disabled, + * or manually specified, or left at the default. + * + * Manual specification is for the case when you + * will be calling AppendVBO instead of just CreateVBO + * and know better bounds than the what CreateVBO + * might produce. + * + * The automatic method tells CreatVBO to compute shift and + * scale vectors that remap the points to the unit cube. + */ + enum ShiftScaleMethod { + DISABLE_SHIFT_SCALE, //!< Do not shift/scale point coordinates. Ever! + AUTO_SHIFT_SCALE, //!< The default, automatic computation. + MANUAL_SHIFT_SCALE //!< Manual shift/scale provided (for use with AppendVBO) + }; + + // Description: + // Get the shift and scale vectors computed by CreateVBO; + // or set the values CreateVBO and AppendVBO will use. + // Note that the "Set" methods **must** be called before the + // first time that CreateVBO or AppendVBO is invoked and + // should never be called afterwards. + // + // The CoordShiftAndScaleMethod describes how the shift + // and scale vectors are obtained (or that they should never + // be used). + // The GetCoordShiftAndScaleEnabled() method returns true if + // a shift and scale are currently being applied (or false if not). + // + // The "Get" methods are used by the mapper to modify the world + // and camera transformation matrices to match the scaling applied + // to coordinates in the VBO. + // CreateVBO only applies a shift and scale when the midpoint + // of the point bounding-box is distant from the origin by a + // factor of 10,000 or more relative to the size of the box + // along any axis. + // + // For example, if the x coordinates of the points range from + // 200,000 to 200,001 then the factor is + // 200,000.5 / (200,001 - 200,000) = 2x10^5, which is larger + // than 10,000 -- so the coordinates will be shifted and scaled. + // + // This is important as many OpenGL drivers use reduced precision + // to hold point coordinates. + // + // These methods are used by the mapper to determine the + // additional transform (if any) to apply to the rendering transform. + vtkGetMacro(CoordShiftAndScaleEnabled,bool); + vtkGetMacro(CoordShiftAndScaleMethod,ShiftScaleMethod); + vtkGetVector3Macro(CoordShift,double); + vtkGetVector3Macro(CoordScale,double); + virtual void SetCoordShiftAndScaleMethod(ShiftScaleMethod meth); + virtual void SetCoordShift(double x, double y, double z); + virtual void SetCoordShift(const double s[3]); + virtual void SetCoordScale(double sx, double sy, double sz); + virtual void SetCoordScale(const double s[3]); + // Sizes/offsets are all in bytes as OpenGL API expects them. size_t VertexCount; // Number of vertices in the VBO int Stride; // The size of a complete vertex + attributes @@ -70,6 +134,11 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOpenGLVertexBufferObject : vtkOpenGLVertexBufferObject(); ~vtkOpenGLVertexBufferObject(); + double CoordShift[3]; + double CoordScale[3]; + ShiftScaleMethod CoordShiftAndScaleMethod; + bool CoordShiftAndScaleEnabled; + private: vtkOpenGLVertexBufferObject(const vtkOpenGLVertexBufferObject&); // Not implemented void operator=(const vtkOpenGLVertexBufferObject&); // Not implemented diff --git a/Rendering/OpenGL2/vtkOverlayPass.h b/Rendering/OpenGL2/vtkOverlayPass.h index def6cb8d74a..57a1919fd45 100644 --- a/Rendering/OpenGL2/vtkOverlayPass.h +++ b/Rendering/OpenGL2/vtkOverlayPass.h @@ -38,12 +38,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkOverlayPass : public vtkDefaultPass vtkTypeMacro(vtkOverlayPass,vtkDefaultPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL2/vtkPointFillPass.cxx b/Rendering/OpenGL2/vtkPointFillPass.cxx index 2a990194144..f155133b58d 100644 --- a/Rendering/OpenGL2/vtkPointFillPass.cxx +++ b/Rendering/OpenGL2/vtkPointFillPass.cxx @@ -242,7 +242,7 @@ void vtkPointFillPass::Render(const vtkRenderState *s) } glDisable(GL_BLEND); - glDisable(GL_DEPTH_TEST); +// glDisable(GL_DEPTH_TEST); this->Pass1->Activate(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); diff --git a/Rendering/OpenGL2/vtkPointFillPass.h b/Rendering/OpenGL2/vtkPointFillPass.h index b04d940d595..234561c9f69 100644 --- a/Rendering/OpenGL2/vtkPointFillPass.h +++ b/Rendering/OpenGL2/vtkPointFillPass.h @@ -41,12 +41,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkPointFillPass : public vtkDepthImageProcessi vtkTypeMacro(vtkPointFillPass,vtkDepthImageProcessingPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL2/vtkRenderPass.cxx b/Rendering/OpenGL2/vtkRenderPass.cxx deleted file mode 100644 index 68c82879487..00000000000 --- a/Rendering/OpenGL2/vtkRenderPass.cxx +++ /dev/null @@ -1,107 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkRenderPass.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#include "vtkRenderPass.h" -#include -#include "vtkOpenGLRenderer.h" - -// ---------------------------------------------------------------------------- -// Description: -// Default constructor. Do nothing. -vtkRenderPass::vtkRenderPass() -{ - this->NumberOfRenderedProps = 0; -} - -// ---------------------------------------------------------------------------- -// Description: -// Destructor. Do nothing. -vtkRenderPass::~vtkRenderPass() -{ -} - -// ---------------------------------------------------------------------------- -// Description: -// Release graphics resources and ask components to release their own -// resources. Default implementation is empty. -// \pre w_exists: w!=0 -void vtkRenderPass::ReleaseGraphicsResources(vtkWindow *w) -{ - assert("pre: w_exists" && w != 0); - // empty implementation; - static_cast(w); // avoid warning in release mode. -} - -// ---------------------------------------------------------------------------- -// Description: -// Call UpdateCamera() on Renderer. This ugly mechanism gives access to -// a protected method of Renderer to subclasses of vtkRenderPass. -// \pre renderer_exists: renderer!=0 -void vtkRenderPass::UpdateCamera(vtkRenderer *renderer) -{ - assert("pre: renderer_exists" && renderer != 0); - renderer->UpdateCamera(); -} - -// ---------------------------------------------------------------------------- -// Description: -// Call ClearLights() on Renderer. See note about UpdateCamera(). -// \pre renderer_exists: renderer!=0 -void vtkRenderPass::ClearLights(vtkRenderer *vtkNotUsed(renderer)) -{ - // assert("pre: renderer_exists" && renderer != 0); - /// FIXME: What to do if there is no clear lights? Remove this API? - //vtkOpenGLRenderer *oRenderer = vtkOpenGLRenderer::SafeDownCast(renderer); - //oRenderer->ClearLights(); -} - -// ---------------------------------------------------------------------------- -// Description: -// Call UpdateLightGeometry() on Renderer. See note about UpdateCamera(). -// \pre renderer_exists: renderer!=0 -void vtkRenderPass::UpdateLightGeometry(vtkRenderer *renderer) -{ - assert("pre: renderer_exists" && renderer != 0); - renderer->UpdateLightGeometry(); -} - -// ---------------------------------------------------------------------------- -// Description: -// Call UpdateLights() on Renderer. See note about UpdateCamera(). -// \pre renderer_exists: renderer!=0 -void vtkRenderPass::UpdateLights(vtkRenderer *renderer) -{ - assert("pre: renderer_exists" && renderer != 0); - renderer->UpdateLights(); -} - -// ---------------------------------------------------------------------------- -// Description: -// Call UpdateGeometry() on Renderer. See note about UpdateCamera(). -// \pre renderer_exists: renderer!=0 -void vtkRenderPass::UpdateGeometry(vtkRenderer *renderer) -{ - assert("pre: renderer_exists" && renderer != 0); - renderer->UpdateGeometry(); -} - -// ---------------------------------------------------------------------------- -void vtkRenderPass::PrintSelf(ostream& os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os ,indent); - - os << indent << "NumberOfRenderedProps:" << this->NumberOfRenderedProps - << endl; -} diff --git a/Rendering/OpenGL2/vtkRenderPass.h b/Rendering/OpenGL2/vtkRenderPass.h deleted file mode 100644 index c0a7f32baa0..00000000000 --- a/Rendering/OpenGL2/vtkRenderPass.h +++ /dev/null @@ -1,116 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkRenderPass.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -// .NAME vtkRenderPass - Perform part of the rendering of a vtkRenderer. -// .SECTION Description -// vtkRenderPass is a deferred class with a simple deferred method Render. -// This method performs a rendering pass of the scene described in -// vtkRenderState. -// Subclasses define what really happens during rendering. -// -// Directions to write a subclass of vtkRenderPass: -// It is up to the subclass to decide if it needs to delegate part of its job -// to some other vtkRenderPass objects ("delegates"). -// - The subclass has to define ivar to set/get its delegates. -// - The documentation of the subclass has to describe: -// - what each delegate is supposed to perform -// - if a delegate is supposed to be used once or multiple times -// - what it expects to have in the framebuffer before starting (status -// of colorbuffers, depth buffer, stencil buffer) -// - what it will change in the framebuffer. -// - A pass cannot modify the vtkRenderState where it will perform but -// it can build a new vtkRenderState (it can change the FrameBuffer, change the -// prop array, changed the required prop properties keys (usually adding some -// to a copy of the existing list) but it has to keep the same vtkRenderer -// object), make it current and pass it to its delegate. -// - at the end of the execution of Render, the pass has to ensure the -// current vtkRenderState is the one it has in argument. -// .SECTION See Also -// vtkRenderState vtkRenderer - -#ifndef vtkRenderPass_h -#define vtkRenderPass_h - -#include "vtkRenderingOpenGL2Module.h" // For export macro -#include "vtkObject.h" - -class vtkRenderState; -class vtkWindow; -class vtkRenderer; - -class VTKRENDERINGOPENGL2_EXPORT vtkRenderPass : public vtkObject -{ - public: - vtkTypeMacro(vtkRenderPass,vtkObject); - void PrintSelf(ostream& os, vtkIndent indent); - - // Description: - // Perform rendering according to a render state \p s. - // It modifies NumberOfRenderedProps. - // \pre s_exists: s!=0 - virtual void Render(const vtkRenderState *s)=0; - - // Description: - // Number of props rendered at the last Render call. - vtkGetMacro(NumberOfRenderedProps,int); - - // Description: - // Release graphics resources and ask components to release their own - // resources. Default implementation is empty. - // \pre w_exists: w!=0 - virtual void ReleaseGraphicsResources(vtkWindow *w); - - protected: - // Description: - // Default constructor. Do nothing. - vtkRenderPass(); - - // Description: - // Destructor. Do nothing. - virtual ~vtkRenderPass(); - - // Description: - // Call UpdateCamera() on Renderer. This ugly mechanism gives access to - // a protected method of Renderer to subclasses of vtkRenderPass. - // \pre renderer_exists: renderer!=0 - void UpdateCamera(vtkRenderer *renderer); - - // Description: - // Call ClearLights() on Renderer. See note about UpdateCamera(). - // \pre renderer_exists: renderer!=0 - void ClearLights(vtkRenderer *renderer); - - // Description: - // Call UpdateLightGeometry() on Renderer. See note about UpdateCamera(). - // \pre renderer_exists: renderer!=0 - void UpdateLightGeometry(vtkRenderer *renderer); - - // Description: - // Call UpdateLights() on Renderer. See note about UpdateCamera(). - // \pre renderer_exists: renderer!=0 - void UpdateLights(vtkRenderer *renderer); - - // Description: - // Call UpdateGeometry() on Renderer. See note about UpdateCamera(). - // \pre renderer_exists: renderer!=0 - void UpdateGeometry(vtkRenderer *renderer); - - int NumberOfRenderedProps; - - private: - vtkRenderPass(const vtkRenderPass&); // Not implemented. - void operator=(const vtkRenderPass&); // Not implemented. -}; - -#endif diff --git a/Rendering/OpenGL2/vtkRenderPassCollection.h b/Rendering/OpenGL2/vtkRenderPassCollection.h index 35a7178c147..11227b38c42 100644 --- a/Rendering/OpenGL2/vtkRenderPassCollection.h +++ b/Rendering/OpenGL2/vtkRenderPassCollection.h @@ -48,12 +48,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkRenderPassCollection : public vtkCollection // Get the last RenderPass in the list. vtkRenderPass *GetLastRenderPass(); - //BTX // Description: // Reentrant safe way to get an object in a collection. Just pass the // same cookie back and forth. vtkRenderPass *GetNextRenderPass(vtkCollectionSimpleIterator &cookie); - //ETX protected: vtkRenderPassCollection(); diff --git a/Rendering/OpenGL2/vtkRenderState.h b/Rendering/OpenGL2/vtkRenderState.h deleted file mode 100644 index 16823148ad6..00000000000 --- a/Rendering/OpenGL2/vtkRenderState.h +++ /dev/null @@ -1,144 +0,0 @@ -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkRenderState.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -// .NAME vtkRenderState - Context in which a vtkRenderPass will render. -// .SECTION Description -// vtkRenderState is a ligthweight effective class which gather information -// used by a vtkRenderPass to perform its execution. -// .SECTION Implementation Notes -// Get methods are const to enforce that a renderpass cannot modify the -// RenderPass object. It works in conjunction with vtkRenderPass::Render where -// the argument vtkRenderState is const. -// .SECTION See Also -// vtkRenderPass vtkRenderer vtkFrameBufferObject vtkProp - -#ifndef vtkRenderState_h -#define vtkRenderState_h - -#include "vtkRenderingOpenGL2Module.h" // For export macro -#include "vtkObject.h" - -class vtkRenderer; -class vtkProp; -class vtkFrameBufferObject; -class vtkInformation; - -class VTKRENDERINGOPENGL2_EXPORT vtkRenderState -{ - public: - // Description: - // Constructor. All values are initialized to 0 or NULL. - // \pre renderer_exists: renderer!=0 - // \post renderer_is_set: GetRenderer()==renderer. - // \post valid_state: IsValid() - vtkRenderState(vtkRenderer *renderer); - - // Description: - // Destructor. As a vtkRenderState does not own any of its variables, - // the destructor does nothing. - ~vtkRenderState(); - - // Description: - // Tells if the RenderState is a valid one (Renderer is not null). - bool IsValid() const; - - // Description: - // Return the Renderer. This is the renderer in which the render pass is - // performed. It gives access to the RenderWindow, to the props. - // \post result_exists: result!=0 - vtkRenderer *GetRenderer() const; - - // Description: - // Return the FrameBuffer. This is the framebuffer in use. NULL means it is - // the FrameBuffer provided by the RenderWindow (it can actually be an FBO - // in case the RenderWindow is in off screen mode). - vtkFrameBufferObject *GetFrameBuffer() const; - - // Description: - // Set the FrameBuffer. See GetFrameBuffer(). - // \post is_set: GetFrameBuffer()==fbo - void SetFrameBuffer(vtkFrameBufferObject *fbo); - - // Description: - // Get the window size of the state. - void GetWindowSize(int size[2]) const; - - // Description: - // Return the array of filtered props. See SetPropArrayAndCount(). - vtkProp **GetPropArray() const; - - // Description: - // Return the size of the array of filtered props. - // See SetPropArrayAndCount(). - // \post positive_result: result>=0 - int GetPropArrayCount() const; - - // Description: - // Set the array of of filtered props and its size. - // It is a subset of props to render. A renderpass might ignore this - // filtered list and access to all the props of the vtkRenderer object - // directly. For example, a render pass may filter props that are visible and - // not culled by the frustum, but a sub render pass building a shadow map may - // need all the visible props. - // \pre positive_size: propArrayCount>=0 - // \pre valid_null_array: propArray!=0 || propArrayCount==0 - // \post is_set: GetPropArray()==propArray && GetPropArrayCount()==propArrayCount - void SetPropArrayAndCount(vtkProp **propArray, - int propArrayCount); - - // Description: - // Return the required property keys for the props. It tells that the - // current render pass it supposed to render only props that have all the - // RequiredKeys in their property keys. - vtkInformation *GetRequiredKeys() const; - - // Description: - // Set the required property keys for the props. See GetRequiredKeys(). - // \post is_set: GetRequiredKeys()==keys - void SetRequiredKeys(vtkInformation *keys); - - protected: - // Description: - // The renderer in which the render pass is performed. - // It gives access to the RenderWindow, to the props. - vtkRenderer *Renderer; - - // Description: - // The framebuffer in use. NULL means the FrameBuffer provided by - // the RenderWindow (it can actually be an FBO in case the RenderWindow - // is in off screen mode). - vtkFrameBufferObject *FrameBuffer; - - // Description: - // Subset of props to render. A renderpass might ignore this filtered list - // and access to all the props of the vtkRenderer object directly. - // For example, a render pass may filter props that are visible and - // not culled by the frustum, but a sub render pass building a shadow map may - // need all the visible props. - vtkProp **PropArray; - int PropArrayCount; - - // Description: - // It tells that the current render pass it supposed to render only props - // that have all the RequiredKeys in their property keys. - vtkInformation *RequiredKeys; - -private: - vtkRenderState(); // no default constructor. - vtkRenderState(const vtkRenderState &); // Not implemented. - void operator=(const vtkRenderState &); // Not implemented. -}; - -#endif -// VTK-HeaderTest-Exclude: vtkRenderState.h diff --git a/Rendering/OpenGL2/vtkRenderStepsPass.h b/Rendering/OpenGL2/vtkRenderStepsPass.h index 6f09eaea8ce..118a48f17e9 100644 --- a/Rendering/OpenGL2/vtkRenderStepsPass.h +++ b/Rendering/OpenGL2/vtkRenderStepsPass.h @@ -43,12 +43,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkRenderStepsPass : public vtkRenderPass vtkTypeMacro(vtkRenderStepsPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL2/vtkRenderbuffer.cxx b/Rendering/OpenGL2/vtkRenderbuffer.cxx index 50649fe7699..f98082582e8 100644 --- a/Rendering/OpenGL2/vtkRenderbuffer.cxx +++ b/Rendering/OpenGL2/vtkRenderbuffer.cxx @@ -47,6 +47,10 @@ bool vtkRenderbuffer::IsSupported(vtkRenderWindow *win) if (glwin) { #if GL_ES_VERSION_2_0 != 1 + if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32()) + { + return true; + } bool floatTex = (glewIsSupported("GL_ARB_texture_float") != 0); bool floatDepth = (glewIsSupported("GL_ARB_depth_buffer_float") != 0); #else diff --git a/Rendering/OpenGL2/vtkSSAAPass.h b/Rendering/OpenGL2/vtkSSAAPass.h index 554a4b3e653..04c9382b2b3 100644 --- a/Rendering/OpenGL2/vtkSSAAPass.h +++ b/Rendering/OpenGL2/vtkSSAAPass.h @@ -48,12 +48,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkSSAAPass : public vtkRenderPass vtkTypeMacro(vtkSSAAPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL2/vtkSequencePass.h b/Rendering/OpenGL2/vtkSequencePass.h index 8705504d4a6..3046e69d010 100644 --- a/Rendering/OpenGL2/vtkSequencePass.h +++ b/Rendering/OpenGL2/vtkSequencePass.h @@ -39,12 +39,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkSequencePass : public vtkRenderPass vtkTypeMacro(vtkSequencePass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL2/vtkShaderProgram.cxx b/Rendering/OpenGL2/vtkShaderProgram.cxx index 9a3c7605d89..9eb34937e00 100644 --- a/Rendering/OpenGL2/vtkShaderProgram.cxx +++ b/Rendering/OpenGL2/vtkShaderProgram.cxx @@ -117,14 +117,14 @@ bool vtkShaderProgram::Substitute(std::string &source, const std::string &search { std::string::size_type pos = 0; bool replaced = false; - while ((pos = source.find(search, 0)) != std::string::npos) + while ((pos = source.find(search, pos)) != std::string::npos) { source.replace(pos, search.length(), replace); if (!all) { return true; } - pos += search.length(); + pos += replace.length(); replaced = true; } return replaced; @@ -295,7 +295,7 @@ bool vtkShaderProgram::Link() } // clear out the list of uniforms used - this->UniformsUsed.clear(); + this->UniformLocs.clear(); #if GL_ES_VERSION_2_0 != 1 // bind the outputs if specified @@ -330,7 +330,7 @@ bool vtkShaderProgram::Link() return false; } this->Linked = true; - this->Attributes.clear(); + this->AttributeLocs.clear(); return true; } @@ -769,54 +769,84 @@ bool vtkShaderProgram::SetAttributeArrayInternal( return true; } -inline int vtkShaderProgram::FindAttributeArray(const char *name) +inline int vtkShaderProgram::FindAttributeArray(const char *cname) { - if (name == NULL || !this->Linked) + if (cname == NULL || !this->Linked) { return -1; } - GLint location = - static_cast(glGetAttribLocation(static_cast(Handle), - (const GLchar *)name)); - if (location == -1) + + std::string name(cname); + GLint loc = -1; + + typedef std::map::iterator IterT; + IterT iter = this->AttributeLocs.find(name); + if (iter == this->AttributeLocs.end()) + { + loc = glGetAttribLocation(static_cast(Handle), + static_cast(cname)); + this->AttributeLocs.insert(std::make_pair(name, static_cast(loc))); + } + else + { + loc = iter->second; + } + + if (loc == -1) { this->Error = "Specified attribute not found in current shader program: "; this->Error += name; } - return location; + return loc; } -inline int vtkShaderProgram::FindUniform(const char *name) +inline int vtkShaderProgram::FindUniform(const char *cname) { - if (name == NULL || !this->Linked) + if (cname == NULL || !this->Linked) { return -1; } - GLint location = - static_cast(glGetUniformLocation(static_cast(Handle), - (const GLchar *)name)); - if (location == -1) + + std::string name(cname); + GLint loc = -1; + + typedef std::map::iterator IterT; + IterT iter = this->UniformLocs.find(name); + if (iter == this->UniformLocs.end()) + { + loc = static_cast(glGetUniformLocation(static_cast(Handle), + (const GLchar *)cname)); + this->UniformLocs.insert(std::make_pair(cname, static_cast(loc))); + } + else + { + loc = iter->second; + } + + if (loc == -1) { - this->Error = "Uniform " + std::string(name) + " not found in current shader program."; + this->Error = "Uniform " + name + " not found in current shader program."; } - return location; + return loc; } -bool vtkShaderProgram::IsUniformUsed(const char *name) +bool vtkShaderProgram::IsUniformUsed(const char *cname) { - if (name == NULL) + if (cname == NULL) { return false; } - // see if we have cached the result - typedef std::map::iterator iter; - iter found = this->UniformsUsed.find(name); + std::string name(cname); + + // see if we have cached the result + typedef std::map::iterator iter; + iter found = this->UniformLocs.find(name); // if not, go query openGL - if (found == this->UniformsUsed.end()) + if (found == this->UniformLocs.end()) { if (!this->Linked) { @@ -825,14 +855,41 @@ bool vtkShaderProgram::IsUniformUsed(const char *name) } GLint location = static_cast(glGetUniformLocation(static_cast(Handle), - (const GLchar *)name)); - this->UniformsUsed[name] = (location == -1 ? false : true); - return (location == -1 ? false : true); + (const GLchar *)cname)); + std::pair res = this->UniformLocs.insert( + std::make_pair(name, static_cast(location))); + found = res.first; } - return found->second; + return found->second != -1; } +// ---------------------------------------------------------------------------- +bool vtkShaderProgram::IsAttributeUsed(const char *cname) +{ + if (cname == NULL || !this->Linked) + { + return -1; + } + + std::string name(cname); + GLint loc = -1; + + typedef std::map::iterator IterT; + IterT iter = this->AttributeLocs.find(name); + if (iter == this->AttributeLocs.end()) + { + loc = glGetAttribLocation(static_cast(Handle), + static_cast(cname)); + this->AttributeLocs.insert(std::make_pair(name, static_cast(loc))); + } + else + { + loc = iter->second; + } + + return loc != -1; +} // ---------------------------------------------------------------------------- void vtkShaderProgram::PrintSelf(ostream& os, vtkIndent indent) diff --git a/Rendering/OpenGL2/vtkShaderProgram.h b/Rendering/OpenGL2/vtkShaderProgram.h index 806acc0a7ae..31d1cfd7378 100644 --- a/Rendering/OpenGL2/vtkShaderProgram.h +++ b/Rendering/OpenGL2/vtkShaderProgram.h @@ -186,7 +186,6 @@ class VTKRENDERINGOPENGL2_EXPORT vtkShaderProgram : public vtkObject // only valid for OpenGL 3.2 or later vtkSetMacro(NumberOfOutputs,unsigned int); -//BTX // Description: // perform in place string substitutions, indicate if a substitution was done // this is useful for building up shader strings which typically involve @@ -203,6 +202,11 @@ class VTKRENDERINGOPENGL2_EXPORT vtkShaderProgram : public vtkObject // or attributes are expensive to compute bool IsUniformUsed(const char *); + // Description: + // Return true if the compiled and linked shader has an attribute matching @a + // name. + bool IsAttributeUsed(const char *name); + protected: vtkShaderProgram(); ~vtkShaderProgram(); @@ -280,10 +284,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkShaderProgram : public vtkObject std::string Error; - std::map Attributes; + std::map AttributeLocs; - std::map UniformsUsed; + std::map UniformLocs; friend class VertexArrayObject; @@ -293,7 +297,7 @@ class VTKRENDERINGOPENGL2_EXPORT vtkShaderProgram : public vtkObject vtkShaderProgram(const vtkShaderProgram&); // Not implemented. void operator=(const vtkShaderProgram&); // Not implemented. -//ETX + }; diff --git a/Rendering/OpenGL2/vtkShadowMapBakerPass.h b/Rendering/OpenGL2/vtkShadowMapBakerPass.h index 10b2f7d55e9..53e23be6ec9 100644 --- a/Rendering/OpenGL2/vtkShadowMapBakerPass.h +++ b/Rendering/OpenGL2/vtkShadowMapBakerPass.h @@ -57,12 +57,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkShadowMapBakerPass : public vtkRenderPass vtkTypeMacro(vtkShadowMapBakerPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own @@ -111,7 +109,6 @@ class VTKRENDERINGOPENGL2_EXPORT vtkShadowMapBakerPass : public vtkRenderPass // \pre l_exists: l!=0 bool LightCreatesShadow(vtkLight *l); -//BTX // Description: // INTERNAL USE ONLY // Internally used by vtkShadowMapBakerPass and vtkShadowMapPass. @@ -125,7 +122,6 @@ class VTKRENDERINGOPENGL2_EXPORT vtkShadowMapBakerPass : public vtkRenderPass // // Give access the cameras builds from the ligths. std::vector > *GetLightCameras(); -//ETX // Description: // INTERNAL USE ONLY. @@ -176,7 +172,6 @@ class VTKRENDERINGOPENGL2_EXPORT vtkShadowMapBakerPass : public vtkRenderPass double &mNear, double &mFar); - //BTX // Description: // Build a camera from spot light parameters. // \pre light_exists: light!=0 @@ -184,7 +179,6 @@ class VTKRENDERINGOPENGL2_EXPORT vtkShadowMapBakerPass : public vtkRenderPass void BuildCameraLight(vtkLight *light, double *boundingBox, vtkCamera *lcamera); - //ETX // Description: // Check if shadow mapping is supported by the current OpenGL context. diff --git a/Rendering/OpenGL2/vtkShadowMapPass.h b/Rendering/OpenGL2/vtkShadowMapPass.h index 6fa73fbf232..aef70c98fa5 100644 --- a/Rendering/OpenGL2/vtkShadowMapPass.h +++ b/Rendering/OpenGL2/vtkShadowMapPass.h @@ -61,12 +61,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkShadowMapPass : public vtkRenderPass vtkTypeMacro(vtkShadowMapPass,vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL2/vtkSobelGradientMagnitudePass.h b/Rendering/OpenGL2/vtkSobelGradientMagnitudePass.h index f6485527294..207c24692ec 100644 --- a/Rendering/OpenGL2/vtkSobelGradientMagnitudePass.h +++ b/Rendering/OpenGL2/vtkSobelGradientMagnitudePass.h @@ -73,12 +73,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkSobelGradientMagnitudePass : public vtkImage vtkTypeMacro(vtkSobelGradientMagnitudePass,vtkImageProcessingPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own diff --git a/Rendering/OpenGL2/vtkTranslucentPass.h b/Rendering/OpenGL2/vtkTranslucentPass.h index 0ce255a9061..b2c166ea6ba 100644 --- a/Rendering/OpenGL2/vtkTranslucentPass.h +++ b/Rendering/OpenGL2/vtkTranslucentPass.h @@ -38,12 +38,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkTranslucentPass : public vtkDefaultPass vtkTypeMacro(vtkTranslucentPass,vtkDefaultPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL2/vtkVolumetricPass.h b/Rendering/OpenGL2/vtkVolumetricPass.h index 32632bf41c7..1244c702092 100644 --- a/Rendering/OpenGL2/vtkVolumetricPass.h +++ b/Rendering/OpenGL2/vtkVolumetricPass.h @@ -38,12 +38,10 @@ class VTKRENDERINGOPENGL2_EXPORT vtkVolumetricPass : public vtkDefaultPass vtkTypeMacro(vtkVolumetricPass,vtkDefaultPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX protected: // Description: diff --git a/Rendering/OpenGL2/vtkWin32OpenGLRenderWindow.cxx b/Rendering/OpenGL2/vtkWin32OpenGLRenderWindow.cxx index f4e03a7eea1..dc17b8a7d3b 100644 --- a/Rendering/OpenGL2/vtkWin32OpenGLRenderWindow.cxx +++ b/Rendering/OpenGL2/vtkWin32OpenGLRenderWindow.cxx @@ -628,7 +628,7 @@ void vtkWin32OpenGLRenderWindow::SetupPixelFormatPaletteAndContext( { // we believe that these later versions are all compatible with // OpenGL 3.2 so get a more recent context if we can. - int attemptedVersions[] = {4,5, 4,4, 4,3, 4,2, 4,1, 4,0, 3,3, 3,2, 3,1, 3,0}; + int attemptedVersions[] = {4,5, 4,4, 4,3, 4,2, 4,1, 4,0, 3,3, 3,2, 3,1}; int iContextAttribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, @@ -639,12 +639,36 @@ void vtkWin32OpenGLRenderWindow::SetupPixelFormatPaletteAndContext( // WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 // End of attributes list }; - for (int i = 0; i < 8 && !this->ContextId; i++) + for (int i = 0; i < 9 && !this->ContextId; i++) { iContextAttribs[1] = attemptedVersions[i*2]; iContextAttribs[3] = attemptedVersions[i*2+1]; this->ContextId = wglCreateContextAttribsARB(hDC, 0, iContextAttribs); } + if (this->ContextId) + { + // if it is a 3.1 context check for systems that we allow + if (iContextAttribs[1] == 3 && iContextAttribs[3] == 1) + { + std::string vendor = (const char *)glGetString(GL_VENDOR); + std::string renderer = (const char *)glGetString(GL_RENDERER); + std::string version = (const char *)glGetString(GL_VERSION); + if (vendor.find("Intel") != std::string::npos && + (renderer.find("HD Graphics 3000") != std::string::npos || + renderer.find("HD Graphics 2000") != std::string::npos)) + { + vtkErrorMacro("We have determined that your graphics system is" + " an Intel SandyBridge based system. These systems only partially " + " support VTK. If you encounter any issues please make sure" + " your graphics drivers from Intel are up to date."); + } + else + { + wglDeleteContext(this->ContextId); + this->ContextId = NULL; + } + } + } if (this->ContextId && (iContextAttribs[1] >= 4 || iContextAttribs[3] >= 2)) { diff --git a/Rendering/OpenGL2/vtkXOpenGLRenderWindow.cxx b/Rendering/OpenGL2/vtkXOpenGLRenderWindow.cxx index 52e2b07dbfa..fb741a3d40a 100644 --- a/Rendering/OpenGL2/vtkXOpenGLRenderWindow.cxx +++ b/Rendering/OpenGL2/vtkXOpenGLRenderWindow.cxx @@ -1150,7 +1150,25 @@ void vtkXOpenGLRenderWindow::SetSize(int width,int height) XResizeWindow(this->DisplayId,this->WindowId, static_cast(width), static_cast(height)); - XSync(this->DisplayId,False); + // this is an async call so we wait until we + // know it has been resized. To avoid infinite + // loops we put in a count limit just to be safe + XWindowAttributes attribs; + int count = 20000; + do + { + XSync(this->DisplayId,False); + + // Find the current window size + XGetWindowAttributes(this->DisplayId, + this->WindowId, &attribs); + count--; + } + while (count && (attribs.width != width || attribs.height != height)); + if (!count) + { + vtkWarningMacro("warning window did not resize in the allotted time"); + } } this->Modified(); diff --git a/Rendering/Parallel/vtkClientServerCompositePass.h b/Rendering/Parallel/vtkClientServerCompositePass.h index 3b831ba4aca..af0b81a6d02 100644 --- a/Rendering/Parallel/vtkClientServerCompositePass.h +++ b/Rendering/Parallel/vtkClientServerCompositePass.h @@ -33,12 +33,10 @@ class VTKRENDERINGPARALLEL_EXPORT vtkClientServerCompositePass : public vtkRende vtkTypeMacro(vtkClientServerCompositePass, vtkRenderPass); void PrintSelf(ostream& os, vtkIndent indent); - //BTX // Description: // Perform rendering according to a render state \p s. // \pre s_exists: s!=0 virtual void Render(const vtkRenderState *s); - //ETX // Description: // Release graphics resources and ask components to release their own @@ -88,7 +86,6 @@ class VTKRENDERINGPARALLEL_EXPORT vtkClientServerCompositePass : public vtkRende vtkBooleanMacro(ServerSideRendering, bool); vtkGetMacro(ServerSideRendering, bool); -//BTX protected: vtkClientServerCompositePass(); ~vtkClientServerCompositePass(); @@ -102,7 +99,7 @@ class VTKRENDERINGPARALLEL_EXPORT vtkClientServerCompositePass : public vtkRende private: vtkClientServerCompositePass(const vtkClientServerCompositePass&); // Not implemented. void operator=(const vtkClientServerCompositePass&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/Parallel/vtkClientServerSynchronizedRenderers.h b/Rendering/Parallel/vtkClientServerSynchronizedRenderers.h index 27709452d98..2d1818d55fa 100644 --- a/Rendering/Parallel/vtkClientServerSynchronizedRenderers.h +++ b/Rendering/Parallel/vtkClientServerSynchronizedRenderers.h @@ -31,7 +31,6 @@ class VTKRENDERINGPARALLEL_EXPORT vtkClientServerSynchronizedRenderers : vtkTypeMacro(vtkClientServerSynchronizedRenderers, vtkSynchronizedRenderers); void PrintSelf(ostream& os, vtkIndent indent); -//BTX protected: vtkClientServerSynchronizedRenderers(); ~vtkClientServerSynchronizedRenderers(); @@ -42,7 +41,7 @@ class VTKRENDERINGPARALLEL_EXPORT vtkClientServerSynchronizedRenderers : private: vtkClientServerSynchronizedRenderers(const vtkClientServerSynchronizedRenderers&); // Not implemented. void operator=(const vtkClientServerSynchronizedRenderers&); // Not implemented. -//ETX + }; #endif diff --git a/Rendering/Parallel/vtkCompositeRGBAPass.cxx b/Rendering/Parallel/vtkCompositeRGBAPass.cxx index 062e55fb19b..da31bb512d0 100644 --- a/Rendering/Parallel/vtkCompositeRGBAPass.cxx +++ b/Rendering/Parallel/vtkCompositeRGBAPass.cxx @@ -191,7 +191,7 @@ void vtkCompositeRGBAPass::Render(const vtkRenderState *s) int w=0; int h=0; - vtkFrameBufferObject *fbo=s->GetFrameBuffer(); + vtkFrameBufferObject *fbo=(vtkFrameBufferObject*)s->GetFrameBuffer(); if(fbo==0) { r->GetTiledSize(&w,&h); diff --git a/Rendering/Parallel/vtkCompositeZPass.cxx b/Rendering/Parallel/vtkCompositeZPass.cxx index ecbfe2e9b95..070c382b119 100644 --- a/Rendering/Parallel/vtkCompositeZPass.cxx +++ b/Rendering/Parallel/vtkCompositeZPass.cxx @@ -200,7 +200,7 @@ void vtkCompositeZPass::Render(const vtkRenderState *s) int w=0; int h=0; - vtkFrameBufferObject *fbo=s->GetFrameBuffer(); + vtkFrameBufferObject *fbo=(vtkFrameBufferObject*)s->GetFrameBuffer(); if(fbo==0) { r->GetTiledSize(&w,&h); diff --git a/Rendering/Parallel/vtkCompositedSynchronizedRenderers.h b/Rendering/Parallel/vtkCompositedSynchronizedRenderers.h index 76c989f6342..df0ee81c15d 100644 --- a/Rendering/Parallel/vtkCompositedSynchronizedRenderers.h +++ b/Rendering/Parallel/vtkCompositedSynchronizedRenderers.h @@ -38,7 +38,6 @@ class VTKRENDERINGPARALLEL_EXPORT vtkCompositedSynchronizedRenderers : public vt void SetCompositer(vtkCompositer*); vtkGetObjectMacro(Compositer, vtkCompositer); -//BTX protected: vtkCompositedSynchronizedRenderers(); ~vtkCompositedSynchronizedRenderers(); @@ -51,7 +50,7 @@ class VTKRENDERINGPARALLEL_EXPORT vtkCompositedSynchronizedRenderers : public vt private: vtkCompositedSynchronizedRenderers(const vtkCompositedSynchronizedRenderers&); // Not implemented void operator=(const vtkCompositedSynchronizedRenderers&); // Not implemented -//ETX + }; #endif diff --git a/Rendering/Parallel/vtkPHardwareSelector.h b/Rendering/Parallel/vtkPHardwareSelector.h index dc1d77da7e7..d32fa4e9245 100644 --- a/Rendering/Parallel/vtkPHardwareSelector.h +++ b/Rendering/Parallel/vtkPHardwareSelector.h @@ -52,7 +52,6 @@ class VTKRENDERINGPARALLEL_EXPORT vtkPHardwareSelector : public vtkOpenGLHardwar // slave to the master render. virtual bool CaptureBuffers(); -//BTX protected: vtkPHardwareSelector(); ~vtkPHardwareSelector(); @@ -69,7 +68,7 @@ class VTKRENDERINGPARALLEL_EXPORT vtkPHardwareSelector : public vtkOpenGLHardwar class vtkObserver; friend class vtkObserver; vtkObserver* Observer; -//ETX + }; #endif diff --git a/Rendering/Parallel/vtkParallelRenderManager.h b/Rendering/Parallel/vtkParallelRenderManager.h index 8122de3be72..27bb90c8ad8 100644 --- a/Rendering/Parallel/vtkParallelRenderManager.h +++ b/Rendering/Parallel/vtkParallelRenderManager.h @@ -245,9 +245,7 @@ class VTKRENDERINGPARALLEL_EXPORT vtkParallelRenderManager : public vtkObject vtkGetMacro(MagnifyImages, int); vtkBooleanMacro(MagnifyImages, int); -//BTX enum { NEAREST, LINEAR }; -//ETX // Description: // Sets the method used to magnify images. Nearest simply replicates @@ -333,7 +331,6 @@ class VTKRENDERINGPARALLEL_EXPORT vtkParallelRenderManager : public vtkObject vtkSetVector2Macro(ForcedRenderWindowSize, int); vtkGetVector2Macro(ForcedRenderWindowSize, int); -//BTX enum Tags { RENDER_RMI_TAG=34532, COMPUTE_VISIBLE_PROP_BOUNDS_RMI_TAG=54636, @@ -346,7 +343,6 @@ class VTKRENDERINGPARALLEL_EXPORT vtkParallelRenderManager : public vtkObject virtual void CheckForAbortRender() {} virtual int CheckForAbortComposite() {return 0;} -//ETX //Description: //The default is to allow the use of the back buffer for compositing. @@ -372,7 +368,6 @@ class VTKRENDERINGPARALLEL_EXPORT vtkParallelRenderManager : public vtkObject virtual void GenericStartRenderCallback(); virtual void GenericEndRenderCallback(); -//BTX protected: vtkParallelRenderManager(); ~vtkParallelRenderManager(); @@ -581,7 +576,7 @@ class VTKRENDERINGPARALLEL_EXPORT vtkParallelRenderManager : public vtkObject private: vtkParallelRenderManager(const vtkParallelRenderManager &); //Not implemented void operator=(const vtkParallelRenderManager &); //Not implemented -//ETX + }; #endif //vtkParalleRenderManager_h diff --git a/Rendering/Parallel/vtkSynchronizedRenderWindows.h b/Rendering/Parallel/vtkSynchronizedRenderWindows.h index 5c52d27674e..a26096bda66 100644 --- a/Rendering/Parallel/vtkSynchronizedRenderWindows.h +++ b/Rendering/Parallel/vtkSynchronizedRenderWindows.h @@ -89,7 +89,6 @@ class VTKRENDERINGPARALLEL_EXPORT vtkSynchronizedRenderWindows : public vtkObjec vtkSetMacro(RootProcessId, int); vtkGetMacro(RootProcessId, int); -//BTX enum { SYNC_RENDER_TAG = 15001, @@ -136,7 +135,7 @@ class VTKRENDERINGPARALLEL_EXPORT vtkSynchronizedRenderWindows : public vtkObjec class vtkObserver; vtkObserver* Observer; friend class vtkObserver; -//ETX + }; #endif diff --git a/Rendering/Parallel/vtkSynchronizedRenderers.h b/Rendering/Parallel/vtkSynchronizedRenderers.h index 815543aaa84..cd157e211a2 100644 --- a/Rendering/Parallel/vtkSynchronizedRenderers.h +++ b/Rendering/Parallel/vtkSynchronizedRenderers.h @@ -108,7 +108,6 @@ class VTKRENDERINGPARALLEL_EXPORT vtkSynchronizedRenderers : public vtkObject vtkGetMacro(AutomaticEventHandling, bool); vtkBooleanMacro(AutomaticEventHandling, bool); -//BTX enum { SYNC_RENDERER_TAG = 15101, @@ -170,7 +169,7 @@ class VTKRENDERINGPARALLEL_EXPORT vtkSynchronizedRenderers : public vtkObject void Allocate(int dx, int dy, int numcomps); }; -//ETX + protected: vtkSynchronizedRenderers(); ~vtkSynchronizedRenderers(); diff --git a/Rendering/ParallelLIC/CMakeLists.txt b/Rendering/ParallelLIC/CMakeLists.txt index 6287010d943..719f5b06701 100644 --- a/Rendering/ParallelLIC/CMakeLists.txt +++ b/Rendering/ParallelLIC/CMakeLists.txt @@ -47,9 +47,9 @@ endif() if(VTK_RENDERING_BACKEND STREQUAL "OpenGL2") list(APPEND Module_SRCS - vtkPSurfaceLICMapper.cxx + vtkPSurfaceLICInterface.cxx ) - vtk_add_override(vtkSurfaceLICMapper vtkPSurfaceLICMapper) + vtk_add_override(vtkSurfaceLICInterface vtkPSurfaceLICInterface) set(shader_files vtkPSurfaceLICComposite_CompFS.glsl ) diff --git a/Rendering/ParallelLIC/vtkMPIPixelTT.h b/Rendering/ParallelLIC/vtkMPIPixelTT.h index 84f5ee658b9..e6bfe9592f9 100644 --- a/Rendering/ParallelLIC/vtkMPIPixelTT.h +++ b/Rendering/ParallelLIC/vtkMPIPixelTT.h @@ -23,7 +23,6 @@ // to the appropriate C or MPI datatype. template class vtkMPIPixelTT; -//BTX #define vtkMPIPixelTTMacro1(_ctype) \ template<> \ class vtkMPIPixelTT<_ctype> \ @@ -48,6 +47,6 @@ vtkMPIPixelTTMacro1(double) //vtkMPIPixelTTMacro1(vtkIdType) vtkMPIPixelTTMacro1(long long) vtkMPIPixelTTMacro1(unsigned long long) -//ETX + #endif // VTK-HeaderTest-Exclude: vtkMPIPixelTT.h diff --git a/Rendering/ParallelLIC/vtkPLineIntegralConvolution2D.h b/Rendering/ParallelLIC/vtkPLineIntegralConvolution2D.h index b1ef1711de7..dee1ff68458 100644 --- a/Rendering/ParallelLIC/vtkPLineIntegralConvolution2D.h +++ b/Rendering/ParallelLIC/vtkPLineIntegralConvolution2D.h @@ -38,7 +38,6 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkPLineIntegralConvolution2D : public vtkL vtkTypeMacro(vtkPLineIntegralConvolution2D, vtkLineIntegralConvolution2D); virtual void PrintSelf(ostream &os, vtkIndent indent); - //BTX // Description: // Set the communicator to use during parallel operation // The communicator will not be duplicated or reference @@ -55,7 +54,6 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkPLineIntegralConvolution2D : public vtkL vtkPainterCommunicator *comm, float &min, float &max); - //ETX // Description: // Methods used for parallel benchmarks. Use cmake to define diff --git a/Rendering/ParallelLIC/vtkPSurfaceLICComposite.cxx b/Rendering/ParallelLIC/vtkPSurfaceLICComposite.cxx index 24c4904b28a..02c416e4cad 100644 --- a/Rendering/ParallelLIC/vtkPSurfaceLICComposite.cxx +++ b/Rendering/ParallelLIC/vtkPSurfaceLICComposite.cxx @@ -1613,23 +1613,32 @@ int vtkPSurfaceLICComposite::ExecuteShader( float fext[4]; next.GetData(fext); - float tcoords[4] = {0.0f,1.0f, 0.0f,1.0f}; - #ifdef VTK_OPENGL2 - tex->Activate(); - this->CompositeShader->Program->SetUniformi("texData", - tex->GetTextureUnit()); - // may beed to divide by winExtSize here - float verts[] = { - fext[0]*2.0f-1.0f, fext[2]*2.0f-1.0f, 0.0f, - fext[1]*2.0f-1.0f, fext[2]*2.0f-1.0f, 0.0f, - fext[1]*2.0f-1.0f, fext[3]*2.0f-1.0f, 0.0f, - fext[0]*2.0f-1.0f, fext[3]*2.0f-1.0f, 0.0f}; - - vtkOpenGLRenderUtilities::RenderQuad(verts, tcoords, - this->CompositeShader->Program, this->CompositeShader->VAO); - tex->Deactivate(); + float tcoords[8] = + {0.0f, 0.0f, + 1.0f, 0.0f, + 1.0f, 1.0f, + 0.0f, 1.0f}; + + tex->Activate(); + this->CompositeShader->Program->SetUniformi("texData", + tex->GetTextureUnit()); + + unsigned int winExtSize[2]; + this->WindowExt.Size(winExtSize); + + float verts[] = { + 2.0f*fext[0]/winExtSize[0]-1.0f, 2.0f*fext[2]/winExtSize[1]-1.0f, 0.0f, + 2.0f*(fext[1]+1.0f)/winExtSize[0]-1.0f, 2.0f*fext[2]/winExtSize[1]-1.0f, 0.0f, + 2.0f*(fext[1]+1.0f)/winExtSize[0]-1.0f, 2.0f*(fext[3]+1.0f)/winExtSize[1]-1.0f, 0.0f, + 2.0f*fext[0]/winExtSize[0]-1.0f, 2.0f*(fext[3]+1.0f)/winExtSize[1]-1.0f, 0.0f}; + + vtkOpenGLRenderUtilities::RenderQuad(verts, tcoords, + this->CompositeShader->Program, this->CompositeShader->VAO); + tex->Deactivate(); #else + float tcoords[4] = {0.0f,1.0f, 0.0f,1.0f}; + tex->Activate(GL_TEXTURE0); int ids[8] = {0,2, 1,2, 1,3, 0,3}; diff --git a/Rendering/ParallelLIC/vtkPSurfaceLICComposite_CompFS.glsl b/Rendering/ParallelLIC/vtkPSurfaceLICComposite_CompFS.glsl index 3992656ba27..e752ff4c8f7 100644 --- a/Rendering/ParallelLIC/vtkPSurfaceLICComposite_CompFS.glsl +++ b/Rendering/ParallelLIC/vtkPSurfaceLICComposite_CompFS.glsl @@ -1,3 +1,4 @@ +//VTK::System::Dec //========================================================================= // // Program: Visualization Toolkit @@ -19,9 +20,9 @@ // The following line handles system declarations such as // default precisions, or defining precisions to null -//VTK::System::Dec // the output of this shader //VTK::Output::Dec + uniform sampler2D texData; varying vec2 tcoordVC; diff --git a/Rendering/ParallelLIC/vtkPSurfaceLICMapper.cxx b/Rendering/ParallelLIC/vtkPSurfaceLICInterface.cxx similarity index 81% rename from Rendering/ParallelLIC/vtkPSurfaceLICMapper.cxx rename to Rendering/ParallelLIC/vtkPSurfaceLICInterface.cxx index 4ad416c6b84..ab2c7f4ecee 100644 --- a/Rendering/ParallelLIC/vtkPSurfaceLICMapper.cxx +++ b/Rendering/ParallelLIC/vtkPSurfaceLICInterface.cxx @@ -1,7 +1,7 @@ /*========================================================================= Program: Visualization Toolkit - Module: vtkPSurfaceLICMapper.cxx + Module: vtkPSurfaceLICInterface.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. @@ -12,7 +12,7 @@ PURPOSE. See the above copyright notice for more information. =========================================================================*/ -#include "vtkPSurfaceLICMapper.h" +#include "vtkPSurfaceLICInterface.h" #include "vtkObjectFactory.h" #include "vtkPainterCommunicator.h" @@ -21,22 +21,22 @@ #include "vtkParallelTimer.h" //---------------------------------------------------------------------------- -vtkStandardNewMacro(vtkPSurfaceLICMapper); +vtkStandardNewMacro(vtkPSurfaceLICInterface); //---------------------------------------------------------------------------- -vtkPSurfaceLICMapper::vtkPSurfaceLICMapper() +vtkPSurfaceLICInterface::vtkPSurfaceLICInterface() {} //---------------------------------------------------------------------------- -vtkPSurfaceLICMapper::~vtkPSurfaceLICMapper() +vtkPSurfaceLICInterface::~vtkPSurfaceLICInterface() { - #ifdef vtkPSurfaceLICMapperDEBUG - cerr << "=====vtkPSurfaceLICMapper::~vtkPSurfaceLICMapper" << endl; + #ifdef vtkPSurfaceLICInterfaceDEBUG + cerr << "=====vtkPSurfaceLICInterface::~vtkPSurfaceLICInterface" << endl; #endif } //---------------------------------------------------------------------------- -bool vtkPSurfaceLICMapper::NeedToUpdateCommunicator() +bool vtkPSurfaceLICInterface::NeedToUpdateCommunicator() { // TODO -- with slice widget in PV the input dataset // MTime is changing at different rates on different @@ -70,7 +70,7 @@ bool vtkPSurfaceLICMapper::NeedToUpdateCommunicator() } // ---------------------------------------------------------------------------- -void vtkPSurfaceLICMapper::GetGlobalMinMax( +void vtkPSurfaceLICInterface::GetGlobalMinMax( vtkPainterCommunicator *painterComm, float &min, float &max) @@ -102,9 +102,9 @@ void vtkPSurfaceLICMapper::GetGlobalMinMax( } //----------------------------------------------------------------------------- -void vtkPSurfaceLICMapper::StartTimerEvent(const char *event) +void vtkPSurfaceLICInterface::StartTimerEvent(const char *event) { - #if defined(vtkSurfaceLICMapperTIME) + #if defined(vtkSurfaceLICInterfaceTIME) vtkParallelTimer *log = vtkParallelTimer::GetGlobalInstance(); log->StartEvent(event); #else @@ -113,9 +113,9 @@ void vtkPSurfaceLICMapper::StartTimerEvent(const char *event) } //----------------------------------------------------------------------------- -void vtkPSurfaceLICMapper::EndTimerEvent(const char *event) +void vtkPSurfaceLICInterface::EndTimerEvent(const char *event) { - #if defined(vtkSurfaceLICMapperTIME) + #if defined(vtkSurfaceLICInterfaceTIME) vtkParallelTimer *log = vtkParallelTimer::GetGlobalInstance(); log->EndEvent(event); #else @@ -124,9 +124,9 @@ void vtkPSurfaceLICMapper::EndTimerEvent(const char *event) } //---------------------------------------------------------------------------- -void vtkPSurfaceLICMapper::WriteTimerLog(const char *fileName) +void vtkPSurfaceLICInterface::WriteTimerLog(const char *fileName) { - #if defined(vtkSurfaceLICMapperTIME) + #if defined(vtkSurfaceLICInterfaceTIME) std::string fname = fileName?fileName:""; if (fname == this->LogFileName) { @@ -146,7 +146,7 @@ void vtkPSurfaceLICMapper::WriteTimerLog(const char *fileName) } //---------------------------------------------------------------------------- -vtkPainterCommunicator *vtkPSurfaceLICMapper::CreateCommunicator(int include) +vtkPainterCommunicator *vtkPSurfaceLICInterface::CreateCommunicator(int include) { // if we're using MPI and it's been initialized then // subset VTK's world communicator otherwise run the @@ -165,7 +165,7 @@ vtkPainterCommunicator *vtkPSurfaceLICMapper::CreateCommunicator(int include) } //---------------------------------------------------------------------------- -void vtkPSurfaceLICMapper::PrintSelf(ostream & os, vtkIndent indent) +void vtkPSurfaceLICInterface::PrintSelf(ostream & os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "LogFileName=" << this->LogFileName << endl; diff --git a/Rendering/ParallelLIC/vtkPSurfaceLICMapper.h b/Rendering/ParallelLIC/vtkPSurfaceLICInterface.h similarity index 72% rename from Rendering/ParallelLIC/vtkPSurfaceLICMapper.h rename to Rendering/ParallelLIC/vtkPSurfaceLICInterface.h index fd05b30407d..fe09a0b2af3 100644 --- a/Rendering/ParallelLIC/vtkPSurfaceLICMapper.h +++ b/Rendering/ParallelLIC/vtkPSurfaceLICInterface.h @@ -1,7 +1,7 @@ /*========================================================================= Program: Visualization Toolkit - Module: vtkPSurfaceLICMapper.h + Module: vtkPSurfaceLICInterface.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. @@ -12,40 +12,39 @@ PURPOSE. See the above copyright notice for more information. =========================================================================*/ -// .NAME vtkPSurfaceLICMapper - parallel parts of the vtkSurfaceLICMapper +// .NAME vtkPSurfaceLICInterface - parallel parts of the vtkSurfaceLICInterface // // .SECTION Description -// Parallel parts of the vtkSurfaceLICMapper, see that class for +// Parallel parts of the vtkSurfaceLICInterface, see that class for // documentation. -#ifndef vtkPSurfaceLICMapper_h -#define vtkPSurfaceLICMapper_h +#ifndef vtkPSurfaceLICInterface_h +#define vtkPSurfaceLICInterface_h -#include "vtkSurfaceLICMapper.h" +#include "vtkSurfaceLICInterface.h" #include "vtkRenderingParallelLICModule.h" // For export macro #include // for string class vtkPainterCommunicator; -class VTKRENDERINGPARALLELLIC_EXPORT vtkPSurfaceLICMapper : public vtkSurfaceLICMapper +class VTKRENDERINGPARALLELLIC_EXPORT vtkPSurfaceLICInterface : public vtkSurfaceLICInterface { public: - static vtkPSurfaceLICMapper* New(); - vtkTypeMacro(vtkPSurfaceLICMapper, vtkSurfaceLICMapper); + static vtkPSurfaceLICInterface* New(); + vtkTypeMacro(vtkPSurfaceLICInterface, vtkSurfaceLICInterface); virtual void PrintSelf(ostream& os, vtkIndent indent); // Description: // Methods used for parallel benchmarks. Use cmake to define - // vtkSurfaceLICMapperTIME to enable benchmarks. During each + // vtkSurfaceLICInterfaceTIME to enable benchmarks. During each // update timing information is stored, it can be written to // disk by calling WriteLog. virtual void WriteTimerLog(const char *fileName); protected: - vtkPSurfaceLICMapper(); - ~vtkPSurfaceLICMapper(); + vtkPSurfaceLICInterface(); + ~vtkPSurfaceLICInterface(); - //BTX // Description: // Get the min/max across all ranks. min/max are in/out. // In serial operation this is a no-op, in parallel it @@ -61,7 +60,6 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkPSurfaceLICMapper : public vtkSurfaceLIC // is included in the new communicator. In parallel this call is mpi // collective on the world communicator. In serial this is a no-op. virtual vtkPainterCommunicator *CreateCommunicator(int include); - //ETX // Description: // Ensure that if any rank udpates the communicator they all @@ -70,7 +68,7 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkPSurfaceLICMapper : public vtkSurfaceLIC // Description: // Methods used for parallel benchmarks. Use cmake to define - // vtkSurfaceLICMapperTIME to enable benchmarks. During each + // vtkSurfaceLICInterfaceTIME to enable benchmarks. During each // update timing information is stored, it can be written to // disk by calling WriteLog. virtual void StartTimerEvent(const char *name); @@ -80,8 +78,8 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkPSurfaceLICMapper : public vtkSurfaceLIC std::string LogFileName; private: - vtkPSurfaceLICMapper(const vtkPSurfaceLICMapper&); // Not implemented. - void operator=(const vtkPSurfaceLICMapper&); // Not implemented. + vtkPSurfaceLICInterface(const vtkPSurfaceLICInterface&); // Not implemented. + void operator=(const vtkPSurfaceLICInterface&); // Not implemented. }; #endif diff --git a/Rendering/ParallelLIC/vtkPSurfaceLICPainter.h b/Rendering/ParallelLIC/vtkPSurfaceLICPainter.h index fd8770ea527..1938708f7d4 100644 --- a/Rendering/ParallelLIC/vtkPSurfaceLICPainter.h +++ b/Rendering/ParallelLIC/vtkPSurfaceLICPainter.h @@ -45,7 +45,6 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkPSurfaceLICPainter : public vtkSurfaceLI vtkPSurfaceLICPainter(); ~vtkPSurfaceLICPainter(); - //BTX // Description: // Get the min/max across all ranks. min/max are in/out. // In serial operation this is a no-op, in parallel it @@ -61,7 +60,6 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkPSurfaceLICPainter : public vtkSurfaceLI // is included in the new communicator. In parallel this call is mpi // collective on the world communicator. In serial this is a no-op. virtual vtkPainterCommunicator *CreateCommunicator(int include); - //ETX // Description: // Ensure that if any rank udpates the communicator they all diff --git a/Rendering/ParallelLIC/vtkParallelTimer.cxx b/Rendering/ParallelLIC/vtkParallelTimer.cxx index 51b7ed5ee34..54be3469026 100644 --- a/Rendering/ParallelLIC/vtkParallelTimer.cxx +++ b/Rendering/ParallelLIC/vtkParallelTimer.cxx @@ -95,7 +95,7 @@ class vtkParallelTimerBuffer ~vtkParallelTimerBuffer(); vtkParallelTimerBuffer(const vtkParallelTimerBuffer &other); - void operator=(const vtkParallelTimerBuffer &other); + vtkParallelTimerBuffer& operator=(const vtkParallelTimerBuffer &other); // Description: // Access state and internal data. @@ -179,15 +179,16 @@ vtkParallelTimerBuffer::vtkParallelTimerBuffer(const vtkParallelTimerBuffer &oth } //----------------------------------------------------------------------------- -void vtkParallelTimerBuffer::operator=(const vtkParallelTimerBuffer &other) +vtkParallelTimerBuffer& vtkParallelTimerBuffer::operator=(const vtkParallelTimerBuffer &other) { if (this == &other) { - return; + return *this; } this->Clear(); this->Resize(other.GetSize()); memcpy(this->Data, other.Data, other.GetSize()); + return *this; } //----------------------------------------------------------------------------- diff --git a/Rendering/ParallelLIC/vtkParallelTimer.h b/Rendering/ParallelLIC/vtkParallelTimer.h index 64db844ba64..2746587b548 100644 --- a/Rendering/ParallelLIC/vtkParallelTimer.h +++ b/Rendering/ParallelLIC/vtkParallelTimer.h @@ -41,14 +41,12 @@ #include "vtkObject.h" #include "vtkRenderingParallelLICModule.h" // for export -//BTX #include // for vector #include // for string #include // for sstream #if vtkParallelTimerDEBUG > 0 #include // for cerr #endif -//ETX class vtkParallelTimerBuffer; @@ -88,10 +86,9 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkParallelTimer : public vtkObject // ROOT_RANKS_PID.log vtkSetStringMacro(FileName); vtkGetStringMacro(FileName); - //BTX + void SetFileName(const std::string &fileName) { this->SetFileName(fileName.c_str()); } - //ETX // Description: // The log works as an event stack. EventStart pushes the @@ -107,7 +104,6 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkParallelTimer : public vtkObject void EndEventSynch(const char *event); void EndEventSynch(int rank, const char *event); - //BTX // Description: // Insert text into the log header on the writer rank. template @@ -122,7 +118,6 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkParallelTimer : public vtkObject // stream output to log body(all ranks). vtkParallelTimer::LogBodyType GetBody() { return vtkParallelTimer::LogBodyType(); } - //ETX // Description: // Clear the log. @@ -173,7 +168,6 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkParallelTimer : public vtkObject vtkParallelTimer(const vtkParallelTimer&); // Not implemented void operator=(const vtkParallelTimer&); // Not implemented -//BTX // Description: // A class responsible for delete'ing the global instance of the log. class VTKRENDERINGPARALLELLIC_EXPORT vtkParallelTimerDestructor @@ -187,7 +181,6 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkParallelTimer : public vtkObject private: vtkParallelTimer *Log; }; -//ETX private: int GlobalLevel; @@ -212,7 +205,6 @@ class VTKRENDERINGPARALLELLIC_EXPORT vtkParallelTimer : public vtkObject friend class LogBodyType; }; -//BTX //----------------------------------------------------------------------------- template vtkParallelTimer &vtkParallelTimer::operator<<(const T& s) @@ -257,6 +249,5 @@ vtkParallelTimer::LogBodyType &vtkParallelTimer::LogBodyType::operator<<(const T return *this; } -//ETX #endif diff --git a/Rendering/Qt/vtkQImageToImageSource.cxx b/Rendering/Qt/vtkQImageToImageSource.cxx index 6b361cc8e0d..43572d63514 100644 --- a/Rendering/Qt/vtkQImageToImageSource.cxx +++ b/Rendering/Qt/vtkQImageToImageSource.cxx @@ -79,7 +79,7 @@ int vtkQImageToImageSource::RequestData( vtkInformation *vtkNotUsed(request), output->SetExtent(this->DataExtent); output->AllocateScalars(VTK_UNSIGNED_CHAR, 4); - vtkUnsignedCharArray* array = vtkUnsignedCharArray::SafeDownCast( output->GetPointData()->GetScalars() ); + vtkUnsignedCharArray* array = vtkArrayDownCast( output->GetPointData()->GetScalars() ); int i, j; unsigned char temp[4]; diff --git a/Rendering/Qt/vtkQImageToImageSource.h b/Rendering/Qt/vtkQImageToImageSource.h index 4d34acd1c5b..ef6c62372c8 100644 --- a/Rendering/Qt/vtkQImageToImageSource.h +++ b/Rendering/Qt/vtkQImageToImageSource.h @@ -22,9 +22,7 @@ PURPOSE. See the above copyright notice for more information. #include "vtkRenderingQtModule.h" // For export macro #include "vtkImageAlgorithm.h" -//BTX class QImage; -//ETX class VTKRENDERINGQT_EXPORT vtkQImageToImageSource : public vtkImageAlgorithm { diff --git a/Rendering/Qt/vtkQtInitialization.h b/Rendering/Qt/vtkQtInitialization.h index 127a31f9105..33e7bd2c17f 100644 --- a/Rendering/Qt/vtkQtInitialization.h +++ b/Rendering/Qt/vtkQtInitialization.h @@ -32,9 +32,7 @@ #include "vtkRenderingQtModule.h" // For export macro #include "vtkObject.h" -//BTX class QApplication; -//ETX class VTKRENDERINGQT_EXPORT vtkQtInitialization : public vtkObject { @@ -50,9 +48,9 @@ class VTKRENDERINGQT_EXPORT vtkQtInitialization : public vtkObject private: vtkQtInitialization(const vtkQtInitialization &); // Not implemented. void operator=(const vtkQtInitialization &); // Not implemented. - //BTX + QApplication *Application; - //ETX + }; #endif // vtkQtInitialization_h diff --git a/Rendering/Qt/vtkQtLabelRenderStrategy.h b/Rendering/Qt/vtkQtLabelRenderStrategy.h index 33f9586bedf..73a9b2fad04 100644 --- a/Rendering/Qt/vtkQtLabelRenderStrategy.h +++ b/Rendering/Qt/vtkQtLabelRenderStrategy.h @@ -80,10 +80,8 @@ class VTKRENDERINGQT_EXPORT vtkQtLabelRenderStrategy : public vtkLabelRenderStra vtkQtLabelRenderStrategy(); ~vtkQtLabelRenderStrategy(); - //BTX class Internals; Internals* Implementation; - //ETX vtkQImageToImageSource* QImageToImage; vtkPlaneSource* PlaneSource; diff --git a/Rendering/Qt/vtkQtTreeRingLabelMapper.cxx b/Rendering/Qt/vtkQtTreeRingLabelMapper.cxx index 1b6d9a891b8..f57bed1e969 100644 --- a/Rendering/Qt/vtkQtTreeRingLabelMapper.cxx +++ b/Rendering/Qt/vtkQtTreeRingLabelMapper.cxx @@ -256,9 +256,9 @@ void vtkQtTreeRingLabelMapper::RenderOpaqueGeometry(vtkViewport *viewport, this->FieldDataArray : pd->GetNumberOfArrays() - 1); abstractData = pd->GetAbstractArray(arrayNum); } - numericData = vtkDataArray::SafeDownCast(abstractData); - stringData = vtkStringArray::SafeDownCast(abstractData); - uStringData = vtkUnicodeStringArray::SafeDownCast(abstractData); + numericData = vtkArrayDownCast(abstractData); + stringData = vtkArrayDownCast(abstractData); + uStringData = vtkArrayDownCast(abstractData); }; break; } diff --git a/Rendering/Qt/vtkQtTreeRingLabelMapper.h b/Rendering/Qt/vtkQtTreeRingLabelMapper.h index e01c05b446e..917aadf43c7 100644 --- a/Rendering/Qt/vtkQtTreeRingLabelMapper.h +++ b/Rendering/Qt/vtkQtTreeRingLabelMapper.h @@ -44,9 +44,7 @@ #include "vtkRenderingQtModule.h" // For export macro #include "vtkLabeledDataMapper.h" -//BTX class QImage; -//ETX class vtkQImageToImageSource; class vtkCoordinate; diff --git a/Rendering/SceneGraph/CMakeLists.txt b/Rendering/SceneGraph/CMakeLists.txt new file mode 100644 index 00000000000..b3dd4ca07a4 --- /dev/null +++ b/Rendering/SceneGraph/CMakeLists.txt @@ -0,0 +1,20 @@ +set(Module_SRCS + vtkActorNode.cxx + vtkCameraNode.cxx + vtkLightNode.cxx + vtkMapperNode.cxx + vtkPolyDataMapperNode.cxx + vtkRendererNode.cxx + vtkViewNode.cxx + vtkViewNodeCollection.cxx + vtkViewNodeFactory.cxx + vtkWindowNode.cxx + ) + + +set_source_files_properties( + vtkViewNode + ABSTRACT + ) + +vtk_module_library(vtkRenderingSceneGraph ${Module_SRCS}) diff --git a/Rendering/SceneGraph/Testing/Cxx/CMakeLists.txt b/Rendering/SceneGraph/Testing/Cxx/CMakeLists.txt new file mode 100644 index 00000000000..124c8702628 --- /dev/null +++ b/Rendering/SceneGraph/Testing/Cxx/CMakeLists.txt @@ -0,0 +1,5 @@ +vtk_add_test_cxx(${vtk-module}CxxTests tests + UnitTests.cxx,NO_DATA,NO_VALID,NO_OUTPUT + ) + +vtk_test_cxx_executable(${vtk-module}CxxTests tests) diff --git a/Rendering/SceneGraph/Testing/Cxx/UnitTests.cxx b/Rendering/SceneGraph/Testing/Cxx/UnitTests.cxx new file mode 100644 index 00000000000..8cbbad03084 --- /dev/null +++ b/Rendering/SceneGraph/Testing/Cxx/UnitTests.cxx @@ -0,0 +1,266 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: Mace.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include "vtkActor.h" +#include "vtkActorNode.h" +#include "vtkCamera.h" +#include "vtkCameraNode.h" +#include "vtkLight.h" +#include "vtkLightNode.h" +#include "vtkObjectFactory.h" +#include "vtkPolyDataMapper.h" +#include "vtkRenderer.h" +#include "vtkRendererNode.h" +#include "vtkRenderWindow.h" +#include "vtkSphereSource.h" +#include "vtkViewNodeCollection.h" +#include "vtkViewNodeFactory.h" +#include "vtkWindowNode.h" + +#include +namespace { + std::string result = ""; +} + +//----------------------------------------------------------------------- +//ViewNode subclasses specialized for this test +class vtkMyActorNode : public vtkActorNode +{ +public: + static vtkMyActorNode* New(); + vtkTypeMacro(vtkMyActorNode, vtkActorNode); + virtual void Render(bool prepass) { + if (prepass) + { + cerr << "Render " << this << " " << this->GetClassName() << endl; + result += "Render "; + result += this->GetClassName(); + result += "\n"; + } + } + vtkMyActorNode() {}; + ~vtkMyActorNode() {}; +}; +vtkStandardNewMacro(vtkMyActorNode); + +class vtkMyCameraNode : public vtkCameraNode +{ +public: + static vtkMyCameraNode* New(); + vtkTypeMacro(vtkMyCameraNode, vtkCameraNode); + virtual void Render(bool prepass) { + if (prepass) + { + cerr << "Render " << this << " " << this->GetClassName() << endl; + result += "Render "; + result += this->GetClassName(); + result += "\n"; + } + } + vtkMyCameraNode() {}; + ~vtkMyCameraNode() {}; +}; +vtkStandardNewMacro(vtkMyCameraNode); + +class vtkMyLightNode : public vtkLightNode +{ +public: + static vtkMyLightNode* New(); + vtkTypeMacro(vtkMyLightNode, vtkLightNode); + virtual void Render( bool prepass) { + if (prepass) + { + cerr << "Render " << this << " " << this->GetClassName() << endl; + result += "Render "; + result += this->GetClassName(); + result += "\n"; + } + } + vtkMyLightNode() {}; + ~vtkMyLightNode() {}; +}; +vtkStandardNewMacro(vtkMyLightNode); + +class vtkMyRendererNode : public vtkRendererNode +{ +public: + static vtkMyRendererNode* New(); + vtkTypeMacro(vtkMyRendererNode, vtkRendererNode); + virtual void Render(bool prepass) { + if (prepass) + { + cerr << "Render " << this << " " << this->GetClassName() << endl; + result += "Render "; + result += this->GetClassName(); + result += "\n"; + } + } + vtkMyRendererNode() {}; + ~vtkMyRendererNode() {}; +}; +vtkStandardNewMacro(vtkMyRendererNode); + +class vtkMyWindowNode : public vtkWindowNode +{ +public: + static vtkMyWindowNode* New(); + vtkTypeMacro(vtkMyWindowNode, vtkWindowNode); + virtual void Render(bool prepass) { + if (prepass) + { + cerr << "Render " << this << " " << this->GetClassName() << endl; + result += "Render "; + result += this->GetClassName(); + result += "\n"; + } + } + vtkMyWindowNode() {}; + ~vtkMyWindowNode() {}; +}; +vtkStandardNewMacro(vtkMyWindowNode); + +//------------------------------------------------------------------------------ + +//builders that produce the specialized ViewNodes +vtkViewNode *act_maker() +{ + vtkMyActorNode *vn = vtkMyActorNode::New(); + cerr << "make actor node " << vn << endl; + result = result + "make actor\n"; + return vn; +} + +vtkViewNode *cam_maker() +{ + vtkMyCameraNode *vn = vtkMyCameraNode::New(); + cerr << "make camera node " << vn << endl; + result = result + "make camera\n"; + return vn; +} + +vtkViewNode *light_maker() +{ + vtkMyLightNode *vn = vtkMyLightNode::New(); + cerr << "make light node " << vn << endl; + result = result + "make light\n"; + return vn; +} + +vtkViewNode *ren_maker() +{ + vtkMyRendererNode *vn = vtkMyRendererNode::New(); + cerr << "make renderer node " << vn << endl; + result = result + "make renderer\n"; + return vn; +} + +vtkViewNode *win_maker() +{ + vtkMyWindowNode *vn = vtkMyWindowNode::New(); + cerr << "make window node " << vn << endl; + result = result + "make window\n"; + return vn; +} + +//exercises the scene graph related classes +int UnitTests( int vtkNotUsed(argc), char *vtkNotUsed(argv)[] ) +{ + vtkWindowNode *wvn = vtkWindowNode::New(); + cerr << "made " << wvn << endl; + + vtkViewNodeCollection *vnc = vtkViewNodeCollection::New(); + cerr << "made " << vnc << endl; + vnc->AddItem(wvn); + vnc->PrintSelf(cerr, vtkIndent(0)); + wvn->Delete(); + vnc->Delete(); + + vtkViewNode *vn = NULL; + vtkViewNodeFactory *vnf = vtkViewNodeFactory::New(); + cerr << "CREATE pre override" << endl; + vnc = NULL; + vn = vnf->CreateNode(vnc); + if (vn) + { + cerr << "Shouldn't have made anything" << endl; + return 1; + } + cerr << "factory made nothing as it should have" << endl; + + vtkRenderWindow *rwin = vtkRenderWindow::New(); + vnf->RegisterOverride(rwin->GetClassName(), win_maker); + cerr << "CREATE node for renderwindow" << endl; + vn = vnf->CreateNode(rwin); + + cerr << "factory makes" << endl; + cerr << vn << endl; + cerr << "BUILD [" << endl; + vn->Traverse(vtkViewNode::build); + cerr << "]" << endl; + + cerr << "add renderer" << endl; + vtkRenderer *ren = vtkRenderer::New(); + vnf->RegisterOverride(ren->GetClassName(), ren_maker); + rwin->AddRenderer(ren); + + vtkLight *light = vtkLight::New(); + vnf->RegisterOverride(light->GetClassName(), light_maker); + ren->AddLight(light); + light->Delete(); + + vtkCamera *cam = vtkCamera::New(); + vnf->RegisterOverride(cam->GetClassName(), cam_maker); + cam->Delete(); + + vtkActor *actor = vtkActor::New(); + vnf->RegisterOverride(actor->GetClassName(), act_maker); + ren->AddActor(actor); + actor->Delete(); + + vtkSphereSource *sphere = vtkSphereSource::New(); + vtkPolyDataMapper *pmap = vtkPolyDataMapper::New(); + pmap->SetInputConnection(sphere->GetOutputPort()); + actor->SetMapper(pmap); + rwin->Render(); + sphere->Delete(); + pmap->Delete(); + + cerr << "BUILD [" << endl; + vn->Traverse(vtkViewNode::build); + cerr << "]" << endl; + cerr << "SYNCHRONIZE [" << endl; + vn->Traverse(vtkViewNode::synchronize); + cerr << "]" << endl; + cerr << "RENDER [" << endl; + vn->Traverse(vtkViewNode::render); + cerr << "]" << endl; + + vn->Delete(); + ren->Delete(); + rwin->Delete(); + + vnf->Delete(); + + cerr << "Results is [" << endl; + cerr << result << "]" << endl; + std::string ok_res = "make window\nmake renderer\nmake light\nmake actor\nmake camera\nRender vtkMyWindowNode\nRender vtkMyRendererNode\nRender vtkMyLightNode\nRender vtkMyActorNode\nRender vtkMyCameraNode\n"; + if (result != ok_res) + { + cerr << "Which does not match [" << endl; + cerr << ok_res << "]" << endl; + return 1; + } + return 0; +} diff --git a/Rendering/SceneGraph/Testing/Temporary/CTestCostData.txt b/Rendering/SceneGraph/Testing/Temporary/CTestCostData.txt new file mode 100644 index 00000000000..ed97d539c09 --- /dev/null +++ b/Rendering/SceneGraph/Testing/Temporary/CTestCostData.txt @@ -0,0 +1 @@ +--- diff --git a/Rendering/SceneGraph/Testing/Temporary/LastTest.log b/Rendering/SceneGraph/Testing/Temporary/LastTest.log new file mode 100644 index 00000000000..3c987df98f0 --- /dev/null +++ b/Rendering/SceneGraph/Testing/Temporary/LastTest.log @@ -0,0 +1,3 @@ +Start testing: Dec 07 12:05 EST +---------------------------------------------------------- +End testing: Dec 07 12:05 EST diff --git a/Rendering/SceneGraph/module.cmake b/Rendering/SceneGraph/module.cmake new file mode 100644 index 00000000000..b54efa859cf --- /dev/null +++ b/Rendering/SceneGraph/module.cmake @@ -0,0 +1,9 @@ +vtk_module(vtkRenderingSceneGraph + DEPENDS + vtkRenderingCore + TEST_DEPENDS + vtkTestingCore + vtkRendering${VTK_RENDERING_BACKEND} + KIT + vtkRendering + ) diff --git a/Rendering/SceneGraph/vtkActorNode.cxx b/Rendering/SceneGraph/vtkActorNode.cxx new file mode 100644 index 00000000000..fc4a59aa438 --- /dev/null +++ b/Rendering/SceneGraph/vtkActorNode.cxx @@ -0,0 +1,63 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkActorNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkActorNode.h" + +#include "vtkActor.h" +#include "vtkCellArray.h" +#include "vtkMapper.h" +#include "vtkMath.h" +#include "vtkMatrix4x4.h" +#include "vtkObjectFactory.h" +#include "vtkPoints.h" +#include "vtkPolyData.h" +#include "vtkPolygon.h" +#include "vtkProperty.h" + +//============================================================================ +vtkStandardNewMacro(vtkActorNode); + +//---------------------------------------------------------------------------- +vtkActorNode::vtkActorNode() +{ +} + +//---------------------------------------------------------------------------- +vtkActorNode::~vtkActorNode() +{ +} + +//---------------------------------------------------------------------------- +void vtkActorNode::Build(bool prepass) +{ + if (prepass) + { + vtkActor *mine = vtkActor::SafeDownCast + (this->GetRenderable()); + if (!mine) + { + return; + } + + this->PrepareNodes(); + this->AddMissingNode(mine->GetMapper()); + this->RemoveUnusedNodes(); + } +} + +//---------------------------------------------------------------------------- +void vtkActorNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/Rendering/SceneGraph/vtkActorNode.h b/Rendering/SceneGraph/vtkActorNode.h new file mode 100644 index 00000000000..ac6fb340478 --- /dev/null +++ b/Rendering/SceneGraph/vtkActorNode.h @@ -0,0 +1,48 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkActorNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkActorNode - vtkViewNode specialized for vtkActors +// .SECTION Description +// State storage and graph traversal for vtkActor/Mapper and Property +// Made a choice to merge actor, mapper and property together. If there +// is a compelling reason to separate them we can. + +#ifndef vtkActorNode_h +#define vtkActorNode_h + +#include "vtkRenderingSceneGraphModule.h" // For export macro +#include "vtkViewNode.h" + +class VTKRENDERINGSCENEGRAPH_EXPORT vtkActorNode : + public vtkViewNode +{ +public: + static vtkActorNode* New(); + vtkTypeMacro(vtkActorNode, vtkViewNode); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //Build containers for our child nodes. + virtual void Build(bool prepass); + +protected: + vtkActorNode(); + ~vtkActorNode(); + + private: + vtkActorNode(const vtkActorNode&); // Not implemented. + void operator=(const vtkActorNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/SceneGraph/vtkCameraNode.cxx b/Rendering/SceneGraph/vtkCameraNode.cxx new file mode 100644 index 00000000000..b0b13d7d5ed --- /dev/null +++ b/Rendering/SceneGraph/vtkCameraNode.cxx @@ -0,0 +1,36 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkCameraNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkCameraNode.h" +#include "vtkCamera.h" +#include "vtkObjectFactory.h" + +//============================================================================ +vtkStandardNewMacro(vtkCameraNode); + +//---------------------------------------------------------------------------- +vtkCameraNode::vtkCameraNode() +{ +} + +//---------------------------------------------------------------------------- +vtkCameraNode::~vtkCameraNode() +{ +} + +//---------------------------------------------------------------------------- +void vtkCameraNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/Rendering/SceneGraph/vtkCameraNode.h b/Rendering/SceneGraph/vtkCameraNode.h new file mode 100644 index 00000000000..dca18f4a488 --- /dev/null +++ b/Rendering/SceneGraph/vtkCameraNode.h @@ -0,0 +1,42 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkCameraNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkCameraNode - vtkViewNode specialized for vtkCameras +// .SECTION Description +// State storage and graph traversal for vtkCamera + +#ifndef vtkCameraNode_h +#define vtkCameraNode_h + +#include "vtkRenderingSceneGraphModule.h" // For export macro +#include "vtkViewNode.h" + +class VTKRENDERINGSCENEGRAPH_EXPORT vtkCameraNode : + public vtkViewNode +{ +public: + static vtkCameraNode* New(); + vtkTypeMacro(vtkCameraNode, vtkViewNode); + void PrintSelf(ostream& os, vtkIndent indent); + +protected: + vtkCameraNode(); + ~vtkCameraNode(); + +private: + vtkCameraNode(const vtkCameraNode&); // Not implemented. + void operator=(const vtkCameraNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/SceneGraph/vtkLightNode.cxx b/Rendering/SceneGraph/vtkLightNode.cxx new file mode 100644 index 00000000000..f7d5742fca7 --- /dev/null +++ b/Rendering/SceneGraph/vtkLightNode.cxx @@ -0,0 +1,37 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkLightNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkLightNode.h" +#include "vtkObjectFactory.h" + +#include "vtkLight.h" + +//============================================================================ +vtkStandardNewMacro(vtkLightNode); + +//---------------------------------------------------------------------------- +vtkLightNode::vtkLightNode() +{ +} + +//---------------------------------------------------------------------------- +vtkLightNode::~vtkLightNode() +{ +} + +//---------------------------------------------------------------------------- +void vtkLightNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/Rendering/SceneGraph/vtkLightNode.h b/Rendering/SceneGraph/vtkLightNode.h new file mode 100644 index 00000000000..8c745c2ce1f --- /dev/null +++ b/Rendering/SceneGraph/vtkLightNode.h @@ -0,0 +1,42 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkLightNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkLightNode - vtkViewNode specialized for vtkLights +// .SECTION Description +// State storage and graph traversal for vtkLight + +#ifndef vtkLightNode_h +#define vtkLightNode_h + +#include "vtkRenderingSceneGraphModule.h" // For export macro +#include "vtkViewNode.h" + +class VTKRENDERINGSCENEGRAPH_EXPORT vtkLightNode : + public vtkViewNode +{ +public: + static vtkLightNode* New(); + vtkTypeMacro(vtkLightNode, vtkViewNode); + void PrintSelf(ostream& os, vtkIndent indent); + +protected: + vtkLightNode(); + ~vtkLightNode(); + +private: + vtkLightNode(const vtkLightNode&); // Not implemented. + void operator=(const vtkLightNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/SceneGraph/vtkMapperNode.cxx b/Rendering/SceneGraph/vtkMapperNode.cxx new file mode 100644 index 00000000000..3784f6a2c2c --- /dev/null +++ b/Rendering/SceneGraph/vtkMapperNode.cxx @@ -0,0 +1,45 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkMapperNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkMapperNode.h" + +#include "vtkMapper.h" +#include "vtkCellArray.h" +#include "vtkMapper.h" +#include "vtkMath.h" +#include "vtkMatrix4x4.h" +#include "vtkObjectFactory.h" +#include "vtkPoints.h" +#include "vtkPolyData.h" +#include "vtkPolygon.h" +#include "vtkProperty.h" + +//============================================================================ +vtkStandardNewMacro(vtkMapperNode); + +//---------------------------------------------------------------------------- +vtkMapperNode::vtkMapperNode() +{ +} + +//---------------------------------------------------------------------------- +vtkMapperNode::~vtkMapperNode() +{ +} + +//---------------------------------------------------------------------------- +void vtkMapperNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} diff --git a/Rendering/SceneGraph/vtkMapperNode.h b/Rendering/SceneGraph/vtkMapperNode.h new file mode 100644 index 00000000000..6ee14756e04 --- /dev/null +++ b/Rendering/SceneGraph/vtkMapperNode.h @@ -0,0 +1,47 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkMapperNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkMapperNode - vtkViewNode specialized for vtkMappers +// .SECTION Description +// State storage and graph traversal for vtkMapper + +#ifndef vtkMapperNode_h +#define vtkMapperNode_h + +#include "vtkRenderingSceneGraphModule.h" // For export macro +#include "vtkViewNode.h" + +#include //for results + +class vtkMapper; +class vtkPolyData; + +class VTKRENDERINGSCENEGRAPH_EXPORT vtkMapperNode : + public vtkViewNode +{ +public: + static vtkMapperNode* New(); + vtkTypeMacro(vtkMapperNode, vtkViewNode); + void PrintSelf(ostream& os, vtkIndent indent); + +protected: + vtkMapperNode(); + ~vtkMapperNode(); + + private: + vtkMapperNode(const vtkMapperNode&); // Not implemented. + void operator=(const vtkMapperNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/SceneGraph/vtkPolyDataMapperNode.cxx b/Rendering/SceneGraph/vtkPolyDataMapperNode.cxx new file mode 100644 index 00000000000..93a6b204f1a --- /dev/null +++ b/Rendering/SceneGraph/vtkPolyDataMapperNode.cxx @@ -0,0 +1,447 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkPolyDataMapperNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkPolyDataMapperNode.h" + +#include "vtkActor.h" +#include "vtkObjectFactory.h" +#include "vtkPolyDataMapper.h" +#include "vtkCellArray.h" +#include "vtkMath.h" +#include "vtkMatrix4x4.h" +#include "vtkPoints.h" +#include "vtkPolyData.h" +#include "vtkPolygon.h" +#include "vtkProperty.h" + +//============================================================================ +vtkStandardNewMacro(vtkPolyDataMapperNode); + +//---------------------------------------------------------------------------- +vtkPolyDataMapperNode::vtkPolyDataMapperNode() +{ +} + +//---------------------------------------------------------------------------- +vtkPolyDataMapperNode::~vtkPolyDataMapperNode() +{ +} + +//---------------------------------------------------------------------------- +void vtkPolyDataMapperNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +void vtkPolyDataMapperNode::TransformPoints(vtkActor *act, + vtkPolyData *poly, + std::vector &_vertices) +{ + vtkSmartPointer m = vtkSmartPointer::New(); + act->GetMatrix(m); + bool ident = (act->GetIsIdentity()==1); + double inPos[4]; + inPos[3] = 1.0; + double transPos[4]; + for (int i = 0; i < poly->GetNumberOfPoints(); i++) + { + double *pos = poly->GetPoints()->GetPoint(i); + bool wasNan = false; + int fixIndex = i - 1; + do + { + wasNan = false; + for (int j = 0; j < 3; j++) + { + if (vtkMath::IsNan(pos[j])) + { + wasNan = true; + } + } + if (wasNan && fixIndex >= 0) + { + pos = poly->GetPoints()->GetPoint(fixIndex--); + } + } while (wasNan == true && fixIndex >= 0); + if (ident) + { + _vertices.push_back(pos[0]); + _vertices.push_back(pos[1]); + _vertices.push_back(pos[2]); + } + else + { + inPos[0] = pos[0]; + inPos[1] = pos[1]; + inPos[2] = pos[2]; + m->MultiplyPoint(inPos, transPos); + //alternatively use an OSPRay instance of something like that + _vertices.push_back(transPos[0]); + _vertices.push_back(transPos[1]); + _vertices.push_back(transPos[2]); + } + } +} + +namespace { + //Helpers for MakeConnectivity() + //The CreateXIndexBuffer's were adapted from vtkOpenGLIndexBufferObject. + //Apply rule of three if made again somewhere in VTK. + + // ---------------------------------------------------------------------------- + //Description: + //Homogenizes everything into a flat list of point indexes. + //At same time creates a reverse cell index array for obtaining cell quantities for points + void CreatePointIndexBuffer(vtkCellArray *cells, + std::vector &indexArray, + std::vector &reverseArray) + { + //TODO: restore the preallocate and append to offset features I omitted + vtkIdType* indices(NULL); + vtkIdType npts(0); + if (!cells->GetNumberOfCells()) + { + return; + } + unsigned int cell_id = 0; + for (cells->InitTraversal(); cells->GetNextCell(npts, indices); ) + { + for (int i = 0; i < npts; ++i) + { + indexArray.push_back(static_cast(*(indices++))); + reverseArray.push_back(cell_id); + } + cell_id++; + } + } + + //---------------------------------------------------------------------------- + //Description: + //Homogenizes lines into a flat list of line segments, each containing two point indexes + //At same time creates a reverse cell index array for obtaining cell quantities for points + void CreateLineIndexBuffer(vtkCellArray *cells, + std::vector &indexArray, + std::vector &reverseArray) + { + //TODO: restore the preallocate and append to offset features I omitted + vtkIdType* indices(NULL); + vtkIdType npts(0); + if (!cells->GetNumberOfCells()) + { + return; + } + unsigned int cell_id = 0; + for (cells->InitTraversal(); cells->GetNextCell(npts, indices); ) + { + for (int i = 0; i < npts-1; ++i) + { + indexArray.push_back(static_cast(indices[i])); + indexArray.push_back(static_cast(indices[i+1])); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + } + cell_id++; + } + } + + //---------------------------------------------------------------------------- + //Description: + //Homogenizes polygons into a flat list of line segments, each containing two point indexes. + //At same time creates a reverse cell index array for obtaining cell quantities for points + //This differs from CreateLineIndexBuffer in that it closes loops, making a segment from last point + //back to first. + void CreateTriangleLineIndexBuffer(vtkCellArray *cells, + std::vector &indexArray, + std::vector &reverseArray) + { + //TODO: restore the preallocate and append to offset features I omitted + vtkIdType* indices(NULL); + vtkIdType npts(0); + if (!cells->GetNumberOfCells()) + { + return; + } + unsigned int cell_id = 0; + for (cells->InitTraversal(); cells->GetNextCell(npts, indices); ) + { + for (int i = 0; i < npts; ++i) + { + indexArray.push_back(static_cast(indices[i])); + indexArray.push_back(static_cast + (indices[i < npts-1 ? i+1 : 0])); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + } + cell_id++; + } + } + + //---------------------------------------------------------------------------- + //Description: + //Homogenizes polygons into a flat list of triangles, each containing three point indexes + //At same time creates a reverse cell index array for obtaining cell quantities for points + void CreateTriangleIndexBuffer(vtkCellArray *cells, vtkPoints *points, + std::vector &indexArray, + std::vector &reverseArray) + { + //TODO: restore the preallocate and append to offset features I omitted + vtkIdType* indices(NULL); + vtkIdType npts(0); + if (!cells->GetNumberOfCells()) + { + return; + } + unsigned int cell_id = 0; + // the folowing are only used if we have to triangulate a polygon + // otherwise they just sit at NULL + vtkPolygon *polygon = NULL; + vtkIdList *tris = NULL; + vtkPoints *triPoints = NULL; + + for (cells->InitTraversal(); cells->GetNextCell(npts, indices); ) + { + // ignore degenerate triangles + if (npts < 3) + { + cell_id++; + continue; + } + + // triangulate needed + if (npts > 3) + { + // special case for quads, penta, hex which are common + if (npts == 4) + { + indexArray.push_back(static_cast(indices[0])); + indexArray.push_back(static_cast(indices[1])); + indexArray.push_back(static_cast(indices[2])); + indexArray.push_back(static_cast(indices[0])); + indexArray.push_back(static_cast(indices[2])); + indexArray.push_back(static_cast(indices[3])); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + } + else if (npts == 5) + { + indexArray.push_back(static_cast(indices[0])); + indexArray.push_back(static_cast(indices[1])); + indexArray.push_back(static_cast(indices[2])); + indexArray.push_back(static_cast(indices[0])); + indexArray.push_back(static_cast(indices[2])); + indexArray.push_back(static_cast(indices[3])); + indexArray.push_back(static_cast(indices[0])); + indexArray.push_back(static_cast(indices[3])); + indexArray.push_back(static_cast(indices[4])); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + } + else if (npts == 6) + { + indexArray.push_back(static_cast(indices[0])); + indexArray.push_back(static_cast(indices[1])); + indexArray.push_back(static_cast(indices[2])); + indexArray.push_back(static_cast(indices[0])); + indexArray.push_back(static_cast(indices[2])); + indexArray.push_back(static_cast(indices[3])); + indexArray.push_back(static_cast(indices[0])); + indexArray.push_back(static_cast(indices[3])); + indexArray.push_back(static_cast(indices[5])); + indexArray.push_back(static_cast(indices[3])); + indexArray.push_back(static_cast(indices[4])); + indexArray.push_back(static_cast(indices[5])); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + } + else // 7 sided polygon or higher, do a full smart triangulation + { + if (!polygon) + { + polygon = vtkPolygon::New(); + tris = vtkIdList::New(); + triPoints = vtkPoints::New(); + } + + vtkIdType *triIndices = new vtkIdType[npts]; + triPoints->SetNumberOfPoints(npts); + for (int i = 0; i < npts; ++i) + { + int idx = indices[i]; + triPoints->SetPoint(i, points->GetPoint(idx)); + triIndices[i] = i; + } + polygon->Initialize(npts, triIndices, triPoints); + polygon->Triangulate(tris); + for (int j = 0; j < tris->GetNumberOfIds(); ++j) + { + indexArray.push_back(static_cast + (indices[tris->GetId(j)])); + reverseArray.push_back(cell_id); + } + delete [] triIndices; + } + } + else + { + indexArray.push_back(static_cast(*(indices++))); + indexArray.push_back(static_cast(*(indices++))); + indexArray.push_back(static_cast(*(indices++))); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + } + + cell_id++; + } + if (polygon) + { + polygon->Delete(); + tris->Delete(); + triPoints->Delete(); + } + } + + //---------------------------------------------------------------------------- + //Description: + //Homogenizes triangle strips. + //Depending on wireframeTriStrips it will produce either line segments (two indices per edge) + //or triangles (three indices per face). + //At same time creates a reverse cell index array for obtaining cell quantities for points + void CreateStripIndexBuffer(vtkCellArray *cells, + std::vector &indexArray, + std::vector &reverseArray, + bool wireframeTriStrips) + { + if (!cells->GetNumberOfCells()) + { + return; + } + unsigned int cell_id = 0; + + vtkIdType *pts = 0; + vtkIdType npts = 0; + + size_t triCount = cells->GetNumberOfConnectivityEntries() + - 3*cells->GetNumberOfCells(); + size_t targetSize = wireframeTriStrips ? 2*(triCount*2+1) + : triCount*3; + indexArray.reserve(targetSize); + + if (wireframeTriStrips) + { + for (cells->InitTraversal(); cells->GetNextCell(npts,pts); ) + { + indexArray.push_back(static_cast(pts[0])); + indexArray.push_back(static_cast(pts[1])); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + for (int j = 0; j < npts-2; ++j) + { + indexArray.push_back(static_cast(pts[j])); + indexArray.push_back(static_cast(pts[j+2])); + indexArray.push_back(static_cast(pts[j+1])); + indexArray.push_back(static_cast(pts[j+2])); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + } + cell_id++; + } + } + else + { + for (cells->InitTraversal(); cells->GetNextCell(npts,pts); ) + { + for (int j = 0; j < npts-2; ++j) + { + indexArray.push_back(static_cast(pts[j])); + indexArray.push_back(static_cast(pts[j+1+j%2])); + indexArray.push_back(static_cast(pts[j+1+(j+1)%2])); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + reverseArray.push_back(cell_id); + } + cell_id++; + } + } + } +} + +//---------------------------------------------------------------------------- +void vtkPolyDataMapperNode::MakeConnectivity(vtkPolyData *poly, + int representation, + std::vector &vertex_index, + std::vector &vertex_reverse, + std::vector &line_index, + std::vector &line_reverse, + std::vector &triangle_index, + std::vector &triangle_reverse, + std::vector &strip_index, + std::vector &strip_reverse + ) +{ + vtkCellArray *prims[4]; + prims[0] = poly->GetVerts(); + prims[1] = poly->GetLines(); + prims[2] = poly->GetPolys(); + prims[3] = poly->GetStrips(); + + CreatePointIndexBuffer(prims[0], vertex_index, vertex_reverse); + switch (representation) + { + case VTK_POINTS: + { + CreatePointIndexBuffer(prims[1], line_index, line_reverse); + CreatePointIndexBuffer(prims[2], triangle_index, triangle_reverse); + CreatePointIndexBuffer(prims[3], strip_index, strip_reverse); + break; + } + case VTK_WIREFRAME: + { + CreateLineIndexBuffer(prims[1], line_index, line_reverse); + CreateTriangleLineIndexBuffer(prims[2], triangle_index, triangle_reverse); + CreateStripIndexBuffer(prims[3], strip_index, strip_reverse, true); + break; + } + default: + { + CreateLineIndexBuffer(prims[1], line_index, line_reverse); + CreateTriangleIndexBuffer(prims[2], poly->GetPoints(), triangle_index, triangle_reverse); + CreateStripIndexBuffer(prims[3], strip_index, strip_reverse, false); + } + } +} diff --git a/Rendering/SceneGraph/vtkPolyDataMapperNode.h b/Rendering/SceneGraph/vtkPolyDataMapperNode.h new file mode 100644 index 00000000000..31bcf330aaa --- /dev/null +++ b/Rendering/SceneGraph/vtkPolyDataMapperNode.h @@ -0,0 +1,74 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkPolyDataMapperNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkPolyDataMapperNode - vtkViewNode specialized for vtkPolyDataMappers +// .SECTION Description +// State storage and graph traversal for vtkPolyDataMapper/PolyDataMapper and Property +// Made a choice to merge PolyDataMapper, PolyDataMapper and property together. If there +// is a compelling reason to separate them we can. + +#ifndef vtkPolyDataMapperNode_h +#define vtkPolyDataMapperNode_h + +#include "vtkRenderingSceneGraphModule.h" // For export macro +#include "vtkMapperNode.h" + +#include //for results + +class vtkActor; +class vtkPolyDataMapper; +class vtkPolyData; + +class VTKRENDERINGSCENEGRAPH_EXPORT vtkPolyDataMapperNode : + public vtkMapperNode +{ +public: + static vtkPolyDataMapperNode* New(); + vtkTypeMacro(vtkPolyDataMapperNode, vtkMapperNode); + void PrintSelf(ostream& os, vtkIndent indent); + +protected: + vtkPolyDataMapperNode(); + ~vtkPolyDataMapperNode(); + + //Utilities for children + //Description: + //Makes a cleaned up version of the polydata's geometry in which NaN are removed + //(substituted with neighbor) and the PolyDataMapper's transformation matrix is applied. + static void TransformPoints(vtkActor *act, + vtkPolyData *poly, + std::vector &vertices); + + //Description: + //Homogenizes the entire polydata using internal CreateXIndexBuffer functions. + //They flatten the input polydata's Points, Lines, Polys, and Strips contents into + //the output arrays. The output "index" arrays contain indices into the Points. The + //output "reverse" array contains indices into the original CellArray. + static void MakeConnectivity(vtkPolyData *poly, + int representation, + std::vector &vertex_index, + std::vector &vertex_reverse, + std::vector &line_index, + std::vector &line_reverse, + std::vector &triangle_index, + std::vector &triangle_reverse, + std::vector &strip_index, + std::vector &strip_reverse); + + private: + vtkPolyDataMapperNode(const vtkPolyDataMapperNode&); // Not implemented. + void operator=(const vtkPolyDataMapperNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/SceneGraph/vtkRendererNode.cxx b/Rendering/SceneGraph/vtkRendererNode.cxx new file mode 100644 index 00000000000..b17cbb0c8c5 --- /dev/null +++ b/Rendering/SceneGraph/vtkRendererNode.cxx @@ -0,0 +1,88 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkRendererNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkRendererNode.h" + +#include "vtkActor.h" +#include "vtkActorNode.h" +#include "vtkCamera.h" +#include "vtkCameraNode.h" +#include "vtkCollectionIterator.h" +#include "vtkLight.h" +#include "vtkLightCollection.h" +#include "vtkLightNode.h" +#include "vtkObjectFactory.h" +#include "vtkRenderer.h" +#include "vtkRendererNode.h" +#include "vtkRenderWindow.h" +#include "vtkViewNodeCollection.h" + +//============================================================================ +vtkStandardNewMacro(vtkRendererNode); + +//---------------------------------------------------------------------------- +vtkRendererNode::vtkRendererNode() +{ + this->Size[0] = 0; + this->Size[1] = 0; +} + +//---------------------------------------------------------------------------- +vtkRendererNode::~vtkRendererNode() +{ +} + +//---------------------------------------------------------------------------- +void vtkRendererNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +void vtkRendererNode::Synchronize(bool prepass) +{ + if (prepass) + { + vtkRenderer *mine = vtkRenderer::SafeDownCast + (this->GetRenderable()); + if (!mine) + { + return; + } + int *tmp = mine->GetSize(); + this->Size[0] = tmp[0]; + this->Size[1] = tmp[1]; + } +} + +//---------------------------------------------------------------------------- +void vtkRendererNode::Build(bool prepass) +{ + if (prepass) + { + vtkRenderer *mine = vtkRenderer::SafeDownCast + (this->GetRenderable()); + if (!mine) + { + return; + } + + this->PrepareNodes(); + this->AddMissingNodes(mine->GetLights()); + this->AddMissingNodes(mine->GetActors()); + //this->AddMissingNodes(mine->GetVolumes()); + this->AddMissingNode(mine->GetActiveCamera()); + this->RemoveUnusedNodes(); + } +} diff --git a/Rendering/SceneGraph/vtkRendererNode.h b/Rendering/SceneGraph/vtkRendererNode.h new file mode 100644 index 00000000000..2189b8840af --- /dev/null +++ b/Rendering/SceneGraph/vtkRendererNode.h @@ -0,0 +1,54 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkRendererNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkRendererNode - vtkViewNode specialized for vtkRenderers +// .SECTION Description +// State storage and graph traversal for vtkRenderer + +#ifndef vtkRendererNode_h +#define vtkRendererNode_h + +#include "vtkRenderingSceneGraphModule.h" // For export macro +#include "vtkViewNode.h" + +class vtkCollection; + +class VTKRENDERINGSCENEGRAPH_EXPORT vtkRendererNode : + public vtkViewNode +{ +public: + static vtkRendererNode* New(); + vtkTypeMacro(vtkRendererNode, vtkViewNode); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //Build containers for our child nodes. + virtual void Build(bool prepass); + + //Description: + //Synchronize our state + virtual void Synchronize(bool prepass); + +protected: + vtkRendererNode(); + ~vtkRendererNode(); + + int Size[2]; + +private: + vtkRendererNode(const vtkRendererNode&); // Not implemented. + void operator=(const vtkRendererNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/SceneGraph/vtkViewNode.cxx b/Rendering/SceneGraph/vtkViewNode.cxx new file mode 100644 index 00000000000..95aa5792459 --- /dev/null +++ b/Rendering/SceneGraph/vtkViewNode.cxx @@ -0,0 +1,285 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkViewNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkViewNode.h" + +#include "vtkCollectionIterator.h" +#include "vtkObjectFactory.h" +#include "vtkViewNodeCollection.h" +#include "vtkViewNodeFactory.h" + +//---------------------------------------------------------------------------- +const char *vtkViewNode::operation_type_strings[] = +{ + "noop", + "build", + "synchronize", + "render", + NULL +}; + +//---------------------------------------------------------------------------- +vtkCxxSetObjectMacro(vtkViewNode,Children,vtkViewNodeCollection); + +//---------------------------------------------------------------------------- +vtkCxxSetObjectMacro(vtkViewNode,MyFactory,vtkViewNodeFactory); + +//---------------------------------------------------------------------------- +vtkViewNode::vtkViewNode() +{ + this->Renderable = NULL; + this->Parent = NULL; + this->Children = vtkViewNodeCollection::New(); + this->PreparedNodes = vtkCollection::New(); + this->MyFactory = NULL; + + this->RenderTime = 0; +} + +//---------------------------------------------------------------------------- +vtkViewNode::~vtkViewNode() +{ + this->Parent = 0; + if (this->Children) + { + this->Children->Delete(); + this->Children = 0; + } + if (this->MyFactory) + { + this->MyFactory->Delete(); + this->MyFactory = 0; + } + if (this->PreparedNodes) + { + this->PreparedNodes->Delete(); + this->PreparedNodes = 0; + } +} + +//---------------------------------------------------------------------------- +void vtkViewNode::SetParent(vtkViewNode *p) +{ + this->Parent = p; +} + +//---------------------------------------------------------------------------- +vtkViewNode *vtkViewNode::GetParent() +{ + return this->Parent.GetPointer(); +} + + +//---------------------------------------------------------------------------- +void vtkViewNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +void vtkViewNode::PrepareNodes() +{ + this->PreparedNodes->RemoveAllItems(); +} + +//---------------------------------------------------------------------------- +void vtkViewNode::RemoveUnusedNodes() +{ + //remove viewnodes if their renderables are no longer present + vtkViewNodeCollection *nodes = this->GetChildren(); + vtkCollectionIterator *nit = nodes->NewIterator(); + nit->InitTraversal(); + while (!nit->IsDoneWithTraversal()) + { + vtkViewNode *node = vtkViewNode::SafeDownCast(nit->GetCurrentObject()); + if (node) + { + vtkObject *obj = node->GetRenderable(); + if (!this->PreparedNodes->IsItemPresent(obj)) + { + nodes->RemoveItem(node); + nit->InitTraversal(); //don't stumble over deleted node + } + } + nit->GoToNextItem(); + } + nit->Delete(); + + this->PrepareNodes(); +} + +//---------------------------------------------------------------------------- +void vtkViewNode::AddMissingNodes(vtkCollection *col) +{ + //add viewnodes for renderables that are not yet present + vtkViewNodeCollection *nodes = this->GetChildren(); + vtkCollectionIterator *rit = col->NewIterator(); + rit->InitTraversal(); + while (!rit->IsDoneWithTraversal()) + { + vtkObject *obj = rit->GetCurrentObject(); + if (obj) + { + this->PreparedNodes->AddItem(obj); + if (!nodes->IsRenderablePresent(obj)) + { + vtkViewNode *node = this->CreateViewNode(obj); + if (node) + { + nodes->AddItem(node); + node->SetParent(this); + node->Delete(); + } + } + } + rit->GoToNextItem(); + } + rit->Delete(); +} + +//---------------------------------------------------------------------------- +void vtkViewNode::AddMissingNode(vtkObject *obj) +{ + if (!obj) + { + return; + } + + //add viewnodes for renderables that are not yet present + vtkViewNodeCollection *nodes = this->GetChildren(); + this->PreparedNodes->AddItem(obj); + if (!nodes->IsRenderablePresent(obj)) + { + vtkViewNode *node = this->CreateViewNode(obj); + if (node) + { + nodes->AddItem(node); + node->SetParent(this); + node->Delete(); + } + } +} + +//---------------------------------------------------------------------------- +void vtkViewNode::TraverseAllPasses() +{ + this->Traverse(build); + this->Traverse(synchronize); + this->Traverse(render); +} + +//---------------------------------------------------------------------------- +void vtkViewNode::Traverse(int operation) +{ + this->Apply(operation,true); + + vtkCollectionIterator *it = this->Children->NewIterator(); + it->InitTraversal(); + while (!it->IsDoneWithTraversal()) + { + vtkViewNode *child = vtkViewNode::SafeDownCast(it->GetCurrentObject()); + child->Traverse(operation); + it->GoToNextItem(); + } + it->Delete(); + + this->Apply(operation, false); +} + +//---------------------------------------------------------------------------- +vtkViewNode *vtkViewNode::CreateViewNode(vtkObject *obj) +{ + vtkViewNode *ret = NULL; + if (!this->MyFactory) + { + vtkWarningMacro("Can not create view nodes without my own factory"); + } + else + { + ret = this->MyFactory->CreateNode(obj); + if (ret) + { + ret->Renderable = obj; + } + } + return ret; +} + +//---------------------------------------------------------------------------- +vtkViewNode *vtkViewNode::GetFirstAncestorOfType(const char *type) +{ + if (!this->Parent) + { + return NULL; + } + if (this->Parent->IsA(type)) + { + return this->Parent; + } + return this->Parent->GetFirstAncestorOfType(type); +} + +//---------------------------------------------------------------------------- +void vtkViewNode::SetRenderable(vtkObject *obj) +{ + this->Renderable = obj; +} + +//---------------------------------------------------------------------------- +void vtkViewNode::Apply(int operation, bool prepass) +{ + //cerr << this->GetClassName() << "(" << this << ") Apply(" + // << vtkViewNode::operation_type_strings[operation] << ")" << endl; + switch (operation) + { + case noop: + break; + case build: + this->Build(prepass); + break; + case synchronize: + this->Synchronize(prepass); + break; + case render: + this->Render(prepass); + break; + default: + cerr << "UNKNOWN OPERATION" << operation << endl; + } +} + +//---------------------------------------------------------------------------- +vtkViewNode* vtkViewNode::GetViewNodeFor(vtkObject *obj) +{ + if (this->Renderable == obj) + { + return this; + } + + vtkViewNode *owner = NULL; + vtkCollectionIterator *it = this->Children->NewIterator(); + it->InitTraversal(); + while (!it->IsDoneWithTraversal()) + { + vtkViewNode *child = vtkViewNode::SafeDownCast(it->GetCurrentObject()); + owner = child->GetViewNodeFor(obj); + if (owner) + { + break; + } + it->GoToNextItem(); + } + it->Delete(); + return owner; +} diff --git a/Rendering/SceneGraph/vtkViewNode.h b/Rendering/SceneGraph/vtkViewNode.h new file mode 100644 index 00000000000..b4b0c72fac2 --- /dev/null +++ b/Rendering/SceneGraph/vtkViewNode.h @@ -0,0 +1,142 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkViewNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkViewNode - a node within a VTK scene graph +// .SECTION Description +// This is the superclass for all nodes within a VTK scene graph. It +// contains the API for a node. It supports the essential operations such +// as graph creation, state storage and traversal. Child classes adapt this +// to VTK's major rendering classes. Grandchild classes adapt those to +// for APIs of different rendering libraries. + +#ifndef vtkViewNode_h +#define vtkViewNode_h + +#include "vtkRenderingSceneGraphModule.h" // For export macro +#include "vtkWeakPointer.h" //avoid ref loop to parent +#include "vtkObject.h" + +class vtkCollection; +class vtkViewNodeFactory; +class vtkViewNodeCollection; + +class VTKRENDERINGSCENEGRAPH_EXPORT vtkViewNode : + public vtkObject +{ +public: + vtkTypeMacro(vtkViewNode, vtkObject); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //This is the VTK class that this node stands in for. + vtkGetObjectMacro(Renderable, vtkObject); + + //Description: + //Builds myself. + virtual void Build(bool /* prepass */) {}; + + //Description: + //Ensures that my state agrees with my Renderable's. + virtual void Synchronize(bool /* prepass */) {}; + + //Description: + //Makes calls to make self visible. + virtual void Render(bool /*prepass*/) {}; + + //Description: + //Access the node that owns this one. + virtual void SetParent(vtkViewNode*); + virtual vtkViewNode * GetParent(); + + //Description: + //Access nodes that this one owns. + virtual void SetChildren(vtkViewNodeCollection*); + vtkGetObjectMacro(Children, vtkViewNodeCollection); + + //Description: + //A factory that creates particular subclasses for different + //rendering back ends. + virtual void SetMyFactory(vtkViewNodeFactory*); + vtkGetObjectMacro(MyFactory, vtkViewNodeFactory); + + //Description: + //Returns the view node that corresponding to the provided object + //Will return NULL if a match is not found in self or descendents + vtkViewNode* GetViewNodeFor(vtkObject *); + + // Description: + // Find the first parent/grandparent of the desired type + vtkViewNode *GetFirstAncestorOfType(const char *type); + + // Description: + // Alow explicit setting of the renderable for a + // view node. + virtual void SetRenderable(vtkObject *); + + // if you want to traverse your children in a specific order + // or way override this method + virtual void Traverse(int operation); + + virtual void TraverseAllPasses(); + + //Descriptions: + //Allows smart caching + unsigned long RenderTime; + + //Description: + //internal mechanics of graph traversal and actions + enum operation_type{noop, build, synchronize, render}; + +protected: + vtkViewNode(); + ~vtkViewNode(); + + static const char* operation_type_strings[]; + + void Apply(int operation, bool prepass); + + // Description:: + //convienience method to add node or nodes + //if missing from our current list + void AddMissingNode(vtkObject *obj); + void AddMissingNodes(vtkCollection *col); + + // Description:: + // Called first before adding missing nodes. + // Keeps track of the nodes that should be in the collection + void PrepareNodes(); + vtkCollection *PreparedNodes; + + // Description: + // Called after PrepareNodes and AddMissingNodes + // removes any extra leftover nodes + void RemoveUnusedNodes(); + + //Description: + //Create the correct ViewNode subclass for the passed in object. + virtual vtkViewNode *CreateViewNode(vtkObject *obj); + + vtkObject *Renderable; + vtkWeakPointer Parent; + vtkViewNodeCollection *Children; + vtkViewNodeFactory *MyFactory; + + friend class vtkViewNodeFactory; + +private: + vtkViewNode(const vtkViewNode&); // Not implemented. + void operator=(const vtkViewNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/SceneGraph/vtkViewNodeCollection.cxx b/Rendering/SceneGraph/vtkViewNodeCollection.cxx new file mode 100644 index 00000000000..b91bc246987 --- /dev/null +++ b/Rendering/SceneGraph/vtkViewNodeCollection.cxx @@ -0,0 +1,71 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkViewNodeCollection.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkViewNodeCollection.h" + +#include "vtkCollectionIterator.h" +#include "vtkObjectFactory.h" +#include "vtkViewNode.h" + +//============================================================================ +vtkStandardNewMacro(vtkViewNodeCollection); + +//---------------------------------------------------------------------------- +void vtkViewNodeCollection::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +void vtkViewNodeCollection::AddItem(vtkViewNode *a) +{ + this->vtkCollection::AddItem(a); +} + +//---------------------------------------------------------------------------- +vtkViewNode *vtkViewNodeCollection::GetNextItem() +{ + return static_cast(this->GetNextItemAsObject()); +} + +//---------------------------------------------------------------------------- +vtkViewNode *vtkViewNodeCollection::GetNextViewNode( + vtkCollectionSimpleIterator &cookie) +{ + return static_cast(this->GetNextItemAsObject(cookie)); +} + +//---------------------------------------------------------------------------- +bool vtkViewNodeCollection::IsRenderablePresent(vtkObject *obj) +{ + vtkCollectionIterator *it = this->NewIterator(); + it->InitTraversal(); + bool found = false; + while (!found && !it->IsDoneWithTraversal()) + { + vtkViewNode *vn = vtkViewNode::SafeDownCast(it->GetCurrentObject()); + if (vn) + { + vtkObject *nobj = vn->GetRenderable(); + if (nobj == obj) + { + found = true; + } + it->GoToNextItem(); + } + } + it->Delete(); + + return found; +} diff --git a/Rendering/SceneGraph/vtkViewNodeCollection.h b/Rendering/SceneGraph/vtkViewNodeCollection.h new file mode 100644 index 00000000000..382a18585ff --- /dev/null +++ b/Rendering/SceneGraph/vtkViewNodeCollection.h @@ -0,0 +1,66 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkViewNodeCollection.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkViewNodeCollection - collection of view nodes +// .SECTION Description +// vtk centric collection of vtkViewNodes + +#ifndef vtkViewNodeCollection_h +#define vtkViewNodeCollection_h + +#include "vtkRenderingSceneGraphModule.h" // For export macro +#include "vtkCollection.h" + +class vtkViewNode; + +class VTKRENDERINGSCENEGRAPH_EXPORT vtkViewNodeCollection : + public vtkCollection +{ +public: + static vtkViewNodeCollection* New(); + vtkTypeMacro(vtkViewNodeCollection, vtkCollection); + void PrintSelf(ostream& os, vtkIndent indent); + + // Description: + // Add a ViewNode to the list. + void AddItem(vtkViewNode *a); + + // Description: + // Get the next ViewNode in the list. NULL is returned when the collection is + // exhausted. + vtkViewNode *GetNextItem(); + + // Description: + // Reentrant safe way to get an object in a collection. Just pass the + // same cookie back and forth. + vtkViewNode *GetNextViewNode(vtkCollectionSimpleIterator &cookie); + + // Description: + // Return true only if we have viewnode for obj. + bool IsRenderablePresent(vtkObject *obj); + +protected: + vtkViewNodeCollection() {}; + ~vtkViewNodeCollection() {}; + +private: + // hide the standard AddItem from the user and the compiler. + void AddItem(vtkObject *o) + { this->vtkCollection::AddItem(o); } + + vtkViewNodeCollection(const vtkViewNodeCollection&); // Not implemented. + void operator=(const vtkViewNodeCollection&); // Not implemented. +}; + +#endif diff --git a/Rendering/SceneGraph/vtkViewNodeFactory.cxx b/Rendering/SceneGraph/vtkViewNodeFactory.cxx new file mode 100644 index 00000000000..f90adf58923 --- /dev/null +++ b/Rendering/SceneGraph/vtkViewNodeFactory.cxx @@ -0,0 +1,94 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkViewNodeFactory.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkViewNodeFactory.h" +#include "vtkObjectFactory.h" +#include "vtkViewNode.h" + +#include +#include + +//============================================================================ +class vtkViewNodeFactory::vtkInternals +{ +public: + std::map Overrides; + + vtkInternals() + { + } + + ~vtkInternals() + { + this->Overrides.clear(); + } +}; + +//============================================================================ +vtkStandardNewMacro(vtkViewNodeFactory); + +//---------------------------------------------------------------------------- +vtkViewNodeFactory::vtkViewNodeFactory() +{ + this->Internals = new vtkInternals; +} + +//---------------------------------------------------------------------------- +vtkViewNodeFactory::~vtkViewNodeFactory() +{ + delete this->Internals; +} + +//---------------------------------------------------------------------------- +void vtkViewNodeFactory::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +vtkViewNode *vtkViewNodeFactory::CreateNode(vtkObject *who) +{ + if (!who) + { + return NULL; + } + const char *forwhom = who->GetClassName(); + vtkViewNode *vn = this->CreateNode(forwhom); + if (vn) + { + vn->SetRenderable(who); + } + return vn; +} + +//---------------------------------------------------------------------------- +vtkViewNode *vtkViewNodeFactory::CreateNode(const char *forwhom) +{ + if (this->Internals->Overrides.find(forwhom) == + this->Internals->Overrides.end()) + { + return NULL; + } + vtkViewNode *(*func)() = this->Internals->Overrides.find(forwhom)->second; + vtkViewNode *vn = func(); + vn->SetMyFactory(this); + return vn; +} + +//---------------------------------------------------------------------------- +void vtkViewNodeFactory::RegisterOverride + (const char *name, vtkViewNode *(*func)()) +{ + this->Internals->Overrides[name] = func; +} diff --git a/Rendering/SceneGraph/vtkViewNodeFactory.h b/Rendering/SceneGraph/vtkViewNodeFactory.h new file mode 100644 index 00000000000..5e1dc2642ee --- /dev/null +++ b/Rendering/SceneGraph/vtkViewNodeFactory.h @@ -0,0 +1,63 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkViewNodeFactory.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkViewNodeFactory - factory that chooses vtkViewNodes to create +// .SECTION Description +// Class tells VTK which specific vtkViewNode subclass to make when it is +// asked to make a vtkViewNode for a particular renderable. modules for +// different rendering backends are expected to use this to customize the +// set of instances for their own purposes + +#ifndef vtkViewNodeFactory_h +#define vtkViewNodeFactory_h + +#include "vtkRenderingSceneGraphModule.h" // For export macro +#include "vtkObject.h" + +class vtkViewNode; + +class VTKRENDERINGSCENEGRAPH_EXPORT vtkViewNodeFactory : + public vtkObject +{ +public: + static vtkViewNodeFactory* New(); + vtkTypeMacro(vtkViewNodeFactory, vtkObject); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //Give a functin pointer to a class that will manufacture a + //vtkViewNode when given a class name string. + void RegisterOverride(const char *name, vtkViewNode *(*func)()); + + //Description: + //Creates and returns a vtkViewNode for the provided renderable. + vtkViewNode *CreateNode(vtkObject *); + + //Description: + //Creates and returns a vtkViewNode for the provided class name. + vtkViewNode *CreateNode(const char *); + +protected: + vtkViewNodeFactory(); + ~vtkViewNodeFactory(); + +private: + vtkViewNodeFactory(const vtkViewNodeFactory&); // Not implemented. + void operator=(const vtkViewNodeFactory&); // Not implemented. + + class vtkInternals; + vtkInternals *Internals; +}; + +#endif diff --git a/Rendering/SceneGraph/vtkWindowNode.cxx b/Rendering/SceneGraph/vtkWindowNode.cxx new file mode 100644 index 00000000000..36e62c7af49 --- /dev/null +++ b/Rendering/SceneGraph/vtkWindowNode.cxx @@ -0,0 +1,113 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkWindowNode.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +#include "vtkWindowNode.h" + +#include "vtkFloatArray.h" +#include "vtkObjectFactory.h" +#include "vtkRenderWindow.h" +#include "vtkRenderer.h" +#include "vtkRendererCollection.h" +#include "vtkUnsignedCharArray.h" +#include "vtkViewNodeCollection.h" + +//============================================================================ +vtkStandardNewMacro(vtkWindowNode); + +//---------------------------------------------------------------------------- +vtkWindowNode::vtkWindowNode() +{ + this->Size[0] = 0; + this->Size[1] = 0; + this->ColorBuffer = vtkUnsignedCharArray::New(); + this->ZBuffer = vtkFloatArray::New(); +} + +//---------------------------------------------------------------------------- +vtkWindowNode::~vtkWindowNode() +{ + this->ColorBuffer->Delete(); + this->ColorBuffer = 0; + this->ZBuffer->Delete(); + this->ZBuffer = 0; +} + +//---------------------------------------------------------------------------- +void vtkWindowNode::PrintSelf(ostream& os, vtkIndent indent) +{ + this->Superclass::PrintSelf(os, indent); +} + +//---------------------------------------------------------------------------- +void vtkWindowNode::Build(bool prepass) +{ + if (prepass) + { + vtkRenderWindow *mine = vtkRenderWindow::SafeDownCast + (this->GetRenderable()); + if (!mine) + { + return; + } + + this->PrepareNodes(); + this->AddMissingNodes(mine->GetRenderers()); + this->RemoveUnusedNodes(); + } +} + +//---------------------------------------------------------------------------- +void vtkWindowNode::Synchronize(bool prepass) +{ + if (prepass) + { + vtkRenderWindow *mine = vtkRenderWindow::SafeDownCast + (this->GetRenderable()); + if (!mine) + { + return; + } + /* + GetAAFrames() vtkRenderWindow virtual + GetActualSize() vtkWindow + GetAlphaBitPlanes() vtkRenderWindow virtual + GetDoubleBuffer() vtkWindow virtual + GetDPI() vtkWindow virtual + GetFDFrames() vtkRenderWindow virtual + GetFullScreen() vtkRenderWindow virtual + GetLineSmoothing() vtkRenderWindow virtual + GetMapped() vtkWindow virtual + GetMTime() vtkObject virtual + GetMultiSamples() vtkRenderWindow virtual + GetNeverRendered() vtkRenderWindow virtual + GetNumberOfLayers() vtkRenderWindow virtual + GetOffScreenRendering() vtkWindow virtual + GetPointSmoothing() vtkRenderWindow virtual + GetPolygonSmoothing() vtkRenderWindow virtual + GetPosition() vtkWindow virtual + GetScreenSize()=0 vtkWindow pure virtual + */ + int * sz = mine->GetSize(); + this->Size[0] = sz[0]; + this->Size[1] = sz[1]; + /* + GetStereoType() vtkRenderWindow virtual + GetSubFrames() vtkRenderWindow virtual + GetSwapBuffers() vtkRenderWindow virtual + GetTileScale() vtkWindow virtual + GetTileViewport() vtkWindow virtual + GetUseConstantFDOffsets() vtkRenderWindow virtual + */ + } +} diff --git a/Rendering/SceneGraph/vtkWindowNode.h b/Rendering/SceneGraph/vtkWindowNode.h new file mode 100644 index 00000000000..d649c22de08 --- /dev/null +++ b/Rendering/SceneGraph/vtkWindowNode.h @@ -0,0 +1,76 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: vtkWindowNode.h + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// .NAME vtkWindowNode - vtkViewNode specialized for vtkRenderWindows +// .SECTION Description +// State storage and graph traversal for vtkRenderWindow + +#ifndef vtkWindowNode_h +#define vtkWindowNode_h + +#include "vtkRenderingSceneGraphModule.h" // For export macro +#include "vtkViewNode.h" + +class vtkUnsignedCharArray; +class vtkFloatArray; + +class VTKRENDERINGSCENEGRAPH_EXPORT vtkWindowNode : + public vtkViewNode +{ +public: + static vtkWindowNode* New(); + vtkTypeMacro(vtkWindowNode, vtkViewNode); + void PrintSelf(ostream& os, vtkIndent indent); + + //Description: + //Build containers for our child nodes. + virtual void Build(bool prepass); + + //Description: + //Get state of my renderable. + virtual void Synchronize(bool prepass); + + // Description: + // Return the size of the last rendered image + virtual int *GetSize() { + return this->Size; } + + // Description: + // Get the most recent color buffer RGBA + virtual vtkUnsignedCharArray *GetColorBuffer() + { return this->ColorBuffer; } + + // Description: + // Get the most recent zbufer buffer + virtual vtkFloatArray *GetZBuffer() + { return this->ZBuffer; } + +protected: + vtkWindowNode(); + ~vtkWindowNode(); + + //TODO: use a map with string keys being renderable's member name + //state + int Size[2]; + + // stores the results of a render + vtkUnsignedCharArray*ColorBuffer; + vtkFloatArray *ZBuffer; + +private: + vtkWindowNode(const vtkWindowNode&); // Not implemented. + void operator=(const vtkWindowNode&); // Not implemented. +}; + +#endif diff --git a/Rendering/Tk/Testing/Python/cursor3D.py b/Rendering/Tk/Testing/Python/cursor3D.py index a9f428e7fed..92e72adeb33 100755 --- a/Rendering/Tk/Testing/Python/cursor3D.py +++ b/Rendering/Tk/Testing/Python/cursor3D.py @@ -171,11 +171,8 @@ def SetCursor(x, y, z): # color_transfer_function[2]) volume_property.SetScalarOpacity(opacity_transfer_function) - composite_function = vtk.vtkVolumeRayCastCompositeFunction() - - volume_mapper = vtk.vtkVolumeRayCastMapper() + volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper() volume_mapper.SetInputConnection(reader.GetOutputPort()) - volume_mapper.SetVolumeRayCastFunction(composite_function) volume = vtk.vtkVolume() volume.SetMapper(volume_mapper) diff --git a/Rendering/Tk/Testing/Tcl/cursor3D.tcl b/Rendering/Tk/Testing/Tcl/cursor3D.tcl index 210aefaf7c6..a1ee1a49afb 100644 --- a/Rendering/Tk/Testing/Tcl/cursor3D.tcl +++ b/Rendering/Tk/Testing/Tcl/cursor3D.tcl @@ -92,11 +92,8 @@ vtkVolumeProperty volume_property volume_property SetColor color_transfer_function volume_property SetScalarOpacity opacity_transfer_function -vtkVolumeRayCastCompositeFunction composite_function - -vtkVolumeRayCastMapper volume_mapper +vtkFixedPointVolumeRayCastMapper volume_mapper volume_mapper SetInputConnection [reader GetOutputPort] - volume_mapper SetVolumeRayCastFunction composite_function vtkVolume volume volume SetMapper volume_mapper diff --git a/Rendering/Volume/Testing/Cxx/CMakeLists.txt b/Rendering/Volume/Testing/Cxx/CMakeLists.txt index 0cf4c60cb5d..a2a02a6c83a 100644 --- a/Rendering/Volume/Testing/Cxx/CMakeLists.txt +++ b/Rendering/Volume/Testing/Cxx/CMakeLists.txt @@ -56,8 +56,11 @@ set (VolumeOpenGL2CxxTests TestGPURayCastCameraInsideSmallSpacing.cxx TestGPURayCastCellData.cxx TestGPURayCastClipping.cxx + TestGPURayCastClippingUserTransform.cxx + TestGPURayCastClippingPolyData.cxx TestGPURayCastFourComponentsDependentGradient.cxx TestGPURayCastGradientOpacity.cxx + TestGPURayCastGradientOpacityLight.cxx TestGPURayCastPositionalLights.cxx TestGPURayCastReleaseResources.cxx TestGPURayCastRenderDepthToImage.cxx @@ -68,10 +71,13 @@ set (VolumeOpenGL2CxxTests TestGPURayCastTwoComponentsDependentGradient.cxx TestGPURayCastTwoComponentsGradient.cxx TestGPURayCastTwoComponentsIndependent.cxx + TestGPURayCastVolumeDepthPass.cxx TestGPURayCastVolumeLightKit.cxx TestGPURayCastVolumePolyData.cxx TestGPURayCastVolumeRotation.cxx TestGPURayCastVolumeScale.cxx + TestProjectedTetrahedraTransform.cxx + TestGPURayCastVolumePicking.cxx ) # everyone gets these tests diff --git a/Rendering/Volume/Testing/Cxx/TestGPURayCastClippingPolyData.cxx b/Rendering/Volume/Testing/Cxx/TestGPURayCastClippingPolyData.cxx new file mode 100644 index 00000000000..e0b09e73235 --- /dev/null +++ b/Rendering/Volume/Testing/Cxx/TestGPURayCastClippingPolyData.cxx @@ -0,0 +1,157 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestGPURayCastVolumePolyData.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test covers additive method. +// This test volume renders a synthetic dataset with unsigned char values, +// with the additive method. + +#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 + + +/// Tests volume clipping when intermixed with geometry. +int TestGPURayCastClippingPolyData(int argc, char *argv[]) +{ + double scalarRange[2]; + + vtkNew outlineActor; + vtkNew outlineMapper; + vtkNew volumeMapper; + + vtkNew reader; + const char* volumeFile = vtkTestUtilities::ExpandDataFileName( + argc, argv, "Data/vase_1comp.vti"); + reader->SetFileName(volumeFile); + volumeMapper->SetInputConnection(reader->GetOutputPort()); + + /// Outline filter + vtkNew outlineFilter; + outlineFilter->SetInputConnection(reader->GetOutputPort()); + outlineMapper->SetInputConnection(outlineFilter->GetOutputPort()); + outlineActor->SetMapper(outlineMapper.GetPointer()); + + volumeMapper->GetInput()->GetScalarRange(scalarRange); + volumeMapper->SetSampleDistance(0.1); + volumeMapper->SetAutoAdjustSampleDistances(0); + volumeMapper->SetBlendModeToComposite(); + + vtkNew renWin; + renWin->SetMultiSamples(0); + vtkNew ren; + renWin->AddRenderer(ren.GetPointer()); + renWin->SetSize(400, 400); + ren->SetBackground(0.2, 0.2, 0.5); + + vtkNew iren; + vtkNew style; + iren->SetInteractorStyle(style.GetPointer()); + iren->SetRenderWindow(renWin.GetPointer()); + + vtkNew scalarOpacity; + scalarOpacity->AddPoint(50, 0.0); + scalarOpacity->AddPoint(75, 1.0); + + vtkNew volumeProperty; + volumeProperty->ShadeOn(); + volumeProperty->SetInterpolationType(VTK_LINEAR_INTERPOLATION); + volumeProperty->SetScalarOpacity(scalarOpacity.GetPointer()); + + vtkSmartPointer colorTransferFunction = + volumeProperty->GetRGBTransferFunction(0); + colorTransferFunction->RemoveAllPoints(); + colorTransferFunction->AddRGBPoint(scalarRange[0], 0.6, 0.4, 0.1); + + vtkSmartPointer volume = vtkSmartPointer::New(); + volume->SetMapper(volumeMapper.GetPointer()); + volume->SetProperty(volumeProperty.GetPointer()); + + /// Sphere + int dims[3]; + double spacing[3], sphereCenter[3], origin[3]; + reader->Update(); + vtkSmartPointer im = reader->GetOutput(); + im->GetDimensions(dims); + im->GetOrigin(origin); + im->GetSpacing(spacing); + + sphereCenter[0] = origin[0] + spacing[0]*dims[0]/2.5; + sphereCenter[1] = origin[1] + spacing[1]*dims[1]/2.5; + sphereCenter[2] = origin[2] + spacing[2]*dims[2]/2.775; + + vtkNew sphereSource; + sphereSource->SetCenter(sphereCenter); + sphereSource->SetRadius(dims[1]/4.0); + sphereSource->SetPhiResolution(40); + sphereSource->SetThetaResolution(40); + vtkNew sphereMapper; + vtkNew sphereActor; + sphereMapper->SetInputConnection(sphereSource->GetOutputPort()); + sphereActor->SetMapper(sphereMapper.GetPointer()); + + ren->AddViewProp(volume.GetPointer()); + ren->AddActor(outlineActor.GetPointer()); + ren->AddActor(sphereActor.GetPointer()); + + /// Clipping planes + vtkNew clipPlane1; + clipPlane1->SetOrigin(sphereCenter[0], sphereCenter[1], sphereCenter[2]); + clipPlane1->SetNormal(1.0, 0.0, 0.0); + vtkNew clipPlane2; + clipPlane2->SetOrigin(sphereCenter[0], sphereCenter[1], sphereCenter[2]); + clipPlane2->SetNormal(0.2, -0.2, 0.0); + + vtkNew clipPlaneCollection; + clipPlaneCollection->AddItem(clipPlane1.GetPointer()); + clipPlaneCollection->AddItem(clipPlane2.GetPointer()); + volumeMapper->SetClippingPlanes(clipPlaneCollection.GetPointer()); + + ren->ResetCamera(); + ren->GetActiveCamera()->Azimuth(-30); + ren->GetActiveCamera()->Elevation(25); + ren->GetActiveCamera()->OrthogonalizeViewUp(); + renWin->Render(); + + iren->Initialize(); + + int retVal = vtkRegressionTestImage( renWin.GetPointer() ); + if( retVal == vtkRegressionTester::DO_INTERACTOR) + { + iren->Start(); + } + + return !retVal; +} diff --git a/Rendering/Volume/Testing/Cxx/TestGPURayCastClippingUserTransform.cxx b/Rendering/Volume/Testing/Cxx/TestGPURayCastClippingUserTransform.cxx new file mode 100644 index 00000000000..0df88f42938 --- /dev/null +++ b/Rendering/Volume/Testing/Cxx/TestGPURayCastClippingUserTransform.cxx @@ -0,0 +1,369 @@ +/*========================================================================= +Program: Visualization Toolkit +Module: TestGPURayCastClippingUserTransform.cxx +Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen +All rights reserved. +See Copyright.txt or http://www.kitware.com/Copyright.htm for details. +This software is distributed WITHOUT ANY WARRANTY; without even +the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +PURPOSE. See the above copyright notice for more information. +=========================================================================*/ + +// Description +// This test creates a vtkImageData with two components. +// The data is volume rendered considering the two components as independent. +#include +#include +using namespace std; + +#include "vtkCamera.h" +#include "vtkColorTransferFunction.h" +#include "vtkGPUVolumeRayCastMapper.h" +#include "vtkImageData.h" +#include "vtkInteractorStyleTrackballCamera.h" +#include "vtkNew.h" +#include "vtkPiecewiseFunction.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkVolume.h" +#include "vtkVolumeProperty.h" +#include "vtkUnsignedShortArray.h" +#include "vtkImageReader2.h" +#include "vtkPlane.h" +#include "vtkPlaneCollection.h" +#include "vtkPointData.h" +#include "vtkInteractorStyleImage.h" +#include "vtkCommand.h" +#include "vtkOutlineFilter.h" +#include "vtkPolyDataMapper.h" +#include "vtkActor.h" +#include "vtkMatrix4x4.h" + +#include "vtkTestUtilities.h" +#include "vtkRegressionTestImage.h" + + +static double* ComputeNormal(double* reference, bool flipSign) +{ + double* normal = new double[3]; + if (flipSign) + { + normal[0] = -reference[0]; + normal[1] = -reference[1]; + normal[2] = -reference[2]; + } + else + { + normal[0] = reference[0]; + normal[1] = reference[1]; + normal[2] = reference[2]; + } + + return normal; +} + + +static double* ComputeOrigin(double* focalPoint, double* reference, + double distance, bool flipSign) +{ + + double* origin = new double[3]; + if (flipSign) + { + origin[0] = focalPoint[0] - distance * reference[0]; + origin[1] = focalPoint[1] - distance * reference[1]; + origin[2] = focalPoint[2] - distance * reference[2]; + } + else + { + origin[0] = focalPoint[0] + distance * reference[0]; + origin[1] = focalPoint[1] + distance * reference[1]; + origin[2] = focalPoint[2] + distance * reference[2]; + } + + return origin; +} + + +static void UpdateFrontClippingPlane(vtkPlane* frontClippingPlane, + double* normal, double* focalPoint, + double slabThickness) +{ + // The front plane is the start of ray cast + // The front normal should be in the same direction as the camera + // direction (opposite to the plane facing direction) + double* frontNormal = ComputeNormal(normal, true); + + // Get the origin of the front clipping plane + double halfSlabThickness = slabThickness / 2; + double* frontOrigin = ComputeOrigin(focalPoint, normal, halfSlabThickness, false); + + // Set the normal and origin of the front clipping plane + frontClippingPlane->SetNormal(frontNormal); + frontClippingPlane->SetOrigin(frontOrigin); +} + + +static void UpdateRearClippingPlane(vtkPlane* rearClippingPlane, double* normal, + double* focalPoint, double slabThickness) +{ + + // The rear normal is the end of ray cast + // The rear normal should be in the opposite direction to the + // camera direction (same as the plane facing direction) + double* rearNormal = ComputeNormal(normal, false); + + // Get the origin of the rear clipping plane + double halfSlabThickness = slabThickness / 2; + double* rearOrigin = ComputeOrigin(focalPoint, normal, halfSlabThickness, true); + + // Set the normal and origin of the rear clipping plane + rearClippingPlane->SetNormal(rearNormal); + rearClippingPlane->SetOrigin(rearOrigin); +} + + +class vtkInteractorStyleCallback : public vtkCommand +{ +public: + static vtkInteractorStyleCallback *New() + { + return new vtkInteractorStyleCallback; + } + + virtual void Execute(vtkObject *caller, unsigned long, void*) + { + vtkInteractorStyle* style = reinterpret_cast(caller); + + vtkCamera * camera = style->GetCurrentRenderer()->GetActiveCamera(); + //vtkCamera *camera = reinterpret_cast(caller); + + // Get the normal and focal point of the camera + double* normal = camera->GetViewPlaneNormal(); + double* focalPoint = camera->GetFocalPoint(); + + // Fixed slab thickness + slabThickness = 3.0; + UpdateFrontClippingPlane(frontClippingPlane, normal, focalPoint, slabThickness); + UpdateRearClippingPlane(rearClippingPlane, normal, focalPoint, slabThickness); + } + + vtkInteractorStyleCallback(){} + + void SetFrontClippingPlane(vtkPlane* fcPlane) + { + this->frontClippingPlane = fcPlane; + } + + void SetRearClippingPlane(vtkPlane* rcPlane) + { + this->rearClippingPlane = rcPlane; + } + + double slabThickness; + vtkPlane* frontClippingPlane; + vtkPlane* rearClippingPlane; +}; + + +int TestGPURayCastClippingUserTransform(int argc, char *argv[]) +{ + int width = 256; + int height = 256; + int depth = 148; + double spacing[3] = { 1.4844, 1.4844, 1.2 }; + + // Read the image + streampos size; + char * memblock; + + char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, + "Data/MagnitudeImage_256x256x148"); + + ifstream file(fname, ios::in | ios::binary | ios::ate); + if (file.is_open()) + { + size = file.tellg(); + memblock = new char[size]; + file.seekg(0, ios::beg); + file.read(memblock, size); + file.close(); + } + else + { + cout << "Unable to open file"; + return 1; + } + + // Convert to short + unsigned short* shortData = new unsigned short[size / 2]; + int idx = 0; + int idx2 = 0; + for (idx = 0; idx < size / 2; idx ++) { + idx2 = idx * 2; + shortData[idx] = (short)(((memblock[idx2] & 0xFF) << 8) | (memblock[idx2+1] & 0xFF)); + } + + // + int volumeSizeInSlice = width * height * depth; + vtkNew dataArrayMag; + dataArrayMag->Allocate(volumeSizeInSlice, 0); + dataArrayMag->SetNumberOfComponents(1); + dataArrayMag->SetNumberOfTuples(volumeSizeInSlice); + dataArrayMag->SetArray(shortData, volumeSizeInSlice, 1); + + vtkNew imageData; + imageData->SetDimensions(width, height, depth); + imageData->SetSpacing(spacing); + imageData->GetPointData()->SetScalars(dataArrayMag.GetPointer()); + + // Create a clipping plane + vtkNew frontClippingPlane; + vtkNew rearClippingPlane; + + // Create a clipping plane collection + vtkNew clippingPlaneCollection; + clippingPlaneCollection->AddItem(frontClippingPlane.GetPointer()); + clippingPlaneCollection->AddItem(rearClippingPlane.GetPointer()); + + // Create a mapper + vtkNew volumeMapper; + //volumeMapper->SetInputConnection(reader->GetOutputPort()); + volumeMapper->SetInputData(imageData.GetPointer()); + volumeMapper->SetBlendModeToMaximumIntensity(); + volumeMapper->AutoAdjustSampleDistancesOff(); + volumeMapper->SetSampleDistance(1.0); + volumeMapper->SetImageSampleDistance(1.0); + volumeMapper->SetClippingPlanes(clippingPlaneCollection.GetPointer()); + + // Create volume scale opacity + vtkNew volumeScalarOpacity; + volumeScalarOpacity->AddPoint(0, 0.0); + volumeScalarOpacity->AddPoint(32767, 1.0); + volumeScalarOpacity->ClampingOn(); + + // Create a property + vtkNew volumeProperty; + volumeProperty->SetInterpolationTypeToLinear(); + volumeProperty->ShadeOff(); + volumeProperty->SetAmbient(1.0); + volumeProperty->SetDiffuse(0.0); + volumeProperty->SetSpecular(0.0); + volumeProperty->IndependentComponentsOn(); + volumeProperty->SetScalarOpacity(volumeScalarOpacity.GetPointer()); + volumeProperty->SetColor(volumeScalarOpacity.GetPointer()); + + // Create a volume + vtkNew volume; + volume->SetMapper(volumeMapper.GetPointer()); + volume->SetProperty(volumeProperty.GetPointer()); + volume->PickableOff(); + + // Rotate the blue props + double rowVector[3] = { 0.0, 0.0, -1.0 }; + double columnVector[3] = { 1.0, 0.0, 0.0 }; + double normalVector[3]; + vtkMath::Cross(rowVector, columnVector, normalVector); + double position[3] = { 0.0, 0.0, 0.0 }; + + vtkSmartPointer matrix = vtkSmartPointer::New(); + matrix->Identity(); + matrix->SetElement(0, 0, rowVector[0]); + matrix->SetElement(0, 1, rowVector[1]); + matrix->SetElement(0, 2, rowVector[2]); + matrix->SetElement(0, 3, position[0]); + matrix->SetElement(1, 0, columnVector[0]); + matrix->SetElement(1, 1, columnVector[1]); + matrix->SetElement(1, 2, columnVector[2]); + matrix->SetElement(1, 3, position[1]); + matrix->SetElement(2, 0, normalVector[0]); + matrix->SetElement(2, 1, normalVector[1]); + matrix->SetElement(2, 2, normalVector[2]); + matrix->SetElement(2, 3, position[2]); + + volume->SetUserMatrix(matrix); + + // Create a outline filter + vtkNew outlineFilter; + outlineFilter->SetInputData(imageData.GetPointer()); + + // Create an outline mapper + vtkNew outlineMapper; + outlineMapper->SetInputConnection(outlineFilter->GetOutputPort()); + + vtkNew outline; + outline->SetMapper(outlineMapper.GetPointer()); + outline->PickableOff(); + + // Create a renderer + vtkNew ren; + ren->AddViewProp(volume.GetPointer()); + ren->AddViewProp(outline.GetPointer()); + + // Get the center of volume + double* center = volume->GetCenter(); + double cameraFocal[3]; + cameraFocal[0] = center[0]; + cameraFocal[1] = center[1]; + cameraFocal[2] = center[2]; + + double cameraViewUp[3] = { 0.00, -1.00, 0.00 }; + double cameraNormal[3] = { 0.00, 0.00, -1.00 }; + double cameraDistance = 1000.0; + + double cameraPosition[3]; + cameraPosition[0] = cameraFocal[0] + cameraDistance * cameraNormal[0]; + cameraPosition[1] = cameraFocal[1] + cameraDistance * cameraNormal[1]; + cameraPosition[2] = cameraFocal[2] + cameraDistance * cameraNormal[2]; + + // Update clipping planes + UpdateFrontClippingPlane(frontClippingPlane.GetPointer(), cameraNormal, cameraFocal, 3.0); + UpdateRearClippingPlane(rearClippingPlane.GetPointer(), cameraNormal, cameraFocal, 3.0); + + // Get the active camera + vtkCamera* camera = ren->GetActiveCamera(); + camera->ParallelProjectionOn(); + camera->SetParallelScale(250); + camera->SetPosition(cameraPosition); + camera->SetFocalPoint(cameraFocal); + camera->SetViewUp(cameraViewUp); + + // Create a render window + vtkNew renWin; + renWin->SetSize(500, 500); + renWin->AddRenderer(ren.GetPointer()); + + // Create a style + vtkNew style; + style->SetInteractionModeToImage3D(); + + // Create a interactor style callback + vtkNew interactorStyleCallback; + interactorStyleCallback->frontClippingPlane = frontClippingPlane.GetPointer(); + interactorStyleCallback->rearClippingPlane = rearClippingPlane.GetPointer(); + style->AddObserver(vtkCommand::InteractionEvent, interactorStyleCallback.GetPointer()); + + // Create an interactor + vtkNew iren; + iren->SetInteractorStyle(style.GetPointer()); + iren->SetRenderWindow(renWin.GetPointer()); + + // Start + iren->Initialize(); + renWin->Render(); + + int retVal = vtkRegressionTestImageThreshold(renWin.GetPointer(), 70); + + if (retVal == vtkRegressionTester::DO_INTERACTOR) + { + iren->Start(); + } + + + delete[] memblock; + delete[] shortData; + delete[] fname; + + return !retVal; +} diff --git a/Rendering/Volume/Testing/Cxx/TestGPURayCastGradientOpacityLight.cxx b/Rendering/Volume/Testing/Cxx/TestGPURayCastGradientOpacityLight.cxx new file mode 100644 index 00000000000..39f96cb4c6c --- /dev/null +++ b/Rendering/Volume/Testing/Cxx/TestGPURayCastGradientOpacityLight.cxx @@ -0,0 +1,108 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestGPURayCastGradientOpacityLight.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// Tests gradient opacity TF support when combined with vtkLightKit. + +#include "vtkCamera.h" +#include "vtkColorTransferFunction.h" +#include "vtkGPUVolumeRayCastMapper.h" +#include "vtkInteractorStyleTrackballCamera.h" +#include "vtkMetaImageReader.h" +#include "vtkNew.h" +#include "vtkPiecewiseFunction.h" +#include "vtkRegressionTestImage.h" +#include "vtkRenderer.h" +#include "vtkRenderWindow.h" +#include "vtkRenderWindowInteractor.h" +#include "vtkTestUtilities.h" +#include "vtkVolume.h" +#include "vtkVolumeProperty.h" +#include "vtkLightKit.h" + + +int TestGPURayCastGradientOpacityLight(int argc, char* argv[]) +{ + cout << "CTEST_FULL_OUTPUT (Avoid ctest truncation of output)" << endl; + + vtkNew renWin; + renWin->SetSize(400, 401); + renWin->SetMultiSamples(0); + + vtkNew ren; + renWin->AddRenderer(ren.GetPointer()); + ren->SetBackground(0.1, 0.4, 0.2); + + // Setup lights + vtkNew lightKit; + lightKit->AddLightsToRenderer(ren.GetPointer()); + + vtkNew iren; + iren->SetRenderWindow(renWin.GetPointer()); + + vtkNew style; + iren->SetInteractorStyle(style.GetPointer()); + + // Load data + char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, + "Data/HeadMRVolume.mhd"); + + vtkNew reader; + reader->SetFileName(fname); + reader->Update(); + delete [] fname; + + vtkNew mapper; + mapper->SetInputConnection(reader->GetOutputPort()); + + // Prepare TFs + vtkNew ctf; + ctf->AddHSVPoint(1.0, 0.095, 0.33, 0.82); + ctf->AddHSVPoint(53.3, 0.04, 0.7, 0.63); + ctf->AddHSVPoint(256, 0.095, 0.33, 0.82); + + vtkNew pwf; + pwf->AddPoint(0.0, 0.0); + pwf->AddPoint(4.48, 0.0); + pwf->AddPoint(43.116, 1.0); + pwf->AddPoint(641.0, 1.0); + + vtkNew gf; + gf->AddPoint(10, 0.0); + gf->AddPoint(70, 1.0); + + vtkNew volumeProperty; + volumeProperty->SetScalarOpacity(pwf.GetPointer()); + volumeProperty->SetGradientOpacity(gf.GetPointer()); + volumeProperty->SetColor(ctf.GetPointer()); + volumeProperty->ShadeOn(); + + vtkNew volume; + volume->SetMapper(mapper.GetPointer()); + volume->SetProperty(volumeProperty.GetPointer()); + ren->AddVolume(volume.GetPointer()); + volume->RotateX(-30); + ren->ResetCamera(); + ren->GetActiveCamera()->Zoom(1.5); + + renWin->Render(); + + int retVal = vtkTesting::Test(argc, argv, renWin.GetPointer(), 90); + if (retVal == vtkRegressionTester::DO_INTERACTOR) + { + iren->Start(); + } + + return !((retVal == vtkTesting::PASSED) || + (retVal == vtkTesting::DO_INTERACTOR)); +} diff --git a/Rendering/Volume/Testing/Cxx/TestGPURayCastRenderDepthToImage.cxx b/Rendering/Volume/Testing/Cxx/TestGPURayCastRenderDepthToImage.cxx index 30fd6480ee6..8c5505c2616 100644 --- a/Rendering/Volume/Testing/Cxx/TestGPURayCastRenderDepthToImage.cxx +++ b/Rendering/Volume/Testing/Cxx/TestGPURayCastRenderDepthToImage.cxx @@ -22,15 +22,16 @@ #include "vtkGPUVolumeRayCastMapper.h" #include "vtkImageActor.h" #include "vtkImageData.h" +#include "vtkImageMapToColors.h" #include "vtkImageMapper3D.h" +#include "vtkLookupTable.h" #include "vtkNew.h" #include "vtkOpenGLGPUVolumeRayCastMapper.h" #include "vtkPiecewiseFunction.h" #include "vtkRegressionTestImage.h" -#include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" -#include "vtkTesting.h" +#include "vtkRenderer.h" #include "vtkTestUtilities.h" #include "vtkVolume16Reader.h" #include "vtkVolumeProperty.h" @@ -105,8 +106,22 @@ int TestGPURayCastRenderDepthToImage(int argc, char *argv[]) // Get depth texture as image volumeMapper->GetDepthImage(im.GetPointer()); + // Create a grayscale lookup table + vtkNew lut; + lut->SetRange(0.0, 1.0); + lut->SetValueRange(0.0, 1.0); + lut->SetSaturationRange(0.0, 0.0); + lut->SetRampToLinear(); + lut->Build(); + + // Map the pixel values of the image with the lookup table + vtkNew imageMap; + imageMap->SetInputData(im.GetPointer()); + imageMap->SetLookupTable(lut.GetPointer()); + + // Render the image in the scene vtkNew ia; - ia->GetMapper()->SetInputData(im.GetPointer()); + ia->GetMapper()->SetInputConnection(imageMap->GetOutputPort()); ren->AddActor(ia.GetPointer()); ren->RemoveVolume(volume.GetPointer()); ren->GetActiveCamera()->SetPosition(0, 0, -1); diff --git a/Rendering/Volume/Testing/Cxx/TestGPURayCastRenderDepthToImage2.cxx b/Rendering/Volume/Testing/Cxx/TestGPURayCastRenderDepthToImage2.cxx index 3bdc7860994..edc13555470 100644 --- a/Rendering/Volume/Testing/Cxx/TestGPURayCastRenderDepthToImage2.cxx +++ b/Rendering/Volume/Testing/Cxx/TestGPURayCastRenderDepthToImage2.cxx @@ -17,23 +17,22 @@ // Test the GPU volume mapper low level API to render depth buffer to texture #include "vtkActor.h" -#include "vtkRTAnalyticSource.h" -#include "vtkCamera.h" #include "vtkColorTransferFunction.h" #include "vtkGPUVolumeRayCastMapper.h" #include "vtkImageActor.h" #include "vtkImageData.h" +#include "vtkImageMapToColors.h" #include "vtkImageMapper3D.h" +#include "vtkLookupTable.h" #include "vtkNew.h" #include "vtkOpenGLGPUVolumeRayCastMapper.h" #include "vtkPiecewiseFunction.h" +#include "vtkRTAnalyticSource.h" #include "vtkRegressionTestImage.h" -#include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" -#include "vtkTesting.h" +#include "vtkRenderer.h" #include "vtkTestUtilities.h" -#include "vtkVolume16Reader.h" #include "vtkVolumeProperty.h" int TestGPURayCastRenderDepthToImage2(int argc, char *argv[]) @@ -44,6 +43,7 @@ int TestGPURayCastRenderDepthToImage2(int argc, char *argv[]) vtkNew waveletSource; volumeMapper->SetInputConnection(waveletSource->GetOutputPort()); volumeMapper->RenderToImageOn(); + volumeMapper->SetClampDepthToBackface(1); vtkNew colorFunction; colorFunction->AddRGBPoint(37.35310363769531, 0.231373, 0.298039, 0.752941); @@ -96,8 +96,22 @@ int TestGPURayCastRenderDepthToImage2(int argc, char *argv[]) // Get depth texture as image volumeMapper->GetDepthImage(im.GetPointer()); + // Create a grayscale lookup table + vtkNew lut; + lut->SetRange(0.0, 1.0); + lut->SetValueRange(0.0, 1.0); + lut->SetSaturationRange(0.0, 0.0); + lut->SetRampToLinear(); + lut->Build(); + + // Map the pixel values of the image with the lookup table + vtkNew imageMap; + imageMap->SetInputData(im.GetPointer()); + imageMap->SetLookupTable(lut.GetPointer()); + + // Render the image in the scene vtkNew ia; - ia->GetMapper()->SetInputData(im.GetPointer()); + ia->GetMapper()->SetInputConnection(imageMap->GetOutputPort()); ren->AddActor(ia.GetPointer()); ren->RemoveVolume(volume.GetPointer()); ren->ResetCamera(); diff --git a/Rendering/Volume/Testing/Cxx/TestGPURayCastVolumeDepthPass.cxx b/Rendering/Volume/Testing/Cxx/TestGPURayCastVolumeDepthPass.cxx new file mode 100644 index 00000000000..fcfd3529bff --- /dev/null +++ b/Rendering/Volume/Testing/Cxx/TestGPURayCastVolumeDepthPass.cxx @@ -0,0 +1,122 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestGPURayCastVolumeUpdate.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test volume tests whether updating the volume MTime updates the , +// geometry in the volume mapper. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int TestGPURayCastVolumeDepthPass(int argc, char *argv[]) +{ + cout << "CTEST_FULL_OUTPUT (Avoid ctest truncation of output)" << endl; + + double scalarRange[2]; + + vtkNew volumeMapper; + + vtkNew reader; + char* volumeFile = vtkTestUtilities::ExpandDataFileName( + argc, argv, "Data/vase_1comp.vti"); + reader->SetFileName(volumeFile); + delete[] volumeFile; + + // This is the feature we are testing + volumeMapper->UseDepthPassOn(); + volumeMapper->GetDepthPassContourValues()->SetValue(0, 50.0); + + // Set other parameters + volumeMapper->SetInputConnection(reader->GetOutputPort()); + volumeMapper->GetInput()->GetScalarRange(scalarRange); + volumeMapper->SetSampleDistance(0.1); + volumeMapper->SetAutoAdjustSampleDistances(0); + volumeMapper->SetBlendModeToComposite(); + + vtkNew renWin; + renWin->SetMultiSamples(0); + renWin->SetSize(400, 400); + + vtkNew iren; + iren->SetRenderWindow(renWin.GetPointer()); + vtkNew style; + iren->SetInteractorStyle(style.GetPointer()); + + renWin->Render(); // make sure we have an OpenGL context. + + vtkNew ren; + ren->SetBackground(0.2, 0.2, 0.5); + renWin->AddRenderer(ren.GetPointer()); + + vtkNew scalarOpacity; + scalarOpacity->AddPoint(50, 0.0); + scalarOpacity->AddPoint(75, 1.0); + + vtkNew volumeProperty; + volumeProperty->ShadeOn(); + volumeProperty->SetInterpolationType(VTK_LINEAR_INTERPOLATION); + volumeProperty->SetScalarOpacity(scalarOpacity.GetPointer()); + + vtkNew colorTransferFunction; + colorTransferFunction->RemoveAllPoints(); + colorTransferFunction->AddRGBPoint(scalarRange[0], 0.6, 0.4, 0.1); + volumeProperty->SetColor(colorTransferFunction.GetPointer()); + + vtkNew volume; + volume->SetMapper(volumeMapper.GetPointer()); + volume->SetProperty(volumeProperty.GetPointer()); + + ren->AddVolume(volume.GetPointer()); + ren->ResetCamera(); + + int valid = volumeMapper->IsRenderSupported(renWin.GetPointer(), + volumeProperty.GetPointer()); + + int retVal; + if (valid) + { + renWin->Render(); + + iren->Initialize(); + + retVal = vtkRegressionTestImage( renWin.GetPointer() ); + if( retVal == vtkRegressionTester::DO_INTERACTOR) + { + iren->Start(); + } + + return !retVal; + } + else + { + retVal = vtkTesting::PASSED; + cout << "Required extensions not supported" << endl; + } + + return !retVal; +} diff --git a/Rendering/Volume/Testing/Cxx/TestGPURayCastVolumePicking.cxx b/Rendering/Volume/Testing/Cxx/TestGPURayCastVolumePicking.cxx new file mode 100644 index 00000000000..78480145edc --- /dev/null +++ b/Rendering/Volume/Testing/Cxx/TestGPURayCastVolumePicking.cxx @@ -0,0 +1,269 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestGPURayCastVolumePicking.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ +// This test covers volume picking with vtkGPURayCastVolumePicking using +// vtkHardwareSelector. +// This test renders volume data along with polydata objects and selects +// the volume. +// Use 'p' for poin picking and 'r' for area selection. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "vtkInteractorStyleRubberBandPick.h" +#include "vtkRenderedAreaPicker.h" + +#include "vtkCommand.h" +#include "vtkHardwareSelector.h" +#include "vtkSelection.h" +#include "vtkSelectionNode.h" +#include "vtkConeSource.h" +#include "vtkSphereSource.h" +#include "vtkInformationIntegerKey.h" +#include "vtkInformationObjectBaseKey.h" + + +class VolumePickingCommand : public vtkCommand +{ +public: + + VolumePickingCommand() + : Renderer(NULL) + , OutlineFilter(NULL) + { + }; + + ~VolumePickingCommand() + { + }; + + virtual void Execute(vtkObject* vtkNotUsed(caller), unsigned long vtkNotUsed(eventId), + void* vtkNotUsed(callData)) + { + assert(this->Renderer != NULL); + + vtkNew selector; + selector->SetRenderer(this->Renderer); + selector->SetFieldAssociation(vtkDataObject::FIELD_ASSOCIATION_CELLS); + + unsigned int const x1 = static_cast(this->Renderer->GetPickX1()); + unsigned int const y1 = static_cast(this->Renderer->GetPickY1()); + unsigned int const x2 = static_cast(this->Renderer->GetPickX2()); + unsigned int const y2 = static_cast(this->Renderer->GetPickY2()); + selector->SetArea(x1, y1, x2, y2); + //std::cout << "->>> SetArea (x1, y1, x2, y2): (" << x1 << ", " << y1 << ", " + // << x2 << ", " << y2 << ")" << '\n'; + + vtkSelection* result = selector->Select(); + //result->Print(std::cout); + + unsigned int const numProps = result->GetNumberOfNodes(); + + for (unsigned int n = 0; n < numProps; n++) + { + vtkSelectionNode* node = result->GetNode(n); + vtkInformation* properties = node->GetProperties(); + vtkInformationIntegerKey* infoIntKey = node->PROP_ID(); + + vtkAbstractArray* abs = node->GetSelectionList(); + vtkIdType size = abs->GetSize(); + std::cout << "PropId: " << infoIntKey->Get(properties) << "/ Num. Attr.: " + << size << '\n'; + + if (numProps > 1) + continue; + + // Get the vtkAlgorithm instance of the prop to connect it to + // the outline filter. + vtkInformationObjectBaseKey* key = node->PROP(); + vtkObjectBase* keyObj = key->Get(properties); + if (!keyObj) + continue; + + vtkAbstractMapper3D* mapper = NULL; + vtkActor* actor = vtkActor::SafeDownCast(keyObj); + vtkVolume* vol = vtkVolume::SafeDownCast(keyObj); + if (actor) + mapper = vtkAbstractMapper3D::SafeDownCast(actor->GetMapper()); + else if (vol) + mapper = vtkAbstractMapper3D::SafeDownCast(vol->GetMapper()); + else + continue; + + if (!mapper) + continue; + + vtkAlgorithm* algo = mapper->GetInputAlgorithm(); + if (!algo) + continue; + + this->OutlineFilter->SetInputConnection(algo->GetOutputPort()); + } + + result->Delete(); + }; + + ////////////////////////////////////////////////////////////////////////////// + + vtkSmartPointer Renderer; + vtkSmartPointer OutlineFilter; +}; + +// ============================================================================= +int TestGPURayCastVolumePicking(int argc, char *argv[]) +{ + // volume source and mapper + vtkNew reader; + const char* volumeFile = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/vase_1comp.vti"); + reader->SetFileName(volumeFile); + + vtkNew changeInformation; + changeInformation->SetInputConnection(reader->GetOutputPort()); + changeInformation->SetOutputSpacing(1, 2, 3); + changeInformation->SetOutputOrigin(10, 20, 30); + changeInformation->Update(); + + vtkNew volumeMapper; + double scalarRange[2]; + volumeMapper->SetInputConnection(changeInformation->GetOutputPort()); + volumeMapper->GetInput()->GetScalarRange(scalarRange); + volumeMapper->SetBlendModeToComposite(); + + vtkNew scalarOpacity; + scalarOpacity->AddPoint(scalarRange[0], 0.0); + scalarOpacity->AddPoint(scalarRange[1], 1.0); + + vtkNew volumeProperty; + volumeProperty->ShadeOff(); + volumeProperty->SetInterpolationType(VTK_LINEAR_INTERPOLATION); + volumeProperty->SetScalarOpacity(scalarOpacity.GetPointer()); + + vtkSmartPointer colorTransferFunction = + volumeProperty->GetRGBTransferFunction(0); + colorTransferFunction->RemoveAllPoints(); + colorTransferFunction->AddRGBPoint(scalarRange[0], 0.0, 0.0, 0.0); + colorTransferFunction->AddRGBPoint(scalarRange[1], 1.0, 1.0, 1.0); + + vtkNew volume; + volume->PickableOn(); + volume->SetMapper(volumeMapper.GetPointer()); + volume->SetProperty(volumeProperty.GetPointer()); + + // polygonal sources and mappers + vtkNew cone; + cone->SetHeight(100.0); + cone->SetRadius(50.0); + cone->SetResolution(200.0); + cone->SetCenter(80, 100, 100); + cone->Update(); + + vtkNew coneMapper; + coneMapper->SetInputConnection(cone->GetOutputPort()); + + vtkNew coneActor; + coneActor->SetMapper(coneMapper.GetPointer()); + coneActor->PickableOn(); + + vtkNew sphere; + sphere->SetPhiResolution(20.0); + sphere->SetThetaResolution(20.0); + sphere->SetCenter(90, 40, 170); + sphere->SetRadius(40.0); + sphere->Update(); + + vtkNew sphereMapper; + sphereMapper->AddInputConnection(sphere->GetOutputPort()); + + vtkNew sphereActor; + sphereActor->SetMapper(sphereMapper.GetPointer()); + sphereActor->PickableOn(); + + // Add outline filter + vtkNew outlineActor; + vtkNew outlineMapper; + vtkNew outlineFilter; + outlineFilter->SetInputConnection(cone->GetOutputPort()); + outlineMapper->SetInputConnection(outlineFilter->GetOutputPort()); + outlineActor->SetMapper(outlineMapper.GetPointer()); + outlineActor->PickableOff(); + + // rendering setup + vtkNew ren; + ren->SetBackground(0.2, 0.2, 0.5); + ren->AddActor(coneActor.GetPointer()); + ren->AddActor(sphereActor.GetPointer()); + ren->AddActor(outlineActor.GetPointer()); + ren->AddViewProp(volume.GetPointer()); + + vtkNew renWin; + //renWin->SetMultiSamples(0); + renWin->AddRenderer(ren.GetPointer()); + renWin->SetSize(400, 400); + + vtkNew iren; + iren->SetRenderWindow(renWin.GetPointer()); + + renWin->Render(); + ren->ResetCamera(); + + // interaction & picking + vtkRenderWindowInteractor* rwi = renWin->GetInteractor(); + vtkInteractorStyleRubberBandPick* rbp = vtkInteractorStyleRubberBandPick::New(); + rwi->SetInteractorStyle(rbp); + vtkRenderedAreaPicker* areaPicker = vtkRenderedAreaPicker::New(); + rwi->SetPicker(areaPicker); + + // Add selection observer + VolumePickingCommand* vpc = new VolumePickingCommand; + vpc->Renderer = ren.GetPointer(); + vpc->OutlineFilter = outlineFilter.GetPointer(); + rwi->AddObserver(vtkCommand::EndPickEvent, vpc); + + // run the actual test + areaPicker->AreaPick(177, 125, 199, 206, ren.GetPointer()); + vpc->Execute(NULL, 0, NULL); + renWin->Render(); + + // initialize render loop + int retVal = vtkRegressionTestImage(renWin.GetPointer()); + if( retVal == vtkRegressionTester::DO_INTERACTOR) + { + iren->Initialize(); + iren->Start(); + } + + areaPicker->Delete(); + rbp->Delete(); + vpc->Delete(); + + return !retVal; +} diff --git a/Rendering/Volume/Testing/Cxx/TestProjectedTetrahedraTransform.cxx b/Rendering/Volume/Testing/Cxx/TestProjectedTetrahedraTransform.cxx new file mode 100644 index 00000000000..cda12a78e4c --- /dev/null +++ b/Rendering/Volume/Testing/Cxx/TestProjectedTetrahedraTransform.cxx @@ -0,0 +1,162 @@ +/*========================================================================= + + Program: Visualization Toolkit + Module: TestProjectedTetrahedraTransform.cxx + + Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + All rights reserved. + See Copyright.txt or http://www.kitware.com/Copyright.htm for details. + + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notice for more information. + +=========================================================================*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Creates a cube volume +vtkSmartPointer CubeVolume(double r, double g, double b) +{ + // Create the coordinates + vtkNew xArray; + xArray->InsertNextValue(0.0); + xArray->InsertNextValue(1.0); + vtkNew yArray; + yArray->InsertNextValue(0.0); + yArray->InsertNextValue(1.0); + vtkNew zArray; + zArray->InsertNextValue(0.0); + zArray->InsertNextValue(1.0); + + // Create the RectilinearGrid + vtkNew grid; + grid->SetDimensions(2, 2, 2); + grid->SetXCoordinates(xArray.GetPointer()); + grid->SetYCoordinates(yArray.GetPointer()); + grid->SetZCoordinates(zArray.GetPointer()); + + // Obtain an UnstructuredGrid made of tetrahedras + vtkNew rectilinearGridToTetrahedra; + rectilinearGridToTetrahedra->SetInputData(grid.GetPointer()); + rectilinearGridToTetrahedra->Update(); + + vtkSmartPointer ugrid + = rectilinearGridToTetrahedra->GetOutput(); + + // Add scalars to the grid + vtkNew scalars; + for (int i = 0; i < 8; i++) + { + scalars->InsertNextValue(0); + } + ugrid->GetPointData()->SetScalars(scalars.GetPointer()); + + // Volume Rendering Mapper + vtkNew mapper; + mapper->SetInputData(ugrid); + mapper->Update(); + + // Create the volume + vtkSmartPointer volume = vtkSmartPointer::New(); + volume->SetMapper(mapper.GetPointer()); + + // Apply a ColorTransferFunction to the volume + vtkNew colorTransferFunction; + colorTransferFunction->AddRGBPoint(0.0, r, g, b); + volume->GetProperty()->SetColor(colorTransferFunction.GetPointer()); + + return volume; +} + +// Creates a cone actor +vtkSmartPointer ConeActor(double r, double g, double b) +{ + // Simple cone mapper + vtkNew mapper; + vtkNew coneSource; + coneSource->SetCenter(0.0, 0.0, 0.0); + mapper->SetInputConnection(coneSource->GetOutputPort()); + + // Create the actor + vtkSmartPointer actor = vtkSmartPointer::New(); + actor->GetProperty()->SetColor(r, g, b); + actor->SetMapper(mapper.GetPointer()); + + return actor; +} + + +int TestProjectedTetrahedraTransform(int argc, char *argv[]) +{ + // Create the props + + // The red cube volume + vtkSmartPointer volume1 = CubeVolume(1, 0, 0); + + // The blue cube volume + vtkSmartPointer volume2 = CubeVolume(0, 0, 1); + + // The red cone actor + vtkSmartPointer actor1 = ConeActor(1, 0, 0); + + // The blue cone actor + vtkSmartPointer actor2 = ConeActor(0, 0, 1); + + // Translate the blue props by (2,2) + vtkNew transform; + transform->Translate(2, 2, 0); + volume2->SetUserTransform(transform.GetPointer()); + actor2->SetUserTransform(transform.GetPointer()); + + // Create a renderer, render window, and interactor + vtkNew renderer; + vtkNew renderWindow; + renderWindow->AddRenderer(renderer.GetPointer()); + renderWindow->SetSize(300, 300); + + vtkNew renderWindowInteractor; + renderWindowInteractor->SetRenderWindow(renderWindow.GetPointer()); + + // Add the props to the scene + renderer->AddVolume(volume1); + renderer->AddVolume(volume2); + renderer->AddActor(actor1); + renderer->AddActor(actor2); + + renderer->SetBackground(1, 1, 1); + + // Render and interact + renderWindow->Render(); + renderer->ResetCamera(); + renderWindow->Render(); + + int retVal = vtkTesting::Test(argc, argv, renderWindow.GetPointer(), 20); + if (retVal == vtkRegressionTester::DO_INTERACTOR) + { + renderWindowInteractor->Start(); + } + + return !retVal; +} diff --git a/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastClippingPolyData.png.md5 b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastClippingPolyData.png.md5 new file mode 100644 index 00000000000..32864898e15 --- /dev/null +++ b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastClippingPolyData.png.md5 @@ -0,0 +1 @@ +8714c2cf5b397014ea1c93320d595089 diff --git a/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastClippingUserTransform.png.md5 b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastClippingUserTransform.png.md5 new file mode 100644 index 00000000000..7c7264678e3 --- /dev/null +++ b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastClippingUserTransform.png.md5 @@ -0,0 +1 @@ +aaf30187a9869e5a04d982c848932ca4 diff --git a/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastGradientOpacityLight.png.md5 b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastGradientOpacityLight.png.md5 new file mode 100644 index 00000000000..57961001e4b --- /dev/null +++ b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastGradientOpacityLight.png.md5 @@ -0,0 +1 @@ +21e78b342df23e6caf8a83bb4b9fea71 diff --git a/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastRenderDepthToImage.png.md5 b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastRenderDepthToImage.png.md5 index 514ce55856b..4261913dbc7 100644 --- a/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastRenderDepthToImage.png.md5 +++ b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastRenderDepthToImage.png.md5 @@ -1 +1 @@ -56f8c9f08e341337b2a8b4c22ded5817 +8e95647888cf1fad534d342a9090a65c diff --git a/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastRenderDepthToImage2.png.md5 b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastRenderDepthToImage2.png.md5 index 6a8c3952e67..c57c07b9914 100644 --- a/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastRenderDepthToImage2.png.md5 +++ b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastRenderDepthToImage2.png.md5 @@ -1 +1 @@ -eb6296f201189dcfc28a5dd2b4a8c787 +f8f76284f385c4eb28a50c38c04e08a0 diff --git a/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastVolumeDepthPass.png.md5 b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastVolumeDepthPass.png.md5 new file mode 100644 index 00000000000..234c2cd8dd1 --- /dev/null +++ b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastVolumeDepthPass.png.md5 @@ -0,0 +1 @@ +6744c2a0cb3bb5253d934ee38b1be88a diff --git a/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastVolumePicking.png.md5 b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastVolumePicking.png.md5 new file mode 100644 index 00000000000..058f61a0fb6 --- /dev/null +++ b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastVolumePicking.png.md5 @@ -0,0 +1 @@ +a38c39b12a7ff495052b758d1d002720 diff --git a/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastVolumePicking_1.png.md5 b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastVolumePicking_1.png.md5 new file mode 100644 index 00000000000..c928a921186 --- /dev/null +++ b/Rendering/Volume/Testing/Data/Baseline/TestGPURayCastVolumePicking_1.png.md5 @@ -0,0 +1 @@ +9292d7981d59826b712db9be699c2798 diff --git a/Rendering/Volume/Testing/Data/Baseline/TestProjectedTetrahedraTransform.png.md5 b/Rendering/Volume/Testing/Data/Baseline/TestProjectedTetrahedraTransform.png.md5 new file mode 100644 index 00000000000..c2c907327b3 --- /dev/null +++ b/Rendering/Volume/Testing/Data/Baseline/TestProjectedTetrahedraTransform.png.md5 @@ -0,0 +1 @@ +2b5ad3919450d0eb5d19b430352a99b1 diff --git a/Rendering/Volume/Testing/Data/Baseline/VolumeOutlineSourceClipped_1.png.md5 b/Rendering/Volume/Testing/Data/Baseline/VolumeOutlineSourceClipped_1.png.md5 new file mode 100644 index 00000000000..191f774aa23 --- /dev/null +++ b/Rendering/Volume/Testing/Data/Baseline/VolumeOutlineSourceClipped_1.png.md5 @@ -0,0 +1 @@ +34ccbd04c88416dffe4121047f2a0db7 diff --git a/Rendering/Volume/Testing/Data/Baseline/gaussian.png.md5 b/Rendering/Volume/Testing/Data/Baseline/gaussian.png.md5 index 1802772610d..a8e1d2da936 100644 --- a/Rendering/Volume/Testing/Data/Baseline/gaussian.png.md5 +++ b/Rendering/Volume/Testing/Data/Baseline/gaussian.png.md5 @@ -1 +1 @@ -8edb1c1f1aa8ad4358234a5073b186c3 +e9035c1e780478786a1c57e0d3347efb diff --git a/Rendering/Volume/Testing/Python/CMakeLists.txt b/Rendering/Volume/Testing/Python/CMakeLists.txt index 8ea2670aa4f..bbd0e43a801 100644 --- a/Rendering/Volume/Testing/Python/CMakeLists.txt +++ b/Rendering/Volume/Testing/Python/CMakeLists.txt @@ -3,34 +3,36 @@ set (GenericVolumePythonTests TestFixedPointRayCasterLinearCropped.py,NO_RT TestFixedPointRayCasterLinear.py,NO_RT TestFixedPointRayCasterNearestCropped.py,NO_RT - TestFixedPointRayCasterNearest.py,NO_RT) + TestFixedPointRayCasterNearest.py,NO_RT + cursor3D.py + gaussian.py + VolumePicker.py,NO_RT + VolumePickerCrop.py + ) if (NOT VTK_LEGACY_REMOVE) list(APPEND GenericVolumePythonTests - cursor3D.py - gaussian.py volRCClipPlanes.py volRCCropRegions.py - volRCRotateClip.py - VolumePicker.py,NO_RT - VolumePickerCrop.py) + volRCRotateClip.py) endif() # These tests are only built when the rendering backend is OpenGL set (VolumeOpenGLPythonTests TestBunykRayCastFunction.py - TestPTZSweep.py) + TestPTZSweep.py + TestLODProp3D.py + VolumeOutlineSourceClipped.py + VolumeOutlineSource.py +) if (NOT VTK_LEGACY_REMOVE) list(APPEND VolumeOpenGLPythonTests - TestLODProp3D.py volTM2DRotateClip.py volTM2DCropRegions.py volTM3DCropRegions.py volTM3DCompressedCropRegions.py - volTM3DRotateClip.py - VolumeOutlineSourceClipped.py - VolumeOutlineSource.py) + volTM3DRotateClip.py) endif() # These tests are only built when the rendering backend is OpenGL2 diff --git a/Rendering/Volume/Testing/Python/TestLODProp3D.py b/Rendering/Volume/Testing/Python/TestLODProp3D.py index 45eb6c362f6..0e544c9d04e 100755 --- a/Rendering/Volume/Testing/Python/TestLODProp3D.py +++ b/Rendering/Volume/Testing/Python/TestLODProp3D.py @@ -22,7 +22,7 @@ volumeProperty.SetColor(colorTransferFunction) volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeProperty.SetInterpolationTypeToLinear() -volumeMapper = vtk.vtkVolumeTextureMapper2D() +volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper() volumeMapper.SetInputConnection(reader.GetOutputPort()) sphereSource = vtk.vtkSphereSource() sphereSource.SetCenter(25,25,25) diff --git a/Rendering/Volume/Testing/Python/VolumeOutlineSource.py b/Rendering/Volume/Testing/Python/VolumeOutlineSource.py index d761d1c7d07..6b037bba03c 100755 --- a/Rendering/Volume/Testing/Python/VolumeOutlineSource.py +++ b/Rendering/Volume/Testing/Python/VolumeOutlineSource.py @@ -47,7 +47,7 @@ while j < 4: idx = str(i) + "_" + str(j) - exec("volumeMapper_" + idx + " = vtk.vtkVolumeTextureMapper2D()") + exec("volumeMapper_" + idx + " = vtk.vtkFixedPointVolumeRayCastMapper()") eval("volumeMapper_" + idx).SetInputConnection(reader.GetOutputPort()) eval("volumeMapper_" + idx).CroppingOn() eval("volumeMapper_" + idx).SetCroppingRegionPlanes( diff --git a/Rendering/Volume/Testing/Python/VolumeOutlineSourceClipped.py b/Rendering/Volume/Testing/Python/VolumeOutlineSourceClipped.py index de28fcf1a62..70b5d30d331 100755 --- a/Rendering/Volume/Testing/Python/VolumeOutlineSourceClipped.py +++ b/Rendering/Volume/Testing/Python/VolumeOutlineSourceClipped.py @@ -80,7 +80,7 @@ clippingPlanes.AddItem(plane6) # Cropping planes are in data coords -volumeMapper1 = vtk.vtkVolumeTextureMapper2D() +volumeMapper1 = vtk.vtkFixedPointVolumeRayCastMapper() volumeMapper1.SetInputConnection(reader.GetOutputPort()) volumeMapper1.CroppingOn() volumeMapper1.SetCroppingRegionPlanes(16, 33, 16, 33, 16, 33) diff --git a/Rendering/Volume/Testing/Python/VolumePicker.py b/Rendering/Volume/Testing/Python/VolumePicker.py index 2e5c907e586..33c27325019 100755 --- a/Rendering/Volume/Testing/Python/VolumePicker.py +++ b/Rendering/Volume/Testing/Python/VolumePicker.py @@ -48,11 +48,8 @@ def testVolumePicker(self): #--------------------------------------------------------- # set up the volume rendering - rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction() - - volumeMapper = vtk.vtkVolumeRayCastMapper() + volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper() volumeMapper.SetInputConnection(v16.GetOutputPort()) - volumeMapper.SetVolumeRayCastFunction(rayCastFunction) volumeColor = vtk.vtkColorTransferFunction() volumeColor.AddRGBPoint(0, 0.0, 0.0, 0.0) diff --git a/Rendering/Volume/Testing/Python/VolumePickerCrop.py b/Rendering/Volume/Testing/Python/VolumePickerCrop.py index 1fbef8111db..a5d0d908632 100755 --- a/Rendering/Volume/Testing/Python/VolumePickerCrop.py +++ b/Rendering/Volume/Testing/Python/VolumePickerCrop.py @@ -22,11 +22,8 @@ #--------------------------------------------------------- # set up the volume rendering -rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction() - -volumeMapper = vtk.vtkVolumeRayCastMapper() +volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper() volumeMapper.SetInputConnection(v16.GetOutputPort()) -volumeMapper.SetVolumeRayCastFunction(rayCastFunction) volumeMapper.CroppingOn() volumeMapper.SetCroppingRegionPlanes(0.0, 141.6, 0.0, 201.6, 0.0, 138.0) diff --git a/Rendering/Volume/Testing/Python/cursor3D.py b/Rendering/Volume/Testing/Python/cursor3D.py index 7a6acdb357e..8386d59fb5e 100755 --- a/Rendering/Volume/Testing/Python/cursor3D.py +++ b/Rendering/Volume/Testing/Python/cursor3D.py @@ -75,11 +75,8 @@ volume_property.SetColor(color_transfer_function) volume_property.SetScalarOpacity(opacity_transfer_function) -composite_function = vtk.vtkVolumeRayCastCompositeFunction() - -volume_mapper = vtk.vtkVolumeRayCastMapper() +volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper() volume_mapper.SetInputConnection(reader.GetOutputPort()) -volume_mapper.SetVolumeRayCastFunction(composite_function) volume = vtk.vtkVolume() volume.SetMapper(volume_mapper) diff --git a/Rendering/Volume/Testing/Python/gaussian.py b/Rendering/Volume/Testing/Python/gaussian.py index b6cd9e88d6c..90e01b9452a 100755 --- a/Rendering/Volume/Testing/Python/gaussian.py +++ b/Rendering/Volume/Testing/Python/gaussian.py @@ -81,12 +81,8 @@ volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeProperty.SetInterpolationTypeToLinear() -# The mapper / ray cast function know how to render the data -compositeFunction = vtk.vtkVolumeRayCastCompositeFunction() - -volumeMapper = vtk.vtkVolumeRayCastMapper() -# vtkVolumeTextureMapper2D = vtk.volumeMapper() -volumeMapper.SetVolumeRayCastFunction(compositeFunction) +# The mapper knows how to render the data +volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper() volumeMapper.SetInputConnection(readerSS.GetOutputPort()) # The volume holds the mapper and the property and diff --git a/Rendering/Volume/vtkEncodedGradientEstimator.h b/Rendering/Volume/vtkEncodedGradientEstimator.h index 55ce3805c89..d2357df986f 100644 --- a/Rendering/Volume/vtkEncodedGradientEstimator.h +++ b/Rendering/Volume/vtkEncodedGradientEstimator.h @@ -165,16 +165,14 @@ class VTKRENDERINGVOLUME_EXPORT vtkEncodedGradientEstimator : public vtkObject // The time at which the normals were last built vtkTimeStamp BuildTime; -//BTX vtkGetVectorMacro( InputSize, int, 3 ); vtkGetVectorMacro( InputAspect, float, 3 ); -//ETX protected: vtkEncodedGradientEstimator(); ~vtkEncodedGradientEstimator(); - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; // The number of threads to use when encoding normals int NumberOfThreads; diff --git a/Rendering/Volume/vtkFixedPointVolumeRayCastHelper.h b/Rendering/Volume/vtkFixedPointVolumeRayCastHelper.h index e061e4ca496..8f61abfd4b5 100644 --- a/Rendering/Volume/vtkFixedPointVolumeRayCastHelper.h +++ b/Rendering/Volume/vtkFixedPointVolumeRayCastHelper.h @@ -23,7 +23,6 @@ #ifndef vtkFixedPointVolumeRayCastHelper_h #define vtkFixedPointVolumeRayCastHelper_h -//BTX #define VTKKWRCHelper_GetCellScalarValues( DATA, SCALE, SHIFT ) \ A = static_cast(SCALE*(*(DATA ) + SHIFT)); \ B = static_cast(SCALE*(*(DATA+Binc) + SHIFT)); \ @@ -33,9 +32,7 @@ F = static_cast(SCALE*(*(DATA+Finc) + SHIFT)); \ G = static_cast(SCALE*(*(DATA+Ginc) + SHIFT)); \ H = static_cast(SCALE*(*(DATA+Hinc) + SHIFT)) -//ETX -//BTX #define VTKKWRCHelper_GetCellScalarValuesSimple( DATA ) \ A = static_cast(*(DATA )); \ B = static_cast(*(DATA+Binc)); \ @@ -45,9 +42,7 @@ F = static_cast(*(DATA+Finc)); \ G = static_cast(*(DATA+Ginc)); \ H = static_cast(*(DATA+Hinc)) -//ETX -//BTX #define VTKKWRCHelper_GetCellMagnitudeValues( ABCD, EFGH ) \ mA = static_cast(*(ABCD )); \ mB = static_cast(*(ABCD+mBFinc)); \ @@ -57,9 +52,7 @@ mF = static_cast(*(EFGH+mBFinc)); \ mG = static_cast(*(EFGH+mCGinc)); \ mH = static_cast(*(EFGH+mDHinc)) -//ETX -//BTX #define VTKKWRCHelper_GetCellDirectionValues( ABCD, EFGH ) \ normalA = static_cast(*(ABCD )); \ normalB = static_cast(*(ABCD+dBFinc)); \ @@ -69,9 +62,7 @@ normalF = static_cast(*(EFGH+dBFinc)); \ normalG = static_cast(*(EFGH+dCGinc)); \ normalH = static_cast(*(EFGH+dDHinc)); -//ETX -//BTX #define VTKKWRCHelper_GetCellComponentScalarValues( DATA, CIDX, SCALE, SHIFT ) \ A[CIDX] = static_cast(SCALE*(*(DATA ) + SHIFT)); \ B[CIDX] = static_cast(SCALE*(*(DATA+Binc) + SHIFT)); \ @@ -81,9 +72,7 @@ F[CIDX] = static_cast(SCALE*(*(DATA+Finc) + SHIFT)); \ G[CIDX] = static_cast(SCALE*(*(DATA+Ginc) + SHIFT)); \ H[CIDX] = static_cast(SCALE*(*(DATA+Hinc) + SHIFT)) -//ETX -//BTX #define VTKKWRCHelper_GetCellComponentRawScalarValues( DATA, CIDX ) \ A[CIDX] = static_cast((*(DATA ))); \ B[CIDX] = static_cast((*(DATA+Binc))); \ @@ -93,9 +82,7 @@ F[CIDX] = static_cast((*(DATA+Finc))); \ G[CIDX] = static_cast((*(DATA+Ginc))); \ H[CIDX] = static_cast((*(DATA+Hinc))) -//ETX -//BTX #define VTKKWRCHelper_GetCellComponentMagnitudeValues( ABCD, EFGH, CIDX ) \ mA[CIDX] = static_cast(*(ABCD )); \ mB[CIDX] = static_cast(*(ABCD+mBFinc)); \ @@ -105,9 +92,7 @@ mF[CIDX] = static_cast(*(EFGH+mBFinc)); \ mG[CIDX] = static_cast(*(EFGH+mCGinc)); \ mH[CIDX] = static_cast(*(EFGH+mDHinc)) -//ETX -//BTX #define VTKKWRCHelper_GetCellComponentDirectionValues( ABCD, EFGH, CIDX ) \ normalA[CIDX] = static_cast(*(ABCD )); \ normalB[CIDX] = static_cast(*(ABCD+dBFinc)); \ @@ -117,10 +102,7 @@ normalF[CIDX] = static_cast(*(EFGH+dBFinc)); \ normalG[CIDX] = static_cast(*(EFGH+dCGinc)); \ normalH[CIDX] = static_cast(*(EFGH+dDHinc)); -//ETX - -//BTX #define VTKKWRCHelper_ComputeWeights( POS ) \ w2X = (POS[0]&VTKKW_FP_MASK); \ w2Y = (POS[1]&VTKKW_FP_MASK); \ @@ -134,10 +116,7 @@ w2Xw1Y = (0x4000+(w2X*w1Y))>>VTKKW_FP_SHIFT; \ w1Xw2Y = (0x4000+(w1X*w2Y))>>VTKKW_FP_SHIFT; \ w2Xw2Y = (0x4000+(w2X*w2Y))>>VTKKW_FP_SHIFT; \ -//ETX - -//BTX #define VTKKWRCHelper_InterpolateScalar( VAL ) \ VAL = \ (0x7fff + ((A*((0x4000 + w1Xw1Y*w1Z)>>VTKKW_FP_SHIFT)) + \ @@ -148,9 +127,7 @@ (F*((0x4000 + w2Xw1Y*w2Z)>>VTKKW_FP_SHIFT)) + \ (G*((0x4000 + w1Xw2Y*w2Z)>>VTKKW_FP_SHIFT)) + \ (H*((0x4000 + w2Xw2Y*w2Z)>>VTKKW_FP_SHIFT)))) >> VTKKW_FP_SHIFT; -//ETX -//BTX #define VTKKWRCHelper_InterpolateMagnitude( VAL ) \ VAL = \ (0x7fff + ((mA*((0x4000 + w1Xw1Y*w1Z)>>VTKKW_FP_SHIFT)) + \ @@ -161,9 +138,7 @@ (mF*((0x4000 + w2Xw1Y*w2Z)>>VTKKW_FP_SHIFT)) + \ (mG*((0x4000 + w1Xw2Y*w2Z)>>VTKKW_FP_SHIFT)) + \ (mH*((0x4000 + w2Xw2Y*w2Z)>>VTKKW_FP_SHIFT)))) >> VTKKW_FP_SHIFT; -//ETX -//BTX #define VTKKWRCHelper_InterpolateScalarComponent( VAL, CIDX, COMPONENTS ) \ for ( CIDX = 0; CIDX < COMPONENTS; CIDX++ ) \ { \ @@ -177,9 +152,7 @@ (G[CIDX]*((0x4000 + w1Xw2Y*w2Z)>>VTKKW_FP_SHIFT)) + \ (H[CIDX]*((0x4000 + w2Xw2Y*w2Z)>>VTKKW_FP_SHIFT)))) >> VTKKW_FP_SHIFT; \ } \ -//ETX -//BTX #define VTKKWRCHelper_InterpolateMagnitudeComponent( VAL, CIDX, COMPONENTS ) \ for ( CIDX = 0; CIDX < COMPONENTS; CIDX++ ) \ { \ @@ -193,9 +166,7 @@ (mG[CIDX]*((0x4000 + w1Xw2Y*w2Z)>>VTKKW_FP_SHIFT)) + \ (mH[CIDX]*((0x4000 + w2Xw2Y*w2Z)>>VTKKW_FP_SHIFT)))) >> VTKKW_FP_SHIFT; \ } -//ETX -//BTX #define VTKKWRCHelper_InterpolateShading( DTABLE, STABLE, COLOR ) \ unsigned int _tmpDColor[3]; \ unsigned int _tmpSColor[3]; \ @@ -267,10 +238,7 @@ COLOR[0] += (_tmpSColor[0]*COLOR[3] + 0x7fff)>>VTKKW_FP_SHIFT; \ COLOR[1] += (_tmpSColor[1]*COLOR[3] + 0x7fff)>>VTKKW_FP_SHIFT; \ COLOR[2] += (_tmpSColor[2]*COLOR[3] + 0x7fff)>>VTKKW_FP_SHIFT; -//ETX - -//BTX #define VTKKWRCHelper_InterpolateShadingComponent( DTABLE, STABLE, COLOR, CIDX ) \ unsigned int _tmpDColor[3]; \ unsigned int _tmpSColor[3]; \ @@ -342,9 +310,7 @@ COLOR[0] += (_tmpSColor[0]*COLOR[3] + 0x7fff)>>VTKKW_FP_SHIFT; \ COLOR[1] += (_tmpSColor[1]*COLOR[3] + 0x7fff)>>VTKKW_FP_SHIFT; \ COLOR[2] += (_tmpSColor[2]*COLOR[3] + 0x7fff)>>VTKKW_FP_SHIFT; -//ETX -//BTX #define VTKKWRCHelper_LookupColorUS( COLORTABLE, SCALAROPACITYTABLE, IDX, COLOR ) \ COLOR[3] = SCALAROPACITYTABLE[IDX]; \ if ( !COLOR[3] ) {continue;} \ @@ -354,9 +320,7 @@ ((COLORTABLE[3*IDX+1]*COLOR[3] + 0x7fff)>>(VTKKW_FP_SHIFT)); \ COLOR[2] = static_cast \ ((COLORTABLE[3*IDX+2]*COLOR[3] + 0x7fff)>>(VTKKW_FP_SHIFT)); -//ETX -//BTX #define VTKKWRCHelper_LookupColorMax( COLORTABLE, SCALAROPACITYTABLE, IDX, COLOR ) \ COLOR[3] = SCALAROPACITYTABLE[IDX]; \ COLOR[0] = static_cast \ @@ -365,9 +329,7 @@ ((COLORTABLE[3*IDX+1]*COLOR[3] + 0x7fff)>>(VTKKW_FP_SHIFT)); \ COLOR[2] = static_cast \ ((COLORTABLE[3*IDX+2]*COLOR[3] + 0x7fff)>>(VTKKW_FP_SHIFT)); -//ETX -//BTX #define VTKKWRCHelper_LookupDependentColorUS( COLORTABLE, SCALAROPACITYTABLE, IDX, CMPS, COLOR ) \ { \ unsigned short _alpha; \ @@ -392,9 +354,7 @@ break; \ } \ } -//ETX -//BTX #define VTKKWRCHelper_LookupColorGOUS( CTABLE, SOTABLE, GOTABLE, IDX, IDX2, COLOR ) \ COLOR[3] = (SOTABLE[IDX] * GOTABLE[IDX2] + 0x7fff)>>VTKKW_FP_SHIFT; \ if ( !COLOR[3] ) {continue;} \ @@ -404,9 +364,7 @@ ((CTABLE[3*IDX+1]*COLOR[3] + 0x7fff)>>(VTKKW_FP_SHIFT)); \ COLOR[2] = static_cast \ ((CTABLE[3*IDX+2]*COLOR[3] + 0x7fff)>>(VTKKW_FP_SHIFT)); -//ETX -//BTX #define VTKKWRCHelper_LookupShading( DTABLE, STABLE, NORMAL, COLOR ) \ COLOR[0] = static_cast((DTABLE[3*NORMAL ]*COLOR[0]+0x7fff)>>VTKKW_FP_SHIFT); \ COLOR[1] = static_cast((DTABLE[3*NORMAL+1]*COLOR[1]+0x7fff)>>VTKKW_FP_SHIFT); \ @@ -414,10 +372,7 @@ COLOR[0] += (STABLE[3*NORMAL ]*COLOR[3] + 0x7fff)>>VTKKW_FP_SHIFT; \ COLOR[1] += (STABLE[3*NORMAL+1]*COLOR[3] + 0x7fff)>>VTKKW_FP_SHIFT; \ COLOR[2] += (STABLE[3*NORMAL+2]*COLOR[3] + 0x7fff)>>VTKKW_FP_SHIFT; -//ETX - -//BTX #define VTKKWRCHelper_LookupAndCombineIndependentColorsUS( COLORTABLE, SOTABLE, \ SCALAR, WEIGHTS, \ COMPONENTS, COLOR ) \ @@ -447,9 +402,7 @@ COLOR[1] = (_tmp[1]>32767)?(32767):(_tmp[1]); \ COLOR[2] = (_tmp[2]>32767)?(32767):(_tmp[2]); \ COLOR[3] = (_tmp[3]>32767)?(32767):(_tmp[3]); -//ETX -//BTX #define VTKKWRCHelper_LookupAndCombineIndependentColorsMax( COLORTABLE, SCALAROPACITYTABLE, \ IDX, WEIGHTS, CMPS, COLOR ) \ { \ @@ -467,9 +420,7 @@ COLOR[2] = (_tmp[2]>32767)?(32767):(_tmp[2]); \ COLOR[3] = (_tmp[3]>32767)?(32767):(_tmp[3]); \ } -//ETX -//BTX #define VTKKWRCHelper_LookupAndCombineIndependentColorsGOUS( COLORTABLE, SOTABLE, \ GOTABLE, \ SCALAR, MAG, WEIGHTS, \ @@ -504,9 +455,7 @@ COLOR[1] = (_tmp[1]>32767)?(32767):(_tmp[1]); \ COLOR[2] = (_tmp[2]>32767)?(32767):(_tmp[2]); \ COLOR[3] = (_tmp[3]>32767)?(32767):(_tmp[3]); -//ETX -//BTX #define VTKKWRCHelper_LookupAndCombineIndependentColorsShadeUS( COLORTABLE, SOTABLE, \ DTABLE, STABLE, \ SCALAR, NORMAL, WEIGHTS, \ @@ -548,9 +497,7 @@ COLOR[1] = (_tmp[1]>32767)?(32767):(_tmp[1]); \ COLOR[2] = (_tmp[2]>32767)?(32767):(_tmp[2]); \ COLOR[3] = (_tmp[3]>32767)?(32767):(_tmp[3]); -//ETX -//BTX #define VTKKWRCHelper_LookupAndCombineIndependentColorsInterpolateShadeUS( COLORTABLE, SOTABLE, \ DTABLE, STABLE, \ SCALAR, WEIGHTS, \ @@ -587,9 +534,7 @@ COLOR[1] = (_tmp[1]>32767)?(32767):(_tmp[1]); \ COLOR[2] = (_tmp[2]>32767)?(32767):(_tmp[2]); \ COLOR[3] = (_tmp[3]>32767)?(32767):(_tmp[3]); -//ETX -//BTX #define VTKKWRCHelper_CompositeColorAndCheckEarlyTermination( COLOR, TMP, REMAININGOPACITY ) \ COLOR[0] += (TMP[0]*REMAININGOPACITY+0x7fff)>>VTKKW_FP_SHIFT; \ COLOR[1] += (TMP[1]*REMAININGOPACITY+0x7fff)>>VTKKW_FP_SHIFT; \ @@ -599,9 +544,7 @@ { \ break; \ } -//ETX -//BTX #define VTKKWRCHelper_LookupAndCombineIndependentColorsGOShadeUS( COLORTABLE, SOTABLE, GOTABLE, \ DTABLE, STABLE, \ SCALAR, MAG, NORMAL, WEIGHTS, \ @@ -647,9 +590,7 @@ COLOR[1] = (_tmp[1]>32767)?(32767):(_tmp[1]); \ COLOR[2] = (_tmp[2]>32767)?(32767):(_tmp[2]); \ COLOR[3] = (_tmp[3]>32767)?(32767):(_tmp[3]); -//ETX -//BTX #define VTKKWRCHelper_LookupAndCombineIndependentColorsGOInterpolateShadeUS( COLORTABLE, SOTABLE, GOTABLE, \ DTABLE, STABLE, \ SCALAR, MAG, WEIGHTS, \ @@ -690,19 +631,14 @@ COLOR[1] = (_tmp[1]>32767)?(32767):(_tmp[1]); \ COLOR[2] = (_tmp[2]>32767)?(32767):(_tmp[2]); \ COLOR[3] = (_tmp[3]>32767)?(32767):(_tmp[3]); -//ETX - -//BTX #define VTKKWRCHelper_SetPixelColor( IMAGEPTR, COLOR, REMAININGOPACITY ) \ IMAGEPTR[0] = (COLOR[0]>32767)?(32767):(COLOR[0]); \ IMAGEPTR[1] = (COLOR[1]>32767)?(32767):(COLOR[1]); \ IMAGEPTR[2] = (COLOR[2]>32767)?(32767):(COLOR[2]); \ unsigned int tmpAlpha = (~REMAININGOPACITY)&VTKKW_FP_MASK; \ IMAGEPTR[3] = (tmpAlpha>32767)?(32767):(tmpAlpha); -//ETX -//BTX #define VTKKWRCHelper_MoveToNextSampleNN() \ if ( k < numSteps-1 ) \ { \ @@ -710,9 +646,7 @@ mapper->ShiftVectorDown( pos, spos ); \ dptr = data + spos[0]*inc[0] + spos[1]*inc[1] + spos[2]*inc[2]; \ } -//ETX -//BTX #define VTKKWRCHelper_MoveToNextSampleGONN() \ if ( k < numSteps-1 ) \ { \ @@ -721,9 +655,7 @@ dptr = data + spos[0]*inc[0] + spos[1]*inc[1] + spos[2]*inc[2]; \ magPtr = gradientMag[spos[2]] + spos[0]*mInc[0] + spos[1]*mInc[1]; \ } -//ETX -//BTX #define VTKKWRCHelper_MoveToNextSampleShadeNN() \ if ( k < numSteps-1 ) \ { \ @@ -732,9 +664,7 @@ dptr = data + spos[0]*inc[0] + spos[1]*inc[1] + spos[2]*inc[2]; \ dirPtr = gradientDir[spos[2]] + spos[0]*dInc[0] + spos[1]*dInc[1]; \ } -//ETX -//BTX #define VTKKWRCHelper_MoveToNextSampleGOShadeNN() \ if ( k < numSteps-1 ) \ { \ @@ -744,9 +674,7 @@ magPtr = gradientMag[spos[2]] + spos[0]*mInc[0] + spos[1]*mInc[1]; \ dirPtr = gradientDir[spos[2]] + spos[0]*dInc[0] + spos[1]*dInc[1]; \ } -//ETX -//BTX #define VTKKWRCHelper_InitializeVariables() \ int i, j; \ unsigned short *imagePtr; \ @@ -790,18 +718,14 @@ inc[0] = components; \ inc[1] = inc[0]*dim[0]; \ inc[2] = inc[1]*dim[1]; -//ETX -//BTX #define VTKKWRCHelper_InitializeWeights() \ float weights[4] = {}; \ weights[0] = vol->GetProperty()->GetComponentWeight(0); \ weights[1] = vol->GetProperty()->GetComponentWeight(1); \ weights[2] = vol->GetProperty()->GetComponentWeight(2); \ weights[3] = vol->GetProperty()->GetComponentWeight(3); -//ETX -//BTX #define VTKKWRCHelper_InitializeVariablesGO() \ unsigned short *gradientOpacityTable[4]; \ for ( c = 0; c < 4; c++ ) \ @@ -823,9 +747,7 @@ mInc[1] = mInc[0]*dim[0]; \ mInc[2] = mInc[1]*dim[1]; \ } -//ETX -//BTX #define VTKKWRCHelper_InitializeVariablesShade() \ unsigned short *diffuseShadingTable[4]; \ unsigned short *specularShadingTable[4]; \ @@ -848,9 +770,7 @@ dInc[1] = dInc[0]*dim[0]; \ dInc[2] = dInc[1]*dim[1]; \ } -//ETX -//BTX #define VTKKWRCHelper_InitializeTrilinVariables() \ vtkIdType Binc = components; \ vtkIdType Cinc = Binc*dim[0]; \ @@ -859,9 +779,7 @@ vtkIdType Finc = Einc + Binc; \ vtkIdType Ginc = Einc + Cinc; \ vtkIdType Hinc = Ginc + Binc; -//ETX -//BTX #define VTKKWRCHelper_InitializeTrilinVariablesGO() \ vtkIdType magOffset; \ if ( vol->GetProperty()->GetIndependentComponents() ) \ @@ -876,9 +794,7 @@ vtkIdType mBFinc = magOffset; \ vtkIdType mCGinc = dim[0]*magOffset; \ vtkIdType mDHinc = dim[0]*magOffset + magOffset; -//ETX -//BTX #define VTKKWRCHelper_InitializeTrilinVariablesShade() \ vtkIdType dirOffset; \ if ( vol->GetProperty()->GetIndependentComponents() ) \ @@ -893,9 +809,7 @@ vtkIdType dBFinc = dirOffset; \ vtkIdType dCGinc = dim[0]*dirOffset; \ vtkIdType dDHinc = dim[0]*dirOffset + dirOffset; -//ETX -//BTX #define VTKKWRCHelper_OuterInitialization() \ if ( j%threadCount != threadID ) \ { \ @@ -914,9 +828,6 @@ } \ imagePtr = image + 4*(j*imageMemorySize[0] + rowBounds[j*2]); -//ETX - -//BTX #define VTKKWRCHelper_InnerInitialization() \ unsigned int numSteps; \ unsigned int pos[3]; \ @@ -933,16 +844,12 @@ } \ unsigned int spos[3]; \ unsigned int k; -//ETX -//BTX #define VTKKWRCHelper_InitializeMIPOneNN() \ mapper->ShiftVectorDown( pos, spos ); \ T *dptr = data + spos[0]*inc[0] + spos[1]*inc[1] + spos[2]*inc[2]; \ T maxValue = *(dptr); -//ETX -//BTX #define VTKKWRCHelper_InitializeMIPMultiNN() \ mapper->ShiftVectorDown( pos, spos ); \ T *dptr = data + spos[0]*inc[0] + spos[1]*inc[1] + spos[2]*inc[2]; \ @@ -951,9 +858,7 @@ { \ maxValue[c] = *(dptr+c); \ } -//ETX -//BTX #define VTKKWRCHelper_InitializeMIPOneTrilin() \ T *dptr; \ unsigned int oldSPos[3]; \ @@ -969,9 +874,7 @@ unsigned short maxValue=0; \ unsigned short val; \ unsigned int A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0; -//ETX -//BTX #define VTKKWRCHelper_InitializeMIPMultiTrilin() \ T *dptr; \ unsigned int oldSPos[3]; \ @@ -988,28 +891,20 @@ unsigned short val[4] = {}; \ unsigned int A[4] = {}, B[4] = {}, C[4] = {}, D[4] = {}, \ E[4] = {}, F[4] = {}, G[4] = {}, H[4] = {}; -//ETX -//BTX #define VTKKWRCHelper_InitializeCompositeGONN() \ unsigned char *magPtr = gradientMag[spos[2]] + spos[0]*mInc[0] + spos[1]*mInc[1]; -//ETX -//BTX #define VTKKWRCHelper_InitializeCompositeShadeNN() \ unsigned short *dirPtr = gradientDir[spos[2]] + spos[0]*dInc[0] + spos[1]*dInc[1]; -//ETX -//BTX #define VTKKWRCHelper_InitializeCompositeOneNN() \ mapper->ShiftVectorDown( pos, spos ); \ T *dptr = data + spos[0]*inc[0] + spos[1]*inc[1] + spos[2]*inc[2]; \ unsigned int color[3] = {0,0,0}; \ unsigned short remainingOpacity = 0x7fff; \ unsigned short tmp[4]; -//ETX -//BTX #define VTKKWRCHelper_InitializeCompositeMultiNN() \ mapper->ShiftVectorDown( pos, spos ); \ T *dptr = data + spos[0]*inc[0] + spos[1]*inc[1] + spos[2]*inc[2]; \ @@ -1017,9 +912,7 @@ unsigned int remainingOpacity = 0x7fff; \ unsigned short tmp[4] = {}; \ unsigned short val[4] = {}; -//ETX -//BTX #define VTKKWRCHelper_InitializeCompositeOneTrilin() \ T *dptr; \ unsigned int oldSPos[3]; \ @@ -1038,23 +931,17 @@ unsigned int color[3] = {0,0,0}; \ unsigned short remainingOpacity = 0x7fff; \ unsigned short tmp[4]; -//ETX -//BTX #define VTKKWRCHelper_InitializeCompositeOneGOTrilin() \ unsigned char *magPtrABCD = 0, *magPtrEFGH = 0; \ unsigned short mag; \ unsigned int mA=0,mB=0,mC=0,mD=0,mE=0,mF=0,mG=0,mH=0; -//ETX -//BTX #define VTKKWRCHelper_InitializeCompositeOneShadeTrilin() \ unsigned short *dirPtrABCD = 0, *dirPtrEFGH = 0; \ unsigned int normalA=0,normalB=0,normalC=0,normalD=0; \ unsigned int normalE=0,normalF=0,normalG=0,normalH=0; -//ETX -//BTX #define VTKKWRCHelper_InitializeCompositeMultiTrilin() \ T *dptr; \ unsigned int oldSPos[3]; \ @@ -1080,25 +967,19 @@ unsigned int color[3] = {0,0,0}; \ unsigned short remainingOpacity = 0x7fff; \ unsigned short tmp[4]; -//ETX -//BTX #define VTKKWRCHelper_InitializeCompositeMultiGOTrilin() \ unsigned char *magPtrABCD = 0, *magPtrEFGH = 0; \ unsigned short mag[4] = {}; \ unsigned int mA[4] = {}, mB[4] = {}, mC[4] = {}, \ mD[4] = {}, mE[4] = {}, mF[4] = {}, \ mG[4] = {}, mH[4] = {}; -//ETX -//BTX #define VTKKWRCHelper_InitializeCompositeMultiShadeTrilin() \ unsigned short *dirPtrABCD = 0, *dirPtrEFGH = 0; \ unsigned int normalA[4],normalB[4],normalC[4],normalD[4]; \ unsigned int normalE[4],normalF[4],normalG[4],normalH[4]; -//ETX -//BTX #define VTKKWRCHelper_InitializationAndLoopStartNN() \ VTKKWRCHelper_InitializeVariables(); \ for ( j = 0; j < imageInUseSize[1]; j++ ) \ @@ -1107,9 +988,7 @@ for ( i = rowBounds[j*2]; i <= rowBounds[j*2+1]; i++ ) \ { \ VTKKWRCHelper_InnerInitialization(); -//ETX -//BTX #define VTKKWRCHelper_InitializationAndLoopStartGONN() \ VTKKWRCHelper_InitializeVariables(); \ VTKKWRCHelper_InitializeVariablesGO(); \ @@ -1119,9 +998,7 @@ for ( i = rowBounds[j*2]; i <= rowBounds[j*2+1]; i++ ) \ { \ VTKKWRCHelper_InnerInitialization(); -//ETX -//BTX #define VTKKWRCHelper_InitializationAndLoopStartShadeNN() \ VTKKWRCHelper_InitializeVariables(); \ VTKKWRCHelper_InitializeVariablesShade(); \ @@ -1131,9 +1008,7 @@ for ( i = rowBounds[j*2]; i <= rowBounds[j*2+1]; i++ ) \ { \ VTKKWRCHelper_InnerInitialization(); -//ETX -//BTX #define VTKKWRCHelper_InitializationAndLoopStartGOShadeNN() \ VTKKWRCHelper_InitializeVariables(); \ VTKKWRCHelper_InitializeVariablesGO(); \ @@ -1144,9 +1019,7 @@ for ( i = rowBounds[j*2]; i <= rowBounds[j*2+1]; i++ ) \ { \ VTKKWRCHelper_InnerInitialization(); -//ETX -//BTX #define VTKKWRCHelper_InitializationAndLoopStartTrilin() \ VTKKWRCHelper_InitializeVariables(); \ VTKKWRCHelper_InitializeTrilinVariables(); \ @@ -1156,9 +1029,7 @@ for ( i = rowBounds[j*2]; i <= rowBounds[j*2+1]; i++ ) \ { \ VTKKWRCHelper_InnerInitialization(); -//ETX -//BTX #define VTKKWRCHelper_InitializationAndLoopStartGOTrilin() \ VTKKWRCHelper_InitializeVariables(); \ VTKKWRCHelper_InitializeVariablesGO(); \ @@ -1170,9 +1041,7 @@ for ( i = rowBounds[j*2]; i <= rowBounds[j*2+1]; i++ ) \ { \ VTKKWRCHelper_InnerInitialization(); -//ETX -//BTX #define VTKKWRCHelper_InitializationAndLoopStartShadeTrilin() \ VTKKWRCHelper_InitializeVariables(); \ VTKKWRCHelper_InitializeVariablesShade(); \ @@ -1184,9 +1053,7 @@ for ( i = rowBounds[j*2]; i <= rowBounds[j*2+1]; i++ ) \ { \ VTKKWRCHelper_InnerInitialization(); -//ETX -//BTX #define VTKKWRCHelper_InitializationAndLoopStartGOShadeTrilin() \ VTKKWRCHelper_InitializeVariables(); \ VTKKWRCHelper_InitializeVariablesShade(); \ @@ -1200,9 +1067,7 @@ for ( i = rowBounds[j*2]; i <= rowBounds[j*2+1]; i++ ) \ { \ VTKKWRCHelper_InnerInitialization(); -//ETX -//BTX #define VTKKWRCHelper_IncrementAndLoopEnd() \ imagePtr+=4; \ } \ @@ -1213,9 +1078,7 @@ mapper->InvokeEvent( vtkCommand::VolumeMapperRenderProgressEvent, fargs ); \ } \ } -//ETX -//BTX #define VTKKWRCHelper_CroppingCheckTrilin( POS ) \ if ( cropping ) \ { \ @@ -1224,9 +1087,7 @@ continue; \ } \ } -//ETX -//BTX #define VTKKWRCHelper_CroppingCheckNN( POS ) \ if ( cropping ) \ { \ @@ -1235,28 +1096,21 @@ continue; \ } \ } -//ETX -//BTX #define VTKKWRCHelper_SpaceLeapSetup() \ unsigned int mmpos[3]; \ mmpos[0] = (pos[0] >> VTKKW_FPMM_SHIFT) + 1; \ mmpos[1] = 0; \ mmpos[2] = 0; \ int mmvalid = 0; -//ETX -//BTX #define VTKKWRCHelper_SpaceLeapSetupMulti() \ unsigned int mmpos[3]; \ mmpos[0] = (pos[0] >> VTKKW_FPMM_SHIFT) + 1; \ mmpos[1] = 0; \ mmpos[2] = 0; \ int mmvalid[4] = {0,0,0,0}; -//ETX - -//BTX #define VTKKWRCHelper_SpaceLeapCheck() \ if ( pos[0] >> VTKKW_FPMM_SHIFT != mmpos[0] || \ pos[1] >> VTKKW_FPMM_SHIFT != mmpos[1] || \ @@ -1272,9 +1126,7 @@ { \ continue; \ } -//ETX -//BTX #define VTKKWRCHelper_MIPSpaceLeapCheck( MAXIDX, MAXIDXDEF, FLIP ) \ if ( pos[0] >> VTKKW_FPMM_SHIFT != mmpos[0] || \ pos[1] >> VTKKW_FPMM_SHIFT != mmpos[1] || \ @@ -1291,10 +1143,7 @@ { \ continue; \ } -//ETX - -//BTX #define VTKKWRCHelper_MIPSpaceLeapPopulateMulti( MAXIDX, FLIP ) \ if ( pos[0] >> VTKKW_FPMM_SHIFT != mmpos[0] || \ pos[1] >> VTKKW_FPMM_SHIFT != mmpos[1] || \ @@ -1308,11 +1157,8 @@ mmvalid[c] = mapper->CheckMIPMinMaxVolumeFlag( mmpos, c, MAXIDX[c], FLIP ); \ } \ } -//ETX -//BTX #define VTKKWRCHelper_MIPSpaceLeapCheckMulti( COMP, FLIP ) mmvalid[COMP] -//ETX #include "vtkRenderingVolumeModule.h" // For export macro #include "vtkObject.h" diff --git a/Rendering/Volume/vtkFixedPointVolumeRayCastMapper.h b/Rendering/Volume/vtkFixedPointVolumeRayCastMapper.h index 5a3ae5c4531..4947ca9428b 100644 --- a/Rendering/Volume/vtkFixedPointVolumeRayCastMapper.h +++ b/Rendering/Volume/vtkFixedPointVolumeRayCastMapper.h @@ -89,11 +89,9 @@ class vtkRayCastImageDisplayHelper; class vtkFixedPointRayCastImage; class vtkDataArray; -//BTX // Forward declaration needed for use by friend declaration below. VTK_THREAD_RETURN_TYPE FixedPointVolumeRayCastMapper_CastRays( void *arg ); VTK_THREAD_RETURN_TYPE vtkFPVRCMSwitchOnDataType( void *arg ); -//ETX class VTKRENDERINGVOLUME_EXPORT vtkFixedPointVolumeRayCastMapper : public vtkVolumeMapper { @@ -188,7 +186,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkFixedPointVolumeRayCastMapper : public vtkVol vtkRenderer *ren, vtkVolume *vol ); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // Initialize rendering for this volume. @@ -223,8 +220,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkFixedPointVolumeRayCastMapper : public vtkVol unsigned char color[4] ); int CheckIfCropped( unsigned int pos[3] ); -//ETX - vtkGetObjectMacro( RenderWindow, vtkRenderWindow ); vtkGetObjectMacro( MIPHelper, vtkFixedPointVolumeRayCastMIPHelper ); vtkGetObjectMacro( CompositeHelper, vtkFixedPointVolumeRayCastCompositeHelper ); diff --git a/Rendering/Volume/vtkGPUVolumeRayCastMapper.cxx b/Rendering/Volume/vtkGPUVolumeRayCastMapper.cxx index 98759a08470..7dc288417f6 100644 --- a/Rendering/Volume/vtkGPUVolumeRayCastMapper.cxx +++ b/Rendering/Volume/vtkGPUVolumeRayCastMapper.cxx @@ -14,24 +14,26 @@ =========================================================================*/ #include "vtkGPUVolumeRayCastMapper.h" -#include "vtkObjectFactory.h" -#include "vtkImageData.h" -#include "vtkPointData.h" -#include "vtkCellData.h" -#include "vtkDataArray.h" -#include "vtkTimerLog.h" -#include "vtkImageResample.h" -#include "vtkVolume.h" -#include "vtkVolumeProperty.h" -#include "vtkRenderer.h" -#include "vtkRenderWindow.h" +#include +#include +#include // for VolumeMapperRender{Start|End|Progress}Event +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + #include -#include "vtkCommand.h" // for VolumeMapperRender{Start|End|Progress}Event -#include "vtkCamera.h" -#include "vtkRendererCollection.h" -#include "vtkMultiThreader.h" -#include "vtkGPUInfoList.h" -#include "vtkGPUInfo.h" // Return NULL if no override is supplied. vtkAbstractObjectFactoryNewMacro(vtkGPUVolumeRayCastMapper) @@ -45,7 +47,11 @@ vtkGPUVolumeRayCastMapper::vtkGPUVolumeRayCastMapper() this->MinimumImageSampleDistance = 1.0; this->MaximumImageSampleDistance = 10.0; this->RenderToImage = 0; + this->DepthImageScalarType = VTK_FLOAT; + this->ClampDepthToBackface = 0; this->UseJittering = 1; + this->UseDepthPass = 0; + this->DepthPassContourValues = NULL; this->SampleDistance = 1.0; this->SmallVolumeRender = 0; this->BigTimeToDraw = 0.0; @@ -104,6 +110,11 @@ vtkGPUVolumeRayCastMapper::~vtkGPUVolumeRayCastMapper() this->SetMaskInput(NULL); this->SetTransformedInput(NULL); this->LastInput = NULL; + + if (this->DepthPassContourValues) + { + this->DepthPassContourValues->Delete(); + } } // ---------------------------------------------------------------------------- @@ -373,8 +384,7 @@ int vtkGPUVolumeRayCastMapper::ValidateRender(vtkRenderer *ren, } } - int numberOfComponents = 0; - numberOfComponents = scalars->GetNumberOfComponents(); + int numberOfComponents = goodSoFar ? scalars->GetNumberOfComponents() : 0; #ifdef VTK_OPENGL2 // This mapper supports anywhere from 1-4 components. Number of components @@ -683,3 +693,32 @@ void vtkGPUVolumeRayCastMapper::SetMaskTypeToLabelMap() { this->MaskType = vtkGPUVolumeRayCastMapper::LabelMapMaskType; } + +//---------------------------------------------------------------------------- +vtkContourValues* vtkGPUVolumeRayCastMapper::GetDepthPassContourValues() +{ + if (!this->DepthPassContourValues) + { + this->DepthPassContourValues = vtkContourValues::New(); + } + + return this->DepthPassContourValues; +} + +//---------------------------------------------------------------------------- +void vtkGPUVolumeRayCastMapper::SetDepthImageScalarTypeToUnsignedChar() +{ + this->SetDepthImageScalarType(VTK_UNSIGNED_CHAR); +} + +//---------------------------------------------------------------------------- +void vtkGPUVolumeRayCastMapper::SetDepthImageScalarTypeToUnsignedShort() +{ + this->SetDepthImageScalarType(VTK_UNSIGNED_SHORT); +} + +//---------------------------------------------------------------------------- +void vtkGPUVolumeRayCastMapper::SetDepthImageScalarTypeToFloat() +{ + this->SetDepthImageScalarType(VTK_FLOAT); +} diff --git a/Rendering/Volume/vtkGPUVolumeRayCastMapper.h b/Rendering/Volume/vtkGPUVolumeRayCastMapper.h index 5ef856a7937..95821d122ff 100644 --- a/Rendering/Volume/vtkGPUVolumeRayCastMapper.h +++ b/Rendering/Volume/vtkGPUVolumeRayCastMapper.h @@ -22,11 +22,13 @@ #ifndef vtkGPUVolumeRayCastMapper_h #define vtkGPUVolumeRayCastMapper_h -#include "vtkRenderingVolumeModule.h" // For export macro +#include // For export macro + #include "vtkVolumeMapper.h" -class vtkVolumeProperty; +class vtkContourValues; class vtkRenderWindow; +class vtkVolumeProperty; //class vtkKWAMRVolumeMapper; // friend class. @@ -54,6 +56,23 @@ class VTKRENDERINGVOLUME_EXPORT vtkGPUVolumeRayCastMapper : public vtkVolumeMapp vtkGetMacro( UseJittering, int ); vtkBooleanMacro( UseJittering, int ); + // Description: + // If UseDepthPass is on, the mapper will use two passes. In the first + // pass, an isocontour depth buffer will be utilized as starting point + // for ray-casting hence eliminating traversal on voxels that are + // not going to participate in final rendering. UseDepthPass requires + // reasonable contour values to be set which can be set by calling + // GetDepthPassContourValues() method and using vtkControurValues API. + vtkSetClampMacro( UseDepthPass, int, 0, 1 ); + vtkGetMacro( UseDepthPass, int ); + vtkBooleanMacro( UseDepthPass, int ); + + // Description: + // Return handle to contour values container so + // that values can be set by the application. Contour values + // will be used only when UseDepthPass is on. + vtkContourValues* GetDepthPassContourValues(); + // Description: // Set/Get the distance between samples used for rendering // when AutoAdjustSampleDistances is off, or when this mapper @@ -166,9 +185,7 @@ class VTKRENDERINGVOLUME_EXPORT vtkGPUVolumeRayCastMapper : public vtkVolumeMapp void SetMaskInput(vtkImageData *mask); vtkGetObjectMacro(MaskInput, vtkImageData); - //BTX enum { BinaryMaskType = 0, LabelMapMaskType }; - //ETX // Description: // Set the mask type, if mask is to be used. See documentation for @@ -193,26 +210,59 @@ class VTKRENDERINGVOLUME_EXPORT vtkGPUVolumeRayCastMapper : public vtkVolumeMapp // color and depth textures. By default this is set to 0 (off). // It should be noted that it is possible that underlying API specific // mapper may not supoport RenderToImage mode. + // \warning + // \li This method ignores any other volumes / props in the scene. + // \li This method does not respect the general attributes of the + // scene i.e. background color, etc. It always produces a color + // image that has a transparent white background outside the + // bounds of the volume. + // + // \sa GetDepthImage(), GetColorImage() vtkSetMacro(RenderToImage, int); vtkGetMacro(RenderToImage, int); vtkBooleanMacro(RenderToImage, int); + // Description: + // Set/Get the scalar type of the depth texture in RenderToImage mode. + // By default, the type if VTK_FLOAT. + // \sa SetRenderToImage() + vtkSetMacro(DepthImageScalarType, int); + vtkGetMacro(DepthImageScalarType, int); + void SetDepthImageScalarTypeToUnsignedChar(); + void SetDepthImageScalarTypeToUnsignedShort(); + void SetDepthImageScalarTypeToFloat(); + + // Description: + // Enable or disable clamping the depth value of the fully + // transparent voxel to the depth of the back-face of the + // volume. This parameter is used when RenderToImage mode is + // enabled. When ClampDepthToBackFace is false, the fully transparent + // voxels will have a value of 1.0 in the depth image. When + // this is true, the fully transparent voxels will have the + // depth value of the face at which the ray exits the volume. + // By default, this is set to 0 (off). + // \sa SetRenderToImage(), GetDepthImage() + vtkSetMacro(ClampDepthToBackface, int); + vtkGetMacro(ClampDepthToBackface, int); + vtkBooleanMacro(ClampDepthToBackface, int); + // Description: // Low level API to export the depth texture as vtkImageData in // RenderToImage mode. // Should be implemented by the graphics API specific mapper (GL or other). + // \sa SetRenderToImage() virtual void GetDepthImage(vtkImageData*) {}; // Description: // Low level API to export the color texture as vtkImageData in // RenderToImage mode. // Should be implemented by the graphics API specific mapper (GL or other). + // \sa SetRenderToImage() virtual void GetColorImage(vtkImageData*) {}; -//BTX // Description: - // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // Initialize rendering for this volume. + // \warning INTERNAL METHOD - NOT INTENDED FOR GENERAL USE void Render( vtkRenderer *, vtkVolume * ); // Description: @@ -221,10 +271,10 @@ class VTKRENDERINGVOLUME_EXPORT vtkGPUVolumeRayCastMapper : public vtkVolumeMapp virtual void GPURender( vtkRenderer *, vtkVolume *) {} // Description: - // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // Release any graphics resources that are being consumed by this mapper. // The parameter window could be used to determine which graphic // resources to release. + // \warning INTERNAL METHOD - NOT INTENDED FOR GENERAL USE void ReleaseGraphicsResources(vtkWindow *) {} // Description: @@ -240,8 +290,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkGPUVolumeRayCastMapper : public vtkVolumeMapp // \post valid_k_ratio: ratio[2]>0 && ratio[2]<=1.0 virtual void GetReductionRatio(double ratio[3])=0; -//ETX - protected: vtkGPUVolumeRayCastMapper(); ~vtkGPUVolumeRayCastMapper(); @@ -284,9 +332,20 @@ class VTKRENDERINGVOLUME_EXPORT vtkGPUVolumeRayCastMapper : public vtkVolumeMapp // Render to texture mode flag int RenderToImage; - // Enable / disable stochasting jittering + // Depth image scalar type + int DepthImageScalarType; + + // Clamp depth values to the depth of the face at which the ray + // exits the volume + int ClampDepthToBackface; + + // Enable / disable stochastic jittering int UseJittering; + // Enable / disable two pass rendering + int UseDepthPass; + vtkContourValues* DepthPassContourValues; + // The distance between sample points along the ray float SampleDistance; diff --git a/Rendering/Volume/vtkHAVSVolumeMapper.h b/Rendering/Volume/vtkHAVSVolumeMapper.h index 04e323fb4eb..d10c82a3f55 100644 --- a/Rendering/Volume/vtkHAVSVolumeMapper.h +++ b/Rendering/Volume/vtkHAVSVolumeMapper.h @@ -176,7 +176,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkHAVSVolumeMapper : public vtkUnstructuredGrid vtkHAVSVolumeMapper(); ~vtkHAVSVolumeMapper(); -//BTX virtual void Initialize(vtkRenderer *ren, vtkVolume *vol) = 0; void InitializePrimitives(vtkVolume *vol); void InitializeScalars(); @@ -249,7 +248,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkHAVSVolumeMapper : public vtkUnstructuredGrid vtkTimeStamp UnstructuredGridMTime; vtkTimeStamp ScalarsMTime; vtkVolume *LastVolume; -//ETX private: vtkHAVSVolumeMapper(const vtkHAVSVolumeMapper&); // Not implemented. diff --git a/Rendering/Volume/vtkProjectedTetrahedraMapper.cxx b/Rendering/Volume/vtkProjectedTetrahedraMapper.cxx index b4a3f040ef1..0bc125abd1e 100644 --- a/Rendering/Volume/vtkProjectedTetrahedraMapper.cxx +++ b/Rendering/Volume/vtkProjectedTetrahedraMapper.cxx @@ -24,11 +24,11 @@ #include "vtkProjectedTetrahedraMapper.h" +#include "vtkArrayDispatch.h" #include "vtkCellArray.h" #include "vtkCellCenterDepthSort.h" #include "vtkCellData.h" #include "vtkColorTransferFunction.h" -#include "vtkDataArrayIteratorMacro.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkGarbageCollector.h" @@ -83,69 +83,80 @@ void vtkProjectedTetrahedraMapper::ReportReferences(vtkGarbageCollector *collect } //----------------------------------------------------------------------------- - -template -void vtkProjectedTetrahedraMapperTransformPoints(PointIterator in_points, - vtkIdType num_points, - const float projection_mat[16], - const float modelview_mat[16], - float *out_points) +namespace { +struct TransformPointsWorker { - float mat[16]; - int row, col; - vtkIdType i; - PointIterator in_p; - float *out_p; - - // Combine two transforms into one transform. - for (col = 0; col < 4; col++) - { - for (row = 0; row < 4; row++) - { - mat[col*4+row] = ( projection_mat[0*4+row]*modelview_mat[col*4+0] - + projection_mat[1*4+row]*modelview_mat[col*4+1] - + projection_mat[2*4+row]*modelview_mat[col*4+2] - + projection_mat[3*4+row]*modelview_mat[col*4+3]); - } - } + const float *Proj; + const float *ModelView; + float *OutPoints; - // Transform all points. - for (i = 0, in_p = in_points, out_p = out_points; i < num_points; - i++, in_p += 3, out_p += 3) - { - for (row = 0; row < 3; row++) + TransformPointsWorker(const float *proj, const float *mv, float *out) + : Proj(proj), ModelView(mv), OutPoints(out) + {} + + template + void operator()(ArrayT *in_points) + { + float mat[16]; + int row, col; + vtkIdType i; + vtkIdType num_points = in_points->GetNumberOfTuples(); + typename ArrayT::ValueType in_p[3]; + float *out_p; + + // Combine two transforms into one transform. + for (col = 0; col < 4; col++) { - out_p[row] = ( mat[0*4+row]*in_p[0] + mat[1*4+row]*in_p[1] - + mat[2*4+row]*in_p[2] + mat[3*4+row]); + for (row = 0; row < 4; row++) + { + mat[col*4+row] = ( this->Proj[0*4+row] * this->ModelView[col*4+0] + + this->Proj[1*4+row] * this->ModelView[col*4+1] + + this->Proj[2*4+row] * this->ModelView[col*4+2] + + this->Proj[3*4+row] * this->ModelView[col*4+3]); + } } - } - // Check to see if we need to divide by w. - if ( (mat[0*4+3] != 0) || (mat[1*4+3] != 0) - || (mat[2*4+3] != 0) || (mat[3*4+3] != 1) ) - { - for (i = 0, in_p = in_points, out_p = out_points; i < num_points; - i++, in_p += 3, out_p += 3) + // Transform all points. + for (i = 0, out_p = this->OutPoints; i < num_points; i++, out_p += 3) { - float w = ( mat[0*4+3]*in_p[0] + mat[1*4+3]*in_p[1] - + mat[2*4+3]*in_p[2] + mat[3*4+3]); - if (w > 0.0) + in_points->GetTypedTuple(i, in_p); + for (row = 0; row < 3; row++) { - out_p[0] /= w; - out_p[1] /= w; - out_p[2] /= w; + out_p[row] = ( mat[0*4+row] * in_p[0] + mat[1*4+row] * in_p[1] + + mat[2*4+row] * in_p[2] + mat[3*4+row]); } - else + } + + // Check to see if we need to divide by w. + if ( (mat[0*4+3] != 0) || (mat[1*4+3] != 0) + || (mat[2*4+3] != 0) || (mat[3*4+3] != 1) ) + { + for (i = 0, out_p = this->OutPoints; i < num_points; i++, out_p += 3) { - // A negative w probably means the point is behind the viewer. Things - // can get screwy if we try to inverse-project that. Instead, just - // set the position somewhere very far behind us. - out_p[2] = -VTK_FLOAT_MAX; + in_points->GetTypedTuple(i, in_p); + float w = ( mat[0*4+3]*in_p[0] + mat[1*4+3]*in_p[1] + + mat[2*4+3]*in_p[2] + mat[3*4+3]); + if (w > 0.0) + { + out_p[0] /= w; + out_p[1] /= w; + out_p[2] /= w; + } + else + { + // A negative w probably means the point is behind the viewer. Things + // can get screwy if we try to inverse-project that. Instead, just + // set the position somewhere very far behind us. + out_p[2] = -VTK_FLOAT_MAX; + } } } - } -} + } + +}; +} // end anon namespace +//----------------------------------------------------------------------------- void vtkProjectedTetrahedraMapper::TransformPoints( vtkPoints *inPoints, const float projection_mat[16], @@ -158,42 +169,40 @@ void vtkProjectedTetrahedraMapper::TransformPoints( } outPoints->SetNumberOfComponents(3); outPoints->SetNumberOfTuples(inPoints->GetNumberOfPoints()); - switch (inPoints->GetDataType()) - { - vtkDataArrayIteratorMacro(inPoints->GetData(), - vtkProjectedTetrahedraMapperTransformPoints( - vtkDABegin, inPoints->GetNumberOfPoints(), - projection_mat, modelview_mat, - outPoints->GetPointer(0))); - } + TransformPointsWorker worker(projection_mat, modelview_mat, + outPoints->GetPointer(0)); + vtkArrayDispatch::Dispatch::Execute(inPoints->GetData(), worker); } //----------------------------------------------------------------------------- namespace vtkProjectedTetrahedraMapperNamespace { - template - void MapScalarsToColors1(ColorType *colors, vtkVolumeProperty *property, - vtkDataArray *scalars); - template - void MapScalarsToColors2(ColorType *colors, vtkVolumeProperty *property, - ScalarIterator scalars, - int num_scalar_components, - vtkIdType num_scalars); - template - void MapIndependentComponents(ColorType *colors, + template + void MapScalarsToColorsImpl(ColorArrayT *colors, vtkVolumeProperty *property, + ScalarArrayT *scalars); + template + void MapIndependentComponents(ColorArrayT *colors, vtkVolumeProperty *property, - ScalarIterator scalars, - int num_scalar_components, - vtkIdType num_scalars); - template - void Map2DependentComponents(ColorType *colors, - vtkVolumeProperty *property, - ScalarIterator scalars, - vtkIdType num_scalars); - template - void Map4DependentComponents(ColorType *colors, ScalarIterator scalars, - vtkIdType num_scalars); + ScalarArrayT *scalars); + template + void Map2DependentComponents(ColorArrayT *colors, vtkVolumeProperty *property, + ScalarArrayT *scalars); + template + void Map4DependentComponents(ColorArrayT *colors, ScalarArrayT *scalars); + + struct Worker + { + vtkVolumeProperty *Property; + + Worker(vtkVolumeProperty *property) : Property(property) {} + + template + void operator()(ColorArrayT *colors, ScalarArrayT *scalars) + { + MapScalarsToColorsImpl(colors, this->Property, scalars); + } + }; } void vtkProjectedTetrahedraMapper::MapScalarsToColors( @@ -228,11 +237,11 @@ void vtkProjectedTetrahedraMapper::MapScalarsToColors( tmpColors->SetNumberOfComponents(4); tmpColors->SetNumberOfTuples(numscalars); - void *colorpointer = tmpColors->GetVoidPointer(0); - switch (tmpColors->GetDataType()) + Worker worker(property); + if (!vtkArrayDispatch::Dispatch2::Execute(tmpColors, scalars, worker)) { - vtkTemplateMacro(MapScalarsToColors1(static_cast(colorpointer), - property, scalars)); + vtkGenericWarningMacro("Dispatch failed for scalar array " + << scalars->GetName()); } if (castColors) @@ -261,74 +270,60 @@ void vtkProjectedTetrahedraMapper::MapScalarsToColors( //----------------------------------------------------------------------------- namespace vtkProjectedTetrahedraMapperNamespace { - - template - void MapScalarsToColors1(ColorType *colors, vtkVolumeProperty *property, - vtkDataArray *scalars) - { - switch(scalars->GetDataType()) - { - vtkDataArrayIteratorMacro( - scalars, - MapScalarsToColors2(colors, property, vtkDABegin, - scalars->GetNumberOfComponents(), - scalars->GetNumberOfTuples())); - } - } - - template - void MapScalarsToColors2(ColorType *colors, vtkVolumeProperty *property, - ScalarIterator scalars, - int num_scalar_components, vtkIdType num_scalars) + template + void MapScalarsToColorsImpl(ColorArrayT *colors, vtkVolumeProperty *property, + ScalarArrayT *scalars) { if (property->GetIndependentComponents()) { - MapIndependentComponents(colors, property, - scalars, num_scalar_components, num_scalars); + MapIndependentComponents(colors, property, scalars); } else { - switch (num_scalar_components) + switch (scalars->GetNumberOfComponents()) { case 2: - Map2DependentComponents(colors, property, scalars, num_scalars); + Map2DependentComponents(colors, property, scalars); break; case 4: - Map4DependentComponents(colors, scalars, num_scalars); + Map4DependentComponents(colors, scalars); break; default: vtkGenericWarningMacro("Attempted to map scalar with " - << num_scalar_components + << scalars->GetNumberOfComponents() << " with dependent components"); break; } } } - template - void MapIndependentComponents(ColorType *colors, + template + void MapIndependentComponents(ColorArrayT *colors, vtkVolumeProperty *property, - ScalarIterator scalars, - int num_scalar_components, - vtkIdType num_scalars) + ScalarArrayT *scalars) { // I don't really know what to do if there is more than one component. // How am I supposed to mix the resulting colors? Since I don't know // what to do, and the whole thing seems kinda pointless anyway, I'm just // going to punt and copy over the first scalar. - ColorType *c = colors; - ScalarIterator s = scalars; vtkIdType i; + vtkIdType num_scalars = scalars->GetNumberOfTuples(); + + typedef typename ScalarArrayT::ValueType ScalarType; + typedef typename ColorArrayT::ValueType ColorType; + ColorType c[4]; if (property->GetColorChannels() == 1) { vtkPiecewiseFunction *gray = property->GetGrayTransferFunction(); vtkPiecewiseFunction *alpha = property->GetScalarOpacity(); - for (i = 0; i < num_scalars; i++, c += 4, s += num_scalar_components) + for (i = 0; i < num_scalars; i++) { - c[0] = c[1] = c[2] = static_cast(gray->GetValue(s[0])); - c[3] = static_cast(alpha->GetValue(s[0])); + ScalarType s = scalars->GetTypedComponent(i, 0); + c[0] = c[1] = c[2] = static_cast(gray->GetValue(s)); + c[3] = static_cast(alpha->GetValue(s)); + colors->SetTypedTuple(i, c); } } else @@ -336,52 +331,49 @@ namespace vtkProjectedTetrahedraMapperNamespace vtkColorTransferFunction *rgb = property->GetRGBTransferFunction(); vtkPiecewiseFunction *alpha = property->GetScalarOpacity(); - for (i = 0; i < num_scalars; i++, c += 4, s += num_scalar_components) + for (i = 0; i < num_scalars; i++) { + ScalarType s = scalars->GetTypedComponent(i, 0); double trgb[3]; - rgb->GetColor(s[0], trgb); + rgb->GetColor(s, trgb); c[0] = static_cast(trgb[0]); c[1] = static_cast(trgb[1]); c[2] = static_cast(trgb[2]); - c[3] = static_cast(alpha->GetValue(s[0])); + c[3] = static_cast(alpha->GetValue(s)); + colors->SetTypedTuple(i, c); } } } - template - void Map2DependentComponents(ColorType *colors, vtkVolumeProperty *property, - ScalarIterator scalars, vtkIdType num_scalars) + template + void Map2DependentComponents(ColorArrayT *colors, vtkVolumeProperty *property, + ScalarArrayT *scalars) { + typedef typename ScalarArrayT::ValueType ScalarType; vtkColorTransferFunction *rgb = property->GetRGBTransferFunction(); vtkPiecewiseFunction *alpha = property->GetScalarOpacity(); - double rgbColor[3]; + vtkIdType num_scalars = scalars->GetNumberOfTuples(); + double rgbColor[4]; + ScalarType scalar[2]; for (vtkIdType i = 0; i < num_scalars; i++) { - rgb->GetColor(scalars[0], rgbColor); - colors[0] = static_cast(rgbColor[0]); - colors[1] = static_cast(rgbColor[1]); - colors[2] = static_cast(rgbColor[2]); - colors[3] = static_cast(alpha->GetValue(scalars[1])); - - colors += 4; - scalars += 2; + scalars->GetTypedTuple(i, scalar); + rgb->GetColor(scalar[0], rgbColor); + rgbColor[3] = alpha->GetValue(scalar[1]); + colors->SetTuple(i, rgbColor); } } - template - void Map4DependentComponents(ColorType *colors, ScalarIterator scalars, - vtkIdType num_scalars) + template + void Map4DependentComponents(ColorArrayT *colors, ScalarArrayT *scalars) { + double val[4]; + vtkIdType num_scalars = scalars->GetNumberOfTuples(); for (vtkIdType i = 0; i < num_scalars; i++) { - colors[0] = static_cast(scalars[0]); - colors[1] = static_cast(scalars[1]); - colors[2] = static_cast(scalars[2]); - colors[3] = static_cast(scalars[3]); - - colors += 4; - scalars += 4; + scalars->GetTuple(i, val); + colors->SetTuple(i, val); } } diff --git a/Rendering/Volume/vtkUnstructuredGridBunykRayCastFunction.cxx b/Rendering/Volume/vtkUnstructuredGridBunykRayCastFunction.cxx index e946117b318..e5a8d95d466 100644 --- a/Rendering/Volume/vtkUnstructuredGridBunykRayCastFunction.cxx +++ b/Rendering/Volume/vtkUnstructuredGridBunykRayCastFunction.cxx @@ -13,6 +13,8 @@ =========================================================================*/ #include "vtkUnstructuredGridBunykRayCastFunction.h" + +#include "vtkArrayDispatch.h" #include "vtkObjectFactory.h" #include "vtkUnstructuredGrid.h" #include "vtkUnstructuredGridVolumeRayCastMapper.h" @@ -26,6 +28,7 @@ #include "vtkMath.h" #include "vtkPointData.h" #include "vtkCellArray.h" +#include "vtkFloatArray.h" #include "vtkDoubleArray.h" #include "vtkIdList.h" #include "vtkPiecewiseFunction.h" @@ -34,29 +37,307 @@ #include "vtkUnstructuredGridVolumeRayCastIterator.h" #include "vtkSmartPointer.h" #include "vtkCellIterator.h" -#include "vtkDataArrayIteratorMacro.h" #include +#include vtkStandardNewMacro(vtkUnstructuredGridBunykRayCastFunction); #define VTK_BUNYKRCF_NUMLISTS 100000 -template -vtkIdType TemplateCastRay( - const ScalarIterator scalars, - vtkUnstructuredGridBunykRayCastFunction *self, - int numComponents, - int x, int y, - double farClipZ, - vtkUnstructuredGridBunykRayCastFunction::Intersection *&intersectionPtr, - vtkUnstructuredGridBunykRayCastFunction::Triangle *¤tTriangle, - vtkIdType ¤tTetra, - vtkIdType *intersectedCells, - double *intersectionLengths, - T *nearIntersections, - T *farIntersections, - int maxNumIntersections); +namespace { + +struct TemplateCastRayWorker +{ + vtkUnstructuredGridBunykRayCastFunction *Self; + int NumComponents; + int X; + int Y; + double FarClipZ; + vtkUnstructuredGridBunykRayCastFunction::Intersection *&IntersectionPtr; + vtkUnstructuredGridBunykRayCastFunction::Triangle *&CurrentTriangle; + vtkIdType &CurrentTetra; + vtkIdType *IntersectedCells; + double *IntersectionLengths; + int MaxNumIntersections; + + // Result: + vtkIdType NumIntersections; + + TemplateCastRayWorker( + vtkUnstructuredGridBunykRayCastFunction *self, + int numComponents, int x, int y, double farClipZ, + vtkUnstructuredGridBunykRayCastFunction::Intersection *&intersectionPtr, + vtkUnstructuredGridBunykRayCastFunction::Triangle *¤tTriangle, + vtkIdType ¤tTetra, vtkIdType *intersectedCells, + double *intersectedLengths, int maxNumIntersections + ) + : Self(self), NumComponents(numComponents), X(x), Y(y), FarClipZ(farClipZ), + IntersectionPtr(intersectionPtr), CurrentTriangle(currentTriangle), + CurrentTetra(currentTetra), IntersectedCells(intersectedCells), + IntersectionLengths(intersectedLengths), + MaxNumIntersections(maxNumIntersections), + NumIntersections(0) + {} + + // Silence warning C4512 on MSVC2015: "assignment operator could not be + // generated.". This class is never copied, so no need for assignment. + TemplateCastRayWorker& operator=(const TemplateCastRayWorker &) + { + return *this; + } + + // Execute the algorithm with all arrays set to NULL. + void operator()() + { + (*this)(static_cast*>(NULL), + static_cast*>(NULL), + static_cast*>(NULL)); + } + + template + void operator()(ScalarArrayT *scalarArray, + NearArrayT *nearIntersectionArray, + FarArrayT *farIntersectionArray) + { + typedef typename NearArrayT::ValueType ValueType; + + int imageViewportSize[2]; + this->Self->GetImageViewportSize( imageViewportSize ); + + int origin[2]; + this->Self->GetImageOrigin( origin ); + float fx = this->X - origin[0]; + float fy = this->Y - origin[1]; + + double *points = this->Self->GetPoints(); + vtkUnstructuredGridBunykRayCastFunction::Triangle **triangles = + this->Self->GetTetraTriangles(); + + vtkMatrix4x4 *viewToWorld = this->Self->GetViewToWorldMatrix(); + + vtkUnstructuredGridBunykRayCastFunction::Triangle *nextTriangle; + vtkIdType nextTetra; + + this->NumIntersections = 0; + + double nearZ = VTK_DOUBLE_MIN; + double nearPoint[4]; + double viewCoords[4]; + viewCoords[0] = ((float)this->X / (float)(imageViewportSize[0]-1)) * 2.0 - 1.0; + viewCoords[1] = ((float)this->Y / (float)(imageViewportSize[1]-1)) * 2.0 - 1.0; + // viewCoords[2] set when an intersection is found. + viewCoords[3] = 1.0; + if (this->CurrentTriangle) + { + // Find intersection in currentTriangle (the entry point). + nearZ = -( fx*this->CurrentTriangle->A + fy*this->CurrentTriangle->B + + this->CurrentTriangle->D) / this->CurrentTriangle->C; + + viewCoords[2] = nearZ; + + viewToWorld->MultiplyPoint( viewCoords, nearPoint ); + nearPoint[0] /= nearPoint[3]; + nearPoint[1] /= nearPoint[3]; + nearPoint[2] /= nearPoint[3]; + } + + while (this->NumIntersections < this->MaxNumIntersections) + { + // If we have exited the mesh (or are entering it for the first time, + // find the next intersection with an external face (which has already + // been found with rasterization). + if (!this->CurrentTriangle) + { + if (!this->IntersectionPtr) + { + break; // No more intersections. + } + this->CurrentTriangle = this->IntersectionPtr->TriPtr; + this->CurrentTetra = this->IntersectionPtr->TriPtr->ReferredByTetra[0]; + this->IntersectionPtr = this->IntersectionPtr->Next; + + // Find intersection in currentTriangle (the entry point). + nearZ = -( fx*this->CurrentTriangle->A + fy*this->CurrentTriangle->B + + this->CurrentTriangle->D) / this->CurrentTriangle->C; + + viewCoords[2] = nearZ; + + viewToWorld->MultiplyPoint( viewCoords, nearPoint ); + nearPoint[0] /= nearPoint[3]; + nearPoint[1] /= nearPoint[3]; + nearPoint[2] /= nearPoint[3]; + } + + // Find all triangles that the ray may exit. + vtkUnstructuredGridBunykRayCastFunction::Triangle *candidate[3]; + + int index = 0; + int i; + for ( i = 0; i < 4; i++ ) + { + if ( triangles[this->CurrentTetra*4+i] != this->CurrentTriangle ) + { + if ( index == 3 ) + { + vtkGenericWarningMacro( "Ugh - found too many triangles!" ); + } + else + { + candidate[index++] = triangles[this->CurrentTetra*4+i]; + } + } + } + + double farZ = VTK_DOUBLE_MAX; + int minIdx = -1; + + // Determine which face the ray exits the cell from. + for ( i = 0; i < 3; i++ ) + { + // Far intersection is the nearest intersectation that is farther + // than nearZ. + double tmpZ = 1.0; + if (candidate[i]->C != 0.0) + { + tmpZ = + -( fx*candidate[i]->A + + fy*candidate[i]->B + + candidate[i]->D) / candidate[i]->C; + } + if (tmpZ > nearZ && tmpZ < farZ) + { + farZ = tmpZ; + minIdx = i; + } + } + + // Now, the code above should ensure that farZ > nearZ, but I have + // seen the case where we reach here with farZ == nearZ. This is very + // bad as we need ensure we always move forward so that we do not get + // into loops. I think there is something with GCC 3.2.3 that makes + // the optimizer be too ambitous and turn the > into >=. + if ((minIdx == -1) || (farZ <= nearZ)) + { + // The ray never exited the cell? Perhaps numerical inaccuracies + // got us here. Just bail out as if we exited the mesh. + nextTriangle = NULL; + nextTetra = -1; + } + else + { + if (farZ > this->FarClipZ) + { + // Exit happened after point of interest. Bail out now (in case + // we wish to restart). + return; + } + + if (this->IntersectedCells) + { + this->IntersectedCells[this->NumIntersections] = this->CurrentTetra; + } + + nextTriangle = candidate[minIdx]; + + // Compute intersection with exiting face. + double farPoint[4]; + viewCoords[2] = farZ; + viewToWorld->MultiplyPoint( viewCoords, farPoint ); + farPoint[0] /= farPoint[3]; + farPoint[1] /= farPoint[3]; + farPoint[2] /= farPoint[3]; + double dist + = sqrt( (nearPoint[0]-farPoint[0])*(nearPoint[0]-farPoint[0]) + + (nearPoint[1]-farPoint[1])*(nearPoint[1]-farPoint[1]) + + (nearPoint[2]-farPoint[2])*(nearPoint[2]-farPoint[2]) ); + + if (this->IntersectionLengths) + { + this->IntersectionLengths[this->NumIntersections] = dist; + } + + // compute the barycentric weights + float ax, ay; + double a1, b1, c1; + ax = points[3*this->CurrentTriangle->PointIndex[0]]; + ay = points[3*this->CurrentTriangle->PointIndex[0]+1]; + b1 = ((fx-ax)*this->CurrentTriangle->P2Y - (fy-ay)*this->CurrentTriangle->P2X) / this->CurrentTriangle->Denominator; + c1 = ((fy-ay)*this->CurrentTriangle->P1X - (fx-ax)*this->CurrentTriangle->P1Y) / this->CurrentTriangle->Denominator; + a1 = 1.0 - b1 - c1; + + double a2, b2, c2; + ax = points[3*nextTriangle->PointIndex[0]]; + ay = points[3*nextTriangle->PointIndex[0]+1]; + b2 = ((fx-ax)*nextTriangle->P2Y - (fy-ay)*nextTriangle->P2X) / nextTriangle->Denominator; + c2 = ((fy-ay)*nextTriangle->P1X - (fx-ax)*nextTriangle->P1Y) / nextTriangle->Denominator; + a2 = 1.0 - b2 - c2; + + if (nearIntersectionArray) + { + for (int c = 0; c < this->NumComponents; c++) + { + ValueType A, B, C; + A = scalarArray->GetTypedComponent(this->CurrentTriangle->PointIndex[0], c); + B = scalarArray->GetTypedComponent(this->CurrentTriangle->PointIndex[1], c); + C = scalarArray->GetTypedComponent(this->CurrentTriangle->PointIndex[2], c); + nearIntersectionArray->SetTypedComponent( + this->NumIntersections, c, + static_cast(a1 * A + b1 * B + c1 * C)); + } + } + + if (farIntersectionArray) + { + for (int c = 0; c < this->NumComponents; c++) + { + ValueType A, B, C; + A = scalarArray->GetTypedComponent(nextTriangle->PointIndex[0], c); + B = scalarArray->GetTypedComponent(nextTriangle->PointIndex[1], c); + C = scalarArray->GetTypedComponent(nextTriangle->PointIndex[2], c); + farIntersectionArray->SetTypedComponent( + this->NumIntersections, c, + static_cast(a2 * A + b2 * B + c2 * C)); + } + } + + this->NumIntersections++; + + // The far triangle has one or two tetras in its referred list. + // If one, return -1 for next tetra and NULL for next triangle + // since we are exiting. If two, return the one that isn't the + // current one. + if ( (nextTriangle)->ReferredByTetra[1] == -1 ) + { + nextTetra = -1; + nextTriangle = NULL; + } + else + { + if ( nextTriangle->ReferredByTetra[0] == this->CurrentTetra ) + { + nextTetra = nextTriangle->ReferredByTetra[1]; + } + else + { + nextTetra = nextTriangle->ReferredByTetra[0]; + } + } + + nearZ = farZ; + nearPoint[0] = farPoint[0]; + nearPoint[1] = farPoint[1]; + nearPoint[2] = farPoint[2]; + nearPoint[3] = farPoint[3]; + } + + this->CurrentTriangle = nextTriangle; + this->CurrentTetra = nextTetra; + } + } +}; + +} // end anon namespace //----------------------------------------------------------------------------- @@ -121,21 +402,15 @@ void vtkUnstructuredGridBunykRayCastIterator::Initialize(int x, int y) this->CurrentTetra = -1; // Intersect cells until we get to Bounds[0] (the near clip plane). - while(TemplateCastRay((const float *)NULL, - this->RayCastFunction, 0, - this->RayPosition[0], this->RayPosition[1], - this->Bounds[0], - this->IntersectionPtr, - this->CurrentTriangle, - this->CurrentTetra, - (vtkIdType *)NULL, - (double *)NULL, - (float *)NULL, - (float *)NULL, - this->MaxNumberOfIntersections) > 0) + TemplateCastRayWorker worker( + this->RayCastFunction, 0, this->RayPosition[0], this->RayPosition[1], + this->Bounds[0], this->IntersectionPtr, this->CurrentTriangle, + this->CurrentTetra, NULL, NULL, this->MaxNumberOfIntersections); + do { - ; + worker(); } + while (worker.NumIntersections > 0); } vtkIdType vtkUnstructuredGridBunykRayCastIterator::GetNextIntersections( @@ -159,13 +434,15 @@ vtkIdType vtkUnstructuredGridBunykRayCastIterator::GetNextIntersections( if (!scalars) { - numIntersections = TemplateCastRay - ((const float *)NULL, this->RayCastFunction, 0, - this->RayPosition[0], this->RayPosition[1], this->Bounds[1], - this->IntersectionPtr, this->CurrentTriangle, this->CurrentTetra, - (intersectedCells ? intersectedCells->GetPointer(0) : NULL), - (intersectionLengths ? intersectionLengths->GetPointer(0) : NULL), - (float *)NULL, (float *)NULL, this->MaxNumberOfIntersections); + TemplateCastRayWorker worker( + this->RayCastFunction, 0, this->RayPosition[0], this->RayPosition[1], + this->Bounds[1], this->IntersectionPtr, this->CurrentTriangle, + this->CurrentTetra, + intersectedCells ? intersectedCells->GetPointer(0) : NULL, + intersectionLengths ? intersectionLengths->GetPointer(0) : NULL, + this->MaxNumberOfIntersections); + worker(); + numIntersections = worker.NumIntersections; } else { @@ -180,18 +457,25 @@ vtkIdType vtkUnstructuredGridBunykRayCastIterator::GetNextIntersections( farIntersections->SetNumberOfComponents(scalars->GetNumberOfComponents()); farIntersections->SetNumberOfTuples(this->MaxNumberOfIntersections); - switch (scalars->GetDataType()) + TemplateCastRayWorker worker( + this->RayCastFunction, scalars->GetNumberOfComponents(), + this->RayPosition[0], this->RayPosition[1], this->Bounds[1], + this->IntersectionPtr, this->CurrentTriangle, this->CurrentTetra, + intersectedCells ? intersectedCells->GetPointer(0) : NULL, + intersectionLengths ? intersectionLengths->GetPointer(0) : NULL, + this->MaxNumberOfIntersections + ); + + if (!vtkArrayDispatch::Dispatch3SameValueType::Execute(scalars, + nearIntersections, + farIntersections, + worker)) { - vtkDataArrayIteratorMacro(scalars, - numIntersections = TemplateCastRay( - vtkDABegin, this->RayCastFunction, scalars->GetNumberOfComponents(), - this->RayPosition[0], this->RayPosition[1], this->Bounds[1], - this->IntersectionPtr, this->CurrentTriangle, this->CurrentTetra, - (intersectedCells ? intersectedCells->GetPointer(0) : NULL), - (intersectionLengths ? intersectionLengths->GetPointer(0) : NULL), - static_cast(nearIntersections->GetVoidPointer(0)), - static_cast(farIntersections->GetVoidPointer(0)), - this->MaxNumberOfIntersections)); + vtkWarningMacro("Dispatch failed for scalars and intersections."); + } + else + { + numIntersections = worker.NumIntersections; } nearIntersections->SetNumberOfTuples(numIntersections); @@ -909,256 +1193,6 @@ int vtkUnstructuredGridBunykRayCastFunction::IsTriangleFrontFacing( Triangle *t return false; } -template -vtkIdType TemplateCastRay( - const ScalarIterator scalars, - vtkUnstructuredGridBunykRayCastFunction *self, - int numComponents, - int x, int y, - double farClipZ, - vtkUnstructuredGridBunykRayCastFunction::Intersection *&intersectionPtr, - vtkUnstructuredGridBunykRayCastFunction::Triangle *¤tTriangle, - vtkIdType ¤tTetra, - vtkIdType *intersectedCells, - double *intersectionLengths, - T *nearIntersections, - T *farIntersections, - int maxNumIntersections) -{ - int imageViewportSize[2]; - self->GetImageViewportSize( imageViewportSize ); - - int origin[2]; - self->GetImageOrigin( origin ); - float fx = x - origin[0]; - float fy = y - origin[1]; - - double *points = self->GetPoints(); - vtkUnstructuredGridBunykRayCastFunction::Triangle - **triangles = self->GetTetraTriangles(); - - vtkMatrix4x4 *viewToWorld = self->GetViewToWorldMatrix(); - - vtkUnstructuredGridBunykRayCastFunction::Triangle *nextTriangle; - vtkIdType nextTetra; - - vtkIdType numIntersections = 0; - - double nearZ = VTK_DOUBLE_MIN; - double nearPoint[4]; - double viewCoords[4]; - viewCoords[0] = ((float)x / (float)(imageViewportSize[0]-1)) * 2.0 - 1.0; - viewCoords[1] = ((float)y / (float)(imageViewportSize[1]-1)) * 2.0 - 1.0; - // viewCoords[2] set when an intersection is found. - viewCoords[3] = 1.0; - if (currentTriangle) - { - // Find intersection in currentTriangle (the entry point). - nearZ = -( fx*currentTriangle->A + fy*currentTriangle->B + - currentTriangle->D) / currentTriangle->C; - - viewCoords[2] = nearZ; - - viewToWorld->MultiplyPoint( viewCoords, nearPoint ); - nearPoint[0] /= nearPoint[3]; - nearPoint[1] /= nearPoint[3]; - nearPoint[2] /= nearPoint[3]; - } - - while (numIntersections < maxNumIntersections) - { - // If we have exited the mesh (or are entering it for the first time, - // find the next intersection with an external face (which has already - // been found with rasterization). - if (!currentTriangle) - { - if (!intersectionPtr) - { - break; // No more intersections. - } - currentTriangle = intersectionPtr->TriPtr; - currentTetra = intersectionPtr->TriPtr->ReferredByTetra[0]; - intersectionPtr = intersectionPtr->Next; - - // Find intersection in currentTriangle (the entry point). - nearZ = -( fx*currentTriangle->A + fy*currentTriangle->B + - currentTriangle->D) / currentTriangle->C; - - viewCoords[2] = nearZ; - - viewToWorld->MultiplyPoint( viewCoords, nearPoint ); - nearPoint[0] /= nearPoint[3]; - nearPoint[1] /= nearPoint[3]; - nearPoint[2] /= nearPoint[3]; - } - - // Find all triangles that the ray may exit. - vtkUnstructuredGridBunykRayCastFunction::Triangle *candidate[3]; - - int index = 0; - int i; - for ( i = 0; i < 4; i++ ) - { - if ( triangles[currentTetra*4+i] != currentTriangle ) - { - if ( index == 3 ) - { - vtkGenericWarningMacro( "Ugh - found too many triangles!" ); - } - else - { - candidate[index++] = triangles[currentTetra*4+i]; - } - } - } - - double farZ = VTK_DOUBLE_MAX; - int minIdx = -1; - - // Determine which face the ray exits the cell from. - for ( i = 0; i < 3; i++ ) - { - // Far intersection is the nearest intersectation that is farther - // than nearZ. - double tmpZ = 1.0; - if (candidate[i]->C != 0.0) - { - tmpZ = - -( fx*candidate[i]->A + - fy*candidate[i]->B + - candidate[i]->D) / candidate[i]->C; - } - if (tmpZ > nearZ && tmpZ < farZ) - { - farZ = tmpZ; - minIdx = i; - } - } - - // Now, the code above should ensure that farZ > nearZ, but I have - // seen the case where we reach here with farZ == nearZ. This is very - // bad as we need ensure we always move forward so that we do not get - // into loops. I think there is something with GCC 3.2.3 that makes - // the optimizer be too ambitous and turn the > into >=. - if ((minIdx == -1) || (farZ <= nearZ)) - { - // The ray never exited the cell? Perhaps numerical inaccuracies - // got us here. Just bail out as if we exited the mesh. - nextTriangle = NULL; - nextTetra = -1; - } - else - { - if (farZ > farClipZ) - { - // Exit happened after point of interest. Bail out now (in case - // we wish to restart). - return numIntersections; - } - - if (intersectedCells) - { - intersectedCells[numIntersections] = currentTetra; - } - - nextTriangle = candidate[minIdx]; - - // Compute intersection with exiting face. - double farPoint[4]; - viewCoords[2] = farZ; - viewToWorld->MultiplyPoint( viewCoords, farPoint ); - farPoint[0] /= farPoint[3]; - farPoint[1] /= farPoint[3]; - farPoint[2] /= farPoint[3]; - double dist - = sqrt( (nearPoint[0]-farPoint[0])*(nearPoint[0]-farPoint[0]) - + (nearPoint[1]-farPoint[1])*(nearPoint[1]-farPoint[1]) - + (nearPoint[2]-farPoint[2])*(nearPoint[2]-farPoint[2]) ); - - if (intersectionLengths) - { - intersectionLengths[numIntersections] = dist; - } - - // compute the barycentric weights - float ax, ay; - double a1, b1, c1; - ax = points[3*currentTriangle->PointIndex[0]]; - ay = points[3*currentTriangle->PointIndex[0]+1]; - b1 = ((fx-ax)*currentTriangle->P2Y - (fy-ay)*currentTriangle->P2X) / currentTriangle->Denominator; - c1 = ((fy-ay)*currentTriangle->P1X - (fx-ax)*currentTriangle->P1Y) / currentTriangle->Denominator; - a1 = 1.0 - b1 - c1; - - double a2, b2, c2; - ax = points[3*nextTriangle->PointIndex[0]]; - ay = points[3*nextTriangle->PointIndex[0]+1]; - b2 = ((fx-ax)*nextTriangle->P2Y - (fy-ay)*nextTriangle->P2X) / nextTriangle->Denominator; - c2 = ((fy-ay)*nextTriangle->P1X - (fx-ax)*nextTriangle->P1Y) / nextTriangle->Denominator; - a2 = 1.0 - b2 - c2; - - if (nearIntersections) - { - for (int c = 0; c < numComponents; c++) - { - double A, B, C; - A = *(scalars + numComponents*currentTriangle->PointIndex[0] + c); - B = *(scalars + numComponents*currentTriangle->PointIndex[1] + c); - C = *(scalars + numComponents*currentTriangle->PointIndex[2] + c); - nearIntersections[numComponents*numIntersections + c] - = static_cast(a1 * A + b1 * B + c1 * C); - } - } - - if (farIntersections) - { - for (int c = 0; c < numComponents; c++) - { - double A, B, C; - A = *(scalars + numComponents*nextTriangle->PointIndex[0] + c); - B = *(scalars + numComponents*nextTriangle->PointIndex[1] + c); - C = *(scalars + numComponents*nextTriangle->PointIndex[2] + c); - farIntersections[numComponents*numIntersections + c] - = static_cast(a2 * A + b2 * B + c2 * C); - } - } - - numIntersections++; - - // The far triangle has one or two tetras in its referred list. - // If one, return -1 for next tetra and NULL for next triangle - // since we are exiting. If two, return the one that isn't the - // current one. - if ( (nextTriangle)->ReferredByTetra[1] == -1 ) - { - nextTetra = -1; - nextTriangle = NULL; - } - else - { - if ( nextTriangle->ReferredByTetra[0] == currentTetra ) - { - nextTetra = nextTriangle->ReferredByTetra[1]; - } - else - { - nextTetra = nextTriangle->ReferredByTetra[0]; - } - } - - nearZ = farZ; - nearPoint[0] = farPoint[0]; - nearPoint[1] = farPoint[1]; - nearPoint[2] = farPoint[2]; - nearPoint[3] = farPoint[3]; - } - - currentTriangle = nextTriangle; - currentTetra = nextTetra; - } - - return numIntersections; -} - vtkUnstructuredGridVolumeRayCastIterator *vtkUnstructuredGridBunykRayCastFunction::NewIterator() { diff --git a/Rendering/Volume/vtkUnstructuredGridBunykRayCastFunction.h b/Rendering/Volume/vtkUnstructuredGridBunykRayCastFunction.h index 2cde860ec76..48feb43e656 100644 --- a/Rendering/Volume/vtkUnstructuredGridBunykRayCastFunction.h +++ b/Rendering/Volume/vtkUnstructuredGridBunykRayCastFunction.h @@ -84,7 +84,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridBunykRayCastFunction : public vtkTypeMacro(vtkUnstructuredGridBunykRayCastFunction,vtkUnstructuredGridVolumeRayCastFunction); virtual void PrintSelf(ostream& os, vtkIndent indent); -//BTX // Description: // Called by the ray cast mapper at the start of rendering virtual void Initialize( vtkRenderer *ren, vtkVolume *vol ); @@ -93,6 +92,7 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridBunykRayCastFunction : public // Called by the ray cast mapper at the end of rendering virtual void Finalize(); + VTK_NEWINSTANCE virtual vtkUnstructuredGridVolumeRayCastIterator *NewIterator(); // Used to store each triangle - made public because of the @@ -148,8 +148,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridBunykRayCastFunction : public // Access to an internal structure for the templated method. Intersection *GetIntersectionList( int x, int y ) { return this->Image[y*this->ImageSize[0] + x]; } -//ETX - protected: vtkUnstructuredGridBunykRayCastFunction(); ~vtkUnstructuredGridBunykRayCastFunction(); @@ -196,7 +194,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridBunykRayCastFunction : public vtkUnstructuredGridBase *SavedTriangleListInput; vtkTimeStamp SavedTriangleListMTime; -//BTX // This is a memory intensive algorithm! For each tetra in the // input data we create up to 4 triangles (we don't create duplicates) // This is the TriangleList. Then, for each tetra we keep track of @@ -254,8 +251,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridBunykRayCastFunction : public // triangles. void ComputePixelIntersections(); -//ETX - private: vtkUnstructuredGridBunykRayCastFunction(const vtkUnstructuredGridBunykRayCastFunction&); // Not implemented. void operator=(const vtkUnstructuredGridBunykRayCastFunction&); // Not implemented. diff --git a/Rendering/Volume/vtkUnstructuredGridPartialPreIntegration.h b/Rendering/Volume/vtkUnstructuredGridPartialPreIntegration.h index 70a02321887..7fb345f5b46 100644 --- a/Rendering/Volume/vtkUnstructuredGridPartialPreIntegration.h +++ b/Rendering/Volume/vtkUnstructuredGridPartialPreIntegration.h @@ -94,9 +94,8 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridPartialPreIntegration : publi vtkTimeStamp TransferFunctionsModified; int NumIndependentComponents; -//BTX enum {PSI_TABLE_SIZE = 512}; -//ETX + static float PsiTable[PSI_TABLE_SIZE*PSI_TABLE_SIZE]; static int PsiTableBuilt; diff --git a/Rendering/Volume/vtkUnstructuredGridVolumeMapper.h b/Rendering/Volume/vtkUnstructuredGridVolumeMapper.h index d45eab5f211..c117a7d7b34 100644 --- a/Rendering/Volume/vtkUnstructuredGridVolumeMapper.h +++ b/Rendering/Volume/vtkUnstructuredGridVolumeMapper.h @@ -53,9 +53,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeMapper : public vtkAbst { this->SetBlendMode( vtkUnstructuredGridVolumeMapper::MAXIMUM_INTENSITY_BLEND ); } vtkGetMacro( BlendMode, int ); - -//BTX - // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS @@ -75,8 +72,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeMapper : public vtkAbst MAXIMUM_INTENSITY_BLEND }; -//ETX - protected: vtkUnstructuredGridVolumeMapper(); ~vtkUnstructuredGridVolumeMapper(); diff --git a/Rendering/Volume/vtkUnstructuredGridVolumeRayCastFunction.h b/Rendering/Volume/vtkUnstructuredGridVolumeRayCastFunction.h index 115d08c4040..1a75b453028 100644 --- a/Rendering/Volume/vtkUnstructuredGridVolumeRayCastFunction.h +++ b/Rendering/Volume/vtkUnstructuredGridVolumeRayCastFunction.h @@ -38,7 +38,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeRayCastFunction : publi vtkTypeMacro(vtkUnstructuredGridVolumeRayCastFunction,vtkObject); virtual void PrintSelf(ostream& os, vtkIndent indent); -//BTX virtual void Initialize( vtkRenderer *ren, vtkVolume *vol )=0; virtual void Finalize( )=0; @@ -47,9 +46,8 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeRayCastFunction : publi // Returns a new object that will iterate over all the intersections of a // ray with the cells of the input. The calling code is responsible for // deleting the returned object. + VTK_NEWINSTANCE virtual vtkUnstructuredGridVolumeRayCastIterator *NewIterator() = 0; -//ETX - protected: vtkUnstructuredGridVolumeRayCastFunction() {} diff --git a/Rendering/Volume/vtkUnstructuredGridVolumeRayCastMapper.h b/Rendering/Volume/vtkUnstructuredGridVolumeRayCastMapper.h index dedb91d8a8a..a55b97f2c5e 100644 --- a/Rendering/Volume/vtkUnstructuredGridVolumeRayCastMapper.h +++ b/Rendering/Volume/vtkUnstructuredGridVolumeRayCastMapper.h @@ -96,7 +96,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeRayCastMapper : public virtual void SetRayIntegrator(vtkUnstructuredGridVolumeRayIntegrator *ri); vtkGetObjectMacro(RayIntegrator, vtkUnstructuredGridVolumeRayIntegrator); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // Initialize rendering for this volume. @@ -113,8 +112,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeRayCastMapper : public vtkGetVectorMacro( ImageOrigin, int, 2 ); vtkGetVectorMacro( ImageViewportSize, int , 2 ); -//ETX - void CastRays( int threadID, int threadCount ); protected: diff --git a/Rendering/Volume/vtkUnstructuredGridVolumeZSweepMapper.h b/Rendering/Volume/vtkUnstructuredGridVolumeZSweepMapper.h index 74ad7163b8e..5c0c7662bb9 100644 --- a/Rendering/Volume/vtkUnstructuredGridVolumeZSweepMapper.h +++ b/Rendering/Volume/vtkUnstructuredGridVolumeZSweepMapper.h @@ -49,7 +49,6 @@ class vtkDoubleArray; class vtkUnstructuredGridVolumeRayIntegrator; class vtkRenderWindow; -//BTX // Internal classes namespace vtkUnstructuredGridVolumeZSweepMapperNamespace { @@ -63,7 +62,6 @@ namespace vtkUnstructuredGridVolumeZSweepMapperNamespace class vtkVertexEntry; class vtkPixelListEntryMemory; }; -//ETX class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeZSweepMapper : public vtkUnstructuredGridVolumeMapper { @@ -129,7 +127,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeZSweepMapper : public v virtual void SetRayIntegrator(vtkUnstructuredGridVolumeRayIntegrator *ri); vtkGetObjectMacro(RayIntegrator, vtkUnstructuredGridVolumeRayIntegrator); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS @@ -140,7 +137,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeZSweepMapper : public v vtkGetVectorMacro( ImageInUseSize, int, 2 ); vtkGetVectorMacro( ImageOrigin, int, 2 ); vtkGetVectorMacro( ImageViewportSize, int , 2 ); -//ETX protected: vtkUnstructuredGridVolumeZSweepMapper(); @@ -185,7 +181,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeZSweepMapper : public v // Perform scan conversion of a triangle face. void RasterizeFace(vtkIdType faceIds[3], int externalSide); -//BTX // Description: // Perform scan conversion of a triangle defined by its vertices. // \pre ve0_exists: ve0!=0 @@ -216,7 +211,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeZSweepMapper : public v vtkUnstructuredGridVolumeZSweepMapperNamespace::vtkVertexEntry *v0, vtkUnstructuredGridVolumeZSweepMapperNamespace::vtkVertexEntry *v1, bool exitFace); -//ETX void StoreRenderTime(vtkRenderer *ren, vtkVolume *vol, @@ -302,7 +296,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeZSweepMapper : public v double FaceScalars[2]; int FaceSide; -//BTX vtkUnstructuredGridVolumeZSweepMapperNamespace::vtkSpan *Span; vtkUnstructuredGridVolumeZSweepMapperNamespace::vtkPixelListFrame *PixelListFrame; @@ -340,7 +333,7 @@ class VTKRENDERINGVOLUME_EXPORT vtkUnstructuredGridVolumeZSweepMapper : public v vtkUnstructuredGridVolumeZSweepMapperNamespace::vtkPixelListEntryMemory *MemoryManager; -//ETX + private: vtkUnstructuredGridVolumeZSweepMapper(const vtkUnstructuredGridVolumeZSweepMapper&); // Not implemented. void operator=(const vtkUnstructuredGridVolumeZSweepMapper&); // Not implemented. diff --git a/Rendering/Volume/vtkVolumeMapper.h b/Rendering/Volume/vtkVolumeMapper.h index 49703ef7922..31b5825c163 100644 --- a/Rendering/Volume/vtkVolumeMapper.h +++ b/Rendering/Volume/vtkVolumeMapper.h @@ -113,8 +113,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeMapper : public vtkAbstractVolumeMapper void SetCroppingRegionFlagsToInvertedCross() {this->SetCroppingRegionFlags( VTK_CROP_INVERTED_CROSS );}; -//BTX - // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS @@ -135,7 +133,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeMapper : public vtkAbstractVolumeMapper MINIMUM_INTENSITY_BLEND, ADDITIVE_BLEND }; -//ETX protected: vtkVolumeMapper(); diff --git a/Rendering/Volume/vtkVolumeOutlineSource.cxx b/Rendering/Volume/vtkVolumeOutlineSource.cxx index cc47250dbd6..f6ddc46f918 100644 --- a/Rendering/Volume/vtkVolumeOutlineSource.cxx +++ b/Rendering/Volume/vtkVolumeOutlineSource.cxx @@ -490,7 +490,7 @@ void vtkVolumeOutlineSource::GeneratePolys( // Color the face if (scalars) { - scalars->InsertNextTupleValue(colors[active]); + scalars->InsertNextTypedTuple(colors[active]); } } @@ -615,7 +615,7 @@ void vtkVolumeOutlineSource::GenerateLines( // Change color if current segment is on active plane if (scalars && active) { - scalars->SetTupleValue(cellId, colors[active]); + scalars->SetTypedTuple(cellId, colors[active]); } foundDuplicate = 1; break; @@ -632,7 +632,7 @@ void vtkVolumeOutlineSource::GenerateLines( // Color the line segment if (scalars) { - scalars->InsertNextTupleValue(colors[active]); + scalars->InsertNextTypedTuple(colors[active]); } } } diff --git a/Rendering/Volume/vtkVolumeRayCastCompositeFunction.h b/Rendering/Volume/vtkVolumeRayCastCompositeFunction.h index c40f7651671..cdbbdc7939f 100644 --- a/Rendering/Volume/vtkVolumeRayCastCompositeFunction.h +++ b/Rendering/Volume/vtkVolumeRayCastCompositeFunction.h @@ -52,23 +52,19 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastCompositeFunction : public vtkVo {this->SetCompositeMethod(VTK_COMPOSITE_CLASSIFY_FIRST);} const char *GetCompositeMethodAsString(void); -//BTX void CastRay( vtkVolumeRayCastDynamicInfo *dynamicInfo, vtkVolumeRayCastStaticInfo *staticInfo); float GetZeroOpacityThreshold( vtkVolume *vol ); -//ETX protected: vtkVolumeRayCastCompositeFunction(); ~vtkVolumeRayCastCompositeFunction(); -//BTX void SpecificFunctionInitialize( vtkRenderer *ren, vtkVolume *vol, vtkVolumeRayCastStaticInfo *staticInfo, vtkVolumeRayCastMapper *mapper ); -//ETX int CompositeMethod; private: diff --git a/Rendering/Volume/vtkVolumeRayCastFunction.h b/Rendering/Volume/vtkVolumeRayCastFunction.h index de7a6c52062..ddf5644a00a 100644 --- a/Rendering/Volume/vtkVolumeRayCastFunction.h +++ b/Rendering/Volume/vtkVolumeRayCastFunction.h @@ -136,7 +136,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastFunction : public vtkObject vtkTypeMacro(vtkVolumeRayCastFunction,vtkObject); virtual void PrintSelf(ostream& os, vtkIndent indent); -//BTX // Description: // Do the basic initialization. This includes saving the parameters // passed in into local variables, as well as grabbing some useful @@ -149,7 +148,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastFunction : public vtkObject virtual void CastRay( vtkVolumeRayCastDynamicInfo *dynamicInfo, vtkVolumeRayCastStaticInfo *staticInfo )=0; -//ETX // Description: // Get the value below which all scalar values are considered to @@ -163,7 +161,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastFunction : public vtkObject } ~vtkVolumeRayCastFunction() {} -//BTX // Description: // This method gives the subclass a chance to do any special // initialization that it may need to do @@ -171,7 +168,7 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastFunction : public vtkObject vtkVolume *vol, vtkVolumeRayCastStaticInfo *staticInfo, vtkVolumeRayCastMapper *mapper )=0; -//ETX + private: vtkVolumeRayCastFunction(const vtkVolumeRayCastFunction&); // Not implemented. void operator=(const vtkVolumeRayCastFunction&); // Not implemented. diff --git a/Rendering/Volume/vtkVolumeRayCastIsosurfaceFunction.h b/Rendering/Volume/vtkVolumeRayCastIsosurfaceFunction.h index 4de63e3b85a..a63ff8d7ac4 100644 --- a/Rendering/Volume/vtkVolumeRayCastIsosurfaceFunction.h +++ b/Rendering/Volume/vtkVolumeRayCastIsosurfaceFunction.h @@ -63,21 +63,18 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastIsosurfaceFunction : public vtkV // These variables are filled in by SpecificFunctionInitialize float Color[3]; -//BTX void CastRay( vtkVolumeRayCastDynamicInfo *dynamicInfo, vtkVolumeRayCastStaticInfo *staticInfo); -//ETX protected: vtkVolumeRayCastIsosurfaceFunction(); ~vtkVolumeRayCastIsosurfaceFunction(); -//BTX void SpecificFunctionInitialize( vtkRenderer *ren, vtkVolume *vol, vtkVolumeRayCastStaticInfo *staticInfo, vtkVolumeRayCastMapper *mapper ); -//ETX + private: vtkVolumeRayCastIsosurfaceFunction(const vtkVolumeRayCastIsosurfaceFunction&); // Not implemented. void operator=(const vtkVolumeRayCastIsosurfaceFunction&); // Not implemented. diff --git a/Rendering/Volume/vtkVolumeRayCastMIPFunction.h b/Rendering/Volume/vtkVolumeRayCastMIPFunction.h index 68f2e25a906..75761eaa9bb 100644 --- a/Rendering/Volume/vtkVolumeRayCastMIPFunction.h +++ b/Rendering/Volume/vtkVolumeRayCastMIPFunction.h @@ -64,11 +64,8 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastMIPFunction : public vtkVolumeRa {this->SetMaximizeMethod(VTK_MAXIMIZE_OPACITY);} const char *GetMaximizeMethodAsString(void); -//BTX void CastRay( vtkVolumeRayCastDynamicInfo *dynamicInfo, vtkVolumeRayCastStaticInfo *staticInfo ); -//ETX - protected: vtkVolumeRayCastMIPFunction(); @@ -76,13 +73,11 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastMIPFunction : public vtkVolumeRa int MaximizeMethod; -//BTX void SpecificFunctionInitialize( vtkRenderer *ren, vtkVolume *vol, vtkVolumeRayCastStaticInfo *staticInfo, vtkVolumeRayCastMapper *mapper ); -//ETX private: vtkVolumeRayCastMIPFunction(const vtkVolumeRayCastMIPFunction&); // Not implemented. void operator=(const vtkVolumeRayCastMIPFunction&); // Not implemented. diff --git a/Rendering/Volume/vtkVolumeRayCastMapper.h b/Rendering/Volume/vtkVolumeRayCastMapper.h index be8d137af4f..30143a5069c 100644 --- a/Rendering/Volume/vtkVolumeRayCastMapper.h +++ b/Rendering/Volume/vtkVolumeRayCastMapper.h @@ -130,7 +130,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastMapper : public vtkVolumeMapper vtkGetMacro( IntermixIntersectingGeometry, int ); vtkBooleanMacro( IntermixIntersectingGeometry, int ); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // Initialize rendering for this volume. @@ -158,8 +157,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastMapper : public vtkVolumeMapper virtual float GetGradientMagnitudeBias(int) {return this->GetGradientMagnitudeBias();}; -//ETX - protected: vtkVolumeRayCastMapper(); ~vtkVolumeRayCastMapper(); @@ -169,7 +166,7 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastMapper : public vtkVolumeMapper vtkEncodedGradientShader *GradientShader; vtkRayCastImageDisplayHelper *ImageDisplayHelper; - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; // The distance between sample points along the ray double SampleDistance; diff --git a/Rendering/Volume/vtkVolumeRayCastSpaceLeapingImageFilter.cxx b/Rendering/Volume/vtkVolumeRayCastSpaceLeapingImageFilter.cxx index 4d7c26a1274..a44d633d3be 100644 --- a/Rendering/Volume/vtkVolumeRayCastSpaceLeapingImageFilter.cxx +++ b/Rendering/Volume/vtkVolumeRayCastSpaceLeapingImageFilter.cxx @@ -59,6 +59,11 @@ vtkVolumeRayCastSpaceLeapingImageFilter::vtkVolumeRayCastSpaceLeapingImageFilter this->GradientOpacityTable[i] = NULL; } this->Cache = NULL; + + // Ensure that no splits occur along X or Y axes when multithreading, + // there seems to be a bug with the increments that requires this. + this->SplitPath[0] = 2; + this->SplitPathLength = 1; } //---------------------------------------------------------------------------- @@ -135,8 +140,7 @@ ::InternalRequestUpdateExtent( int *inExt, //---------------------------------------------------------------------------- static void -vtkVolumeRayCastSpaceLeapingImageFilterClearOutput(vtkDataArray *scalars, - vtkImageData *outData, +vtkVolumeRayCastSpaceLeapingImageFilterClearOutput(vtkImageData *outData, int outExt[6], int nComponents ) { @@ -146,10 +150,7 @@ vtkVolumeRayCastSpaceLeapingImageFilterClearOutput(vtkDataArray *scalars, // Get increments to march through the thread's output extents vtkIdType outInc0, outInc1, outInc2; - outData->GetContinuousIncrements(scalars, - outExt, outInc0, outInc1, outInc2); - outInc1 *= 3; - outInc2 *= 3; + outData->GetContinuousIncrements(outExt, outInc0, outInc1, outInc2); // A. Initialize the arrays with a blank flag. int i,j,k; @@ -680,8 +681,7 @@ ::FillScalarAndGradientOpacityFlags( vtkImageData *outData, int outExt[6] ) // Get increments to march through the output vtkIdType outInc0, outInc1, outInc2; - outData->GetContinuousIncrements(this->CurrentScalars, - outExt, outInc0, outInc1, outInc2); + outData->GetContinuousIncrements(outExt, outInc0, outInc1, outInc2); // Now process the flags @@ -768,11 +768,7 @@ ::FillScalarOpacityFlags( vtkImageData *outData, int outExt[6] ) // Get increments to march through the output vtkIdType outInc0, outInc1, outInc2; - outData->GetContinuousIncrements(this->CurrentScalars, - outExt, outInc0, outInc1, outInc2); - - outInc1 *= 3; - outInc2 *= 3; + outData->GetContinuousIncrements(outExt, outInc0, outInc1, outInc2); // Now process the flags @@ -873,8 +869,8 @@ void vtkVolumeRayCastSpaceLeapingImageFilter::ThreadedRequestData( if (this->ComputeMinMax) { - vtkVolumeRayCastSpaceLeapingImageFilterClearOutput(this->CurrentScalars, - outData[0], outExt, nComponents ); + vtkVolumeRayCastSpaceLeapingImageFilterClearOutput( + outData[0], outExt, nComponents ); } diff --git a/Rendering/Volume/vtkVolumeRayCastSpaceLeapingImageFilter.h b/Rendering/Volume/vtkVolumeRayCastSpaceLeapingImageFilter.h index a522eb2977f..2b845aeff8e 100644 --- a/Rendering/Volume/vtkVolumeRayCastSpaceLeapingImageFilter.h +++ b/Rendering/Volume/vtkVolumeRayCastSpaceLeapingImageFilter.h @@ -132,7 +132,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastSpaceLeapingImageFilter : public unsigned short * GetMinNonZeroScalarIndex(); unsigned char * GetMinNonZeroGradientMagnitudeIndex(); - //BTX // Description: // Pointer to the pre-computed gradient magnitude structure. This is pre- // computed by the vtkFixedPointVolumeRayCastMapper class. This should be @@ -145,7 +144,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastSpaceLeapingImageFilter : public // component by the vtkFixedPointVolumeRayCastMapper void SetScalarOpacityTable( int c, unsigned short * t); void SetGradientOpacityTable( int c, unsigned short * t ); - //ETX // Description: // INTERNAL - Do not use @@ -154,12 +152,10 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeRayCastSpaceLeapingImageFilter : public vtkIdType ComputeOffset(const int ext[6], const int wholeExt[6], int nComponents); - //BTX // This method helps debug. It writes out a specific component of the // computed min-max-volume structure //static void WriteMinMaxVolume( int component, unsigned short *minMaxVolume, // int minMaxVolumeSize[4], const char *filename ); - //ETX protected: vtkVolumeRayCastSpaceLeapingImageFilter(); diff --git a/Rendering/Volume/vtkVolumeTextureMapper.h b/Rendering/Volume/vtkVolumeTextureMapper.h index e9cf8e2cdd3..c1457cfb497 100644 --- a/Rendering/Volume/vtkVolumeTextureMapper.h +++ b/Rendering/Volume/vtkVolumeTextureMapper.h @@ -48,7 +48,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeTextureMapper : public vtkVolumeMapper // Get the gradient shader. vtkGetObjectMacro( GradientShader, vtkEncodedGradientShader ); -//BTX // Description: // Allow access to the arrays / variables from the templated functions in the // subclasses. @@ -83,8 +82,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeTextureMapper : public vtkVolumeMapper virtual float GetGradientMagnitudeBias(int) { return this->GetGradientMagnitudeBias(); }; -//ETX - // Description: // see vtkAlgorithm for details virtual int ProcessRequest(vtkInformation*, @@ -97,7 +94,7 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeTextureMapper : public vtkVolumeMapper void InitializeRender( vtkRenderer *ren, vtkVolume *vol ); - virtual void ReportReferences(vtkGarbageCollector*); + void ReportReferences(vtkGarbageCollector*) VTK_OVERRIDE; // Objects / variables needed for shading / gradient magnitude opacity vtkEncodedGradientEstimator *GradientEstimator; diff --git a/Rendering/Volume/vtkVolumeTextureMapper2D.h b/Rendering/Volume/vtkVolumeTextureMapper2D.h index 03a61740ebb..55ff8f0f115 100644 --- a/Rendering/Volume/vtkVolumeTextureMapper2D.h +++ b/Rendering/Volume/vtkVolumeTextureMapper2D.h @@ -63,8 +63,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeTextureMapper2D : public vtkVolumeTextu vtkSetMacro( MaximumStorageSize, int ); vtkGetMacro( MaximumStorageSize, int ); -//BTX - // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS @@ -88,9 +86,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeTextureMapper2D : public vtkVolumeTextu unsigned char *GetTexture() {return this->Texture;}; -//ETX - - protected: vtkVolumeTextureMapper2D(); ~vtkVolumeTextureMapper2D(); diff --git a/Rendering/Volume/vtkVolumeTextureMapper3D.h b/Rendering/Volume/vtkVolumeTextureMapper3D.h index 3ff28dd427c..94ee4a99af9 100644 --- a/Rendering/Volume/vtkVolumeTextureMapper3D.h +++ b/Rendering/Volume/vtkVolumeTextureMapper3D.h @@ -125,8 +125,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeTextureMapper3D : public vtkVolumeMappe // the image. vtkGetMacro( ActualSampleDistance, float ); -//BTX - // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS @@ -146,7 +144,6 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeTextureMapper3D : public vtkVolumeMappe // Description: // Returns the number of components of the point scalar field int GetNumberOfScalarComponents(vtkImageData *input); -//ETX // Description: // Set the preferred render method. If it is supported, this @@ -235,13 +232,12 @@ class VTKRENDERINGVOLUME_EXPORT vtkVolumeTextureMapper3D : public vtkVolumeMappe // Description: // Impemented in subclass - check is texture size is OK. - //BTX + virtual int IsTextureSizeSupported(int vtkNotUsed(size)[3], int vtkNotUsed(components)) { return 0; } - //ETX private: vtkVolumeTextureMapper3D(const vtkVolumeTextureMapper3D&); // Not implemented. diff --git a/Rendering/VolumeAMR/vtkAMRVolumeMapper.h b/Rendering/VolumeAMR/vtkAMRVolumeMapper.h index 8381f221734..f0ada221b86 100644 --- a/Rendering/VolumeAMR/vtkAMRVolumeMapper.h +++ b/Rendering/VolumeAMR/vtkAMRVolumeMapper.h @@ -129,7 +129,6 @@ class VTKRENDERINGVOLUMEAMR_EXPORT vtkAMRVolumeMapper : public vtkVolumeMapper virtual void SetCroppingRegionFlags(int mode); virtual int GetCroppingRegionFlags(); -//BTX // The possible values for the default and current render mode ivars enum { @@ -141,7 +140,6 @@ class VTKRENDERINGVOLUMEAMR_EXPORT vtkAMRVolumeMapper : public vtkVolumeMapper UndefinedRenderMode, InvalidRenderMode }; -//ETX // Description: // Set the requested render mode. The default is @@ -208,7 +206,6 @@ class VTKRENDERINGVOLUMEAMR_EXPORT vtkAMRVolumeMapper : public vtkVolumeMapper vtkSetVector3Macro(NumberOfSamples,int); vtkGetVector3Macro(NumberOfSamples,int); -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS @@ -230,7 +227,6 @@ class VTKRENDERINGVOLUMEAMR_EXPORT vtkAMRVolumeMapper : public vtkVolumeMapper vtkInformationVector *outputVector); void UpdateResampler(vtkRenderer *ren, vtkOverlappingAMR *amr); void UpdateResamplerFrustrumMethod(vtkRenderer *ren, vtkOverlappingAMR *amr); -//ETX // Description: //Select the type of resampling techinque approach to use. diff --git a/Rendering/VolumeOpenGL/vtkOpenGLGPUVolumeRayCastMapper.cxx b/Rendering/VolumeOpenGL/vtkOpenGLGPUVolumeRayCastMapper.cxx index 0468cc7e143..fb00bbc20a1 100644 --- a/Rendering/VolumeOpenGL/vtkOpenGLGPUVolumeRayCastMapper.cxx +++ b/Rendering/VolumeOpenGL/vtkOpenGLGPUVolumeRayCastMapper.cxx @@ -89,8 +89,9 @@ #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLError.h" -// Uncomment the following line to debug Snow Leopard -//#define APPLE_SNOW_LEOPARD_BUG +#if defined(__APPLE__) +#include +#endif //----------------------------------------------------------------------------- // @@ -1506,11 +1507,6 @@ void vtkOpenGLGPUVolumeRayCastMapper::CheckFrameBufferStatus() default: cout << "Unknown framebuffer status=0x" << hex<< status << dec << endl; } - // DO NOT REMOVE THE FOLLOWING COMMENTED LINE. FOR DEBUGGING PURPOSE. -#ifdef APPLE_SNOW_LEOPARD_BUG - this->DisplayFrameBufferAttachments(); - this->DisplayReadAndDrawBuffers(); -#endif } //----------------------------------------------------------------------------- @@ -2153,15 +2149,19 @@ void vtkOpenGLGPUVolumeRayCastMapper::LoadExtensions( } vtkOpenGLExtensionManager *extensions = context->GetExtensionManager(); - // It does not work on Apple OS X Snow Leopard with nVidia. - // However it works with Apple OS X Lion with nVidia - // There is a bug in the OpenGL driver with an error in the + // It does not work on Mac OS X 10.6 (Snow Leopard) with nVidia. + // There is a bug in that OpenGL driver with an error in the // Cg compiler about an infinite loop. -#if defined(__APPLE__) && !defined(APPLE_SNOW_LEOPARD_BUG) - const char *minNVIDIAVersion = "2.1 NVIDIA-8"; - const char *version = extensions->GetDriverGLVersion(); - if (!extensions->DriverIsNvidia() || - strncmp(version, minNVIDIAVersion, strlen(minNVIDIAVersion)) < 0) + // However it works with Mac OS X 10.7 (Lion) with nVidia. +#if defined(__APPLE__) && (MAC_OS_X_VERSION_MIN_REQUIRED < 1070) + // Gestalt() is deprecated, but all this code will go away when 10.7 is VTK's minimum. + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdeprecated-declarations" + SInt32 major, minor; + Gestalt (gestaltSystemVersionMajor, &major); + Gestalt (gestaltSystemVersionMinor, &minor); + #pragma clang diagnostic pop + if (extensions->DriverIsNvidia() && (major == 10) && (minor == 6)) { this->UnsupportedRequiredExtensions->Stream << " Disabled on unsupported Apple OS X driver."; @@ -4259,10 +4259,6 @@ void vtkOpenGLGPUVolumeRayCastMapper::PreRender(vtkRenderer *ren, parallelProjection,rayCastMethod,shadeMethod, componentMethod); -#ifdef APPLE_SNOW_LEOPARD_BUG - this->Program->Build(); -#endif - vtkUniformVariables *v=this->Program->GetUniformVariables(); // for active texture 0, dataset @@ -4332,18 +4328,6 @@ void vtkOpenGLGPUVolumeRayCastMapper::PreRender(vtkRenderer *ren, this->CheckFrameBufferStatus(); -#ifdef APPLE_SNOW_LEOPARD_BUG - this->Program->SendUniforms(); - cout << "BEFORE isValid0" << endl; - if(!this->Program->IsValid()) - { - cout <Program->GetLastValidateLog() << endl; - this->Program->PrintActiveUniformVariablesOnCout(); - v->Print(cout); - } - cout << "AFTER isValid0" << endl; -#endif - if(this->NumberOfCroppingRegions>1) { // framebuffer texture @@ -4359,18 +4343,6 @@ void vtkOpenGLGPUVolumeRayCastMapper::PreRender(vtkRenderer *ren, } this->CheckFrameBufferStatus(); -#ifdef APPLE_SNOW_LEOPARD_BUG - this->Program->SendUniforms(); - cout << "BEFORE isValid1" << endl; - if(!this->Program->IsValid()) - { - cout <Program->GetLastValidateLog() << endl; - this->Program->PrintActiveUniformVariablesOnCout(); - v->Print(cout); - } - cout << "AFTER isValid1" << endl; -#endif - // max scalar value framebuffer texture if(this->BlendMode==vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND || this->BlendMode==vtkGPUVolumeRayCastMapper::MINIMUM_INTENSITY_BLEND @@ -4386,19 +4358,6 @@ void vtkOpenGLGPUVolumeRayCastMapper::PreRender(vtkRenderer *ren, this->CheckFrameBufferStatus(); -#ifdef APPLE_SNOW_LEOPARD_BUG - this->Program->SendUniforms(); - cout << "BEFORE isValid2" << endl; - if(!this->Program->IsValid()) - { - cout <Program->GetLastValidateLog() << endl; - this->Program->PrintActiveUniformVariablesOnCout(); - v->Print(cout); - } - cout << "AFTER isValid2" << endl; -#endif - - fvalue[0]=static_cast(lowerLeft[0]); fvalue[1]=static_cast(lowerLeft[1]); v->SetUniformf("windowLowerLeftCorner",2,fvalue); @@ -5934,14 +5893,6 @@ int vtkOpenGLGPUVolumeRayCastMapper::RenderSubVolume(vtkRenderer *ren, this->LoadProjectionParameters(ren,volume); this->ClipBoundingBox(ren,bounds,volume); this->Program->SendUniforms(); -#ifdef APPLE_SNOW_LEOPARD_BUG - if(!this->Program->IsValid()) - { - cout << "line " << __LINE__ << " " << - this->Program->GetLastValidateLog() << endl; - } - this->Program->PrintActiveUniformVariablesOnCout(); -#endif int abort=this->RenderClippedBoundingBox(1,0,1,ren->GetRenderWindow()); if (!abort) { diff --git a/Rendering/VolumeOpenGL/vtkOpenGLHAVSVolumeMapper.h b/Rendering/VolumeOpenGL/vtkOpenGLHAVSVolumeMapper.h index 562a3fbbf38..844dfb5a48d 100644 --- a/Rendering/VolumeOpenGL/vtkOpenGLHAVSVolumeMapper.h +++ b/Rendering/VolumeOpenGL/vtkOpenGLHAVSVolumeMapper.h @@ -148,7 +148,6 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkOpenGLHAVSVolumeMapper ~vtkOpenGLHAVSVolumeMapper(); virtual int FillInputPortInformation(int port, vtkInformation* info); -//BTX virtual void Initialize(vtkRenderer *ren, vtkVolume *vol); virtual void InitializeLookupTables(vtkVolume *vol); void InitializeGPUDataStructures(); @@ -185,7 +184,6 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkOpenGLHAVSVolumeMapper unsigned int TransferFunctionTexture; vtkWeakPointer RenderWindow; -//ETX private: vtkOpenGLHAVSVolumeMapper(const vtkOpenGLHAVSVolumeMapper&); // Not implemented. diff --git a/Rendering/VolumeOpenGL/vtkOpenGLVolumeTextureMapper2D.h b/Rendering/VolumeOpenGL/vtkOpenGLVolumeTextureMapper2D.h index 6887a5ac457..048b4ecc2ff 100644 --- a/Rendering/VolumeOpenGL/vtkOpenGLVolumeTextureMapper2D.h +++ b/Rendering/VolumeOpenGL/vtkOpenGLVolumeTextureMapper2D.h @@ -38,8 +38,6 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkOpenGLVolumeTextureMapper2D static vtkOpenGLVolumeTextureMapper2D *New(); -//BTX - // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS @@ -49,8 +47,6 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkOpenGLVolumeTextureMapper2D void RenderQuads( int count, float *v, float *t, unsigned char *texture, int size[2], int reverseFlag); -//ETX - protected: vtkOpenGLVolumeTextureMapper2D(); ~vtkOpenGLVolumeTextureMapper2D(); diff --git a/Rendering/VolumeOpenGL/vtkOpenGLVolumeTextureMapper3D.h b/Rendering/VolumeOpenGL/vtkOpenGLVolumeTextureMapper3D.h index 65e3115a36c..c7d2d6e9a0e 100644 --- a/Rendering/VolumeOpenGL/vtkOpenGLVolumeTextureMapper3D.h +++ b/Rendering/VolumeOpenGL/vtkOpenGLVolumeTextureMapper3D.h @@ -49,16 +49,12 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkOpenGLVolumeTextureMapper3D int IsRenderSupported(vtkVolumeProperty *, vtkRenderer *ren); -//BTX - // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS // Render the volume virtual void Render(vtkRenderer *ren, vtkVolume *vol); -//ETX - // Desciption: // Initialize when we go to render, or go to answer the // IsRenderSupported question. Don't call unless we have @@ -75,8 +71,6 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkOpenGLVolumeTextureMapper3D vtkOpenGLVolumeTextureMapper3D(); ~vtkOpenGLVolumeTextureMapper3D(); -//BTX - void GetLightInformation(vtkRenderer *ren, vtkVolume *vol, GLfloat lightDirection[2][4], @@ -84,7 +78,6 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkOpenGLVolumeTextureMapper3D GLfloat lightSpecularColor[2][4], GLfloat halfwayVector[2][4], GLfloat *ambient ); -//ETX int Initialized; GLuint Volume1Index; diff --git a/Rendering/VolumeOpenGL/vtkSmartVolumeMapper.h b/Rendering/VolumeOpenGL/vtkSmartVolumeMapper.h index a767552747d..3ee18e9e01b 100644 --- a/Rendering/VolumeOpenGL/vtkSmartVolumeMapper.h +++ b/Rendering/VolumeOpenGL/vtkSmartVolumeMapper.h @@ -147,7 +147,6 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkSmartVolumeMapper : public vtkVolumeMap // Get the final color level. vtkGetMacro( FinalColorLevel, float ); -//BTX // The possible values for the default and current render mode ivars enum { @@ -159,7 +158,6 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkSmartVolumeMapper : public vtkVolumeMap UndefinedRenderMode, InvalidRenderMode }; -//ETX // Description: // Set the requested render mode. The default is @@ -263,8 +261,6 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkSmartVolumeMapper : public vtkVolumeMap double viewDirection[3], double viewUp[3] ); - -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // Initialize rendering for this volume. @@ -276,7 +272,6 @@ class VTKRENDERINGVOLUMEOPENGL_EXPORT vtkSmartVolumeMapper : public vtkVolumeMap // The parameter window could be used to determine which graphic // resources to release. void ReleaseGraphicsResources(vtkWindow *); -//ETX protected: vtkSmartVolumeMapper(); diff --git a/Rendering/VolumeOpenGL2/module.cmake b/Rendering/VolumeOpenGL2/module.cmake index 49997431f8e..c85afeacfb8 100644 --- a/Rendering/VolumeOpenGL2/module.cmake +++ b/Rendering/VolumeOpenGL2/module.cmake @@ -4,6 +4,7 @@ vtk_module(vtkRenderingVolumeOpenGL2 DEPENDS vtkglew vtkRenderingOpenGL2 + vtkIOImage IMPLEMENTS vtkRenderingVolume BACKEND diff --git a/Rendering/VolumeOpenGL2/shaders/raycasterfs.glsl b/Rendering/VolumeOpenGL2/shaders/raycasterfs.glsl index 838c3ca2849..09100bb01b4 100644 --- a/Rendering/VolumeOpenGL2/shaders/raycasterfs.glsl +++ b/Rendering/VolumeOpenGL2/shaders/raycasterfs.glsl @@ -71,6 +71,8 @@ uniform vec4 in_volume_bias; //VTK::ComputeRayDirection::Dec +//VTK::Picking::Dec + /// We support only 8 clipping planes for now /// The first value is the size of the data array for clipping /// planes (origin, normal) @@ -101,7 +103,9 @@ void main() //VTK::Clipping::Init - //VTK::RenderToImage::Depth::Init + //VTK::RenderToImage::Init + + //VTK::DepthPass::Init /// For all samples along the ray while (!g_exit) @@ -118,7 +122,9 @@ void main() //VTK::Shading::Impl - //VTK::RenderToImage::Depth::Impl + //VTK::RenderToImage::Impl + + //VTK::DepthPass::Impl /// Advance ray g_dataPos += g_dirStep; @@ -136,10 +142,14 @@ void main() //VTK::Shading::Exit + //VTK::Picking::Exit + g_fragColor.r = g_fragColor.r * in_scale + in_bias * g_fragColor.a; g_fragColor.g = g_fragColor.g * in_scale + in_bias * g_fragColor.a; g_fragColor.b = g_fragColor.b * in_scale + in_bias * g_fragColor.a; gl_FragData[0] = g_fragColor; - //VTK::RenderToImage::Depth::Exit + //VTK::RenderToImage::Exit + + //VTK::DepthPass::Exit } diff --git a/Rendering/VolumeOpenGL2/vtkOpenGLGPUVolumeRayCastMapper.cxx b/Rendering/VolumeOpenGL2/vtkOpenGLGPUVolumeRayCastMapper.cxx index d7a5ab8dc97..932e6fa2845 100644 --- a/Rendering/VolumeOpenGL2/vtkOpenGLGPUVolumeRayCastMapper.cxx +++ b/Rendering/VolumeOpenGL2/vtkOpenGLGPUVolumeRayCastMapper.cxx @@ -26,51 +26,55 @@ #include // VTK includes -#include "vtkBoundingBox.h" -#include "vtkCamera.h" -#include "vtkCellArray.h" -#include "vtkCellData.h" -#include "vtkClipConvexPolyData.h" -#include "vtkColorTransferFunction.h" -#include "vtkCommand.h" -#include "vtkDataArray.h" -#include "vtkDensifyPolyData.h" -#include "vtkFloatArray.h" -#include "vtkFrameBufferObject2.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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + #include -#include "vtkImageData.h" -#include "vtkLightCollection.h" -#include "vtkLight.h" -#include "vtkMath.h" -#include "vtkMatrix4x4.h" -#include "vtkNew.h" -#include "vtkObjectFactory.h" -#include "vtkOpenGLError.h" -#include "vtkOpenGLCamera.h" -#include "vtkOpenGLRenderWindow.h" -#include "vtkOpenGLShaderCache.h" -#include "vtkPerlinNoise.h" -#include "vtkPixelBufferObject.h" -#include "vtkPixelExtent.h" -#include "vtkPixelTransfer.h" -#include "vtkPlaneCollection.h" -#include "vtkPointData.h" -#include "vtkPoints.h" -#include "vtkPolyData.h" -#include "vtkRenderer.h" -#include "vtkRenderWindow.h" -#include "vtkShader.h" -#include "vtkShaderProgram.h" -#include "vtkSmartPointer.h" -#include "vtkTessellatedBoxSource.h" -#include "vtkTextureObject.h" -#include "vtkTimerLog.h" -#include "vtkTransform.h" -#include "vtkUnsignedCharArray.h" -#include "vtkUnsignedIntArray.h" -#include "vtkVolumeMask.h" -#include "vtkVolumeProperty.h" -#include "vtkWeakPointer.h" // C/C++ includes #include @@ -112,12 +116,14 @@ class vtkOpenGLGPUVolumeRayCastMapper::vtkInternal this->TextureSize[0] = this->TextureSize[1] = this->TextureSize[2] = -1; this->WindowLowerLeft[0] = this->WindowLowerLeft[1] = 0; this->WindowSize[0] = this->WindowSize[1] = 0; - this->LastWindowSize[0] = this->LastWindowSize[1] = 0; + this->LastDepthPassWindowSize[0] = this->LastDepthPassWindowSize[1] = 0; + this->LastRenderToImageWindowSize[0] = 0; + this->LastRenderToImageWindowSize[1] = 0; this->ScalarsRange[0][0] = this->ScalarsRange[0][1] = 0.0; this->ScalarsRange[1][0] = this->ScalarsRange[1][1] = 0.0; this->ScalarsRange[2][0] = this->ScalarsRange[2][1] = 0.0; this->ScalarsRange[3][0] = this->ScalarsRange[3][1] = 0.0; - + this->CurrentSelectionPass = vtkHardwareSelector::MIN_KNOWN_PASS - 1; this->CellScale[0] = this->CellScale[1] = this->CellScale[2] = 0.0; this->NoiseTextureData = 0; @@ -144,6 +150,11 @@ class vtkOpenGLGPUVolumeRayCastMapper::vtkInternal this->RTTDepthBufferTextureObject = 0; this->RTTDepthTextureObject = 0; this->RTTColorTextureObject = 0; + this->RTTDepthTextureType = -1; + + this->DPFBO = 0; + this->DPDepthBufferTextureObject = 0; + this->DPColorTextureObject = 0; } // Destructor @@ -164,6 +175,12 @@ class vtkOpenGLGPUVolumeRayCastMapper::vtkInternal this->DepthTextureObject = 0; } + if (this->FBO) + { + this->FBO->Delete(); + this->FBO = 0; + } + if (this->RTTDepthBufferTextureObject) { this->RTTDepthBufferTextureObject->Delete(); @@ -247,31 +264,49 @@ class vtkOpenGLGPUVolumeRayCastMapper::vtkInternal // Update noise texture (used to reduce rendering artifacts // specifically banding effects) - void UpdateNoiseTexture(vtkRenderer* ren); + void CreateNoiseTexture(vtkRenderer* ren); // Update depth texture (used for early termination of the ray) - void UpdateDepthTexture(vtkRenderer* ren, vtkVolume* vol); - - // Update parameters for lighting that will be used in the shader. - void UpdateLightingParameters(vtkRenderer* ren, vtkVolume* vol); + void CaptureDepthTexture(vtkRenderer* ren, vtkVolume* vol); // Test if camera is inside the volume geometry bool IsCameraInside(vtkRenderer* ren, vtkVolume* vol); + // Update parameters for lighting that will be used in the shader. + void SetLightingParameters(vtkRenderer* ren, + vtkShaderProgram* prog, + vtkVolume* vol); + // Update the volume geometry - void UpdateVolumeGeometry(vtkRenderer* ren, vtkVolume* vol, + void RenderVolumeGeometry(vtkRenderer* ren, + vtkShaderProgram* prog, + vtkVolume* vol, vtkImageData* input); // Update cropping params to shader - void UpdateCropping(vtkRenderer* ren, vtkVolume* vol); + void SetCroppingRegions(vtkRenderer* ren, vtkShaderProgram* prog, + vtkVolume* vol); // Update clipping params to shader - void UpdateClipping(vtkRenderer* ren, vtkVolume* vol); + void SetClippingPlanes(vtkRenderer* ren, vtkShaderProgram* prog, + vtkVolume* vol); // Update the interval of sampling void UpdateSamplingDistance(vtkImageData *input, vtkRenderer* ren, vtkVolume* vol); + // Check if the mapper should enter picking mode. + void CheckPickingState(vtkRenderer* ren); + + // Configure the vtkHardwareSelector to begin a picking pass. + void BeginPicking(vtkRenderer* ren); + + // Update the prop Id if hardware selection is enabled. + void SetPickingId(vtkRenderer* ren); + + // Configure the vtkHardwareSelector to end a picking pass. + void EndPicking(vtkRenderer* ren); + // Load OpenGL extensiosn required to grab depth sampler buffer void LoadRequireDepthTextureExtensions(vtkRenderWindow* renWin); @@ -285,10 +320,17 @@ class vtkOpenGLGPUVolumeRayCastMapper::vtkInternal void ConvertTextureToImageData(vtkTextureObject* texture, vtkImageData* output); - // Render to framebuffer object - void RenderToFBO(vtkRenderer* ren); + // Render to texture for final rendering + void SetupRenderToTexture(vtkRenderer* ren); + void ExitRenderToTexture(vtkRenderer* ren); + + // Render to texture for depth pass + void SetupDepthPass(vtkRenderer* ren); + void ExitDepthPass(vtkRenderer* ren); + + void ReleaseRenderToTextureGraphicsResources(vtkWindow* win); - void ReleaseRenderToImageGraphicsResources(vtkWindow* win); + void ReleaseDepthPassGraphicsResources(vtkWindow* win); // Private member variables //-------------------------------------------------------------------------- @@ -324,7 +366,8 @@ class vtkOpenGLGPUVolumeRayCastMapper::vtkInternal int TextureSize[3]; int WindowLowerLeft[2]; int WindowSize[2]; - int LastWindowSize[2]; + int LastDepthPassWindowSize[2]; + int LastRenderToImageWindowSize[2]; double ScalarsRange[4][2]; double LoadedBounds[6]; @@ -361,7 +404,8 @@ class vtkOpenGLGPUVolumeRayCastMapper::vtkInternal vtkNew TextureToEyeTransposeInverse; - vtkNew TempMatrix4x4; + vtkNew TempMatrix1; + vtkNew TempMatrix2; vtkSmartPointer BBoxPolyData; @@ -372,6 +416,11 @@ class vtkOpenGLGPUVolumeRayCastMapper::vtkInternal vtkTimeStamp InputUpdateTime; vtkTimeStamp VolumeUpdateTime; vtkTimeStamp ReleaseResourcesTime; + vtkTimeStamp DepthPassTime; + vtkTimeStamp DepthPassSetupTime; + vtkTimeStamp SelectionStateTime; + int CurrentSelectionPass; + bool IsPicking; bool NeedToInitializeResources; @@ -382,6 +431,15 @@ class vtkOpenGLGPUVolumeRayCastMapper::vtkInternal vtkTextureObject* RTTDepthBufferTextureObject; vtkTextureObject* RTTDepthTextureObject; vtkTextureObject* RTTColorTextureObject; + int RTTDepthTextureType; + + vtkFrameBufferObject2* DPFBO; + vtkTextureObject* DPDepthBufferTextureObject; + vtkTextureObject* DPColorTextureObject; + + vtkNew ContourFilter; + vtkNew ContourMapper; + vtkNew ContourActor; }; //---------------------------------------------------------------------------- @@ -1258,7 +1316,7 @@ int vtkOpenGLGPUVolumeRayCastMapper::vtkInternal:: } //---------------------------------------------------------------------------- -void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateNoiseTexture( +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::CreateNoiseTexture( vtkRenderer* ren) { if (!this->NoiseTextureObject) @@ -1323,7 +1381,7 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateNoiseTexture( } //---------------------------------------------------------------------------- -void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateDepthTexture( +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::CaptureDepthTexture( vtkRenderer* ren, vtkVolume* vtkNotUsed(vol)) { // Make sure our render window is the current OpenGL context @@ -1373,10 +1431,10 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateDepthTexture( } //---------------------------------------------------------------------------- -void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateLightingParameters( - vtkRenderer* ren, vtkVolume* vol) +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetLightingParameters( + vtkRenderer* ren, vtkShaderProgram* prog, vtkVolume* vol) { - if (!this->ShaderProgram) + if (!ren || !prog || !vol) { return; } @@ -1386,8 +1444,7 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateLightingParameters( return; } - this->ShaderProgram->SetUniformi("in_twoSidedLighting", - ren->GetTwoSidedLighting()); + prog->SetUniformi("in_twoSidedLighting", ren->GetTwoSidedLighting()); // for lightkit case there are some parameters to set vtkCamera* cam = ren->GetActiveCamera(); @@ -1436,15 +1493,15 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateLightingParameters( } } - this->ShaderProgram->SetUniform3fv("in_lightAmbientColor", + prog->SetUniform3fv("in_lightAmbientColor", numberOfLights, lightAmbientColor); - this->ShaderProgram->SetUniform3fv("in_lightDiffuseColor", + prog->SetUniform3fv("in_lightDiffuseColor", numberOfLights, lightDiffuseColor); - this->ShaderProgram->SetUniform3fv("in_lightSpecularColor", + prog->SetUniform3fv("in_lightSpecularColor", numberOfLights, lightSpecularColor); - this->ShaderProgram->SetUniform3fv("in_lightDirection", + prog->SetUniform3fv("in_lightDirection", numberOfLights, lightDirection); - this->ShaderProgram->SetUniformi("in_numberOfLights", + prog->SetUniformi("in_numberOfLights", numberOfLights); // we are done unless we have positional lights @@ -1481,19 +1538,21 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateLightingParameters( numberOfLights++; } } - this->ShaderProgram->SetUniform3fv("in_lightAttenuation", numberOfLights, lightAttenuation); - this->ShaderProgram->SetUniform1iv("in_lightPositional", numberOfLights, lightPositional); - this->ShaderProgram->SetUniform3fv("in_lightPosition", numberOfLights, lightPosition); - this->ShaderProgram->SetUniform1fv("in_lightExponent", numberOfLights, lightExponent); - this->ShaderProgram->SetUniform1fv("in_lightConeAngle", numberOfLights, lightConeAngle); + prog->SetUniform3fv("in_lightAttenuation", numberOfLights, lightAttenuation); + prog->SetUniform1iv("in_lightPositional", numberOfLights, lightPositional); + prog->SetUniform3fv("in_lightPosition", numberOfLights, lightPosition); + prog->SetUniform1fv("in_lightExponent", numberOfLights, lightExponent); + prog->SetUniform1fv("in_lightConeAngle", numberOfLights, lightConeAngle); } //---------------------------------------------------------------------------- bool vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::IsCameraInside( - vtkRenderer* ren, vtkVolume* vtkNotUsed(vol)) + vtkRenderer* ren, vtkVolume* vol) { - vtkMatrix4x4::Transpose(this->InverseVolumeMat.GetPointer(), - this->TempMatrix4x4.GetPointer()); + this->TempMatrix1->DeepCopy(vol->GetMatrix()); + this->TempMatrix1->Invert(); + this->TempMatrix2->DeepCopy(this->TempMatrix1.GetPointer()); + this->TempMatrix2->Transpose(); vtkCamera* cam = ren->GetActiveCamera(); double camWorldRange[2]; @@ -1505,7 +1564,7 @@ bool vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::IsCameraInside( cam->GetPosition(camWorldPos); camWorldPos[3] = 1.0; - this->InverseVolumeMat->MultiplyPoint( camWorldPos, camPos ); + this->TempMatrix1->MultiplyPoint( camWorldPos, camPos ); if ( camPos[3] ) { camPos[0] /= camPos[3]; @@ -1524,7 +1583,7 @@ bool vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::IsCameraInside( camWorldDirection[3] = 1.0; // Compute the normalized near plane normal - this->TempMatrix4x4->MultiplyPoint( camWorldDirection, camPlaneNormal ); + this->TempMatrix2->MultiplyPoint( camWorldDirection, camPlaneNormal ); vtkMath::Normalize(camWorldDirection); vtkMath::Normalize(camPlaneNormal); @@ -1538,7 +1597,8 @@ bool vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::IsCameraInside( camNearWorldPoint[2] = camWorldPos[2] + camWorldRange[0]*camWorldDirection[2]; camNearWorldPoint[3] = 1.; - this->InverseVolumeMat->MultiplyPoint( camNearWorldPoint, camNearPoint ); + this->TempMatrix1->Transpose(); + this->TempMatrix1->MultiplyPoint( camNearWorldPoint, camNearPoint ); if (camNearPoint[3]!=0.0) { camNearPoint[0] /= camNearPoint[3]; @@ -1556,8 +1616,9 @@ bool vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::IsCameraInside( } //---------------------------------------------------------------------------- -void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateVolumeGeometry( - vtkRenderer* ren, vtkVolume* vol, vtkImageData* input) +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::RenderVolumeGeometry( + vtkRenderer* ren, vtkShaderProgram* prog, + vtkVolume* vol, vtkImageData* input) { if (this->NeedToInitializeResources || input->GetMTime() > this->InputUpdateTime.GetMTime() || @@ -1576,9 +1637,10 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateVolumeGeometry( { // Normals should be transformed using the transpose of inverse // InverseVolumeMat - vtkNew tempMat; - vtkMatrix4x4::Transpose(this->InverseVolumeMat.GetPointer(), - tempMat.GetPointer()); + this->TempMatrix1->DeepCopy(vol->GetMatrix()); + this->TempMatrix1->Invert(); + this->TempMatrix2->DeepCopy(this->TempMatrix1.GetPointer()); + this->TempMatrix2->Transpose(); vtkCamera* cam = ren->GetActiveCamera(); double camWorldRange[2]; @@ -1590,7 +1652,7 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateVolumeGeometry( cam->GetPosition(camWorldPos); camWorldPos[3] = 1.0; - this->InverseVolumeMat->MultiplyPoint( camWorldPos, camPos ); + this->TempMatrix1->MultiplyPoint( camWorldPos, camPos ); if ( camPos[3] ) { camPos[0] /= camPos[3]; @@ -1609,7 +1671,7 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateVolumeGeometry( camWorldDirection[3] = 1.0; // Compute the normalized near plane normal - tempMat->MultiplyPoint( camWorldDirection, camPlaneNormal ); + this->TempMatrix2->MultiplyPoint( camWorldDirection, camPlaneNormal ); vtkMath::Normalize(camWorldDirection); vtkMath::Normalize(camPlaneNormal); @@ -1630,7 +1692,7 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateVolumeGeometry( camFarWorldPoint[2] = camWorldPos[2] + camWorldRange[1]*camWorldDirection[2]; camFarWorldPoint[3] = 1.; - this->InverseVolumeMat->MultiplyPoint( camNearWorldPoint, camNearPoint ); + this->TempMatrix1->MultiplyPoint( camNearWorldPoint, camNearPoint ); if (camNearPoint[3]!=0.0) { camNearPoint[0] /= camNearPoint[3]; @@ -1638,7 +1700,7 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateVolumeGeometry( camNearPoint[2] /= camNearPoint[3]; } - this->InverseVolumeMat->MultiplyPoint( camFarWorldPoint, camFarPoint ); + this->TempMatrix1->MultiplyPoint( camFarWorldPoint, camFarPoint ); if (camFarPoint[3]!=0.0) { camFarPoint[0] /= camFarPoint[3]; @@ -1722,15 +1784,16 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateVolumeGeometry( { glBindVertexArray(this->CubeVAOId); } + // Pass cube vertices to buffer object memory glBindBuffer (GL_ARRAY_BUFFER, this->CubeVBOId); glBufferData (GL_ARRAY_BUFFER, points->GetData()->GetDataSize() * points->GetData()->GetDataTypeSize(), points->GetData()->GetVoidPointer(0), GL_STATIC_DRAW); - this->ShaderProgram->EnableAttributeArray("in_vertexPos"); - this->ShaderProgram->UseAttributeArray("in_vertexPos", 0, 0, VTK_FLOAT, - 3, vtkShaderProgram::NoNormalize); + prog->EnableAttributeArray("in_vertexPos"); + prog->UseAttributeArray("in_vertexPos", 0, 0, VTK_FLOAT, + 3, vtkShaderProgram::NoNormalize); glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->CubeIndicesId); glBufferData (GL_ELEMENT_ARRAY_BUFFER, polys->GetDataSize() * @@ -1743,8 +1806,8 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateVolumeGeometry( if (!vtkOpenGLRenderWindow::GetContextSupportsOpenGL32()) { glBindBuffer (GL_ARRAY_BUFFER, this->CubeVBOId); - this->ShaderProgram->EnableAttributeArray("in_vertexPos"); - this->ShaderProgram->UseAttributeArray("in_vertexPos", 0, 0, VTK_FLOAT, + prog->EnableAttributeArray("in_vertexPos"); + prog->UseAttributeArray("in_vertexPos", 0, 0, VTK_FLOAT, 3, vtkShaderProgram::NoNormalize); glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->CubeIndicesId); } @@ -1754,11 +1817,30 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateVolumeGeometry( glBindVertexArray(this->CubeVAOId); } } + + glDrawElements(GL_TRIANGLES, + this->BBoxPolyData->GetNumberOfCells() * 3, + GL_UNSIGNED_INT, 0); + +#ifdef __APPLE__ + if (!vtkOpenGLRenderWindow::GetContextSupportsOpenGL32()) + { + glBindBuffer (GL_ARRAY_BUFFER, 0); + glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0); + } + else +#endif + { + glBindVertexArray(0); + glBindBuffer (GL_ARRAY_BUFFER, 0); + glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0); + } } //---------------------------------------------------------------------------- -void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateCropping( - vtkRenderer* vtkNotUsed(ren), vtkVolume* vtkNotUsed(vol)) +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetCroppingRegions( + vtkRenderer* vtkNotUsed(ren), vtkShaderProgram* prog, + vtkVolume* vtkNotUsed(vol)) { if (this->Parent->GetCropping()) { @@ -1801,7 +1883,7 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateCropping( static_cast(croppingRegionPlanes[4]), static_cast(croppingRegionPlanes[5]) }; - this->ShaderProgram->SetUniform1fv("in_croppingPlanes", 6, cropPlanes); + prog->SetUniform1fv("in_croppingPlanes", 6, cropPlanes); const int numberOfRegions = 32; int cropFlagsArray[numberOfRegions]; cropFlagsArray[0] = 0; @@ -1817,15 +1899,14 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateCropping( cropFlagsArray[i] = 0; } - this->ShaderProgram->SetUniform1iv("in_croppingFlags", - numberOfRegions, - cropFlagsArray); + prog->SetUniform1iv("in_croppingFlags", numberOfRegions, cropFlagsArray); } } //---------------------------------------------------------------------------- -void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateClipping( - vtkRenderer* vtkNotUsed(ren), vtkVolume* vtkNotUsed(vol)) +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetClippingPlanes( + vtkRenderer* vtkNotUsed(ren), vtkShaderProgram* prog, + vtkVolume* vtkNotUsed(vol)) { if (this->Parent->GetClippingPlanes()) { @@ -1853,9 +1934,88 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::UpdateClipping( clippingPlanes[0] = clippingPlanes.size() > 1 ? static_cast(clippingPlanes.size() - 1): 0; - this->ShaderProgram->SetUniform1fv("in_clippingPlanes", - static_cast(clippingPlanes.size()), - &clippingPlanes[0]); + prog->SetUniform1fv("in_clippingPlanes", + static_cast(clippingPlanes.size()), + &clippingPlanes[0]); + } +} + +// ----------------------------------------------------------------------------- +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::CheckPickingState(vtkRenderer* ren) +{ + vtkHardwareSelector* selector = ren->GetSelector(); + bool selectorPicking = selector != NULL; + if (selector) + { + // this mapper currently only supports cell picking + selectorPicking &= selector->GetFieldAssociation() == vtkDataObject::FIELD_ASSOCIATION_CELLS; + } + + this->IsPicking = selectorPicking || ren->GetRenderWindow()->GetIsPicking(); + if (this->IsPicking) + { + // rebuild the shader on every pass + this->SelectionStateTime.Modified(); + this->CurrentSelectionPass = selector ? selector->GetCurrentPass() : vtkHardwareSelector::ACTOR_PASS; + } + else if (this->CurrentSelectionPass != vtkHardwareSelector::MIN_KNOWN_PASS - 1) + { + // return to the regular rendering state + this->SelectionStateTime.Modified(); + this->CurrentSelectionPass = vtkHardwareSelector::MIN_KNOWN_PASS - 1; + } +} + +// ----------------------------------------------------------------------------- +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::BeginPicking(vtkRenderer* ren) +{ + vtkHardwareSelector* selector = ren->GetSelector(); + if (selector && this->IsPicking) + { + selector->BeginRenderProp(); + + if (this->CurrentSelectionPass >= vtkHardwareSelector::ID_LOW24) + { + selector->RenderAttributeId(0); + } + } +} + +//------------------------------------------------------------------------------ +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetPickingId + (vtkRenderer* ren) +{ + float propIdColor[3] = {0.0, 0.0, 0.0}; + vtkHardwareSelector* selector = ren->GetSelector(); + + if (selector && this->IsPicking) + { + // query the selector for the appropriate id + selector->GetPropColorValue(propIdColor); + } + else // RenderWindow is picking + { + unsigned int const idx = ren->GetCurrentPickId(); + vtkHardwareSelector::Convert(idx, propIdColor); + } + + this->ShaderProgram->SetUniform3f("in_propId", propIdColor); +} + +// --------------------------------------------------------------------------- +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::EndPicking(vtkRenderer* ren) +{ + vtkHardwareSelector* selector = ren->GetSelector(); + if(selector && this->IsPicking) + { + if (this->CurrentSelectionPass >= vtkHardwareSelector::ID_LOW24) + { + // tell the selector the maximum number of cells that the mapper could render + unsigned int const numVoxels = (this->Extents[1] - this->Extents[0]) * + (this->Extents[3] - this->Extents[2]) * (this->Extents[5] - this->Extents[4]); + selector->RenderAttributeId(numVoxels); + } + selector->EndRenderProp(); } } @@ -1985,8 +2145,7 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::DeleteBufferObjects() //---------------------------------------------------------------------------- void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal:: - ConvertTextureToImageData(vtkTextureObject* texture, - vtkImageData* output) + ConvertTextureToImageData(vtkTextureObject* texture, vtkImageData* output) { if (!texture) { @@ -1998,43 +2157,34 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal:: int tt = texture->GetVTKDataType(); vtkPixelExtent texExt(0U, tw-1U, 0U, th-1U); - vtkPixelExtent subExt(texExt); - vtkUnsignedCharArray* ta = vtkUnsignedCharArray::New(); - ta->SetNumberOfComponents(tnc); - ta->SetNumberOfTuples(subExt.Size()); - ta->SetName("tex"); - unsigned char *pTa = ta->GetPointer(0); + int dataExt[6]={0,0, 0,0, 0,0}; + texExt.GetData(dataExt); + + double dataOrigin[6] = {0, 0, 0, 0, 0, 0}; + + vtkImageData *id = vtkImageData::New(); + id->SetOrigin(dataOrigin); + id->SetDimensions(tw, th, 1); + id->SetExtent(dataExt); + id->AllocateScalars(tt, tnc); vtkPixelBufferObject *pbo = texture->Download(); vtkPixelTransfer::Blit(texExt, - subExt, - subExt, - subExt, + texExt, + texExt, + texExt, tnc, tt, pbo->MapPackedBuffer(), tnc, - VTK_UNSIGNED_CHAR, - pTa); + tt, + id->GetScalarPointer(0, 0, 0)); pbo->UnmapPackedBuffer(); pbo->Delete(); - int dataExt[6]={0,0, 0,0, 0,0}; - texExt.CellToNode(); - texExt.GetData(dataExt); - - double dataOrigin[6] = {0, 0, 0, 0, 0, 0}; - - vtkImageData *id = vtkImageData::New(); - id->SetExtent(dataExt); - id->SetOrigin(dataOrigin); - id->SetDimensions(tw, th, 1); - id->GetPointData()->SetScalars(ta); - ta->Delete(); - if (!output) { output = vtkImageData::New(); @@ -2044,97 +2194,227 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal:: } //---------------------------------------------------------------------------- -void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::RenderToFBO(vtkRenderer* ren) +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetupRenderToTexture( + vtkRenderer* ren) +{ + if (this->Parent->RenderToImage && this->Parent->CurrentPass == RenderPass) + { + if ( (this->LastRenderToImageWindowSize[0] != this->WindowSize[0]) || + (this->LastRenderToImageWindowSize[1] != this->WindowSize[1]) ) + { + this->LastRenderToImageWindowSize[0] = this->WindowSize[0]; + this->LastRenderToImageWindowSize[1] = this->WindowSize[1]; + this->ReleaseRenderToTextureGraphicsResources(ren->GetRenderWindow()); + } + + if (!this->FBO) + { + this->FBO = vtkFrameBufferObject2::New(); + } + + this->FBO->SetContext(vtkOpenGLRenderWindow::SafeDownCast( + ren->GetRenderWindow())); + + this->FBO->Bind(GL_FRAMEBUFFER); + this->FBO->InitializeViewport(this->WindowSize[0], this->WindowSize[1]); + + int depthImageScalarType = this->Parent->GetDepthImageScalarType(); + bool initDepthTexture = true; + // Re-instantiate the depth texture object if the scalar type requested has + // changed from the last frame + if (this->RTTDepthTextureObject && + this->RTTDepthTextureType == depthImageScalarType) + { + initDepthTexture = false; + } + + if (initDepthTexture) + { + if (this->RTTDepthTextureObject) + { + this->RTTDepthTextureObject->Delete(); + this->RTTDepthTextureObject = 0; + } + this->RTTDepthTextureObject = vtkTextureObject::New(); + this->RTTDepthTextureObject->SetContext( + vtkOpenGLRenderWindow::SafeDownCast( + ren->GetRenderWindow())); + this->RTTDepthTextureObject->Create2D(this->WindowSize[0], + this->WindowSize[1], 1, + depthImageScalarType, false); + this->RTTDepthTextureObject->Activate(); + this->RTTDepthTextureObject->SetMinificationFilter( + vtkTextureObject::Nearest); + this->RTTDepthTextureObject->SetMagnificationFilter( + vtkTextureObject::Nearest); + this->RTTDepthTextureObject->SetAutoParameters(0); + + // Cache the value of the scalar type + this->RTTDepthTextureType = depthImageScalarType; + } + + if (!this->RTTColorTextureObject) + { + this->RTTColorTextureObject = vtkTextureObject::New(); + + this->RTTColorTextureObject->SetContext( + vtkOpenGLRenderWindow::SafeDownCast( + ren->GetRenderWindow())); + this->RTTColorTextureObject->Create2D(this->WindowSize[0], + this->WindowSize[1], 4, + VTK_UNSIGNED_CHAR, false); + this->RTTColorTextureObject->Activate(); + this->RTTColorTextureObject->SetMinificationFilter( + vtkTextureObject::Nearest); + this->RTTColorTextureObject->SetMagnificationFilter( + vtkTextureObject::Nearest); + this->RTTColorTextureObject->SetAutoParameters(0); + } + + if (!this->RTTDepthBufferTextureObject) + { + this->RTTDepthBufferTextureObject = vtkTextureObject::New(); + this->RTTDepthBufferTextureObject->SetContext( + vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow())); + this->RTTDepthBufferTextureObject->AllocateDepth( + this->WindowSize[0], this->WindowSize[1], vtkTextureObject::Float32); + this->RTTDepthBufferTextureObject->Activate(); + this->RTTDepthBufferTextureObject->SetMinificationFilter( + vtkTextureObject::Nearest); + this->RTTDepthBufferTextureObject->SetMagnificationFilter( + vtkTextureObject::Nearest); + this->RTTDepthBufferTextureObject->SetAutoParameters(0); + } + + this->FBO->Bind(GL_FRAMEBUFFER); + this->FBO->AddTexDepthAttachment( + GL_DRAW_FRAMEBUFFER, + this->RTTDepthBufferTextureObject->GetHandle()); + this->FBO->AddTexColorAttachment( + GL_DRAW_FRAMEBUFFER, 0U, + this->RTTColorTextureObject->GetHandle()); + this->FBO->AddTexColorAttachment( + GL_DRAW_FRAMEBUFFER, 1U, + this->RTTDepthTextureObject->GetHandle()); + this->FBO->ActivateDrawBuffers(2); + + this->FBO->CheckFrameBufferStatus(GL_FRAMEBUFFER); + + glClearColor(1.0, 1.0, 1.0, 0.0); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + } +} + +//---------------------------------------------------------------------------- +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ExitRenderToTexture( + vtkRenderer* vtkNotUsed(ren)) { - if ( (this->LastWindowSize[0] != this->WindowSize[0]) || - (this->LastWindowSize[1] != this->WindowSize[1]) ) + if (this->Parent->RenderToImage && this->Parent->CurrentPass == RenderPass) { - this->LastWindowSize[0] = this->WindowSize[0]; - this->LastWindowSize[1] = this->WindowSize[1]; - this->ReleaseRenderToImageGraphicsResources(ren->GetRenderWindow()); + this->FBO->RemoveTexDepthAttachment(GL_DRAW_FRAMEBUFFER); + this->FBO->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 0U); + this->FBO->RemoveTexColorAttachment(GL_DRAW_FRAMEBUFFER, 1U); + this->FBO->DeactivateDrawBuffers(); + this->FBO->UnBind(GL_FRAMEBUFFER); + + this->RTTDepthBufferTextureObject->Deactivate(); + this->RTTColorTextureObject->Deactivate(); + this->RTTDepthTextureObject->Deactivate(); + } +} + +//---------------------------------------------------------------------------- +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::SetupDepthPass( + vtkRenderer* ren) +{ + if ( (this->LastDepthPassWindowSize[0] != this->WindowSize[0]) || + (this->LastDepthPassWindowSize[1] != this->WindowSize[1]) ) + { + this->LastDepthPassWindowSize[0] = this->WindowSize[0]; + this->LastDepthPassWindowSize[1] = this->WindowSize[1]; + this->ReleaseDepthPassGraphicsResources(ren->GetRenderWindow()); } - if (!this->FBO) + if (!this->DPFBO) { - this->FBO = vtkFrameBufferObject2::New(); + this->DPFBO = vtkFrameBufferObject2::New(); } - this->FBO->SetContext(vtkOpenGLRenderWindow::SafeDownCast( + this->DPFBO->SetContext(vtkOpenGLRenderWindow::SafeDownCast( ren->GetRenderWindow())); - this->FBO->Bind(GL_FRAMEBUFFER); - this->FBO->InitializeViewport(this->WindowSize[0], this->WindowSize[1]); + this->DPFBO->Bind(GL_FRAMEBUFFER); + this->DPFBO->InitializeViewport(this->WindowSize[0], this->WindowSize[1]); - if (!this->RTTDepthBufferTextureObject || - !this->RTTDepthTextureObject || - !this->RTTColorTextureObject) + if (!this->DPDepthBufferTextureObject || + !this->DPColorTextureObject) { - this->RTTDepthBufferTextureObject = vtkTextureObject::New(); - this->RTTDepthBufferTextureObject->SetContext( + this->DPDepthBufferTextureObject = vtkTextureObject::New(); + this->DPDepthBufferTextureObject->SetContext( vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow())); - this->RTTDepthBufferTextureObject->AllocateDepth( - this->WindowSize[0], this->WindowSize[1], vtkTextureObject::Float32); - this->RTTDepthBufferTextureObject->SetMinificationFilter( + this->DPDepthBufferTextureObject->AllocateDepth( + this->WindowSize[0], this->WindowSize[1], vtkTextureObject::Native); + this->DPDepthBufferTextureObject->Activate(); + this->DPDepthBufferTextureObject->SetMinificationFilter( vtkTextureObject::Nearest); - this->RTTDepthBufferTextureObject->SetMagnificationFilter( + this->DPDepthBufferTextureObject->SetMagnificationFilter( vtkTextureObject::Nearest); - this->RTTDepthBufferTextureObject->SetAutoParameters(0); - this->RTTDepthBufferTextureObject->Bind(); + this->DPDepthBufferTextureObject->SetAutoParameters(0); + this->DPDepthBufferTextureObject->Bind(); - this->RTTDepthTextureObject = vtkTextureObject::New(); - this->RTTDepthTextureObject->SetContext( - vtkOpenGLRenderWindow::SafeDownCast( - ren->GetRenderWindow())); - this->RTTDepthTextureObject->Create2D(this->WindowSize[0], - this->WindowSize[1], 1, - VTK_UNSIGNED_CHAR, false); - this->RTTDepthTextureObject->SetMinificationFilter( - vtkTextureObject::Nearest); - this->RTTDepthTextureObject->SetMagnificationFilter( - vtkTextureObject::Nearest); - this->RTTDepthTextureObject->SetAutoParameters(0); - this->RTTDepthTextureObject->Bind(); - this->RTTColorTextureObject = vtkTextureObject::New(); + this->DPColorTextureObject = vtkTextureObject::New(); - this->RTTColorTextureObject->SetContext( + this->DPColorTextureObject->SetContext( vtkOpenGLRenderWindow::SafeDownCast( ren->GetRenderWindow())); - this->RTTColorTextureObject->SetMinificationFilter( + this->DPColorTextureObject->Create2D(this->WindowSize[0], + this->WindowSize[1], 4, + VTK_UNSIGNED_CHAR, false); + this->DPColorTextureObject->Activate(); + this->DPColorTextureObject->SetMinificationFilter( vtkTextureObject::Nearest); - this->RTTColorTextureObject->SetMagnificationFilter( + this->DPColorTextureObject->SetMagnificationFilter( vtkTextureObject::Nearest); - this->RTTColorTextureObject->Create2D(this->WindowSize[0], - this->WindowSize[1], 4, - VTK_UNSIGNED_CHAR, false); - this->RTTColorTextureObject->SetAutoParameters(0); - this->RTTColorTextureObject->Bind(); + this->DPColorTextureObject->SetAutoParameters(0); - this->FBO->AddTexDepthAttachment( + this->DPFBO->AddTexDepthAttachment( GL_DRAW_FRAMEBUFFER, - this->RTTDepthBufferTextureObject->GetHandle()); - this->FBO->AddTexColorAttachment( - GL_DRAW_FRAMEBUFFER, 0U, - this->RTTColorTextureObject->GetHandle()); - this->FBO->AddTexColorAttachment( - GL_DRAW_FRAMEBUFFER, 1U, - this->RTTDepthTextureObject->GetHandle()); + this->DPDepthBufferTextureObject->GetHandle()); - this->FBO->ActivateDrawBuffers(2); - this->FBO->UnBind(GL_FRAMEBUFFER); + this->DPFBO->AddTexColorAttachment( + GL_DRAW_FRAMEBUFFER, 0U, + this->DPColorTextureObject->GetHandle()); } - this->FBO->Bind(GL_FRAMEBUFFER); - this->FBO->CheckFrameBufferStatus(GL_FRAMEBUFFER); + + this->DPFBO->ActivateDrawBuffers(1); + this->DPFBO->CheckFrameBufferStatus(GL_FRAMEBUFFER); + + // Setup the contour polydata mapper to render to DPFBO + this->ContourMapper->SetInputConnection( + this->ContourFilter->GetOutputPort()); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); } +//---------------------------------------------------------------------------- +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal::ExitDepthPass( + vtkRenderer* vtkNotUsed(ren)) +{ + this->DPFBO->DeactivateDrawBuffers(); + this->DPFBO->UnBind(GL_FRAMEBUFFER); + + this->DPDepthBufferTextureObject->Deactivate(); + this->DPColorTextureObject->Deactivate(); + glDisable(GL_DEPTH_TEST); +} + //---------------------------------------------------------------------------- void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal - ::ReleaseRenderToImageGraphicsResources(vtkWindow* win) + ::ReleaseRenderToTextureGraphicsResources(vtkWindow* win) { vtkOpenGLRenderWindow *rwin = vtkOpenGLRenderWindow::SafeDownCast(win); @@ -2168,7 +2448,40 @@ void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal this->RTTColorTextureObject = 0; } } - } +} + +//---------------------------------------------------------------------------- +void vtkOpenGLGPUVolumeRayCastMapper::vtkInternal + ::ReleaseDepthPassGraphicsResources(vtkWindow* win) +{ + vtkOpenGLRenderWindow *rwin = + vtkOpenGLRenderWindow::SafeDownCast(win); + + if (rwin) + { + if (this->DPFBO) + { + this->DPFBO->Delete(); + this->DPFBO = 0; + } + + if (this->DPDepthBufferTextureObject) + { + this->DPDepthBufferTextureObject->ReleaseGraphicsResources(win); + this->DPDepthBufferTextureObject->Delete(); + this->DPDepthBufferTextureObject = 0; + } + + if (this->DPColorTextureObject) + { + this->DPColorTextureObject->ReleaseGraphicsResources(win); + this->DPColorTextureObject->Delete(); + this->DPColorTextureObject = 0; + } + + this->ContourMapper->ReleaseGraphicsResources(win); + } +} //---------------------------------------------------------------------------- vtkOpenGLGPUVolumeRayCastMapper::vtkOpenGLGPUVolumeRayCastMapper() : @@ -2176,9 +2489,9 @@ vtkOpenGLGPUVolumeRayCastMapper::vtkOpenGLGPUVolumeRayCastMapper() : { this->Impl = new vtkInternal(this); this->ReductionFactor = 1.0; + this->CurrentPass = RenderPass; } -/// //---------------------------------------------------------------------------- vtkOpenGLGPUVolumeRayCastMapper::~vtkOpenGLGPUVolumeRayCastMapper() { @@ -2191,16 +2504,8 @@ void vtkOpenGLGPUVolumeRayCastMapper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); - os << indent << "Dimensions: " << this->Impl->Dimensions[0] << ", " << - this->Impl->Dimensions[1] << ", " << - this->Impl->Dimensions[2] << ", " << "\n"; - os << indent << "Bounds: " << this->Impl->LoadedBounds[0] << ", " << - this->Impl->LoadedBounds[1] << ", " << - this->Impl->LoadedBounds[2] << "\n"; - os << indent << "ActualSampleDistance: " << - this->Impl->ActualSampleDistance << "\n"; - os << indent << "LastProjectionParallel: " << - this->Impl->LastProjectionParallel << "\n"; + os << indent << "ReductionFactor: " << this->ReductionFactor << "\n"; + os << indent << "CurrentPass: " << this->CurrentPass << "\n"; } //---------------------------------------------------------------------------- @@ -2256,7 +2561,8 @@ void vtkOpenGLGPUVolumeRayCastMapper::ReleaseGraphicsResources( this->Impl->DepthTextureObject = 0; } - this->Impl->ReleaseRenderToImageGraphicsResources(window); + this->Impl->ReleaseRenderToTextureGraphicsResources(window); + this->Impl->ReleaseDepthPassGraphicsResources(window); if(this->Impl->MaskTextures != 0) { @@ -2618,26 +2924,50 @@ void vtkOpenGLGPUVolumeRayCastMapper::BuildShader(vtkRenderer* ren, noOfComponents), true); + // Picking replacements + //-------------------------------------------------------------------------- + if (this->Impl->CurrentSelectionPass != (vtkHardwareSelector::MIN_KNOWN_PASS - 1)) + { + switch(this->Impl->CurrentSelectionPass) + { + case vtkHardwareSelector::ID_LOW24: + fragmentShader = vtkvolume::replace(fragmentShader, "//VTK::Picking::Exit", + vtkvolume::PickingIdLow24PassExit(ren, this, vol), true); + break; + case vtkHardwareSelector::ID_MID24: + fragmentShader = vtkvolume::replace(fragmentShader, "//VTK::Picking::Exit", + vtkvolume::PickingIdMid24PassExit(ren, this, vol), true); + break; + default: // ACTOR_PASS, PROCESS_PASS + fragmentShader = vtkvolume::replace(fragmentShader, "//VTK::Picking::Dec", + vtkvolume::PickingActorPassDeclaration(ren, this, vol), true); + + fragmentShader = vtkvolume::replace(fragmentShader, "//VTK::Picking::Exit", + vtkvolume::PickingActorPassExit(ren, this, vol), true); + break; + } + } + // Render to texture //-------------------------------------------------------------------------- if (this->RenderToImage) { fragmentShader = vtkvolume::replace( fragmentShader, - "//VTK::RenderToImage::Depth::Init", - vtkvolume::RenderToImageDepthInit( + "//VTK::RenderToImage::Init", + vtkvolume::RenderToImageInit( ren, this, vol), true); fragmentShader = vtkvolume::replace( fragmentShader, - "//VTK::RenderToImage::Depth::Impl", - vtkvolume::RenderToImageDepthImplementation( + "//VTK::RenderToImage::Impl", + vtkvolume::RenderToImageImplementation( ren, this, vol), true); fragmentShader = vtkvolume::replace( fragmentShader, - "//VTK::RenderToImage::Depth::Exit", - vtkvolume::RenderToImageDepthExit( + "//VTK::RenderToImage::Exit", + vtkvolume::RenderToImageExit( ren, this, vol), true); } @@ -2645,7 +2975,7 @@ void vtkOpenGLGPUVolumeRayCastMapper::BuildShader(vtkRenderer* ren, //-------------------------------------------------------------------------- this->Impl->ShaderProgram = this->Impl->ShaderCache->ReadyShaderProgram( vertexShader.c_str(), fragmentShader.c_str(), ""); - if (!this->Impl->ShaderProgram->GetCompiled()) + if (!this->Impl->ShaderProgram || !this->Impl->ShaderProgram->GetCompiled()) { vtkErrorMacro("Shader failed to compile"); } @@ -2740,13 +3070,16 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, { vtkOpenGLClearErrorMacro(); - this->Impl->TempMatrix4x4->Identity(); + this->Impl->TempMatrix1->Identity(); this->Impl->NeedToInitializeResources = (this->Impl->ReleaseResourcesTime.GetMTime() > this->Impl->InitializationTime.GetMTime()); + // Make sure the context is current - ren->GetRenderWindow()->MakeCurrent(); + vtkOpenGLRenderWindow* renWin = + vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()); + renWin->MakeCurrent(); // Update in_volume first to make sure states are current vol->Update(); @@ -2778,16 +3111,9 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, // How many components are there? int noOfComponents = scalars->GetNumberOfComponents(); - if (this->RenderToImage) - { - this->Impl->RenderToFBO(ren); - } - // Allocate important variables this->Impl->Bias.resize(noOfComponents, 0.0); - // Set OpenGL states - vtkVolumeStateRAII glState; if (this->Impl->NeedToInitializeResources || (volumeProperty->GetMTime() > @@ -2812,12 +3138,6 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, } } - // Invert the volume matrix - // Will require transpose of this matrix for OpenGL - // Scene matrix - this->Impl->InverseVolumeMat->DeepCopy(vol->GetMatrix()); - this->Impl->InverseVolumeMat->Invert(); - // Update the volume if needed bool volumeModified = false; if (this->Impl->NeedToInitializeResources || @@ -2858,36 +3178,6 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, this->ComputeReductionFactor(vol->GetAllocatedRenderTime()); this->Impl->UpdateSamplingDistance(input, ren, vol); - // Build shader now - // First get the shader cache from the render window. This is important - // to make sure that shader cache knows the state of various shader programs - // in use. - vtkOpenGLRenderWindow* renWin = - vtkOpenGLRenderWindow::SafeDownCast(ren->GetRenderWindow()); - this->Impl->ShaderCache = renWin->GetShaderCache(); - - if (this->Impl->NeedToInitializeResources || - volumeProperty->GetMTime() > - this->Impl->ShaderBuildTime.GetMTime() || - this->GetMTime() > this->Impl->ShaderBuildTime.GetMTime() || - cam->GetParallelProjection() != - this->Impl->LastProjectionParallel) - { - this->Impl->LastProjectionParallel = - cam->GetParallelProjection(); - this->BuildShader(ren, vol, noOfComponents); - } - else - { - // Bind the shader - this->Impl->ShaderCache->ReadyShaderProgram( - this->Impl->ShaderProgram); - } - - // And now update the geometry that will be used - // to render the 3D texture - this->Impl->UpdateVolumeGeometry(ren, vol, input); - // Update the transfer functions if (independentComponents) { @@ -2910,19 +3200,12 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, } // Update noise sampler texture - this->Impl->UpdateNoiseTexture(ren); + this->Impl->CreateNoiseTexture(ren); // Grab depth sampler buffer (to handle cases when we are rendering geometry // and in_volume together - this->Impl->UpdateDepthTexture(ren, vol); + this->Impl->CaptureDepthTexture(ren, vol); - // Update lighting parameters - this->Impl->UpdateLightingParameters(ren, vol); - - // Temporary variables - float fvalue2[2]; - float fvalue3[3]; - float fvalue4[4]; // Update sampling distance int* loadedExtent = input->GetExtent(); @@ -2948,58 +3231,199 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, this->Impl->DatasetStepSize[2] = 1.0 / (this->Impl->LoadedBounds[5] - this->Impl->LoadedBounds[4]); - if (cam->GetParallelProjection()) + // Compute texture to dataset matrix + this->Impl->TextureToDataSetMat->Identity(); + this->Impl->TextureToDataSetMat->SetElement(0, 0, + (1.0 / this->Impl->DatasetStepSize[0])); + this->Impl->TextureToDataSetMat->SetElement(1, 1, + (1.0 / this->Impl->DatasetStepSize[1])); + this->Impl->TextureToDataSetMat->SetElement(2, 2, + (1.0 / this->Impl->DatasetStepSize[2])); + this->Impl->TextureToDataSetMat->SetElement(3, 3, + 1.0); + this->Impl->TextureToDataSetMat->SetElement(0, 3, + this->Impl->LoadedBounds[0]); + this->Impl->TextureToDataSetMat->SetElement(1, 3, + this->Impl->LoadedBounds[2]); + this->Impl->TextureToDataSetMat->SetElement(2, 3, + this->Impl->LoadedBounds[4]); + + this->Impl->ShaderCache = vtkOpenGLRenderWindow::SafeDownCast( + ren->GetRenderWindow())->GetShaderCache(); + + this->Impl->CheckPickingState(ren); + + if (this->UseDepthPass && this->GetBlendMode() == + vtkVolumeMapper::COMPOSITE_BLEND) { - double dir[4]; - cam->GetDirectionOfProjection(dir); - vtkInternal::ToFloat(dir[0], dir[1], dir[2], fvalue3); - this->Impl->ShaderProgram->SetUniform3fv( - "in_projectionDirection", 1, &fvalue3); - } + this->CurrentPass = DepthPass; - // Pass constant uniforms at initialization - this->Impl->ShaderProgram->SetUniformi("in_noOfComponents", - noOfComponents); - this->Impl->ShaderProgram->SetUniformi("in_independentComponents", - independentComponents); + if (this->Impl->NeedToInitializeResources || + volumeProperty->GetMTime() > this->Impl->DepthPassSetupTime.GetMTime() || + this->GetMTime() > this->Impl->DepthPassSetupTime.GetMTime() || + cam->GetParallelProjection() != this->Impl->LastProjectionParallel || + this->Impl->SelectionStateTime.GetMTime() > this->Impl->ShaderBuildTime.GetMTime()) + { + this->Impl->LastProjectionParallel = + cam->GetParallelProjection(); - float tscale[4] = {1.0, 1.0, 1.0, 1.0}; - float tbias[4] = {0.0, 0.0, 0.0, 0.0}; - if (!this->Impl->HandleLargeDataTypes && - (noOfComponents == 1 || noOfComponents == 2 || independentComponents)) + this->Impl->ContourFilter->SetInputData(input); + for (int i = 0; i < this->GetDepthPassContourValues()->GetNumberOfContours(); ++i) + { + this->Impl->ContourFilter->SetValue(i, + this->DepthPassContourValues->GetValue(i)); + } + + vtkNew newMatrix; + newMatrix->DeepCopy(vol->GetMatrix()); + + this->Impl->SetupDepthPass(ren); + + this->Impl->ContourActor->Render(ren, + this->Impl->ContourMapper.GetPointer()); + + this->Impl->ExitDepthPass(ren); + + this->Impl->DepthPassSetupTime.Modified(); + this->Impl->DepthPassTime.Modified(); + + this->CurrentPass = RenderPass; + this->BuildShader(ren, vol, noOfComponents); + } + else if (cam->GetMTime() > this->Impl->DepthPassTime.GetMTime()) + { + this->Impl->SetupDepthPass(ren); + + this->Impl->ContourActor->Render(ren, + this->Impl->ContourMapper.GetPointer()); + + this->Impl->ExitDepthPass(ren); + this->Impl->DepthPassTime.Modified(); + + this->CurrentPass = RenderPass; + } + + // Configure picking begin (changes blending, so needs to be called before + // vtkVolumeStateRAII) + if (this->Impl->IsPicking) + { + this->Impl->BeginPicking(ren); + } + // Set OpenGL states + vtkVolumeStateRAII glState; + + if (this->RenderToImage) + { + this->Impl->SetupRenderToTexture(ren); + } + + // NOTE: This is a must call or else, multiple viewport + // rendering would not work. We need this primarily because + // FBO set it otherwise. + glViewport(this->Impl->WindowLowerLeft[0], + this->Impl->WindowLowerLeft[1], + this->Impl->WindowSize[0], + this->Impl->WindowSize[1]); + + renWin->GetShaderCache()->ReadyShaderProgram(this->Impl->ShaderProgram); + + this->Impl->DPDepthBufferTextureObject->Activate(); + this->Impl->ShaderProgram->SetUniformi("in_depthPassSampler", + this->Impl->DPDepthBufferTextureObject->GetTextureUnit()); + + this->DoGPURender(ren, vol, input, + cam, this->Impl->ShaderProgram, + noOfComponents, independentComponents); + + this->Impl->DPDepthBufferTextureObject->Deactivate(); + } + else { - for (int i = 0; i < noOfComponents; i++) + // Configure picking begin (changes blending, so needs to be called before + // vtkVolumeStateRAII) + if (this->Impl->IsPicking) { - tscale[i] = this->Impl->Scale[i]; - tbias[i] = this->Impl->Bias[i]; + this->Impl->BeginPicking(ren); + } + // Set OpenGL states + vtkVolumeStateRAII glState; + + // Build shader now + // First get the shader cache from the render window. This is important + // to make sure that shader cache knows the state of various shader programs + // in use. + if (this->Impl->NeedToInitializeResources || + volumeProperty->GetMTime() > + this->Impl->ShaderBuildTime.GetMTime() || + this->GetMTime() > this->Impl->ShaderBuildTime.GetMTime() || + cam->GetParallelProjection() != this->Impl->LastProjectionParallel || + this->Impl->SelectionStateTime.GetMTime() > this->Impl->ShaderBuildTime.GetMTime()) + { + this->Impl->LastProjectionParallel = + cam->GetParallelProjection(); + this->BuildShader(ren, vol, noOfComponents); + } + else + { + // Bind the shader + this->Impl->ShaderCache->ReadyShaderProgram( + this->Impl->ShaderProgram); + } + + if (this->RenderToImage) + { + this->Impl->SetupRenderToTexture(ren); + + + this->DoGPURender(ren, vol, input, + cam, this->Impl->ShaderProgram, + noOfComponents, independentComponents); + + this->Impl->ExitRenderToTexture(ren); + } + else + { + this->DoGPURender(ren, vol, input, + cam, this->Impl->ShaderProgram, + noOfComponents, independentComponents); } } - this->Impl->ShaderProgram->SetUniform4f("in_volume_scale",tscale); - this->Impl->ShaderProgram->SetUniform4f("in_volume_bias",tbias); - // Step should be dependant on the bounds and not on the texture size - // since we can have non uniform voxel size / spacing / aspect ratio - vtkInternal::ToFloat(this->Impl->CellStep, fvalue3); - this->Impl->ShaderProgram->SetUniform3fv("in_cellStep", 1, &fvalue3); + // Configure picking end + if (this->Impl->IsPicking) + { + this->Impl->EndPicking(ren); + } - vtkInternal::ToFloat(this->Impl->CellScale, fvalue3); - this->Impl->ShaderProgram->SetUniform3fv("in_cellScale", 1, &fvalue3); + if (volumeModified) + { + this->Impl->InputUpdateTime.Modified(); + } - vtkInternal::ToFloat(this->Impl->CellSpacing, fvalue3); - this->Impl->ShaderProgram->SetUniform3fv("in_cellSpacing", 1, &fvalue3); + glFinish(); +} - this->Impl->ShaderProgram->SetUniformf("in_sampleDistance", - this->Impl->ActualSampleDistance); +//---------------------------------------------------------------------------- +void vtkOpenGLGPUVolumeRayCastMapper::DoGPURender(vtkRenderer* ren, + vtkVolume* vol, + vtkImageData* input, + vtkOpenGLCamera* cam, + vtkShaderProgram* prog, + int noOfComponents, + int independentComponents) +{ + // Temporary variables + float fvalue2[2]; + float fvalue3[3]; + float fvalue4[4]; - float scalarsRange[4][2]; - vtkInternal::ToFloat(this->Impl->ScalarsRange, scalarsRange); - this->Impl->ShaderProgram->SetUniform2fv("in_scalarsRange", 4, - scalarsRange); + vtkVolumeProperty* volumeProperty = vol->GetProperty(); // Bind textures + //-------------------------------------------------------------------------- this->Impl->VolumeTextureObject->Activate(); - this->Impl->ShaderProgram->SetUniformi("in_volume", - this->Impl->VolumeTextureObject->GetTextureUnit()); + prog->SetUniformi("in_volume", + this->Impl->VolumeTextureObject->GetTextureUnit()); // Opacity, color, and gradient opacity samplers / textures int numberOfSamplers = (independentComponents ? noOfComponents : 1); @@ -3007,14 +3431,14 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, for (int i = 0; i < numberOfSamplers; ++i) { this->Impl->OpacityTables->GetTable(i)->Activate(); - this->Impl->ShaderProgram->SetUniformi( + prog->SetUniformi( this->Impl->OpacityTablesMap[i].c_str(), this->Impl->OpacityTables->GetTable(i)->GetTextureUnit()); if (this->BlendMode != vtkGPUVolumeRayCastMapper::ADDITIVE_BLEND) { this->Impl->RGBTables->GetTable(i)->Activate(); - this->Impl->ShaderProgram->SetUniformi( + prog->SetUniformi( this->Impl->RGBTablesMap[i].c_str(), this->Impl->RGBTables->GetTable(i)->GetTextureUnit()); } @@ -3022,27 +3446,27 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, if (this->Impl->GradientOpacityTables) { this->Impl->GradientOpacityTables->GetTable(i)->Activate(); - this->Impl->ShaderProgram->SetUniformi( + prog->SetUniformi( this->Impl->GradientOpacityTablesMap[i].c_str(), this->Impl->GradientOpacityTables->GetTable(i)->GetTextureUnit()); } } this->Impl->NoiseTextureObject->Activate(); - this->Impl->ShaderProgram->SetUniformi("in_noiseSampler", + prog->SetUniformi("in_noiseSampler", this->Impl->NoiseTextureObject->GetTextureUnit()); // currently broken on ES #if GL_ES_VERSION_2_0 != 1 this->Impl->DepthTextureObject->Activate(); - this->Impl->ShaderProgram->SetUniformi("in_depthSampler", + prog->SetUniformi("in_depthSampler", this->Impl->DepthTextureObject->GetTextureUnit()); #endif if (this->Impl->CurrentMask) { this->Impl->CurrentMask->Activate(); - this->Impl->ShaderProgram->SetUniformi( + prog->SetUniformi( "in_mask", this->Impl->CurrentMask->GetTextureUnit()); } @@ -3052,32 +3476,36 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, if (this->MaskInput != 0 && this->MaskType == LabelMapMaskType) { this->Impl->Mask1RGBTable->Activate(); - this->Impl->ShaderProgram->SetUniformi("in_mask1", + prog->SetUniformi("in_mask1", this->Impl->Mask1RGBTable->GetTextureUnit()); this->Impl->Mask2RGBTable->Activate(); - this->Impl->ShaderProgram->SetUniformi("in_mask2", - this->Impl->Mask2RGBTable->GetTextureUnit()); - this->Impl->ShaderProgram->SetUniformf("in_maskBlendFactor", - this->MaskBlendFactor); + prog->SetUniformi("in_mask2", this->Impl->Mask2RGBTable->GetTextureUnit()); + prog->SetUniformf("in_maskBlendFactor", this->MaskBlendFactor); } } + // Bind light and material properties + //-------------------------------------------------------------------------- + this->Impl->SetLightingParameters(ren, prog, vol); + fvalue3[0] = fvalue3[1] = fvalue3[2] = volumeProperty->GetAmbient(); - this->Impl->ShaderProgram->SetUniform3f("in_ambient", fvalue3); + prog->SetUniform3f("in_ambient", fvalue3); fvalue3[0] = fvalue3[1] = fvalue3[2] = volumeProperty->GetDiffuse(); - this->Impl->ShaderProgram->SetUniform3f("in_diffuse", fvalue3); + prog->SetUniform3f("in_diffuse", fvalue3); fvalue3[0] = fvalue3[1] = fvalue3[2] = volumeProperty->GetSpecular(); - this->Impl->ShaderProgram->SetUniform3f("in_specular", fvalue3); + prog->SetUniform3f("in_specular", fvalue3); fvalue3[0] = volumeProperty->GetSpecularPower(); - this->Impl->ShaderProgram->SetUniformf("in_shininess", fvalue3[0]); + prog->SetUniformf("in_shininess", fvalue3[0]); double clippingRange[2]; cam->GetClippingRange(clippingRange); + // Bind matrices + //-------------------------------------------------------------------------- vtkMatrix4x4* glTransformMatrix; vtkMatrix4x4* modelviewMatrix; vtkMatrix3x3* normalMatrix; @@ -3087,56 +3515,37 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, this->Impl->InverseProjectionMat->DeepCopy(projectionMatrix); this->Impl->InverseProjectionMat->Invert(); - this->Impl->ShaderProgram->SetUniformMatrix( - "in_projectionMatrix", projectionMatrix); - this->Impl->ShaderProgram->SetUniformMatrix( - "in_inverseProjectionMatrix", this->Impl->InverseProjectionMat.GetPointer()); + prog->SetUniformMatrix("in_projectionMatrix", projectionMatrix); + prog->SetUniformMatrix("in_inverseProjectionMatrix", + this->Impl->InverseProjectionMat.GetPointer()); this->Impl->InverseModelViewMat->DeepCopy(modelviewMatrix); this->Impl->InverseModelViewMat->Invert(); - this->Impl->ShaderProgram->SetUniformMatrix( - "in_modelViewMatrix", modelviewMatrix); - this->Impl->ShaderProgram->SetUniformMatrix( - "in_inverseModelViewMatrix", this->Impl->InverseModelViewMat.GetPointer()); - - vtkMatrix4x4* volumeMatrix4x4 = vol->GetMatrix(); - this->Impl->TempMatrix4x4->DeepCopy(volumeMatrix4x4); - this->Impl->TempMatrix4x4->Transpose(); - this->Impl->InverseVolumeMat->DeepCopy(this->Impl->TempMatrix4x4.GetPointer()); - this->Impl->InverseVolumeMat->Invert(); - this->Impl->ShaderProgram->SetUniformMatrix( - "in_volumeMatrix", this->Impl->TempMatrix4x4.GetPointer()); - this->Impl->ShaderProgram->SetUniformMatrix( - "in_inverseVolumeMatrix", this->Impl->InverseVolumeMat.GetPointer()); + prog->SetUniformMatrix("in_modelViewMatrix", modelviewMatrix); + prog->SetUniformMatrix("in_inverseModelViewMatrix", + this->Impl->InverseModelViewMat.GetPointer()); - // Compute texture to dataset matrix - this->Impl->TextureToDataSetMat->Identity(); - this->Impl->TextureToDataSetMat->SetElement(0, 0, - (1.0 / this->Impl->DatasetStepSize[0])); - this->Impl->TextureToDataSetMat->SetElement(1, 1, - (1.0 / this->Impl->DatasetStepSize[1])); - this->Impl->TextureToDataSetMat->SetElement(2, 2, - (1.0 / this->Impl->DatasetStepSize[2])); - this->Impl->TextureToDataSetMat->SetElement(3, 3, - 1.0); - this->Impl->TextureToDataSetMat->SetElement(0, 3, - this->Impl->LoadedBounds[0]); - this->Impl->TextureToDataSetMat->SetElement(1, 3, - this->Impl->LoadedBounds[2]); - this->Impl->TextureToDataSetMat->SetElement(2, 3, - this->Impl->LoadedBounds[4]); + this->Impl->TempMatrix1->DeepCopy(vol->GetMatrix()); + this->Impl->TempMatrix1->Transpose(); + this->Impl->InverseVolumeMat->DeepCopy(this->Impl->TempMatrix1.GetPointer()); + this->Impl->InverseVolumeMat->Invert(); + prog->SetUniformMatrix("in_volumeMatrix", + this->Impl->TempMatrix1.GetPointer()); + prog->SetUniformMatrix("in_inverseVolumeMatrix", + this->Impl->InverseVolumeMat.GetPointer()); - this->Impl->TextureToDataSetMat->Transpose(); + this->Impl->TempMatrix1->DeepCopy(this->Impl->TextureToDataSetMat.GetPointer()); + this->Impl->TempMatrix1->Transpose(); this->Impl->InverseTextureToDataSetMat->DeepCopy( - this->Impl->TextureToDataSetMat.GetPointer()); + this->Impl->TempMatrix1.GetPointer()); this->Impl->InverseTextureToDataSetMat->Invert(); - this->Impl->ShaderProgram->SetUniformMatrix( - "in_textureDatasetMatrix", this->Impl->TextureToDataSetMat.GetPointer()); - this->Impl->ShaderProgram->SetUniformMatrix( - "in_inverseTextureDatasetMatrix", this->Impl->InverseTextureToDataSetMat.GetPointer()); + prog->SetUniformMatrix("in_textureDatasetMatrix", + this->Impl->TempMatrix1.GetPointer()); + prog->SetUniformMatrix("in_inverseTextureDatasetMatrix", + this->Impl->InverseTextureToDataSetMat.GetPointer()); - vtkMatrix4x4::Multiply4x4(this->Impl->TempMatrix4x4.GetPointer(), + vtkMatrix4x4::Multiply4x4(this->Impl->TempMatrix1.GetPointer(), modelviewMatrix, this->Impl->TextureToEyeTransposeInverse.GetPointer()); @@ -3146,57 +3555,115 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, this->Impl->TextureToEyeTransposeInverse->Invert(); - this->Impl->ShaderProgram->SetUniformMatrix( + prog->SetUniformMatrix( "in_texureToEyeIt", this->Impl->TextureToEyeTransposeInverse.GetPointer()); + // Bind other misc parameters + //-------------------------------------------------------------------------- + if (cam->GetParallelProjection()) + { + double dir[4]; + cam->GetDirectionOfProjection(dir); + vtkInternal::ToFloat(dir[0], dir[1], dir[2], fvalue3); + prog->SetUniform3fv( + "in_projectionDirection", 1, &fvalue3); + } + + // Pass constant uniforms at initialization + prog->SetUniformi("in_noOfComponents", noOfComponents); + prog->SetUniformi("in_independentComponents", independentComponents); + + float tscale[4] = {1.0, 1.0, 1.0, 1.0}; + float tbias[4] = {0.0, 0.0, 0.0, 0.0}; + if (!this->Impl->HandleLargeDataTypes && (noOfComponents == 1 || + noOfComponents == 2 || independentComponents)) + { + for (int i = 0; i < noOfComponents; i++) + { + tscale[i] = this->Impl->Scale[i]; + tbias[i] = this->Impl->Bias[i]; + } + } + + prog->SetUniform4f("in_volume_scale", tscale); + prog->SetUniform4f("in_volume_bias", tbias); + + // Step should be dependant on the bounds and not on the texture size + // since we can have non uniform voxel size / spacing / aspect ratio + vtkInternal::ToFloat(this->Impl->CellStep, fvalue3); + prog->SetUniform3fv("in_cellStep", 1, &fvalue3); + + vtkInternal::ToFloat(this->Impl->CellScale, fvalue3); + prog->SetUniform3fv("in_cellScale", 1, &fvalue3); + + vtkInternal::ToFloat(this->Impl->CellSpacing, fvalue3); + prog->SetUniform3fv("in_cellSpacing", 1, &fvalue3); + + prog->SetUniformf("in_sampleDistance", this->Impl->ActualSampleDistance); + + float scalarsRange[4][2]; + vtkInternal::ToFloat(this->Impl->ScalarsRange, scalarsRange); + prog->SetUniform2fv("in_scalarsRange", 4, scalarsRange); + vtkInternal::ToFloat(cam->GetPosition(), fvalue3, 3); - this->Impl->ShaderProgram->SetUniform3fv("in_cameraPos", 1, &fvalue3); + prog->SetUniform3fv("in_cameraPos", 1, &fvalue3); vtkInternal::ToFloat(this->Impl->LoadedBounds[0], this->Impl->LoadedBounds[2], this->Impl->LoadedBounds[4], fvalue3); - this->Impl->ShaderProgram->SetUniform3fv("in_volumeExtentsMin", 1, &fvalue3); + prog->SetUniform3fv("in_volumeExtentsMin", 1, &fvalue3); vtkInternal::ToFloat(this->Impl->LoadedBounds[1], this->Impl->LoadedBounds[3], this->Impl->LoadedBounds[5], fvalue3); - this->Impl->ShaderProgram->SetUniform3fv("in_volumeExtentsMax", 1, &fvalue3); + prog->SetUniform3fv("in_volumeExtentsMax", 1, &fvalue3); vtkInternal::ToFloat(this->Impl->Extents[0], this->Impl->Extents[2], this->Impl->Extents[4], fvalue3); - this->Impl->ShaderProgram->SetUniform3fv("in_textureExtentsMin", 1, &fvalue3); + prog->SetUniform3fv("in_textureExtentsMin", 1, &fvalue3); vtkInternal::ToFloat(this->Impl->Extents[1], this->Impl->Extents[3], this->Impl->Extents[5], fvalue3); - this->Impl->ShaderProgram->SetUniform3fv("in_textureExtentsMax", 1, &fvalue3); + prog->SetUniform3fv("in_textureExtentsMax", 1, &fvalue3); // TODO Take consideration of reduction factor vtkInternal::ToFloat(this->Impl->WindowLowerLeft, fvalue2); - this->Impl->ShaderProgram->SetUniform2fv("in_windowLowerLeftCorner", 1, &fvalue2); + prog->SetUniform2fv("in_windowLowerLeftCorner", 1, &fvalue2); vtkInternal::ToFloat(1.0 / this->Impl->WindowSize[0], 1.0 / this->Impl->WindowSize[1], fvalue2); - this->Impl->ShaderProgram->SetUniform2fv("in_inverseOriginalWindowSize", 1, &fvalue2); + prog->SetUniform2fv("in_inverseOriginalWindowSize", 1, &fvalue2); vtkInternal::ToFloat(1.0 / this->Impl->WindowSize[0], 1.0 / this->Impl->WindowSize[1], fvalue2); - this->Impl->ShaderProgram->SetUniform2fv("in_inverseWindowSize", 1, &fvalue2); + prog->SetUniform2fv("in_inverseWindowSize", 1, &fvalue2); - this->Impl->ShaderProgram->SetUniformi("in_useJittering", this->GetUseJittering()); - this->Impl->ShaderProgram->SetUniformi("in_cellFlag", this->CellFlag); + prog->SetUniformi("in_useJittering", this->GetUseJittering()); + prog->SetUniformi("in_cellFlag", this->CellFlag); + + prog->SetUniformi("in_clampDepthToBackface", this->GetClampDepthToBackface()); + + // Bind cropping + //-------------------------------------------------------------------------- + this->Impl->SetCroppingRegions(ren, prog, vol); - // Updating cropping if enabled - this->Impl->UpdateCropping(ren, vol); + // Bind clipping + //-------------------------------------------------------------------------- + this->Impl->SetClippingPlanes(ren, prog, vol); - // Updating clipping if enabled - this->Impl->UpdateClipping(ren, vol); + // Bind the prop Id + //-------------------------------------------------------------------------- + if (this->Impl->CurrentSelectionPass < vtkHardwareSelector::ID_LOW24) + { + this->Impl->SetPickingId(ren); + } // Finally set the scale and bias for color correction - this->Impl->ShaderProgram->SetUniformf("in_scale", - 1.0 / this->FinalColorWindow); - this->Impl->ShaderProgram->SetUniformf("in_bias", + //-------------------------------------------------------------------------- + prog->SetUniformf("in_scale", 1.0 / this->FinalColorWindow); + prog->SetUniformf("in_bias", (0.5 - (this->FinalColorLevel/this->FinalColorWindow))); if (noOfComponents > 1 && independentComponents) @@ -3205,20 +3672,16 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, { fvalue4[i] = static_cast(volumeProperty->GetComponentWeight(i)); } - this->Impl->ShaderProgram->SetUniform4fv("in_componentWeight", 1, &fvalue4); + prog->SetUniform4fv("in_componentWeight", 1, &fvalue4); } -#ifdef __APPLE__ - if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32()) -#endif - { - glBindVertexArray(this->Impl->CubeVAOId); - } - glDrawElements(GL_TRIANGLES, - this->Impl->BBoxPolyData->GetNumberOfCells() * 3, - GL_UNSIGNED_INT, 0); + // Render volume geometry to trigger render + //-------------------------------------------------------------------------- + this->Impl->RenderVolumeGeometry(ren, prog, vol, input); + - // relase the texture units we were using + // Undo binds and de-activate buffers + //-------------------------------------------------------------------------- this->Impl->VolumeTextureObject->Deactivate(); this->Impl->NoiseTextureObject->Deactivate(); this->Impl->DepthTextureObject->Deactivate(); @@ -3251,17 +3714,5 @@ void vtkOpenGLGPUVolumeRayCastMapper::GPURender(vtkRenderer* ren, } } - if (volumeModified) - { - this->Impl->InputUpdateTime.Modified(); - } - - if (this->RenderToImage) - { - this->Impl->FBO->UnBind(GL_FRAMEBUFFER); - } - - glFinish(); - vtkOpenGLCheckErrorMacro("failed after Render"); } diff --git a/Rendering/VolumeOpenGL2/vtkOpenGLGPUVolumeRayCastMapper.h b/Rendering/VolumeOpenGL2/vtkOpenGLGPUVolumeRayCastMapper.h index 0f07fa53808..b7fb3efd6d9 100644 --- a/Rendering/VolumeOpenGL2/vtkOpenGLGPUVolumeRayCastMapper.h +++ b/Rendering/VolumeOpenGL2/vtkOpenGLGPUVolumeRayCastMapper.h @@ -18,9 +18,11 @@ #include "vtkRenderingVolumeOpenGL2Module.h" // For export macro -#include "vtkGPUVolumeRayCastMapper.h" +#include // Forward declarations +class vtkOpenGLCamera; +class vtkShaderProgram; class vtkTextureObject; //---------------------------------------------------------------------------- @@ -30,6 +32,12 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkOpenGLGPUVolumeRayCastMapper : public: static vtkOpenGLGPUVolumeRayCastMapper* New(); + enum Passes + { + RenderPass, + DepthPass = 1 + }; + vtkTypeMacro(vtkOpenGLGPUVolumeRayCastMapper, vtkGPUVolumeRayCastMapper); void PrintSelf( ostream& os, vtkIndent indent ); @@ -57,6 +65,13 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkOpenGLGPUVolumeRayCastMapper : // RenderToImage mode. void GetColorImage(vtkImageData* im); + // Description: + // Mapper can have multiple passes and internally it will set + // the state. The state can not be set externally explicitly + // but can be set indirectly depending on the options set by + // the user. + vtkGetMacro(CurrentPass, int); + protected: vtkOpenGLGPUVolumeRayCastMapper(); ~vtkOpenGLGPUVolumeRayCastMapper(); @@ -66,6 +81,12 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkOpenGLGPUVolumeRayCastMapper : // \post done: this->OpenGLObjectsCreated==0 virtual void ReleaseGraphicsResources(vtkWindow *window); + // Description: + // Build vertex and fragment shader for the volume rendering + void BuildDepthPassShader(vtkRenderer* ren, vtkVolume* vol, + int noOfComponents, + int independentComponents); + // Description: // Build vertex and fragment shader for the volume rendering void BuildShader(vtkRenderer* ren, vtkVolume* vol, int noOfCmponents); @@ -77,7 +98,7 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkOpenGLGPUVolumeRayCastMapper : double vtkNotUsed(datasetBounds)[6], double vtkNotUsed(scalarRange)[2], int vtkNotUsed(noOfComponents), - unsigned int vtkNotUsed(numberOfLevels)) {} + unsigned int vtkNotUsed(numberOfLevels)) {}; // \pre input is up-to-date virtual void RenderBlock(vtkRenderer *vtkNotUsed(ren), @@ -91,6 +112,16 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkOpenGLGPUVolumeRayCastMapper : // Rendering volume on GPU void GPURender(vtkRenderer *ren, vtkVolume *vol); + // Description: + // Method that performs the actual rendering given a volume and a shader + void DoGPURender(vtkRenderer* ren, + vtkVolume* vol, + vtkImageData* input, + vtkOpenGLCamera* cam, + vtkShaderProgram* shaderProgram, + int noOfComponents, + int independentComponents); + // Description: // Update the reduction factor of the render viewport (this->ReductionFactor) // according to the time spent in seconds to render the previous frame @@ -109,6 +140,7 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkOpenGLGPUVolumeRayCastMapper : ratio[0] = ratio[1] = ratio[2] = 1.0; } + // Description: // Empty implementation. virtual int IsRenderSupported(vtkRenderWindow *vtkNotUsed(window), @@ -118,6 +150,7 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkOpenGLGPUVolumeRayCastMapper : } double ReductionFactor; + int CurrentPass; private: class vtkInternal; diff --git a/Rendering/VolumeOpenGL2/vtkOpenGLProjectedTetrahedraMapper.cxx b/Rendering/VolumeOpenGL2/vtkOpenGLProjectedTetrahedraMapper.cxx index 8aaeaf8b72b..b40669b368d 100644 --- a/Rendering/VolumeOpenGL2/vtkOpenGLProjectedTetrahedraMapper.cxx +++ b/Rendering/VolumeOpenGL2/vtkOpenGLProjectedTetrahedraMapper.cxx @@ -140,6 +140,14 @@ bool vtkOpenGLProjectedTetrahedraMapper::IsSupported(vtkRenderWindow *rwin) this->CanDoFloatingPointFrameBuffer = false; if (this->UseFloatingPointFrameBuffer) { +#if GL_ES_VERSION_2_0 != 1 + if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32()) + { + this->CanDoFloatingPointFrameBuffer = true; + return true; + } +#endif + this->CanDoFloatingPointFrameBuffer #if GL_ES_VERSION_2_0 != 1 = (glewIsSupported("GL_EXT_framebuffer_object") != 0) @@ -204,42 +212,70 @@ bool vtkOpenGLProjectedTetrahedraMapper::AllocateFBOResources(vtkRenderer *r) this->FloatingPointFrameBufferResourcesAllocated = true; } + GLint winSampleBuffers = 0; + glGetIntegerv(GL_SAMPLE_BUFFERS, &winSampleBuffers); + + GLint winSamples = 0; + glGetIntegerv(GL_SAMPLES, &winSamples); + + GLint fboSampleBuffers = 0; + glGetIntegerv(GL_SAMPLE_BUFFERS, &fboSampleBuffers); + + int fboSamples + = ((fboSampleBuffers >= 1) + && (winSampleBuffers >= 1) + && (winSamples >= 1))?winSamples:0; + + // do not special handle multisampling, use the default. // Multisampling is becoming less common as it // is replaced with other techniques glBindFramebuffer(GL_FRAMEBUFFER, - this->Internals->FrameBufferObjectId); + this->Internals->FrameBufferObjectId); // allocate storage for renderbuffers glBindRenderbuffer( - GL_RENDERBUFFER, - this->Internals->RenderBufferObjectIds[0]); + GL_RENDERBUFFER, + this->Internals->RenderBufferObjectIds[0]); vtkOpenGLCheckErrorMacro("failed at glBindRenderBuffer color"); + glRenderbufferStorageMultisample( + GL_RENDERBUFFER, + fboSamples, + GL_RGBA32F, + this->CurrentFBOWidth, + this->CurrentFBOHeight); + vtkOpenGLCheckErrorMacro("failed at glRenderBufferStorage color"); + glBindRenderbuffer( - GL_RENDERBUFFER, - this->Internals->RenderBufferObjectIds[1]); + GL_RENDERBUFFER, + this->Internals->RenderBufferObjectIds[1]); vtkOpenGLCheckErrorMacro("failed at glBindRenderBuffer depth"); + glRenderbufferStorageMultisample( + GL_RENDERBUFFER, + fboSamples, + GL_DEPTH_COMPONENT, + this->CurrentFBOWidth, + this->CurrentFBOHeight); + + // Best way to make it complete: bind the fbo for both draw+read + // durring setup + glBindFramebuffer( + GL_FRAMEBUFFER, + this->Internals->FrameBufferObjectId); - // best way to make it complete: bind the fbo for both draw+read - // durring setup - glBindFramebuffer( - GL_FRAMEBUFFER, - this->Internals->FrameBufferObjectId); - vtkOpenGLCheckErrorMacro("failed at glBindFramebuffer"); - - glFramebufferRenderbuffer( - GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_RENDERBUFFER, - this->Internals->RenderBufferObjectIds[0]); + glFramebufferRenderbuffer( + GL_FRAMEBUFFER, + GL_COLOR_ATTACHMENT0, + GL_RENDERBUFFER, + this->Internals->RenderBufferObjectIds[0]); vtkOpenGLCheckErrorMacro("failed at glFramebufferRenderBuffer for color"); glFramebufferRenderbuffer( - GL_FRAMEBUFFER, - GL_DEPTH_ATTACHMENT, - GL_RENDERBUFFER, - this->Internals->RenderBufferObjectIds[1]); + GL_FRAMEBUFFER, + GL_DEPTH_ATTACHMENT, + GL_RENDERBUFFER, + this->Internals->RenderBufferObjectIds[1]); vtkOpenGLCheckErrorMacro("failed at glFramebufferRenderBuffer for depth"); // verify that it is usable @@ -492,7 +528,7 @@ inline float vtkOpenGLProjectedTetrahedraMapper::GetCorrectedDepth( //----------------------------------------------------------------------------- void vtkOpenGLProjectedTetrahedraMapper::ProjectTetrahedra(vtkRenderer *renderer, - vtkVolume *volume) + vtkVolume *volume) { vtkOpenGLClearErrorMacro(); @@ -524,11 +560,11 @@ void vtkOpenGLProjectedTetrahedraMapper::ProjectTetrahedra(vtkRenderer *renderer this->Internals->FrameBufferObjectId); glBlitFramebuffer(0, 0, - this->CurrentFBOWidth, this->CurrentFBOHeight, - 0, 0, - this->CurrentFBOWidth, this->CurrentFBOHeight, - GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, - GL_NEAREST); + this->CurrentFBOWidth, this->CurrentFBOHeight, + 0, 0, + this->CurrentFBOWidth, this->CurrentFBOHeight, + GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, + GL_NEAREST); vtkOpenGLCheckErrorMacro("failed at glBlitFramebuffer"); } @@ -572,8 +608,12 @@ void vtkOpenGLProjectedTetrahedraMapper::ProjectTetrahedra(vtkRenderer *renderer if (!volume->GetIsIdentity()) { vtkMatrix4x4 *tmpMat = vtkMatrix4x4::New(); + vtkMatrix4x4 *tmpMat2 = vtkMatrix4x4::New(); vtkMatrix4x4 *mcwc = volume->GetMatrix(); - vtkMatrix4x4::Multiply4x4(mcwc, wcvc, tmpMat); + tmpMat2->DeepCopy(wcvc); + tmpMat2->Transpose(); + vtkMatrix4x4::Multiply4x4(tmpMat2, mcwc, tmpMat); + tmpMat->Transpose(); for(int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) @@ -582,6 +622,7 @@ void vtkOpenGLProjectedTetrahedraMapper::ProjectTetrahedra(vtkRenderer *renderer } } tmpMat->Delete(); + tmpMat2->Delete(); } else { @@ -1076,13 +1117,13 @@ void vtkOpenGLProjectedTetrahedraMapper::ProjectTetrahedra(vtkRenderer *renderer // read from fbo glBindFramebuffer(GL_READ_FRAMEBUFFER, - this->Internals->FrameBufferObjectId); + this->Internals->FrameBufferObjectId); // draw to default fbo glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBlitFramebuffer(0, 0, this->CurrentFBOWidth, this->CurrentFBOHeight, - 0, 0, this->CurrentFBOWidth, this->CurrentFBOHeight, - GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); + 0, 0, this->CurrentFBOWidth, this->CurrentFBOHeight, + GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); vtkOpenGLCheckErrorMacro("failed at glBlitFramebuffer"); diff --git a/Rendering/VolumeOpenGL2/vtkSmartVolumeMapper.h b/Rendering/VolumeOpenGL2/vtkSmartVolumeMapper.h index 2fd4360d8e0..39fc3eb892f 100644 --- a/Rendering/VolumeOpenGL2/vtkSmartVolumeMapper.h +++ b/Rendering/VolumeOpenGL2/vtkSmartVolumeMapper.h @@ -114,7 +114,6 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkSmartVolumeMapper : public vtkVolumeMa // Get the final color level. vtkGetMacro( FinalColorLevel, float ); -//BTX // The possible values for the default and current render mode ivars enum { @@ -130,7 +129,6 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkSmartVolumeMapper : public vtkVolumeMa UndefinedRenderMode=5, InvalidRenderMode=6 }; -//ETX // Description: // Set the requested render mode. The default is @@ -248,8 +246,6 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkSmartVolumeMapper : public vtkVolumeMa vtkSetMacro( SampleDistance, float ); vtkGetMacro( SampleDistance, float ); - -//BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // Initialize rendering for this volume. @@ -261,7 +257,6 @@ class VTKRENDERINGVOLUMEOPENGL2_EXPORT vtkSmartVolumeMapper : public vtkVolumeMa // The parameter window could be used to determine which graphic // resources to release. void ReleaseGraphicsResources(vtkWindow *); -//ETX protected: vtkSmartVolumeMapper(); diff --git a/Rendering/VolumeOpenGL2/vtkVolumeShaderComposer.h b/Rendering/VolumeOpenGL2/vtkVolumeShaderComposer.h index 142ebd4d10c..8a84a820c45 100644 --- a/Rendering/VolumeOpenGL2/vtkVolumeShaderComposer.h +++ b/Rendering/VolumeOpenGL2/vtkVolumeShaderComposer.h @@ -19,6 +19,7 @@ #include "vtkVolumeMask.h" #include +#include #include #include #include @@ -28,6 +29,12 @@ #include #include +// NOTE: +// In this code, we referred to various spaces described below: +// Object space: Raw coordinates in space defined by volume matrix +// Dataset space: Raw coordinates +// Eye space: Coordinates in eye space (as referred in computer graphics) + namespace vtkvolume { //-------------------------------------------------------------------------- @@ -77,20 +84,7 @@ namespace vtkvolume return std::string( "\n // For point dataset, we offset the texture coordinate\ \n // to account for OpenGL treating voxel at the center of the cell.\ - \n vec3 spacingSign = vec3(1.0);\ - \n if (in_cellSpacing.x < 0.0)\ - \n {\ - \n spacingSign.x = -1.0;\ - \n }\ - \n if (in_cellSpacing.y < 0.0)\ - \n {\ - \n spacingSign.y = -1.0;\ - \n }\ - \n if (in_cellSpacing.z < 0.0)\ - \n {\ - \n spacingSign.z = -1.0;\ - \n }\ - \n vec3 uvx = spacingSign * (in_vertexPos - in_volumeExtentsMin) /\ + \n vec3 uvx = sign(in_cellSpacing) * (in_vertexPos - in_volumeExtentsMin) /\ \n (in_volumeExtentsMax - in_volumeExtentsMin);\ \n if (in_cellFlag)\ \n {\ @@ -126,7 +120,7 @@ namespace vtkvolume //-------------------------------------------------------------------------- std::string BaseDeclarationFragment(vtkRenderer* vtkNotUsed(ren), - vtkVolumeMapper* vtkNotUsed(mapper), + vtkVolumeMapper* mapper, vtkVolume* vtkNotUsed(vol), int vtkNotUsed(numberOfLights), int lightingComplexity, @@ -184,24 +178,24 @@ namespace vtkvolume \n// Others\ \nuniform bool in_cellFlag;\ \n uniform bool in_useJittering;\ + \n uniform bool in_clampDepthToBackface;\ "); - if (hasGradientOpacity || lightingComplexity > 0) + if (lightingComplexity > 0 || hasGradientOpacity) { shaderStr += std::string("\ + \nuniform bool in_twoSidedLighting;\ \nvec3 g_xvec;\ \nvec3 g_yvec;\ - \nvec3 g_zvec;" - ); + \nvec3 g_zvec;"); } - if (lightingComplexity > 0 || hasGradientOpacity) + if (hasGradientOpacity) { shaderStr += std::string("\ - \nuniform bool in_twoSidedLighting;\ + \nvec3 g_aspect;\ \nvec3 g_cellSpacing;\ - \nfloat g_avgSpacing;" - ); + \nfloat g_avgSpacing;"); } if (lightingComplexity == 3) @@ -240,9 +234,7 @@ namespace vtkvolume \nvec4 g_lightPosObj;\ \nvec3 g_ldir;\ \nvec3 g_vdir;\ - \nvec3 g_h;\ - \nvec3 g_aspect;" - ); + \nvec3 g_h;"); } if (noOfComponents > 1 && independentComponents) @@ -251,54 +243,107 @@ namespace vtkvolume \nuniform vec4 in_componentWeight;"); } + vtkOpenGLGPUVolumeRayCastMapper* glMapper + = vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper); + if (glMapper->GetCurrentPass() != vtkOpenGLGPUVolumeRayCastMapper::DepthPass && + glMapper->GetUseDepthPass()) + { + shaderStr += std::string("\ + \nuniform sampler2D in_depthPassSampler;"); + } + return shaderStr; } //-------------------------------------------------------------------------- std::string BaseInit(vtkRenderer* vtkNotUsed(ren), - vtkVolumeMapper* vtkNotUsed(mapper), + vtkVolumeMapper* mapper, vtkVolume* vol, int lightingComplexity) { + vtkOpenGLGPUVolumeRayCastMapper* glMapper + = vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper); + std::string shaderStr = std::string("\ - \n // Get the 3D texture coordinates for lookup into the in_volume dataset\ - \n g_dataPos = ip_textureCoords.xyz;\ - \n\ - \n // Eye position in object space\ - \n g_eyePosObj = (in_inverseVolumeMatrix * vec4(in_cameraPos, 1.0));\ - \n if (g_eyePosObj.w != 0.0)\ - \n {\ - \n g_eyePosObj.x /= g_eyePosObj.w;\ - \n g_eyePosObj.y /= g_eyePosObj.w;\ - \n g_eyePosObj.z /= g_eyePosObj.w;\ - \n g_eyePosObj.w = 1.0;\ - \n }\ - \n\ - \n // Getting the ray marching direction (in object space);\ - \n vec3 rayDir = computeRayDirection();\ - \n\ - \n // Multiply the raymarching direction with the step size to get the\ - \n // sub-step size we need to take at each raymarching step\ - \n g_dirStep = (in_inverseTextureDatasetMatrix *\ - \n vec4(rayDir, 0.0)).xyz * in_sampleDistance;\ - \n\ - \n float jitterValue = (texture2D(in_noiseSampler, g_dataPos.xy).x);\ - \n if (in_useJittering)\ - \n {\ - \n g_dataPos += g_dirStep * jitterValue;\ - \n }\ - \n else\ - \n {\ - \n g_dataPos += g_dirStep;\ - \n }\ - \n\ - \n // Flag to deternmine if voxel should be considered for the rendering\ - \n bool l_skip = false;"); + \n bool l_adjustTextureExtents = !in_cellFlag;" + ); + + if (glMapper->GetCurrentPass() != vtkOpenGLGPUVolumeRayCastMapper::DepthPass && + glMapper->GetUseDepthPass() && glMapper->GetBlendMode() == + vtkVolumeMapper::COMPOSITE_BLEND) + { + shaderStr += std::string("\ + \n //\ + \n vec2 fragTexCoord2 = (gl_FragCoord.xy - in_windowLowerLeftCorner) *\ + \n in_inverseWindowSize;\ + \n vec4 depthValue = texture2D(in_depthPassSampler, fragTexCoord2);\ + \n vec4 dataPos;\ + \n dataPos.x = (gl_FragCoord.x - in_windowLowerLeftCorner.x) * 2.0 *\ + \n in_inverseWindowSize.x - 1.0;\ + \n dataPos.y = (gl_FragCoord.y - in_windowLowerLeftCorner.y) * 2.0 *\ + \n in_inverseWindowSize.y - 1.0;\ + \n dataPos.z = (2.0 * depthValue.x - (gl_DepthRange.near +\ + \n gl_DepthRange.far)) / gl_DepthRange.diff;\ + \n dataPos.w = 1.0;\ + \n\ + \n // From normalized device coordinates to eye coordinates.\ + \n // in_projectionMatrix is inversed because of way VT\ + \n // From eye coordinates to texture coordinates\ + \n dataPos = in_inverseTextureDatasetMatrix *\ + \n in_inverseVolumeMatrix *\ + \n in_inverseModelViewMatrix *\ + \n in_inverseProjectionMatrix *\ + \n dataPos;\ + \n dataPos /= dataPos.w;\ + \n g_dataPos = dataPos.xyz;\ + \n l_adjustTextureExtents = true;" + ); + } + else + { + shaderStr += std::string("\ + \n // Get the 3D texture coordinates for lookup into the in_volume dataset\ + \n g_dataPos = ip_textureCoords.xyz;" + ); + } + + shaderStr += std::string("\ + \n\ + \n // Eye position in dataset space\ + \n g_eyePosObj = (in_inverseVolumeMatrix * vec4(in_cameraPos, 1.0));\ + \n if (g_eyePosObj.w != 0.0)\ + \n {\ + \n g_eyePosObj.x /= g_eyePosObj.w;\ + \n g_eyePosObj.y /= g_eyePosObj.w;\ + \n g_eyePosObj.z /= g_eyePosObj.w;\ + \n g_eyePosObj.w = 1.0;\ + \n }\ + \n\ + \n // Getting the ray marching direction (in dataset space);\ + \n vec3 rayDir = computeRayDirection();\ + \n\ + \n // Multiply the raymarching direction with the step size to get the\ + \n // sub-step size we need to take at each raymarching step\ + \n g_dirStep = (in_inverseTextureDatasetMatrix *\ + \n vec4(rayDir, 0.0)).xyz * in_sampleDistance;\ + \n\ + \n float jitterValue = (texture2D(in_noiseSampler, g_dataPos.xy).x);\ + \n if (in_useJittering)\ + \n {\ + \n g_dataPos += g_dirStep * jitterValue;\ + \n }\ + \n else\ + \n {\ + \n g_dataPos += g_dirStep;\ + \n }\ + \n\ + \n // Flag to deternmine if voxel should be considered for the rendering\ + \n bool l_skip = false;"); if (vol->GetProperty()->GetShade() && lightingComplexity == 1) { shaderStr += std::string("\ - \n // Light position in object space\ + \n // Light position in dataset space\ \n g_lightPosObj = (in_inverseVolumeMatrix *\ \n vec4(in_cameraPos, 1.0));\ \n if (g_lightPosObj.w != 0.0)\ @@ -313,16 +358,11 @@ namespace vtkvolume \n g_h = normalize(g_ldir + g_vdir);" ); } - if (vol->GetProperty()->GetShade() || - vol->GetProperty()->HasGradientOpacity()) + if ( (vol->GetProperty()->GetShade() || + vol->GetProperty()->HasGradientOpacity()) && + glMapper->GetCurrentPass() != vtkOpenGLGPUVolumeRayCastMapper::DepthPass) { shaderStr += std::string("\ - \n g_cellSpacing = vec3(in_cellSpacing[0],\ - \n in_cellSpacing[1],\ - \n in_cellSpacing[2]);\ - \n g_avgSpacing = (g_cellSpacing[0] +\ - \n g_cellSpacing[1] +\ - \n g_cellSpacing[2])/3.0;\ \n g_xvec = vec3(in_cellStep[0], 0.0, 0.0);\ \n g_yvec = vec3(0.0, in_cellStep[1], 0.0);\ \n g_zvec = vec3(0.0, 0.0, in_cellStep[2]);" @@ -332,6 +372,12 @@ namespace vtkvolume if (vol->GetProperty()->HasGradientOpacity()) { shaderStr += std::string("\ + \n g_cellSpacing = vec3(in_cellSpacing[0],\ + \n in_cellSpacing[1],\ + \n in_cellSpacing[2]);\ + \n g_avgSpacing = (g_cellSpacing[0] +\ + \n g_cellSpacing[1] +\ + \n g_cellSpacing[2])/3.0;\ \n // Adjust the aspect\ \n g_aspect.x = g_cellSpacing[0] * 2.0 / g_avgSpacing;\ \n g_aspect.y = g_cellSpacing[1] * 2.0 / g_avgSpacing;\ @@ -932,7 +978,8 @@ namespace vtkvolume \n vec4 l_maxValue = vec4(0.0);" ); } - else if (mapper->GetBlendMode() == vtkVolumeMapper::MINIMUM_INTENSITY_BLEND) + else if (mapper->GetBlendMode() == + vtkVolumeMapper::MINIMUM_INTENSITY_BLEND) { return std::string("\ \n //We get data between 0.0 - 1.0 range\ @@ -962,6 +1009,8 @@ namespace vtkvolume int noOfComponents, int independentComponents = 0) { + vtkOpenGLGPUVolumeRayCastMapper* glMapper = + vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper); std::string shaderStr = std::string("\ \n if (!l_skip)\ \n {\ @@ -1119,12 +1168,25 @@ namespace vtkvolume if (noOfComponents > 1 && independentComponents) { shaderStr += std::string("\ - \n vec4 color[4]; vec4 tmp = vec4(0.0);\ - \n float totalAlpha = 0.0;\ - \n for (int i = 0; i < in_noOfComponents; ++i)\ - \n {\ + \n vec4 color[4]; vec4 tmp = vec4(0.0);\ + \n float totalAlpha = 0.0;\ + \n for (int i = 0; i < in_noOfComponents; ++i)\ + \n {\ "); - if (!mask || !maskInput || + if (glMapper->GetUseDepthPass() && glMapper->GetCurrentPass() == + vtkOpenGLGPUVolumeRayCastMapper::DepthPass) + { + shaderStr += std::string("\ + \n // Data fetching from the red channel of volume texture\ + \n float opacity = computeOpacity(scalar, i);\ + \n if (opacity > 0.0)\ + \n {\ + \n g_srcColor.a = opacity;\ + \n }\ + \n }" + ); + } + else if (!mask || !maskInput || maskType != vtkGPUVolumeRayCastMapper::LabelMapMaskType) { shaderStr += std::string("\ @@ -1147,6 +1209,14 @@ namespace vtkvolume ); } } + else if (glMapper->GetUseDepthPass() && glMapper->GetCurrentPass() == + vtkOpenGLGPUVolumeRayCastMapper::DepthPass) + { + shaderStr += std::string("\ + \n g_srcColor = vec4(0.0);\ + \n g_srcColor.a = computeOpacity(scalar);" + ); + } else { if (!mask || !maskInput || @@ -1196,6 +1266,78 @@ namespace vtkvolume return shaderStr; } + //-------------------------------------------------------------------------- + std::string PickingActorPassExit(vtkRenderer* vtkNotUsed(ren), + vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol)) + { + return std::string("\ + \n // Special coloring mode which renders the Prop Id in fragments that\ + \n // have accumulated certain level of opacity. Used during the selection\ + \n // pass vtkHardwareSelection::ACTOR_PASS.\ + \n if (g_fragColor.a > 3.0/ 255.0)\ + \n {\ + \n gl_FragData[0] = vec4(in_propId, 1.0);\ + \n }\ + \n else\ + \n {\ + \n gl_FragData[0] = vec4(0.0);\ + \n }\ + \n return;"); + }; + + //-------------------------------------------------------------------------- + std::string PickingIdLow24PassExit(vtkRenderer* vtkNotUsed(ren), + vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol)) + { + return std::string("\ + \n // Special coloring mode which renders the voxel index in fragments that\ + \n // have accumulated certain level of opacity. Used during the selection\ + \n // pass vtkHardwareSelection::ID_LOW24.\ + \n if (g_fragColor.a > 3.0/ 255.0)\ + \n {\ + \n uvec3 volumeDim = uvec3(in_textureExtentsMax - in_textureExtentsMin);\ + \n uvec3 voxelCoords = uvec3(volumeDim * g_dataPos);\ + \n // vtkHardwareSelector assumes index 0 to be empty space, so add uint(1).\ + \n uint idx = volumeDim.x * volumeDim.y * voxelCoords.z +\ + \n volumeDim.x * voxelCoords.y + voxelCoords.x + uint(1);\ + \n gl_FragData[0] = vec4(float(idx % uint(256)) / 255.0,\ + \n float((idx / uint(256)) % uint(256)) / 255.0,\ + \n float((idx / uint(65536)) % uint(256)) / 255.0, 1.0);\ + \n }\ + \n else\ + \n {\ + \n gl_FragData[0] = vec4(0.0);\ + \n }\ + \n return;"); + }; + + //-------------------------------------------------------------------------- + std::string PickingIdMid24PassExit(vtkRenderer* vtkNotUsed(ren), + vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol)) + { + return std::string("\ + \n // Special coloring mode which renders the voxel index in fragments that\ + \n // have accumulated certain level of opacity. Used during the selection\ + \n // pass vtkHardwareSelection::ID_MID24.\ + \n if (g_fragColor.a > 3.0/ 255.0)\ + \n {\ + \n uvec3 volumeDim = uvec3(in_textureExtentsMax - in_textureExtentsMin);\ + \n uvec3 voxelCoords = uvec3(volumeDim * g_dataPos);\ + \n // vtkHardwareSelector assumes index 0 to be empty space, so add uint(1).\ + \n uint idx = volumeDim.x * volumeDim.y * voxelCoords.z +\ + \n volumeDim.x * voxelCoords.y + voxelCoords.x + uint(1);\ + \n idx = ((idx & 0xff000000) >> 24);\ + \n gl_FragData[0] = vec4(float(idx % uint(256)) / 255.0,\ + \n float((idx / uint(256)) % uint(256)) / 255.0,\ + \n float(idx / uint(65536)) / 255.0, 1.0);\ + \n }\ + \n else\ + \n {\ + \n gl_FragData[0] = vec4(0.0);\ + \n }\ + \n return;"); + }; + //-------------------------------------------------------------------------- std::string ShadingExit(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* mapper, @@ -1203,7 +1345,16 @@ namespace vtkvolume int noOfComponents, int independentComponents = 0) { - if (mapper->GetBlendMode() == vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND) + vtkOpenGLGPUVolumeRayCastMapper* glMapper = + vtkOpenGLGPUVolumeRayCastMapper::SafeDownCast(mapper); + + if (glMapper->GetUseDepthPass() && glMapper->GetCurrentPass() == + vtkOpenGLGPUVolumeRayCastMapper::DepthPass && + mapper->GetBlendMode() == vtkVolumeMapper::COMPOSITE_BLEND) + { + return std::string(); + } + else if (mapper->GetBlendMode() == vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND) { if (noOfComponents > 1 && independentComponents) { @@ -1296,6 +1447,14 @@ namespace vtkvolume return std::string(); } + //-------------------------------------------------------------------------- + std::string PickingActorPassDeclaration(vtkRenderer* vtkNotUsed(ren), + vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol)) + { + return std::string("\ + \n uniform vec3 in_propId;"); + }; + //-------------------------------------------------------------------------- std::string TerminationInit(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), @@ -1305,7 +1464,7 @@ namespace vtkvolume \n // Minimum texture access coordinate\ \n vec3 l_texMin = vec3(0.0);\ \n vec3 l_texMax = vec3(1.0);\ - \n if (!in_cellFlag)\ + \n if (l_adjustTextureExtents)\ \n {\ \n vec3 delta = in_textureExtentsMax - in_textureExtentsMin;\ \n l_texMin = vec3(0.5) / delta;\ @@ -1376,19 +1535,12 @@ namespace vtkvolume vtkVolume* vtkNotUsed(vol)) { return std::string("\ - \n // sign function performs component wise operation and returns -1\ - \n // if the difference is less than 0, 0 if equal to 0, and 1 if\ - \n // above 0. So if the ray is inside the volume, dot product will\ - \n // always be 3.\ - \n stop = dot(sign(g_dataPos - l_texMin), sign(l_texMax - g_dataPos))\ - \n < 3.0;\ - \n\ - \n // If the stopping condition is true we brek out of the ray marching\ - \n // loop\ - \n if (stop)\ + \n if(any(greaterThan(g_dataPos, l_texMax)) ||\ + \n any(lessThan(g_dataPos, l_texMin)))\ \n {\ \n break;\ \n }\ + \n\ \n // Early ray termination\ \n // if the currently composited colour alpha is already fully saturated\ \n // we terminated the loop or if we have hit an obstacle in the\ @@ -1574,7 +1726,7 @@ namespace vtkvolume } //-------------------------------------------------------------------------- - std::string ClippingInit(vtkRenderer* vtkNotUsed(ren), + std::string ClippingInit(vtkRenderer* ren, vtkVolumeMapper* mapper, vtkVolume* vtkNotUsed(vol)) { @@ -1582,67 +1734,111 @@ namespace vtkvolume { return std::string(); } - else + + std::string shaderStr; + if (!ren->GetActiveCamera()->GetParallelProjection()) { - return std::string("\ - \n int clippingPlanesSize = int(in_clippingPlanes[0]);\ - \n vec4 objDataPos = vec4(0.0);\ - \n mat4 textureToObjMat = in_volumeMatrix *\ - \n in_textureDatasetMatrix;\ - \n for (int i = 0; i < clippingPlanesSize; i = i + 6)\ - \n {\ - \n if (in_useJittering)\ - \n {\ - \n objDataPos = textureToObjMat * vec4(g_dataPos - (g_dirStep\ - \n * jitterValue), 1.0);\ - \n }\ - \n else\ - \n {\ - \n objDataPos = textureToObjMat * vec4(g_dataPos - g_dirStep, 1.0);\ - \n }\ - \n if (objDataPos.w != 0.0)\ + shaderStr = std::string("\ + vec4 temp = in_volumeMatrix * vec4(rayDir, 0.0);\ + \n if (temp.w != 0.0)\ \n {\ - \n objDataPos = objDataPos/objDataPos.w; objDataPos.w = 1.0;\ - \n }\ - \n vec3 planeOrigin = vec3(in_clippingPlanes[i + 1],\ - \n in_clippingPlanes[i + 2],\ - \n in_clippingPlanes[i + 3]);\ - \n vec3 planeNormal = vec3(in_clippingPlanes[i + 4],\ - \n in_clippingPlanes[i + 5],\ - \n in_clippingPlanes[i + 6]);\ - \n vec3 normalizedPlaneNormal = normalize(planeNormal);\ - \n\ - \n float planeD = -planeOrigin[0] * normalizedPlaneNormal[0] - planeOrigin[1]\ - \n * normalizedPlaneNormal[1] - planeOrigin[2] * normalizedPlaneNormal[2];\ - \n bool frontFace = dot(rayDir, normalizedPlaneNormal) > 0;\ - \n float dist = dot(rayDir, normalizedPlaneNormal);\ - \n if (dist != 0.0) { dist = (-planeD - dot(normalizedPlaneNormal, objDataPos.xyz)) / dist; }\ - \n if (frontFace && dist > 0.0 && dot(vec3(objDataPos.xyz - planeOrigin), planeNormal) < 0)\ - \n {\ - \n vec4 newObjDataPos = vec4(objDataPos.xyz + dist * rayDir, 1.0);\ - \n newObjDataPos = in_inverseTextureDatasetMatrix\ - \n * in_inverseVolumeMatrix * vec4(newObjDataPos.xyz, 1.0);\ - \n if (newObjDataPos.w != 0.0)\ - \n {\ - \n newObjDataPos /= newObjDataPos.w;\ - \n }\ - \n if (in_useJittering)\ - \n {\ - \n g_dataPos = newObjDataPos.xyz + g_dirStep * jitterValue;\ - \n }\ - \n else\ - \n {\ - \n g_dataPos = newObjDataPos.xyz + g_dirStep;\ - \n }\ - \n bool stop = dot(sign(g_dataPos - l_texMin), sign(l_texMax - g_dataPos))\ - \n < 3.0;\ - \n if (stop)\ - \n {\ - \n discard;\ - \n }\ + \n temp = temp/temp.w;\ + \n temp.w = 1.0;\ \n }\ - \n }"); + vec3 objRayDir = temp.xyz;"); + } + else + { + shaderStr = std::string("\ + vec3 objRayDir = normalize(in_projectionDirection);"); } + + shaderStr += std::string("\ + \n int clippingPlanesSize = int(in_clippingPlanes[0]);\ + \n vec4 objDataPos = vec4(0.0);\ + \n mat4 textureToObjMat = in_volumeMatrix *\ + \n in_textureDatasetMatrix;\ + \n\ + \n vec4 terminatePointObj = textureToObjMat * terminatePoint;\ + \n if (terminatePointObj.w != 0.0)\ + \n {\ + \n terminatePointObj = terminatePointObj/ terminatePointObj.w ;\ + \n terminatePointObj.w = 1.0;\ + \n }\ + \n\ + \n for (int i = 0; i < clippingPlanesSize; i = i + 6)\ + \n {\ + \n if (in_useJittering)\ + \n {\ + \n objDataPos = textureToObjMat * vec4(g_dataPos - (g_dirStep\ + \n * jitterValue), 1.0);\ + \n }\ + \n else\ + \n {\ + \n objDataPos = textureToObjMat * vec4(g_dataPos - g_dirStep, 1.0);\ + \n }\ + \n if (objDataPos.w != 0.0)\ + \n {\ + \n objDataPos = objDataPos/objDataPos.w; objDataPos.w = 1.0;\ + \n }\ + \n vec3 planeOrigin = vec3(in_clippingPlanes[i + 1],\ + \n in_clippingPlanes[i + 2],\ + \n in_clippingPlanes[i + 3]);\ + \n vec3 planeNormal = vec3(in_clippingPlanes[i + 4],\ + \n in_clippingPlanes[i + 5],\ + \n in_clippingPlanes[i + 6]);\ + \n vec3 normalizedPlaneNormal = normalize(planeNormal);\ + \n\ + \n float rayDotNormal = dot(objRayDir, normalizedPlaneNormal);\ + \n bool frontFace = rayDotNormal > 0;\ + \n float distance = dot(normalizedPlaneNormal, planeOrigin - objDataPos.xyz);\ + \n\ + \n if (frontFace && // Observing from the clipped side (plane's front face)\ + \n distance > 0.0) // Ray-entry lies on the clipped side.\ + \n {\ + \n // Scale the point-plane distance to the ray direction and update the\ + \n // entry point.\ + \n float rayScaledDist = distance / rayDotNormal;\ + \n vec4 newObjDataPos = vec4(objDataPos.xyz + rayScaledDist * objRayDir, 1.0);\ + \n newObjDataPos = in_inverseTextureDatasetMatrix\ + \n * in_inverseVolumeMatrix * vec4(newObjDataPos.xyz, 1.0);\ + \n if (newObjDataPos.w != 0.0)\ + \n {\ + \n newObjDataPos /= newObjDataPos.w;\ + \n }\ + \n if (in_useJittering)\ + \n {\ + \n g_dataPos = newObjDataPos.xyz + g_dirStep * jitterValue;\ + \n }\ + \n else\ + \n {\ + \n g_dataPos = newObjDataPos.xyz + g_dirStep;\ + \n }\ + \n\ + \n bool stop = any(greaterThan(g_dataPos, l_texMax)) || any(lessThan(g_dataPos, l_texMin));\ + \n if (stop)\ + \n {\ + \n // The ray exits the bounding box before ever intersecting the plane (only\ + \n // the clipped space is hit).\ + \n discard;\ + \n }\ + \n\ + \n bool behindGeometry = dot(terminatePointObj.xyz - planeOrigin.xyz, normalizedPlaneNormal) < 0.0;\ + \n if (behindGeometry)\ + \n {\ + \n // Geometry appears in front of the plane.\ + \n discard;\ + \n }\ + \n\ + \n // Update the number of ray marching steps to account for the clipped entry point (\ + \n // this is necessary in case the ray hits geometry after marching behind the plane,\ + \n // given that the number of steps was assumed to be from the not-clipped entry).\ + \n l_terminatePointMax = length(terminatePoint.xyz - g_dataPos.xyz) /\ + \n length(g_dirStep);\ + \n }\ + \n }"); + + return shaderStr; } //-------------------------------------------------------------------------- @@ -1670,7 +1866,7 @@ namespace vtkvolume \n vec3 planeNormal = vec3(in_clippingPlanes[i + 4],\ \n in_clippingPlanes[i + 5],\ \n in_clippingPlanes[i + 6]);\ - \n if (dot(vec3(objDataPos.xyz - planeOrigin), planeNormal) < 0 && dot(rayDir, planeNormal) < 0)\ + \n if (dot(vec3(objDataPos.xyz - planeOrigin), planeNormal) < 0 && dot(objRayDir, planeNormal) < 0)\ \n {\ \n l_skip = true;\ \n g_exit = true;\ @@ -1829,18 +2025,22 @@ namespace vtkvolume } //-------------------------------------------------------------------------- - std::string RenderToImageDepthInit(vtkRenderer* vtkNotUsed(ren), - vtkVolumeMapper* vtkNotUsed(mapper), - vtkVolume* vtkNotUsed(vol)) + std::string RenderToImageInit(vtkRenderer* vtkNotUsed(ren), + vtkVolumeMapper* vtkNotUsed(mapper), + vtkVolume* vtkNotUsed(vol)) { return std::string("\ - \n vec3 l_opaqueFragPos = g_dataPos;\ + \n vec3 l_opaqueFragPos = vec3(-1.0);\ + \n if(in_clampDepthToBackface)\ + \n {\ + \n l_opaqueFragPos = g_dataPos;\ + \n }\ \n bool l_updateDepth = true;" ); } //-------------------------------------------------------------------------- - std::string RenderToImageDepthImplementation( + std::string RenderToImageImplementation( vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol)) { @@ -1854,14 +2054,62 @@ namespace vtkvolume } //-------------------------------------------------------------------------- - std::string RenderToImageDepthExit(vtkRenderer* vtkNotUsed(ren), + std::string RenderToImageExit(vtkRenderer* vtkNotUsed(ren), + vtkVolumeMapper* vtkNotUsed(mapper), + vtkVolume* vtkNotUsed(vol)) + { + return std::string("\ + \n if (l_opaqueFragPos == vec3(-1.0))\ + \n {\ + \n gl_FragData[1] = vec4(1.0);\ + \n }\ + \n else\ + \n {\ + \n vec4 depthValue = in_projectionMatrix * in_modelViewMatrix *\ + \n in_volumeMatrix * in_textureDatasetMatrix *\ + \n vec4(l_opaqueFragPos, 1.0);\ + \n depthValue /= depthValue.w;\ + \n gl_FragData[1] = vec4(vec3(0.5 * (gl_DepthRange.far -\ + \n gl_DepthRange.near) * depthValue.z + 0.5 *\ + \n (gl_DepthRange.far + gl_DepthRange.near)), 1.0);\ + \n }" + ); + } + + //-------------------------------------------------------------------------- + std::string DepthPassInit(vtkRenderer* vtkNotUsed(ren), + vtkVolumeMapper* vtkNotUsed(mapper), + vtkVolume* vtkNotUsed(vol)) + { + return std::string("\ + \n vec3 l_isoPos = g_dataPos;" + ); + } + + //-------------------------------------------------------------------------- + std::string DepthPassImplementation( + vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), + vtkVolume* vtkNotUsed(vol)) + { + return std::string("\ + \n if(!l_skip && g_srcColor.a > 0.0)\ + \n {\ + \n l_isoPos = g_dataPos;\ + \n g_exit = true; l_skip = true;\ + \n }" + ); + } + + //-------------------------------------------------------------------------- + std::string DepthPassExit(vtkRenderer* vtkNotUsed(ren), vtkVolumeMapper* vtkNotUsed(mapper), vtkVolume* vtkNotUsed(vol)) { return std::string("\ \n vec4 depthValue = in_projectionMatrix * in_modelViewMatrix *\ \n in_volumeMatrix * in_textureDatasetMatrix *\ - \n vec4(l_opaqueFragPos, 1.0);\ + \n vec4(l_isoPos, 1.0);\ + \n gl_FragData[0] = vec4(l_isoPos, 1.0);\ \n gl_FragData[1] = vec4(vec3((depthValue.z/depthValue.w) * 0.5 + 0.5),\ \n 1.0);" ); diff --git a/Rendering/VolumeOpenGL2/vtkVolumeStateRAII.h b/Rendering/VolumeOpenGL2/vtkVolumeStateRAII.h index 9f0fac3b173..78750c84642 100644 --- a/Rendering/VolumeOpenGL2/vtkVolumeStateRAII.h +++ b/Rendering/VolumeOpenGL2/vtkVolumeStateRAII.h @@ -24,16 +24,20 @@ class vtkVolumeStateRAII public: vtkVolumeStateRAII() { - this->DepthTestEnabled = (glIsEnabled(GL_DEPTH_TEST) != 0); + this->DepthTestEnabled = (glIsEnabled(GL_DEPTH_TEST) != GL_FALSE); - this->BlendEnabled = (glIsEnabled(GL_BLEND) != 0); + this->BlendEnabled = (glIsEnabled(GL_BLEND) != GL_FALSE); - this->CullFaceEnabled = (glIsEnabled(GL_CULL_FACE) != 0); + this->CullFaceEnabled = (glIsEnabled(GL_CULL_FACE) != GL_FALSE); + glGetIntegerv(GL_CULL_FACE_MODE, &this->CullFaceMode); + + GLboolean depthMaskWrite = GL_TRUE; + glGetBooleanv(GL_DEPTH_WRITEMASK, &depthMaskWrite); + this->DepthMaskEnabled = (depthMaskWrite == GL_TRUE); // Enable depth_sampler test if (!this->DepthTestEnabled) { - std::cerr << "enabling depth test" << std::endl; glEnable(GL_DEPTH_TEST); } @@ -47,11 +51,22 @@ class vtkVolumeStateRAII glEnable(GL_BLEND); } - // Enable cull face + // Enable cull face and set cull face mode + if (this->CullFaceMode != GL_BACK) + { + glCullFace(GL_BACK); + } + if (!this->CullFaceEnabled) { glEnable(GL_CULL_FACE); } + + // Disable depth mask writing + if (this->DepthMaskEnabled) + { + glDepthMask(GL_FALSE); + } } ~vtkVolumeStateRAII() @@ -65,6 +80,7 @@ class vtkVolumeStateRAII glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + glCullFace(this->CullFaceMode); if (!this->CullFaceEnabled) { glDisable(GL_CULL_FACE); @@ -81,12 +97,19 @@ class vtkVolumeStateRAII { glDisable(GL_DEPTH_TEST); } + + if (this->DepthMaskEnabled) + { + glDepthMask(GL_TRUE); + } } private: bool DepthTestEnabled; bool BlendEnabled; bool CullFaceEnabled; + GLint CullFaceMode; + bool DepthMaskEnabled; }; #endif // vtkVolumeStateRAII_h diff --git a/Testing/Core/HeaderTesting.py b/Testing/Core/HeaderTesting.py index 6b2403a1f86..3a5af18505b 100755 --- a/Testing/Core/HeaderTesting.py +++ b/Testing/Core/HeaderTesting.py @@ -236,7 +236,8 @@ def CheckParent(self): rm = regx.match(lastline + line) if rm: export = rm.group(1) - export = export.strip() + if export: + export = export.strip() cname = rm.group(2) pname = rm.group(3) classlines.append(" %4d: %s" % (cc, line)) diff --git a/Testing/Data/MagnitudeImage_256x256x148.md5 b/Testing/Data/MagnitudeImage_256x256x148.md5 new file mode 100644 index 00000000000..65c8374f42b --- /dev/null +++ b/Testing/Data/MagnitudeImage_256x256x148.md5 @@ -0,0 +1 @@ +90d2a04742624b41b44d8db1cafefd02 diff --git a/Testing/Data/Microscopy/Small.ndpi.md5 b/Testing/Data/Microscopy/Small.ndpi.md5 new file mode 100644 index 00000000000..fe3a611206a --- /dev/null +++ b/Testing/Data/Microscopy/Small.ndpi.md5 @@ -0,0 +1 @@ +f90e3de39f83b7b86cac190d4c9091f4 diff --git a/Testing/Data/Microscopy/pathology.tif.md5 b/Testing/Data/Microscopy/pathology.tif.md5 new file mode 100644 index 00000000000..fba183d5be3 --- /dev/null +++ b/Testing/Data/Microscopy/pathology.tif.md5 @@ -0,0 +1 @@ +6a89389966723771bc54d12bbcba1a0b diff --git a/Testing/Data/Microscopy/small2.ndpi.md5 b/Testing/Data/Microscopy/small2.ndpi.md5 new file mode 100644 index 00000000000..e034a6ba214 --- /dev/null +++ b/Testing/Data/Microscopy/small2.ndpi.md5 @@ -0,0 +1 @@ +7a3a6d1db332aba39a61ee62414a5298 diff --git a/Testing/Data/SPH_Points.vtu.md5 b/Testing/Data/SPH_Points.vtu.md5 new file mode 100644 index 00000000000..baa7353430e --- /dev/null +++ b/Testing/Data/SPH_Points.vtu.md5 @@ -0,0 +1 @@ +7deaa4d5dacd9ad40baab8e8c7ce200f diff --git a/Testing/Data/SPH_Points2D.vtu.md5 b/Testing/Data/SPH_Points2D.vtu.md5 new file mode 100644 index 00000000000..e8047f5b1b0 --- /dev/null +++ b/Testing/Data/SPH_Points2D.vtu.md5 @@ -0,0 +1 @@ +b61bc71bd021e3633497ad69a3f22bcd diff --git a/Testing/External/CMakeLists.txt b/Testing/External/CMakeLists.txt index e8222dfcc91..bd63ec73628 100644 --- a/Testing/External/CMakeLists.txt +++ b/Testing/External/CMakeLists.txt @@ -42,7 +42,7 @@ set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${VTK_REQUIRED_SHARE set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${VTK_REQUIRED_MODULE_LINKER_FLAGS}") # This is a cross-platform project so we cannot use the MS _s API. -if(WIN32 AND "${CMAKE_C_COMPILER_ID}" MATCHES "^(Intel)$") +if(WIN32 AND "x${CMAKE_C_COMPILER_ID}" STREQUAL "xIntel") set(_INTEL_WINDOWS 1) endif() if(MSVC OR _INTEL_WINDOWS) diff --git a/Testing/GenericBridge/vtkBridgeDataSet.h b/Testing/GenericBridge/vtkBridgeDataSet.h index b4340e7a3e3..e5b48d301dd 100644 --- a/Testing/GenericBridge/vtkBridgeDataSet.h +++ b/Testing/GenericBridge/vtkBridgeDataSet.h @@ -140,7 +140,6 @@ class VTKTESTINGGENERICBRIDGE_EXPORT vtkBridgeDataSet : public vtkGenericDataSet vtkBridgeDataSet(); virtual ~vtkBridgeDataSet(); - //BTX friend class vtkBridgeCell; friend class vtkBridgeCellIterator; friend class vtkBridgeCellIteratorOnDataSet; @@ -149,7 +148,6 @@ class VTKTESTINGGENERICBRIDGE_EXPORT vtkBridgeDataSet : public vtkGenericDataSet friend class vtkBridgePointIteratorOnCell; friend class vtkBridgePointIteratorOnDataSet; friend class vtkBridgePointIteratorOne; - //ETX // Description: // Compute the number of cells for each dimension and the list of types of diff --git a/Testing/GenericBridge/vtkBridgeExport.h b/Testing/GenericBridge/vtkBridgeExport.h index 694468f657b..686f36a8b4f 100644 --- a/Testing/GenericBridge/vtkBridgeExport.h +++ b/Testing/GenericBridge/vtkBridgeExport.h @@ -26,7 +26,7 @@ # define VTK_BRIDGE_EXPORT #else -#if defined(WIN32) && defined(VTK_BUILD_SHARED_LIBS) +#if defined(_WIN32) && defined(VTK_BUILD_SHARED_LIBS) #if defined(vtkBridge_EXPORTS) #define VTK_BRIDGE_EXPORT __declspec( dllexport ) diff --git a/Testing/Rendering/vtkTesting.cxx b/Testing/Rendering/vtkTesting.cxx index 7c2b3532d65..bc30ebc522e 100644 --- a/Testing/Rendering/vtkTesting.cxx +++ b/Testing/Rendering/vtkTesting.cxx @@ -832,18 +832,18 @@ int vtkTesting::CompareAverageOfL2Norm(vtkDataArray *daA, { case VTK_DOUBLE: { - vtkDoubleArray *A = vtkDoubleArray::SafeDownCast(daA); + vtkDoubleArray *A = vtkArrayDownCast(daA); double *pA = A->GetPointer(0); - vtkDoubleArray *B = vtkDoubleArray::SafeDownCast(daB); + vtkDoubleArray *B = vtkArrayDownCast(daB); double *pB = B->GetPointer(0); N = AccumulateScaledL2Norm(pA, pB, nTupsA, nCompsA, L2); } break; case VTK_FLOAT: { - vtkFloatArray *A = vtkFloatArray::SafeDownCast(daA); + vtkFloatArray *A = vtkArrayDownCast(daA); float *pA = A->GetPointer(0); - vtkFloatArray *B = vtkFloatArray::SafeDownCast(daB); + vtkFloatArray *B = vtkArrayDownCast(daB); float *pB = B->GetPointer(0); N = AccumulateScaledL2Norm(pA, pB, nTupsA, nCompsA, L2); } diff --git a/Testing/Rendering/vtkTesting.h b/Testing/Rendering/vtkTesting.h index 7d4e7cc40d4..1ccf5f0bd43 100644 --- a/Testing/Rendering/vtkTesting.h +++ b/Testing/Rendering/vtkTesting.h @@ -78,7 +78,6 @@ class VTKTESTINGRENDERING_EXPORT vtkTesting : public vtkObject vtkTypeMacro(vtkTesting,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); -//BTX enum ReturnValue { FAILED = 0, PASSED = 1, @@ -147,8 +146,6 @@ class VTKTESTINGRENDERING_EXPORT vtkTesting : public vtkObject vtkRenderWindowInteractor *iren, const char *stream = NULL); -//ETX - // Description: // Use the front buffer first for regression test comparisons. By // default use back buffer first, then try the front buffer if the @@ -223,13 +220,11 @@ class VTKTESTINGRENDERING_EXPORT vtkTesting : public vtkObject void AddArguments(int argc,const char **argv); void AddArguments(int argc, char **argv); - //BTX // Description: // Search for a specific argument by name and return its value // (assumed to be the next on the command tail). Up to caller // to delete the returned string. char *GetArgument(const char *arg); - //ETX // Description // This method delete all arguments in vtkTesting, this way you can reuse @@ -284,9 +279,8 @@ class VTKTESTINGRENDERING_EXPORT vtkTesting : public vtkObject int BorderOffset; int Verbose; -//BTX std::vector Args; -//ETX + char *DataRoot; double StartWallTime; double StartCPUTime; diff --git a/Testing/Rendering/vtkTestingInteractor.h b/Testing/Rendering/vtkTestingInteractor.h index 01236630e64..f1b70fb1b62 100644 --- a/Testing/Rendering/vtkTestingInteractor.h +++ b/Testing/Rendering/vtkTestingInteractor.h @@ -28,9 +28,7 @@ #include "vtkRenderWindowInteractor.h" #include "vtkObjectFactoryCollection.h" // Generated object overrides -//BTX #include // STL Header; Required for string -//ETX class VTKTESTINGRENDERING_EXPORT vtkTestingInteractor : public vtkRenderWindowInteractor { diff --git a/ThirdParty/VPIC/VPICGlobal.cxx b/ThirdParty/VPIC/VPICGlobal.cxx index d57f9c59ca3..a14a9337044 100644 --- a/ThirdParty/VPIC/VPICGlobal.cxx +++ b/ThirdParty/VPIC/VPICGlobal.cxx @@ -12,7 +12,7 @@ #include #include -#ifdef WIN32 +#ifdef _WIN32 const static char * Slash = "\\"; #else const static char * Slash = "/"; diff --git a/ThirdParty/VPIC/VPICView.cxx b/ThirdParty/VPIC/VPICView.cxx index ef8fc680e81..fc140c52238 100644 --- a/ThirdParty/VPIC/VPICView.cxx +++ b/ThirdParty/VPIC/VPICView.cxx @@ -8,7 +8,7 @@ #include #include "math.h" -#ifdef WIN32 +#ifdef _WIN32 const static char * Slash = "\\"; #else const static char * Slash = "/"; diff --git a/ThirdParty/diy2/vtkdiy2/README.md b/ThirdParty/diy2/vtkdiy2/README.md index bcddcc352e5..dba302433b5 100644 --- a/ThirdParty/diy2/vtkdiy2/README.md +++ b/ThirdParty/diy2/vtkdiy2/README.md @@ -1,9 +1,9 @@ -## DIY2 is a data-parallel out-of-core library +## DIY2 is a block-parallel library -DIY2 is a data-parallel library for implementing scalable algorithms that can execute both +DIY2 is a block-parallel library for implementing scalable algorithms that can execute both in-core and out-of-core. The same program can be executed with one or more threads per MPI process, seamlessly combining distributed-memory message passing with shared-memory thread -parallelism. The abstraction enabling these capabilities is block-based parallelism; blocks +parallelism. The abstraction enabling these capabilities is block parallelism; blocks and their message queues are mapped onto processing elements (MPI processes or threads) and are migrated between memory and storage by the DIY2 runtime. Complex communication patterns, including neighbor exchange, merge reduction, swap reduction, and all-to-all exchange, are diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/algorithms.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/algorithms.hpp index b620a8f27dc..6920a5dd4c2 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/algorithms.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/algorithms.hpp @@ -11,6 +11,7 @@ #include "detail/algorithms/sort.hpp" #include "detail/algorithms/kdtree.hpp" +#include "detail/algorithms/kdtree-sampling.hpp" namespace diy { @@ -36,7 +37,8 @@ namespace diy detail::SampleSort sorter(values, samples, cmp, num_samples); // swap-reduce to all-gather samples - RegularSwapPartners partners(1, assigner.nblocks(), k); + RegularDecomposer decomposer(1, interval(0,assigner.nblocks()), assigner.nblocks()); + RegularSwapPartners partners(decomposer, k); reduce(master, assigner, partners, sorter.sample(), detail::SkipIntermediate(partners.rounds())); // all_to_all to exchange the values @@ -66,7 +68,7 @@ namespace diy /** * \ingroup Algorithms - * \brief build a kd-tree and sort a set of points into it + * \brief build a kd-tree and sort a set of points into it (use histograms to determine split values) */ template void kdtree(Master& master, //!< master object @@ -85,11 +87,33 @@ namespace diy typedef diy::RegularContinuousLink RCLink; - for (int i = 0; i < master.size(); ++i) + for (size_t i = 0; i < master.size(); ++i) { RCLink* link = static_cast(master.link(i)); - link->core() = domain; - link->bounds() = domain; + *link = RCLink(dim, domain, domain); + + if (wrap) // set up the links to self + { + diy::BlockID self = { master.gid(i), master.communicator().rank() }; + for (int j = 0; j < dim; ++j) + { + diy::Direction dir, wrap_dir; + + // left + dir.x[j] = -1; wrap_dir.x[j] = -1; + link->add_neighbor(self); + link->add_bounds(domain); + link->add_direction(dir); + link->add_wrap(wrap_dir); + + // right + dir.x[j] = 1; wrap_dir.x[j] = 1; + link->add_neighbor(self); + link->add_bounds(domain); + link->add_direction(dir); + link->add_wrap(wrap_dir); + } + } } detail::KDTreePartition kdtree_partition(dim, points, bins); @@ -99,11 +123,73 @@ namespace diy // update master.expected to match the links int expected = 0; - for (int i = 0; i < master.size(); ++i) + for (size_t i = 0; i < master.size(); ++i) expected += master.link(i)->size_unique(); master.set_expected(expected); } + /** + * \ingroup Algorithms + * \brief build a kd-tree and sort a set of points into it (use sampling to determine split values) + */ + template + void kdtree_sampling + (Master& master, //!< master object + const Assigner& assigner, //!< assigner object + int dim, //!< dimensionality + const ContinuousBounds& domain, //!< global data extents + std::vector Block::* points, //!< input points to sort into kd-tree + size_t samples, //!< number of samples to take in each block + bool wrap = false)//!< periodic boundaries in all dimensions + { + if (assigner.nblocks() & (assigner.nblocks() - 1)) + { + fprintf(stderr, "KD-tree requires a number of blocks that's a power of 2, got %d\n", assigner.nblocks()); + std::abort(); + } + + typedef diy::RegularContinuousLink RCLink; + + for (size_t i = 0; i < master.size(); ++i) + { + RCLink* link = static_cast(master.link(i)); + *link = RCLink(dim, domain, domain); + + if (wrap) // set up the links to self + { + diy::BlockID self = { master.gid(i), master.communicator().rank() }; + for (int j = 0; j < dim; ++j) + { + diy::Direction dir, wrap_dir; + + // left + dir.x[j] = -1; wrap_dir.x[j] = -1; + link->add_neighbor(self); + link->add_bounds(domain); + link->add_direction(dir); + link->add_wrap(wrap_dir); + + // right + dir.x[j] = 1; wrap_dir.x[j] = 1; + link->add_neighbor(self); + link->add_bounds(domain); + link->add_direction(dir); + link->add_wrap(wrap_dir); + } + } + } + + detail::KDTreeSamplingPartition kdtree_partition(dim, points, samples); + + detail::KDTreePartners partners(dim, assigner.nblocks(), wrap, domain); + reduce(master, assigner, partners, kdtree_partition); + + // update master.expected to match the links + int expected = 0; + for (size_t i = 0; i < master.size(); ++i) + expected += master.link(i)->size_unique(); + master.set_expected(expected); + } } #endif diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/constants.h b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/constants.h index 5ea7fd7029f..cf087a5c94b 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/constants.h +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/constants.h @@ -7,23 +7,9 @@ #define DIY_MAX_DIM 4 #endif -/* DIY directions: neighbor direction enumeration - used to identify direction of one neighbor block for both regular and - wrapround neighbors - can be bitwise ORed, eg., maximum-side neighboring block in 3 dimensions - would be DIY_X1 | DIY_Y1 | DIY_Z1 - each use identifies exactly one block - eg. DIY_X0 is the (one) left neighbor block, not the entire left plane */ -typedef enum +struct dir_t { - DIY_X0 = 0x01, /* minimum-side x (left) neighbor */ - DIY_X1 = 0x02, /* maximum-side x (right) neighbor */ - DIY_Y0 = 0x04, /* minimum-side y (bottom) neighbor */ - DIY_Y1 = 0x08, /* maximum-side y (top) neighbor */ - DIY_Z0 = 0x10, /* minimum-side z (back) neighbor */ - DIY_Z1 = 0x20, /* maximum-side z (front)neighbor */ - DIY_T0 = 0x40, /* minimum-side t (earlier) neighbor */ - DIY_T1 = 0x80 /* maximum-side t (later) neighbor */ -} dir_t; + int x[DIY_MAX_DIM]; +}; #endif diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/critical-resource.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/critical-resource.hpp index 0b81e3169d8..61a5a4b8a71 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/critical-resource.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/critical-resource.hpp @@ -3,6 +3,14 @@ namespace diy { + // TODO: when not running under C++11, i.e., when lock_guard is TinyThread's + // lock_guard, and not C++11's unique_lock, this implementation might + // be buggy since the copy constructor is invoked when + // critical_resource::access() returns an instance of this class. Once + // the temporary is destroyed the mutex is unlocked. I'm not 100% + // certain of this because I'd expect a deadlock on copy constructor, + // but it's clearly not happening -- so I may be missing something. + // (This issue will take care of itself in DIY3 once we switch to C++11 completely.) template class resource_accessor { diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/decomposition.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/decomposition.hpp index f285f8409d1..a51123c211b 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/decomposition.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/decomposition.hpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include "link.hpp" #include "assigner.hpp" @@ -74,35 +76,37 @@ namespace detail typedef std::vector CoordinateVector; typedef std::vector DivisionsVector; - /// @param assigner: decides how processors are assigned to blocks (maps a gid to a rank) - /// also communicates the total number of blocks /// @param wrap: indicates dimensions on which to wrap the boundary /// @param ghosts: indicates how many ghosts to use in each dimension /// @param divisions: indicates how many cuts to make along each dimension /// (0 means "no constraint," i.e., leave it up to the algorithm) RegularDecomposer(int dim_, const Bounds& domain_, - const Assigner& assigner_, + int nblocks_, BoolVector share_face_ = BoolVector(), BoolVector wrap_ = BoolVector(), CoordinateVector ghosts_ = CoordinateVector(), DivisionsVector divisions_ = DivisionsVector()): - dim(dim_), domain(domain_), assigner(assigner_), + dim(dim_), domain(domain_), nblocks(nblocks_), share_face(share_face_), wrap(wrap_), ghosts(ghosts_), divisions(divisions_) { - if (share_face.size() < dim) share_face.resize(dim); - if (wrap.size() < dim) wrap.resize(dim); - if (ghosts.size() < dim) ghosts.resize(dim); - if (divisions.size() < dim) divisions.resize(dim); + if ((int) share_face.size() < dim) share_face.resize(dim); + if ((int) wrap.size() < dim) wrap.resize(dim); + if ((int) ghosts.size() < dim) ghosts.resize(dim); + if ((int) divisions.size() < dim) divisions.resize(dim); - int nblocks = assigner.nblocks(); - fill_divisions(nblocks); + fill_divisions(divisions); } // Calls create(int gid, const Bounds& bounds, const Link& link) template - void decompose(int rank, const Creator& create); + void decompose(int rank, const Assigner& assigner, const Creator& create); + + template + void decompose(int rank, const Assigner& assigner, Master& master, const Updater& update); + + void decompose(int rank, const Assigner& assigner, Master& master); // find lowest gid that owns a particular point template @@ -110,7 +114,7 @@ namespace detail void gid_to_coords(int gid, DivisionsVector& coords) const { gid_to_coords(gid, coords, divisions); } int coords_to_gid(const DivisionsVector& coords) const { return coords_to_gid(coords, divisions); } - void fill_divisions(int nblocks) { fill_divisions(dim, nblocks, divisions); } + void fill_divisions(std::vector& divisions) const; void fill_bounds(Bounds& bounds, const DivisionsVector& coords, bool add_ghosts = false) const; void fill_bounds(Bounds& bounds, int gid, bool add_ghosts = false) const; @@ -118,7 +122,7 @@ namespace detail static bool all(const std::vector& v, int x); static void gid_to_coords(int gid, DivisionsVector& coords, const DivisionsVector& divisions); static int coords_to_gid(const DivisionsVector& coords, const DivisionsVector& divisions); - static void fill_divisions(int dim, int nblocks, std::vector& divisions); + static void factor(std::vector& factors, int n); // Point to GIDs functions @@ -137,8 +141,8 @@ namespace detail int dim; - const Bounds& domain; - const Assigner& assigner; + Bounds domain; + int nblocks; BoolVector share_face; BoolVector wrap; CoordinateVector ghosts; @@ -162,7 +166,7 @@ namespace detail * * `create(...)` is called with each block assigned to the local domain. See [decomposition example](#decomposition-example). */ - template + template void decompose(int dim, int rank, const Bounds& domain, @@ -173,7 +177,7 @@ namespace detail typename RegularDecomposer::CoordinateVector ghosts = typename RegularDecomposer::CoordinateVector(), typename RegularDecomposer::DivisionsVector divs = typename RegularDecomposer::DivisionsVector()) { - RegularDecomposer(dim, domain, assigner, share_face, wrap, ghosts, divs).decompose(rank, create); + RegularDecomposer(dim, domain, assigner.nblocks(), share_face, wrap, ghosts, divs).decompose(rank, assigner, create); } namespace detail @@ -195,6 +199,26 @@ namespace detail diy::Master* master_; }; + + template + struct Updater + { + typedef typename RegularDecomposer::Link Link; + + Updater(diy::Master* master, const Update& update): + master_(master), update_(update) {} + + void operator()(int gid, const Bounds& core, const Bounds& bounds, const Bounds& domain, const Link& link) const + { + int lid = master_->lid(gid); + Link* l = new Link(link); + master_->replace_link(lid, l); + update_(gid, lid, core, bounds, domain, *l); + } + + diy::Master* master_; + const Update& update_; + }; } /** @@ -213,7 +237,7 @@ namespace detail * * `master` must have been supplied a create function in order for this function to work. */ - template + template void decompose(int dim, int rank, const Bounds& domain, @@ -224,7 +248,7 @@ namespace detail typename RegularDecomposer::CoordinateVector ghosts = typename RegularDecomposer::CoordinateVector(), typename RegularDecomposer::DivisionsVector divs = typename RegularDecomposer::DivisionsVector()) { - RegularDecomposer(dim, domain, assigner, share_face, wrap, ghosts, divs).decompose(rank, detail::AddBlock(&master)); + RegularDecomposer(dim, domain, assigner.nblocks(), share_face, wrap, ghosts, divs).decompose(rank, assigner, master); } /** @@ -248,15 +272,53 @@ namespace detail master.add(local_gids[i], master.create(), new diy::Link); } + /** + * \ingroup Decomposition + * \brief Add a decomposition (modify links) of an existing set of blocks that were + * added to the master previously + * + * @param rank local rank + * @param assigner decides how processors are assigned to blocks (maps a gid to a rank) + * also communicates the total number of blocks + */ + template + void decompose(int dim, + int rank, + const Bounds& domain, + const Assigner& assigner, + Master& master, + const Update& update, + typename RegularDecomposer::BoolVector share_face = + typename RegularDecomposer::BoolVector(), + typename RegularDecomposer::BoolVector wrap = + typename RegularDecomposer::BoolVector(), + typename RegularDecomposer::CoordinateVector ghosts = + typename RegularDecomposer::CoordinateVector(), + typename RegularDecomposer::DivisionsVector divs = + typename RegularDecomposer::DivisionsVector()) + { + RegularDecomposer(dim, domain, share_face, wrap, ghosts, divs). + decompose(rank, assigner, master, update); + } + //! Decomposition example: \example decomposition/test-decomposition.cpp //! Direct master insertion example: \example decomposition/test-direct-master.cpp } +// decomposes domain and adds blocks to the master +template +void +diy::RegularDecomposer:: +decompose(int rank, const Assigner& assigner, Master& master) +{ + decompose(rank, assigner, detail::AddBlock(&master)); +} + template template void diy::RegularDecomposer:: -decompose(int rank, const Creator& create) +decompose(int rank, const Assigner& assigner, const Creator& create) { std::vector gids; assigner.local_gids(rank, gids); @@ -289,7 +351,7 @@ decompose(int rank, const Creator& create) if (all(offsets, 0)) continue; // skip ourselves DivisionsVector nhbr_coords(dim); - int dir = 0; + Direction dir, wrap_dir; bool inbounds = true; for (int i = 0; i < dim; ++i) { @@ -301,7 +363,7 @@ decompose(int rank, const Creator& create) if (wrap[i]) { nhbr_coords[i] = divisions[i] - 1; - link.add_wrap(Direction(1 << 2*i)); + wrap_dir[i] = -1; } else inbounds = false; @@ -312,17 +374,15 @@ decompose(int rank, const Creator& create) if (wrap[i]) { nhbr_coords[i] = 0; - link.add_wrap(Direction(1 << (2*i + 1))); + wrap_dir[i] = 1; } else inbounds = false; } // NB: this needs to match the addressing scheme in dir_t (in constants.h) - if (offsets[i] == -1) - dir |= 1 << (2*i + 0); - if (offsets[i] == 1) - dir |= 1 << (2*i + 1); + if (offsets[i] == -1 || offsets[i] == 1) + dir[i] = offsets[i]; } if (!inbounds) continue; @@ -334,13 +394,24 @@ decompose(int rank, const Creator& create) fill_bounds(nhbr_bounds, nhbr_coords); link.add_bounds(nhbr_bounds); - link.add_direction(static_cast(dir)); + link.add_direction(dir); + link.add_wrap(wrap_dir); } create(gid, core, bounds, domain, link); } } +// decomposes domain but does not add blocks to master, assumes they were added already +template +template +void +diy::RegularDecomposer:: +decompose(int rank, const Assigner& assigner, Master& master, const Update& update) +{ + decompose(rank, assigner, detail::Updater(&master, update)); +} + template bool diy::RegularDecomposer:: @@ -436,40 +507,116 @@ fill_bounds(Bounds& bounds, //!< (output) bounds fill_bounds(bounds, coords); } +namespace diy { namespace detail { +// current state of division in one dimension used in fill_divisions below +template +struct Div +{ + int dim; // 0, 1, 2, etc. e.g. for x, y, z etc. + int nb; // number of blocks so far in this dimension + Coordinate b_size; // block size so far in this dimension + + // sort on descending block size unless tied, in which case + // sort on ascending num blocks in current dim unless tied, in which case + // sort on ascending dimension + bool operator<(Div rhs) const + { + // sort on second value of the pair unless tied, in which case sort on first + if (b_size == rhs.b_size) + { + if (nb == rhs.nb) + return(dim < rhs.dim); + return(nb < rhs.nb); + } + return(b_size > rhs.b_size); + } +}; +} } + template void diy::RegularDecomposer:: -fill_divisions(int dim, int nblocks, std::vector& divisions) +fill_divisions(std::vector& divisions) const { - int prod = 1; int c = 0; - for (unsigned i = 0; i < dim; ++i) - if (divisions[i] != 0) + // prod = number of blocks unconstrained by user; c = number of unconstrained dimensions + int prod = 1; int c = 0; + for (int i = 0; i < dim; ++i) + if (divisions[i] != 0) + { + prod *= divisions[i]; + ++c; + } + + if (nblocks % prod != 0) { - prod *= divisions[i]; - ++c; + fprintf(stderr, "Total number of blocks cannot be factored into provided divs\n"); + return; } - if (nblocks % prod != 0) - { - std::cerr << "Incompatible requirements" << std::endl; - return; - } + if (c == (int) divisions.size()) // nothing to do; user provided all divs + return; - if (c == divisions.size()) - return; + // factor number of blocks left in unconstrained dimensions + // factorization is sorted from smallest to largest factors + std::vector factors; + factor(factors, nblocks/prod); + + using detail::Div; + std::vector< Div > missing_divs; // pairs consisting of (dim, #divs) - std::vector factors; - factor(factors, nblocks/prod); + // init missing_divs + for (int i = 0; i < dim; i++) + { + if (divisions[i] == 0) + { + Div div; + div.dim = i; + div.nb = 1; + div.b_size = domain.max[i] - domain.min[i]; + missing_divs.push_back(div); + } + } - // Fill the missing divs using LPT algorithm - std::vector missing_divs(divisions.size() - c, 1); - for (int i = factors.size() - 1; i >= 0; --i) - *std::min_element(missing_divs.begin(), missing_divs.end()) *= factors[i]; + // iterate over factorization of number of blocks (factors are sorted smallest to largest) + // NB: using int instead of size_t because must be negative in order to break out of loop + for (int i = factors.size() - 1; i >= 0; --i) + { + // fill in missing divs by dividing dimension w/ largest block size + // except when this would be illegal (resulting in bounds.max < bounds.min; + // only a problem for discrete bounds + + // sort on decreasing block size + std::sort(missing_divs.begin(), missing_divs.end()); + + // split the dimension with the largest block size (first element in vector) + Coordinate min = + detail::BoundsHelper::from(0, + missing_divs[0].nb * factors[i], + domain.min[missing_divs[0].dim], + domain.max[missing_divs[0].dim], + share_face[missing_divs[0].dim]); + Coordinate max = + detail::BoundsHelper::to(0, + missing_divs[0].nb * factors[i], + domain.min[missing_divs[0].dim], + domain.max[missing_divs[0].dim], + share_face[missing_divs[0].dim]); + if (max >= min) + { + missing_divs[0].nb *= factors[i]; + missing_divs[0].b_size = max - min; + } + else + { + std::ostringstream oss; + oss << "Unable to decompose domain into " << nblocks << " blocks: " << min << " " << max; + throw std::runtime_error(oss.str()); + } + } - c = 0; - for (unsigned i = 0; i < dim; ++i) - if (divisions[i] == 0) - divisions[i] = missing_divs[c++]; + // assign the divisions + for (size_t i = 0; i < missing_divs.size(); i++) + divisions[missing_divs[i].dim] = missing_divs[i].nb; } template @@ -478,7 +625,7 @@ diy::RegularDecomposer:: factor(std::vector& factors, int n) { while (n != 1) - for (unsigned i = 2; i <= n; ++i) + for (int i = 2; i <= n; ++i) { if (n % i == 0) { diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/kdtree-sampling.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/kdtree-sampling.hpp new file mode 100644 index 00000000000..1b21a91de97 --- /dev/null +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/kdtree-sampling.hpp @@ -0,0 +1,453 @@ +#ifndef DIY_DETAIL_ALGORITHMS_KDTREE_SAMPLING_HPP +#define DIY_DETAIL_ALGORITHMS_KDTREE_SAMPLING_HPP + +#include +#include +#include "../../partners/all-reduce.hpp" + +// TODO: technically, what's done now is not a perfect subsample: +// we take the same number of samples from every block, in reality this number should be selected at random, +// so that the total number of samples adds up to samples*nblocks +// +// NB: random samples are chosen using rand(), which is assumed to be seeded +// externally. Once we switch to C++11, we should use its more advanced +// random number generators (and take a generator as an external parameter) +// (TODO) + +namespace diy +{ +namespace detail +{ + +template +struct KDTreeSamplingPartition +{ + typedef diy::RegularContinuousLink RCLink; + typedef diy::ContinuousBounds Bounds; + + typedef std::vector Samples; + + KDTreeSamplingPartition(int dim, + std::vector Block::* points, + size_t samples): + dim_(dim), points_(points), samples_(samples) {} + + void operator()(void* b_, const diy::ReduceProxy& srp, const KDTreePartners& partners) const; + + int divide_gid(int gid, bool lower, int round, int rounds) const; + void update_links(Block* b, const diy::ReduceProxy& srp, int dim, int round, int rounds, bool wrap, const Bounds& domain) const; + void split_to_neighbors(Block* b, const diy::ReduceProxy& srp, int dim) const; + diy::Direction + find_wrap(const Bounds& bounds, const Bounds& nbr_bounds, const Bounds& domain) const; + + void compute_local_samples(Block* b, const diy::ReduceProxy& srp, int dim) const; + void add_samples(Block* b, const diy::ReduceProxy& srp, Samples& samples) const; + void receive_samples(Block* b, const diy::ReduceProxy& srp, Samples& samples) const; + void forward_samples(Block* b, const diy::ReduceProxy& srp, const Samples& samples) const; + + void enqueue_exchange(Block* b, const diy::ReduceProxy& srp, int dim, const Samples& samples) const; + void dequeue_exchange(Block* b, const diy::ReduceProxy& srp, int dim) const; + + void update_neighbor_bounds(Bounds& bounds, float split, int dim, bool lower) const; + bool intersects(const Bounds& x, const Bounds& y, int dim, bool wrap, const Bounds& domain) const; + float find_split(const Bounds& changed, const Bounds& original) const; + + int dim_; + std::vector Block::* points_; + size_t samples_; +}; + +} +} + + +template +void +diy::detail::KDTreeSamplingPartition:: +operator()(void* b_, const diy::ReduceProxy& srp, const KDTreePartners& partners) const +{ + Block* b = static_cast(b_); + + int dim; + if (srp.round() < partners.rounds()) + dim = partners.dim(srp.round()); + else + dim = partners.dim(srp.round() - 1); + + if (srp.round() == partners.rounds()) + update_links(b, srp, dim, partners.sub_round(srp.round() - 2), partners.swap_rounds(), partners.wrap, partners.domain); // -1 would be the "uninformative" link round + else if (partners.swap_round(srp.round()) && partners.sub_round(srp.round()) < 0) // link round + { + dequeue_exchange(b, srp, dim); // from the swap round + split_to_neighbors(b, srp, dim); + } + else if (partners.swap_round(srp.round())) + { + Samples samples; + receive_samples(b, srp, samples); + enqueue_exchange(b, srp, dim, samples); + } else if (partners.sub_round(srp.round()) == 0) + { + if (srp.round() > 0) + { + int prev_dim = dim - 1; + if (prev_dim < 0) + prev_dim += dim_; + update_links(b, srp, prev_dim, partners.sub_round(srp.round() - 2), partners.swap_rounds(), partners.wrap, partners.domain); // -1 would be the "uninformative" link round + } + + compute_local_samples(b, srp, dim); + } else if (partners.sub_round(srp.round()) < (int) partners.histogram.rounds()/2) // we are reusing partners class, so really we are talking about the samples rounds here + { + Samples samples; + add_samples(b, srp, samples); + srp.enqueue(srp.out_link().target(0), samples); + } else + { + Samples samples; + add_samples(b, srp, samples); + if (samples.size() != 1) + { + // pick the median + std::nth_element(samples.begin(), samples.begin() + samples.size()/2, samples.end()); + std::swap(samples[0], samples[samples.size()/2]); + //std::sort(samples.begin(), samples.end()); + //samples[0] = (samples[samples.size()/2] + samples[samples.size()/2 + 1])/2; + samples.resize(1); + } + forward_samples(b, srp, samples); + } +} + +template +int +diy::detail::KDTreeSamplingPartition:: +divide_gid(int gid, bool lower, int round, int rounds) const +{ + if (lower) + gid &= ~(1 << (rounds - 1 - round)); + else + gid |= (1 << (rounds - 1 - round)); + return gid; +} + +// round here is the outer iteration of the algorithm +template +void +diy::detail::KDTreeSamplingPartition:: +update_links(Block* b, const diy::ReduceProxy& srp, int dim, int round, int rounds, bool wrap, const Bounds& domain) const +{ + int gid = srp.gid(); + int lid = srp.master()->lid(gid); + RCLink* link = static_cast(srp.master()->link(lid)); + + // (gid, dir) -> i + std::map, int> link_map; + for (int i = 0; i < link->size(); ++i) + link_map[std::make_pair(link->target(i).gid, link->direction(i))] = i; + + // NB: srp.enqueue(..., ...) should match the link + std::vector splits(link->size()); + for (int i = 0; i < link->size(); ++i) + { + float split; diy::Direction dir; + + int in_gid = link->target(i).gid; + while(srp.incoming(in_gid)) + { + srp.dequeue(in_gid, split); + srp.dequeue(in_gid, dir); + + // reverse dir + for (int j = 0; j < dim_; ++j) + dir[j] = -dir[j]; + + int k = link_map[std::make_pair(in_gid, dir)]; + //printf("%d %d %f -> %d\n", in_gid, dir, split, k); + splits[k] = split; + } + } + + RCLink new_link(dim_, link->core(), link->core()); + + bool lower = !(gid & (1 << (rounds - 1 - round))); + + // fill out the new link + for (int i = 0; i < link->size(); ++i) + { + diy::Direction dir = link->direction(i); + //diy::Direction wrap_dir = link->wrap(i); // we don't use existing wrap, but restore it from scratch + if (dir[dim] != 0) + { + if ((dir[dim] < 0 && lower) || (dir[dim] > 0 && !lower)) + { + int nbr_gid = divide_gid(link->target(i).gid, !lower, round, rounds); + diy::BlockID nbr = { nbr_gid, srp.assigner().rank(nbr_gid) }; + new_link.add_neighbor(nbr); + + new_link.add_direction(dir); + + Bounds bounds = link->bounds(i); + update_neighbor_bounds(bounds, splits[i], dim, !lower); + new_link.add_bounds(bounds); + + if (wrap) + new_link.add_wrap(find_wrap(new_link.bounds(), bounds, domain)); + else + new_link.add_wrap(diy::Direction()); + } + } else // non-aligned side + { + for (int j = 0; j < 2; ++j) + { + int nbr_gid = divide_gid(link->target(i).gid, j == 0, round, rounds); + + Bounds bounds = link->bounds(i); + update_neighbor_bounds(bounds, splits[i], dim, j == 0); + + if (intersects(bounds, new_link.bounds(), dim, wrap, domain)) + { + diy::BlockID nbr = { nbr_gid, srp.assigner().rank(nbr_gid) }; + new_link.add_neighbor(nbr); + new_link.add_direction(dir); + new_link.add_bounds(bounds); + + if (wrap) + new_link.add_wrap(find_wrap(new_link.bounds(), bounds, domain)); + else + new_link.add_wrap(diy::Direction()); + } + } + } + } + + // add link to the dual block + int dual_gid = divide_gid(gid, !lower, round, rounds); + diy::BlockID dual = { dual_gid, srp.assigner().rank(dual_gid) }; + new_link.add_neighbor(dual); + + Bounds nbr_bounds = link->bounds(); // old block bounds + update_neighbor_bounds(nbr_bounds, find_split(new_link.bounds(), nbr_bounds), dim, !lower); + new_link.add_bounds(nbr_bounds); + + new_link.add_wrap(diy::Direction()); // dual block cannot be wrapped + + if (lower) + { + diy::Direction right; + right[dim] = 1; + new_link.add_direction(right); + } else + { + diy::Direction left; + left[dim] = -1; + new_link.add_direction(left); + } + + // update the link; notice that this won't conflict with anything since + // reduce is using its own notion of the link constructed through the + // partners + link->swap(new_link); +} + +template +void +diy::detail::KDTreeSamplingPartition:: +split_to_neighbors(Block* b, const diy::ReduceProxy& srp, int dim) const +{ + int lid = srp.master()->lid(srp.gid()); + RCLink* link = static_cast(srp.master()->link(lid)); + + // determine split + float split = find_split(link->core(), link->bounds()); + + for (int i = 0; i < link->size(); ++i) + { + srp.enqueue(link->target(i), split); + srp.enqueue(link->target(i), link->direction(i)); + } +} + +template +void +diy::detail::KDTreeSamplingPartition:: +compute_local_samples(Block* b, const diy::ReduceProxy& srp, int dim) const +{ + // compute and enqueue local samples + Samples samples; + size_t points_size = (b->*points_).size(); + size_t n = std::min(points_size, samples_); + samples.reserve(n); + for (size_t i = 0; i < n; ++i) + { + float x = (b->*points_)[rand() % points_size][dim]; + samples.push_back(x); + } + + srp.enqueue(srp.out_link().target(0), samples); +} + +template +void +diy::detail::KDTreeSamplingPartition:: +add_samples(Block* b, const diy::ReduceProxy& srp, Samples& samples) const +{ + // dequeue and combine the samples + for (int i = 0; i < srp.in_link().size(); ++i) + { + int nbr_gid = srp.in_link().target(i).gid; + + Samples smpls; + srp.dequeue(nbr_gid, smpls); + for (size_t i = 0; i < smpls.size(); ++i) + samples.push_back(smpls[i]); + } +} + +template +void +diy::detail::KDTreeSamplingPartition:: +receive_samples(Block* b, const diy::ReduceProxy& srp, Samples& samples) const +{ + srp.dequeue(srp.in_link().target(0).gid, samples); +} + +template +void +diy::detail::KDTreeSamplingPartition:: +forward_samples(Block* b, const diy::ReduceProxy& srp, const Samples& samples) const +{ + for (int i = 0; i < srp.out_link().size(); ++i) + srp.enqueue(srp.out_link().target(i), samples); +} + +template +void +diy::detail::KDTreeSamplingPartition:: +enqueue_exchange(Block* b, const diy::ReduceProxy& srp, int dim, const Samples& samples) const +{ + int lid = srp.master()->lid(srp.gid()); + RCLink* link = static_cast(srp.master()->link(lid)); + + int k = srp.out_link().size(); + + if (k == 0) // final round; nothing needs to be sent; this is actually redundant + return; + + // pick split points + float split = samples[0]; + + // subset and enqueue + std::vector< std::vector > out_points(srp.out_link().size()); + for (size_t i = 0; i < (b->*points_).size(); ++i) + { + float x = (b->*points_)[i][dim]; + int loc = x < split ? 0 : 1; + out_points[loc].push_back((b->*points_)[i]); + } + int pos = -1; + for (int i = 0; i < k; ++i) + { + if (srp.out_link().target(i).gid == srp.gid()) + { + (b->*points_).swap(out_points[i]); + pos = i; + } + else + srp.enqueue(srp.out_link().target(i), out_points[i]); + } + if (pos == 0) + link->core().max[dim] = split; + else + link->core().min[dim] = split; +} + +template +void +diy::detail::KDTreeSamplingPartition:: +dequeue_exchange(Block* b, const diy::ReduceProxy& srp, int dim) const +{ + int lid = srp.master()->lid(srp.gid()); + RCLink* link = static_cast(srp.master()->link(lid)); + + for (int i = 0; i < srp.in_link().size(); ++i) + { + int nbr_gid = srp.in_link().target(i).gid; + if (nbr_gid == srp.gid()) + continue; + + std::vector in_points; + srp.dequeue(nbr_gid, in_points); + for (size_t j = 0; j < in_points.size(); ++j) + { + if (in_points[j][dim] < link->core().min[dim] || in_points[j][dim] > link->core().max[dim]) + { + fprintf(stderr, "Warning: dequeued %f outside [%f,%f] (%d)\n", + in_points[j][dim], link->core().min[dim], link->core().max[dim], dim); + std::abort(); + } + (b->*points_).push_back(in_points[j]); + } + } +} + +template +void +diy::detail::KDTreeSamplingPartition:: +update_neighbor_bounds(Bounds& bounds, float split, int dim, bool lower) const +{ + if (lower) + bounds.max[dim] = split; + else + bounds.min[dim] = split; +} + +template +bool +diy::detail::KDTreeSamplingPartition:: +intersects(const Bounds& x, const Bounds& y, int dim, bool wrap, const Bounds& domain) const +{ + if (wrap) + { + if (x.min[dim] == domain.min[dim] && y.max[dim] == domain.max[dim]) + return true; + if (y.min[dim] == domain.min[dim] && x.max[dim] == domain.max[dim]) + return true; + } + return x.min[dim] <= y.max[dim] && y.min[dim] <= x.max[dim]; +} + +template +float +diy::detail::KDTreeSamplingPartition:: +find_split(const Bounds& changed, const Bounds& original) const +{ + for (int i = 0; i < dim_; ++i) + { + if (changed.min[i] != original.min[i]) + return changed.min[i]; + if (changed.max[i] != original.max[i]) + return changed.max[i]; + } + assert(0); + return -1; +} + +template +diy::Direction +diy::detail::KDTreeSamplingPartition:: +find_wrap(const Bounds& bounds, const Bounds& nbr_bounds, const Bounds& domain) const +{ + diy::Direction wrap; + for (int i = 0; i < dim_; ++i) + { + if (bounds.min[i] == domain.min[i] && nbr_bounds.max[i] == domain.max[i]) + wrap[i] = -1; + if (bounds.max[i] == domain.max[i] && nbr_bounds.min[i] == domain.min[i]) + wrap[i] = 1; + } + return wrap; +} + + +#endif diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/kdtree.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/kdtree.hpp index 0bce1359177..5e0c3ddfa1b 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/kdtree.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/kdtree.hpp @@ -30,6 +30,8 @@ struct KDTreePartition int divide_gid(int gid, bool lower, int round, int rounds) const; void update_links(Block* b, const diy::ReduceProxy& srp, int dim, int round, int rounds, bool wrap, const Bounds& domain) const; void split_to_neighbors(Block* b, const diy::ReduceProxy& srp, int dim) const; + diy::Direction + find_wrap(const Bounds& bounds, const Bounds& nbr_bounds, const Bounds& domain) const; void compute_local_histogram(Block* b, const diy::ReduceProxy& srp, int dim) const; void add_histogram(Block* b, const diy::ReduceProxy& srp, Histogram& histogram) const; @@ -59,8 +61,9 @@ struct diy::detail::KDTreePartners typedef diy::ContinuousBounds Bounds; KDTreePartners(int dim, int nblocks, bool wrap_, const Bounds& domain_): - histogram(1, nblocks, 2), - swap(1, nblocks, 2, false), + decomposer(1, interval(0,nblocks-1), nblocks), + histogram(decomposer, 2), + swap(decomposer, 2, false), wrap(wrap_), domain(domain_) { @@ -94,7 +97,7 @@ struct diy::detail::KDTreePartners inline bool active(int round, int gid, const diy::Master& m) const { - if (round == rounds()) + if (round == (int) rounds()) return true; else if (swap_round(round) && sub_round(round) < 0) // link round return true; @@ -106,7 +109,7 @@ struct diy::detail::KDTreePartners inline void incoming(int round, int gid, std::vector& partners, const diy::Master& m) const { - if (round == rounds()) + if (round == (int) rounds()) link_neighbors(-1, gid, partners, m); else if (swap_round(round) && sub_round(round) < 0) // link round swap.incoming(sub_round(round - 1) + 1, gid, partners, m); @@ -125,7 +128,7 @@ struct diy::detail::KDTreePartners inline void outgoing(int round, int gid, std::vector& partners, const diy::Master& m) const { - if (round == rounds()) + if (round == (int) rounds()) swap.outgoing(sub_round(round-1) + 1, gid, partners, m); else if (swap_round(round) && sub_round(round) < 0) // link round link_neighbors(-1, gid, partners, m); @@ -141,13 +144,16 @@ struct diy::detail::KDTreePartners diy::Link* link = m.link(lid); std::set result; // partners must be unique - for (size_t i = 0; i < link->size(); ++i) + for (int i = 0; i < link->size(); ++i) result.insert(link->target(i).gid); for (std::set::const_iterator it = result.begin(); it != result.end(); ++it) partners.push_back(*it); } + // 1-D domain to feed into histogram and swap + diy::RegularDecomposer decomposer; + diy::RegularAllReducePartners histogram; diy::RegularSwapPartners swap; @@ -194,7 +200,7 @@ operator()(void* b_, const diy::ReduceProxy& srp, const KDTreePartners& partners } compute_local_histogram(b, srp, dim); - } else if (partners.sub_round(srp.round()) < partners.histogram.rounds()/2) + } else if (partners.sub_round(srp.round()) < (int) partners.histogram.rounds()/2) { Histogram histogram(bins_); add_histogram(b, srp, histogram); @@ -248,45 +254,41 @@ update_links(Block* b, const diy::ReduceProxy& srp, int dim, int round, int roun srp.dequeue(in_gid, dir); // reverse dir - int j = 0; - while (dir >> (j + 1)) - ++j; - - if (j % 2 == 0) - dir = static_cast(dir << 1); - else - dir = static_cast(dir >> 1); + for (int j = 0; j < dim_; ++j) + dir[j] = -dir[j]; int k = link_map[std::make_pair(in_gid, dir)]; - //printf("%d %d %f -> %d\n", in_gid, dir, split, k); splits[k] = split; } } RCLink new_link(dim_, link->core(), link->core()); - diy::Direction left = static_cast(1 << 2*dim); - diy::Direction right = static_cast(1 << (2*dim + 1)); - bool lower = !(gid & (1 << (rounds - 1 - round))); // fill out the new link for (int i = 0; i < link->size(); ++i) { - diy::Direction dir = link->direction(i); - if (dir == left || dir == right) + diy::Direction dir = link->direction(i); + //diy::Direction wrap_dir = link->wrap(i); // we don't use existing wrap, but restore it from scratch + if (dir[dim] != 0) { - if ((dir == left && lower) || (dir == right && !lower)) + if ((dir[dim] < 0 && lower) || (dir[dim] > 0 && !lower)) { - int nbr_gid = divide_gid(link->target(i).gid, dir != left, round, rounds); + int nbr_gid = divide_gid(link->target(i).gid, !lower, round, rounds); diy::BlockID nbr = { nbr_gid, srp.assigner().rank(nbr_gid) }; new_link.add_neighbor(nbr); new_link.add_direction(dir); Bounds bounds = link->bounds(i); - update_neighbor_bounds(bounds, splits[i], dim, dir != left); + update_neighbor_bounds(bounds, splits[i], dim, !lower); new_link.add_bounds(bounds); + + if (wrap) + new_link.add_wrap(find_wrap(new_link.bounds(), bounds, domain)); + else + new_link.add_wrap(diy::Direction()); } } else // non-aligned side { @@ -303,6 +305,11 @@ update_links(Block* b, const diy::ReduceProxy& srp, int dim, int round, int roun new_link.add_neighbor(nbr); new_link.add_direction(dir); new_link.add_bounds(bounds); + + if (wrap) + new_link.add_wrap(find_wrap(new_link.bounds(), bounds, domain)); + else + new_link.add_wrap(diy::Direction()); } } } @@ -317,10 +324,19 @@ update_links(Block* b, const diy::ReduceProxy& srp, int dim, int round, int roun update_neighbor_bounds(nbr_bounds, find_split(new_link.bounds(), nbr_bounds), dim, !lower); new_link.add_bounds(nbr_bounds); + new_link.add_wrap(diy::Direction()); // dual block cannot be wrapped + if (lower) + { + diy::Direction right; + right[dim] = 1; new_link.add_direction(right); - else + } else + { + diy::Direction left; + left[dim] = -1; new_link.add_direction(left); + } // update the link; notice that this won't conflict with anything since // reduce is using its own notion of the link constructed through the @@ -339,7 +355,7 @@ split_to_neighbors(Block* b, const diy::ReduceProxy& srp, int dim) const // determine split float split = find_split(link->core(), link->bounds()); - for (size_t i = 0; i < link->size(); ++i) + for (int i = 0; i < link->size(); ++i) { srp.enqueue(link->target(i), split); srp.enqueue(link->target(i), link->direction(i)); @@ -367,7 +383,7 @@ compute_local_histogram(Block* b, const diy::ReduceProxy& srp, int dim) const std::cerr << loc << " " << x << " " << link->core().min[dim] << std::endl; std::abort(); } - if (loc >= bins_) + if (loc >= (int) bins_) loc = bins_ - 1; ++(histogram[loc]); } @@ -381,7 +397,7 @@ diy::detail::KDTreePartition:: add_histogram(Block* b, const diy::ReduceProxy& srp, Histogram& histogram) const { // dequeue and add up the histograms - for (unsigned i = 0; i < srp.in_link().size(); ++i) + for (int i = 0; i < srp.in_link().size(); ++i) { int nbr_gid = srp.in_link().target(i).gid; @@ -405,7 +421,7 @@ void diy::detail::KDTreePartition:: forward_histogram(Block* b, const diy::ReduceProxy& srp, const Histogram& histogram) const { - for (unsigned i = 0; i < srp.out_link().size(); ++i) + for (int i = 0; i < srp.out_link().size(); ++i) srp.enqueue(srp.out_link().target(i), histogram); } @@ -429,9 +445,8 @@ enqueue_exchange(Block* b, const diy::ReduceProxy& srp, int dim, const Histogram //fprintf(stderr, "Histogram total: %lu\n", total); size_t cur = 0; - size_t last, next; float width = (link->core().max[dim] - link->core().min[dim])/bins_; - float split; + float split = 0; for (size_t i = 0; i < histogram.size(); ++i) { if (cur + histogram[i] > total/2) @@ -476,7 +491,7 @@ dequeue_exchange(Block* b, const diy::ReduceProxy& srp, int dim) const int lid = srp.master()->lid(srp.gid()); RCLink* link = static_cast(srp.master()->link(lid)); - for (unsigned i = 0; i < srp.in_link().size(); ++i) + for (int i = 0; i < srp.in_link().size(); ++i) { int nbr_gid = srp.in_link().target(i).gid; if (nbr_gid == srp.gid()) @@ -528,19 +543,32 @@ float diy::detail::KDTreePartition:: find_split(const Bounds& changed, const Bounds& original) const { - diy::Direction dir = DIY_X0; for (int i = 0; i < dim_; ++i) { if (changed.min[i] != original.min[i]) return changed.min[i]; - dir = static_cast(dir << 1); if (changed.max[i] != original.max[i]) return changed.max[i]; - dir = static_cast(dir << 1); } assert(0); return -1; } +template +diy::Direction +diy::detail::KDTreePartition:: +find_wrap(const Bounds& bounds, const Bounds& nbr_bounds, const Bounds& domain) const +{ + diy::Direction wrap; + for (int i = 0; i < dim_; ++i) + { + if (bounds.min[i] == domain.min[i] && nbr_bounds.max[i] == domain.max[i]) + wrap[i] = -1; + if (bounds.max[i] == domain.max[i] && nbr_bounds.min[i] == domain.min[i]) + wrap[i] = 1; + } + return wrap; +} + #endif diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/sort.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/sort.hpp index 49541957bbc..90f8035057c 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/sort.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/algorithms/sort.hpp @@ -99,7 +99,7 @@ struct SampleSort::Sampler if (k_in == 0) { // draw random samples - for (int i = 0; i < num_samples; ++i) + for (size_t i = 0; i < num_samples; ++i) samples.push_back((b->*values)[std::rand() % (b->*values).size()]); } else dequeue_values(samples, srp, false); @@ -110,7 +110,7 @@ struct SampleSort::Sampler std::sort(samples.begin(), samples.end(), cmp); std::vector subsamples(srp.nblocks() - 1); int step = samples.size() / srp.nblocks(); // NB: subsamples.size() + 1 - for (int i = 0; i < subsamples.size(); ++i) + for (size_t i = 0; i < subsamples.size(); ++i) subsamples[i] = samples[(i+1)*step]; (b->*dividers).swap(subsamples); } diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/reduce/all-to-all.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/reduce/all-to-all.hpp index 88bfb877e64..c49b7d28cdb 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/reduce/all-to-all.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/detail/reduce/all-to-all.hpp @@ -154,7 +154,7 @@ namespace detail SkipIntermediate(size_t rounds_): rounds(rounds_) {} - bool operator()(int round, int, const Master&) const { if (round == 0 || round == rounds) return false; return true; } + bool operator()(int round, int, const Master&) const { if (round == 0 || round == (int) rounds) return false; return true; } size_t rounds; }; diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/block.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/block.hpp index 4161d592092..4667a32101a 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/block.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/block.hpp @@ -174,65 +174,45 @@ namespace io * \ingroup IO * \brief Read blocks from storage collectively from one shared file */ - inline - void - read_blocks(const std::string& infilename, //!< input file name - const mpi::communicator& comm, //!< communicator - Assigner& assigner, //!< assigner object - Master& master, //!< master object - MemoryBuffer& extra, //!< user-defined metadata in file header - Master::LoadBlock load = 0) //!< load block function in case different than or unefined in the master - { - if (!load) load = master.loader(); // load is likely to be different from master.load() + inline + void + read_blocks(const std::string& infilename, //!< input file name + const mpi::communicator& comm, //!< communicator + Assigner& assigner, //!< assigner object + Master& master, //!< master object + MemoryBuffer& extra, //!< user-defined metadata in file header + Master::LoadBlock load = 0) //!< load block function in case different than or unefined in the master + { + if (!load) load = master.loader(); // load is likely to be different from master.load() - typedef detail::offset_t offset_t; - typedef detail::GidOffsetCount GidOffsetCount; + typedef detail::offset_t offset_t; + typedef detail::GidOffsetCount GidOffsetCount; - mpi::io::file f(comm, infilename, mpi::io::file::rdonly); + mpi::io::file f(comm, infilename, mpi::io::file::rdonly); - offset_t footer_offset = f.size() - sizeof(size_t); - size_t footer_size; + offset_t footer_offset = f.size() - sizeof(size_t); + size_t footer_size; - // Read the size - try - { + // Read the size f.read_at_all(footer_offset, (char*) &footer_size, sizeof(footer_size)); - } - catch(...) - { - fprintf(stderr, "Error reading footer size\n"); - throw(1); - } - // Read all_offset_counts - footer_offset -= footer_size; - MemoryBuffer footer; - try - { + // Read all_offset_counts + footer_offset -= footer_size; + MemoryBuffer footer; footer.buffer.resize(footer_size); f.read_at_all(footer_offset, footer.buffer); - } - catch(...) - { - fprintf(stderr, "Error reading footer\n"); - throw(1); - } - std::vector all_offset_counts; - diy::load(footer, all_offset_counts); - diy::load(footer, extra); - extra.reset(); + std::vector all_offset_counts; + diy::load(footer, all_offset_counts); + diy::load(footer, extra); + extra.reset(); - // Get local gids from assigner - size_t size = all_offset_counts.size(); - assigner.set_nblocks(size); - std::vector gids; - assigner.local_gids(comm.rank(), gids); + // Get local gids from assigner + size_t size = all_offset_counts.size(); + assigner.set_nblocks(size); + std::vector gids; + assigner.local_gids(comm.rank(), gids); - // Read our blocks; - // TODO: use collective IO, when possible - try - { for (unsigned i = 0; i < gids.size(); ++i) { if (gids[i] != all_offset_counts[gids[i]].gid) @@ -251,12 +231,6 @@ namespace io master.add(gids[i], b, l); } } - catch(...) - { - fprintf(stderr, "Error reading blocks\n"); - throw(1); - } - } // Functions without the extra buffer, for compatibility with the old code diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/bov.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/bov.hpp index f4ead18bff7..cb059d0317a 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/bov.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/bov.hpp @@ -74,7 +74,7 @@ read(const DiscreteBounds& bounds, T* buffer, bool collective, int chunk) const int dim = shape_.size(); int total = 1; std::vector subsizes; - for (unsigned i = 0; i < dim; ++i) + for (int i = 0; i < dim; ++i) { subsizes.push_back(bounds.max[i] - bounds.min[i] + 1); total *= subsizes.back(); @@ -88,15 +88,15 @@ read(const DiscreteBounds& bounds, T* buffer, bool collective, int chunk) const // create an MPI struct of size chunk to read the data in those chunks // (this allows to work around MPI-IO weirdness where crucial quantities // are ints, which are too narrow of a type) - const int array_of_blocklengths[] = { chunk }; - const MPI_Aint array_of_displacements[] = { 0 }; - const MPI_Datatype array_of_types[] = { mpi::detail::get_mpi_datatype() }; + int array_of_blocklengths[] = { chunk }; + MPI_Aint array_of_displacements[] = { 0 }; + MPI_Datatype array_of_types[] = { mpi::detail::get_mpi_datatype() }; MPI_Type_create_struct(1, array_of_blocklengths, array_of_displacements, array_of_types, &T_type); MPI_Type_commit(&T_type); } MPI_Datatype fileblk; - MPI_Type_create_subarray(dim, &shape_[0], &subsizes[0], &bounds.min[0], MPI_ORDER_C, T_type, &fileblk); + MPI_Type_create_subarray(dim, (int*) &shape_[0], &subsizes[0], (int*) &bounds.min[0], MPI_ORDER_C, T_type, &fileblk); MPI_Type_commit(&fileblk); MPI_File_set_view(f_.handle(), offset_, T_type, fileblk, "native", MPI_INFO_NULL); @@ -128,7 +128,7 @@ write(const DiscreteBounds& bounds, const T* buffer, const DiscreteBounds& core, int dim = shape_.size(); std::vector subsizes; std::vector buffer_shape, buffer_start; - for (unsigned i = 0; i < dim; ++i) + for (int i = 0; i < dim; ++i) { buffer_shape.push_back(bounds.max[i] - bounds.min[i] + 1); buffer_start.push_back(core.min[i] - bounds.min[i]); @@ -141,16 +141,16 @@ write(const DiscreteBounds& bounds, const T* buffer, const DiscreteBounds& core, else { // assume T is a binary block and create an MPI struct of appropriate size - const int array_of_blocklengths[] = { chunk }; - const MPI_Aint array_of_displacements[] = { 0 }; - const MPI_Datatype array_of_types[] = { mpi::detail::get_mpi_datatype() }; + int array_of_blocklengths[] = { chunk }; + MPI_Aint array_of_displacements[] = { 0 }; + MPI_Datatype array_of_types[] = { mpi::detail::get_mpi_datatype() }; MPI_Type_create_struct(1, array_of_blocklengths, array_of_displacements, array_of_types, &T_type); MPI_Type_commit(&T_type); } MPI_Datatype fileblk, subbuffer; - MPI_Type_create_subarray(dim, &shape_[0], &subsizes[0], &bounds.min[0], MPI_ORDER_C, T_type, &fileblk); - MPI_Type_create_subarray(dim, &buffer_shape[0], &subsizes[0], &buffer_start[0], MPI_ORDER_C, T_type, &subbuffer); + MPI_Type_create_subarray(dim, (int*) &shape_[0], &subsizes[0], (int*) &bounds.min[0], MPI_ORDER_C, T_type, &fileblk); + MPI_Type_create_subarray(dim, (int*) &buffer_shape[0], &subsizes[0], (int*) &buffer_start[0], MPI_ORDER_C, T_type, &subbuffer); MPI_Type_commit(&fileblk); MPI_Type_commit(&subbuffer); diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/numpy.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/numpy.hpp index ae295dc26da..0199a0c38f4 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/numpy.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/io/numpy.hpp @@ -143,7 +143,7 @@ write_header(const S& shape) convert_and_save(dict, sizeof(T)); save(dict, "', 'fortran_order': False, 'shape': ("); convert_and_save(dict, shape[0]); - for (int i = 1; i < shape.size(); i++) + for (int i = 1; i < (int) shape.size(); i++) { save(dict, ", "); convert_and_save(dict, shape[i]); @@ -174,7 +174,8 @@ char diy::io::detail::big_endian() { unsigned char x[] = {1,0}; - short y = *(short*) x; + void* x_void = x; + short y = *static_cast(x_void); return y == 1 ? '<' : '>'; } diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/link.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/link.hpp index 16f64ec4c0c..3262eef610a 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/link.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/link.hpp @@ -77,19 +77,21 @@ namespace diy typedef std::vector DirVec; public: - RegularLink(int dim, const Bounds& core, const Bounds& bounds, Direction wrap = Direction(0)): - dim_(dim), wrap_(wrap), core_(core), bounds_(bounds) {} + RegularLink(int dim, const Bounds& core, const Bounds& bounds): + dim_(dim), core_(core), bounds_(bounds) {} - int dimension() const { return dim_; } + // dimension + int dimension() const { return dim_; } // direction - int direction(Direction dir) const; // convert direction to a neighbor (-1 if no neighbor) - Direction direction(int i) const { return dir_vec_[i]; } - void add_direction(Direction dir) { int c = dir_map_.size(); dir_map_[dir] = c; dir_vec_.push_back(dir); } + int direction(Direction dir) const; // convert direction to a neighbor (-1 if no neighbor) + Direction direction(int i) const { return dir_vec_[i]; } + void add_direction(Direction dir) { int c = dir_map_.size(); dir_map_[dir] = c; dir_vec_.push_back(dir); } // wrap - void add_wrap(Direction dir) { wrap_ = static_cast(wrap_ | dir); } - Direction wrap() const { return wrap_; } + void add_wrap(Direction dir) { wrap_.push_back(dir); } + Direction wrap(int i) const { return wrap_[i]; } + Direction& wrap(int i) { return wrap_[i]; } // bounds const Bounds& core() const { return core_; } @@ -99,7 +101,7 @@ namespace diy const Bounds& bounds(int i) const { return nbr_bounds_[i]; } void add_bounds(const Bounds& bounds) { nbr_bounds_.push_back(bounds); } - void swap(RegularLink& other) { Link::swap(other); dir_map_.swap(other.dir_map_); dir_vec_.swap(other.dir_vec_); nbr_bounds_.swap(other.nbr_bounds_); std::swap(dim_, other.dim_); std::swap(wrap_, other.wrap_); std::swap(core_, other.core_); std::swap(bounds_, other.bounds_); } + void swap(RegularLink& other) { Link::swap(other); dir_map_.swap(other.dir_map_); dir_vec_.swap(other.dir_vec_); nbr_bounds_.swap(other.nbr_bounds_); std::swap(dim_, other.dim_); wrap_.swap(other.wrap_); std::swap(core_, other.core_); std::swap(bounds_, other.bounds_); } void save(BinaryBuffer& bb) const { @@ -107,10 +109,10 @@ namespace diy diy::save(bb, dim_); diy::save(bb, dir_map_); diy::save(bb, dir_vec_); - diy::save(bb, wrap_); diy::save(bb, core_); diy::save(bb, bounds_); diy::save(bb, nbr_bounds_); + diy::save(bb, wrap_); } void load(BinaryBuffer& bb) @@ -119,10 +121,10 @@ namespace diy diy::load(bb, dim_); diy::load(bb, dir_map_); diy::load(bb, dir_vec_); - diy::load(bb, wrap_); diy::load(bb, core_); diy::load(bb, bounds_); diy::load(bb, nbr_bounds_); + diy::load(bb, wrap_); } virtual size_t id() const { return RegularLinkSelector::id; } @@ -132,11 +134,11 @@ namespace diy DirMap dir_map_; DirVec dir_vec_; - Direction wrap_; - Bounds core_; - Bounds bounds_; - std::vector nbr_bounds_; + Bounds core_; + Bounds bounds_; + std::vector nbr_bounds_; + std::vector wrap_; }; // Other cover candidates: KDTreeLink, AMRGridLink diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/master.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/master.hpp index 65c2baddef0..06676350377 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/master.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/master.hpp @@ -206,6 +206,8 @@ namespace diy int threads() const { return threads_; } int in_memory() const { return *blocks_.in_memory().const_access(); } + void set_threads(int threads) { threads_ = threads; } + CreateBlock creator() const { return blocks_.creator(); } DestroyBlock destroyer() const { return blocks_.destroyer(); } LoadBlock loader() const { return blocks_.loader(); } @@ -256,6 +258,7 @@ namespace diy void set_expected(int expected) { expected_ = expected; } void add_expected(int i) { expected_ += i; } int expected() const { return expected_; } + void replace_link(int i, Link* link) { expected_ -= links_[i]->size_unique(); delete links_[i]; links_[i] = link; expected_ += links_[i]->size_unique(); } public: // Communicator functionality diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/mpi/collectives.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/mpi/collectives.hpp index fd7e5582085..d1cc0bdd808 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/mpi/collectives.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/mpi/collectives.hpp @@ -135,10 +135,10 @@ namespace mpi out.resize(comm.size()); size_t cur = 0; - for (unsigned i = 0; i < comm.size(); ++i) + for (int i = 0; i < comm.size(); ++i) { out[i].reserve(counts[i]); - for (unsigned j = 0; j < counts[i]; ++j) + for (int j = 0; j < counts[i]; ++j) out[i].push_back(buffer[cur++]); } } @@ -173,6 +173,17 @@ namespace mpi comm); } + static void all_reduce(const communicator& comm, const std::vector& in, std::vector& out, const Op&) + { + out.resize(in.size()); + MPI_Allreduce(Datatype::address(const_cast(in[0])), + Datatype::address(out[0]), + in.size(), + Datatype::datatype(), + detail::mpi_op::get(), + comm); + } + static void scan(const communicator& comm, const T& in, T& out, const Op&) { MPI_Scan(Datatype::address(const_cast(in)), @@ -274,6 +285,13 @@ namespace mpi Collectives::all_reduce(comm, in, out, op); } + //! Same as above, but for vectors. + template + void all_reduce(const communicator& comm, const std::vector& in, std::vector& out, const Op& op) + { + Collectives::all_reduce(comm, in, out, op); + } + //! scan template void scan(const communicator& comm, const T& in, T& out, const Op& op) diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/mpi/optional.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/mpi/optional.hpp index 973a65f7d22..ab58aaf8108 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/mpi/optional.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/mpi/optional.hpp @@ -21,14 +21,17 @@ namespace mpi operator bool() const { return init_; } - T& operator*() { return *reinterpret_cast(buf_); } - const T& operator*() const { return *reinterpret_cast(buf_); } + T& operator*() { return *static_cast(address()); } + const T& operator*() const { return *static_cast(address()); } T* operator->() { return &(operator*()); } const T* operator->() const { return &(operator*()); } private: - void clear() { reinterpret_cast(buf_)->~T(); } + void clear() { static_cast(address())->~T(); } + + void* address() { return buf_; } + const void* address() const { return buf_; } private: bool init_; diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/all-reduce.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/all-reduce.hpp index d51f5507bf7..e340665951f 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/all-reduce.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/all-reduce.hpp @@ -24,12 +24,12 @@ struct RegularAllReducePartners: public RegularMergePartners //! contiguous parameter indicates whether to match partners contiguously or in a round-robin fashion; //! contiguous is useful when data needs to be united; //! round-robin is useful for vector-"halving" - RegularAllReducePartners(int dim, //!< dimensionality of regular block grid - int nblocks, //!< total number of blocks - int k, //!< target k value - bool contiguous = true //!< distance doubling (true) or halving (false) + template + RegularAllReducePartners(const Decomposer& decomposer, //!< domain decomposition + int k, //!< target k value + bool contiguous = true //!< distance doubling (true) or halving (false) ): - Parent(dim, nblocks, k, contiguous) {} + Parent(decomposer, k, contiguous) {} RegularAllReducePartners(const DivisionVector& divs,//!< explicit division vector const KVSVector& kvs, //!< explicit k vector bool contiguous = true //!< distance doubling (true) or halving (false) @@ -45,12 +45,12 @@ struct RegularAllReducePartners: public RegularMergePartners //! returns whether a given block in a given round has dropped out of the merge yet or not inline bool active(int round, int gid, const Master& m) const { return Parent::active(parent_round(round), gid, m); } //! returns what the current round would be in the first or second parent merge reduction - int parent_round(int round) const { return round < Parent::rounds() ? round : rounds() - round; } + int parent_round(int round) const { return round < (int) Parent::rounds() ? round : rounds() - round; } // incoming is only valid for an active gid; it will only be called with an active gid inline void incoming(int round, int gid, std::vector& partners, const Master& m) const { - if (round <= Parent::rounds()) + if (round <= (int) Parent::rounds()) Parent::incoming(round, gid, partners, m); else Parent::outgoing(parent_round(round), gid, partners, m); @@ -58,7 +58,7 @@ struct RegularAllReducePartners: public RegularMergePartners inline void outgoing(int round, int gid, std::vector& partners, const Master& m) const { - if (round < Parent::rounds()) + if (round < (int) Parent::rounds()) Parent::outgoing(round, gid, partners, m); else Parent::incoming(parent_round(round), gid, partners, m); diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/common.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/common.hpp index 496a4483fb3..43f8297a0fe 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/common.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/common.hpp @@ -19,17 +19,18 @@ struct RegularPartners int size; // group size }; - // The part of RegularDecomposer that we need works the same with either Bounds (so we fix them arbitrarily) - typedef DiscreteBounds Bounds; - typedef RegularDecomposer Decomposer; - typedef std::vector CoordVector; typedef std::vector DivisionVector; typedef std::vector KVSVector; - RegularPartners(int dim, int nblocks, int k, bool contiguous = true): - divisions_(dim, 0), - contiguous_(contiguous) { Decomposer::fill_divisions(dim, nblocks, divisions_); factor(k, divisions_, kvs_); fill_steps(); } + // The part of RegularDecomposer that we need works the same with either Bounds (so we fix them arbitrarily) + typedef DiscreteBounds Bounds; + typedef RegularDecomposer Decomposer; + + template + RegularPartners(const Decomposer_& decomposer, int k, bool contiguous = true): + divisions_(decomposer.divisions), + contiguous_(contiguous) { factor(k, divisions_, kvs_); fill_steps(); } RegularPartners(const DivisionVector& divs, const KVSVector& kvs, bool contiguous = true): @@ -73,7 +74,7 @@ fill_steps() { std::vector cur_steps(divisions().size(), 1); - for (int r = 0; r < rounds(); ++r) + for (size_t r = 0; r < rounds(); ++r) { steps_.push_back(cur_steps[kvs_[r].dim]); cur_steps[kvs_[r].dim] *= kvs_[r].size; @@ -81,7 +82,7 @@ fill_steps() } else { std::vector cur_steps(divisions().begin(), divisions().end()); - for (int r = 0; r < rounds(); ++r) + for (size_t r = 0; r < rounds(); ++r) { cur_steps[kvs_[r].dim] /= kvs_[r].size; steps_.push_back(cur_steps[kvs_[r].dim]); @@ -152,7 +153,7 @@ factor(int k, const DivisionVector& divisions, KVSVector& kvs) bool changed = false; for (unsigned i = 0; i < divisions.size(); ++i) { - if (round_per_dim[i] == tmp_kvs[i].size()) + if (round_per_dim[i] == (int) tmp_kvs[i].size()) continue; kvs.push_back(DimK(i, tmp_kvs[i][round_per_dim[i]++])); changed = true; diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/merge.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/merge.hpp index 3c4cfa134de..c6be4253318 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/merge.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/merge.hpp @@ -20,12 +20,12 @@ struct RegularMergePartners: public RegularPartners // contiguous parameter indicates whether to match partners contiguously or in a round-robin fashion; // contiguous is useful when data needs to be united; // round-robin is useful for vector-"halving" - RegularMergePartners(int dim, //!< dimensionality of regular block grid - int nblocks, //!< total number of blocks - int k, //!< target k value - bool contiguous = true //!< distance doubling (true) or halving (false) + template + RegularMergePartners(const Decomposer& decomposer, //!< domain decomposition + int k, //!< target k value + bool contiguous = true //!< distance doubling (true) or halving (false) ): - Parent(dim, nblocks, k, contiguous) {} + Parent(decomposer, k, contiguous) {} RegularMergePartners(const DivisionVector& divs, //!< explicit division vector const KVSVector& kvs, //!< explicit k vector bool contiguous = true //!< distance doubling (true) or halving (false) diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/swap.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/swap.hpp index f06b09e3746..cc3b3e4941a 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/swap.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/partners/swap.hpp @@ -20,12 +20,12 @@ struct RegularSwapPartners: public RegularPartners // contiguous parameter indicates whether to match partners contiguously or in a round-robin fashion; // contiguous is useful when data needs to be united; // round-robin is useful for vector-"halving" - RegularSwapPartners(int dim, //!< dimensionality of regular block grid - int nblocks, //!< total number of blocks - int k, //!< target k value - bool contiguous = true //!< distance halving (true) or doubling (false) + template + RegularSwapPartners(const Decomposer& decomposer, //!< domain decomposition + int k, //!< target k value + bool contiguous = true //!< distance halving (true) or doubling (false) ): - Parent(dim, nblocks, k, contiguous) {} + Parent(decomposer, k, contiguous) {} RegularSwapPartners(const DivisionVector& divs, //!< explicit division vector const KVSVector& kvs, //!< explicit k vector bool contiguous = true //!< distance halving (true) or doubling (false) diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/pick.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/pick.hpp index f6aea2c2277..f884157b203 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/pick.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/pick.hpp @@ -15,19 +15,14 @@ namespace diy template float distance(int dim, const ContinuousBounds& bounds, const Point& p); - template - void wrap_bounds(Bounds& bounds, int wrap_dir, const Bounds& domain, int dim); + inline + float distance(int dim, const ContinuousBounds& bounds1, const ContinuousBounds& bounds2); - namespace detail - { - template - void shift(float new_pt[DIY_MAX_DIM], const Point& p, float r, Direction dir, int dim); - } + template + void wrap_bounds(Bounds& bounds, Direction wrap_dir, const Bounds& domain, int dim); } -//! Finds the neighbors within radius r of a target point. Assumptions: -//! 1. Point p needs to be in the current block -//! 2. Only for a regular decomposition +//! Finds the neighbors within radius r of a target point. template void diy:: @@ -37,8 +32,6 @@ near(const RegularLink& link, //!< neighbors OutIter out, //!< insert iterator for output set of neighbors const Bounds& domain) //!< global domain bounds { - int d; // current dimension - float new_pt[DIY_MAX_DIM]; // offset point Bounds neigh_bounds; // neighbor block bounds // for all neighbors of this block @@ -46,26 +39,10 @@ near(const RegularLink& link, //!< neighbors { // wrap neighbor bounds, if necessary, otherwise bounds will be unchanged neigh_bounds = link.bounds(n); - wrap_bounds(neigh_bounds, link.wrap() & link.direction(n), domain, link.dimension()); + wrap_bounds(neigh_bounds, link.wrap(n), domain, link.dimension()); - detail::shift(new_pt, p, r, link.direction(n), link.dimension()); - - // check if neighbor is near enough - for (d = 0; d < link.dimension(); d++) - { - // if shifted point did not move into or past the neighbor, - // break and proceed to next neighbor - // note dist can be large enough to shift the point beyond the neighbor - // that means the point was definitely near enough to neighbor - if (((link.direction(n) & (1 << (2*d + 1))) && new_pt[d] < neigh_bounds.min[d]) || - ((link.direction(n) & (1 << (2*d))) && new_pt[d] > neigh_bounds.max[d])) - break; - } - - if (d < link.dimension()) - continue; // next neighbor - - *out++ = n; + if (distance(link.dimension(), neigh_bounds, p) <= r) + *out++ = n; } // for all neighbors } @@ -92,8 +69,31 @@ distance(int dim, const ContinuousBounds& bounds, const Point& p) return sqrt(res); } -//! Finds the neighbor(s) containing the target point. Assumptions: -//! 1. Only for a regular decomposition +float +diy:: +distance(int dim, const ContinuousBounds& bounds1, const ContinuousBounds& bounds2) +{ + float res = 0; + for (int i = 0; i < dim; ++i) + { + float diff = 0, d; + + float d1 = bounds1.max[i] - bounds2.min[i]; + float d2 = bounds2.max[i] - bounds1.min[i]; + + if (d1 > 0 && d2 > 0) + diff = 0; + else if (d1 <= 0) + diff = -d1; + else if (d2 <= 0) + diff = -d2; + + res += diff*diff; + } + return sqrt(res); +} + +//! Finds the neighbor(s) containing the target point. template void diy:: @@ -102,7 +102,6 @@ in(const RegularLink& link, //!< neighbors OutIter out, //!< insert iterator for output set of neighbors const Bounds& domain) //!< global domain bounds { - int d; // current dimension Bounds neigh_bounds; // neighbor block bounds // for all neighbors of this block @@ -110,19 +109,10 @@ in(const RegularLink& link, //!< neighbors { // wrap neighbor bounds, if necessary, otherwise bounds will be unchanged neigh_bounds = link.bounds(n); - wrap_bounds(neigh_bounds, link.wrap() & link.direction(n), domain, link.dimension()); - - // check if p is in neighbor - for (d = 0; d < link.dimension(); d++) - { - if (p[d] < neigh_bounds.min[d] || p[d] > neigh_bounds.max[d]) - break; - } + wrap_bounds(neigh_bounds, link.wrap(n), domain, link.dimension()); - if (d < link.dimension()) - continue; // next neighbor - - *out++ = n; + if (distance(link.dimension(), neigh_bounds, p) == 0) + *out++ = n; } // for all neighbors } @@ -132,75 +122,13 @@ in(const RegularLink& link, //!< neighbors template void diy:: -wrap_bounds(Bounds& bounds, int wrap_dir, const Bounds& domain, int dim) +wrap_bounds(Bounds& bounds, Direction wrap_dir, const Bounds& domain, int dim) { - // wrapping toward the left transforms block bounds to the left, and vice versa - if (dim > 0 && (wrap_dir & DIY_X0) == DIY_X0) - { - bounds.min[0] -= (domain.max[0] - domain.min[0]); - bounds.max[0] -= (domain.max[0] - domain.min[0]); - } - if (dim > 0 && (wrap_dir & DIY_X1) == DIY_X1) - { - bounds.min[0] += (domain.max[0] - domain.min[0]); - bounds.max[0] += (domain.max[0] - domain.min[0]); - } - - if (dim > 1 && (wrap_dir & DIY_Y0) == DIY_Y0) - { - bounds.min[1] -= (domain.max[1] - domain.min[1]); - bounds.max[1] -= (domain.max[1] - domain.min[1]); - } - if (dim > 1 && (wrap_dir & DIY_Y1) == DIY_Y1) - { - bounds.min[1] += (domain.max[1] - domain.min[1]); - bounds.max[1] += (domain.max[1] - domain.min[1]); - } - - if (dim > 2 && (wrap_dir & DIY_Z0) == DIY_Z0) + for (int i = 0; i < dim; ++i) { - bounds.min[2] -= (domain.max[2] - domain.min[2]); - bounds.max[2] -= (domain.max[2] - domain.min[2]); + bounds.min[i] += wrap_dir[i] * (domain.max[i] - domain.min[i]); + bounds.max[i] += wrap_dir[i] * (domain.max[i] - domain.min[i]); } - if (dim > 2 && (wrap_dir & DIY_Z1) == DIY_Z1) - { - bounds.min[2] += (domain.max[2] - domain.min[2]); - bounds.max[2] += (domain.max[2] - domain.min[2]); - } - - if (dim > 3 && (wrap_dir & DIY_T0) == DIY_T0) - { - bounds.min[3] -= (domain.max[3] - domain.min[3]); - bounds.max[3] -= (domain.max[3] - domain.min[3]); - } - if (dim > 3 && (wrap_dir & DIY_T1) == DIY_T1) - { - bounds.min[3] += (domain.max[3] - domain.min[3]); - bounds.max[3] += (domain.max[3] - domain.min[3]); - } -} - -template -void -diy::detail:: -shift(float new_pt[DIY_MAX_DIM], const Point& p, float r, Direction dir, int dim) -{ - if (dim > 0 && (dir & DIY_X0)) - new_pt[0] = p[0] - r; - if (dim > 0 && (dir & DIY_X1)) - new_pt[0] = p[0] + r; - if (dim > 1 && (dir & DIY_Y0)) - new_pt[1] = p[1] - r; - if (dim > 1 && (dir & DIY_Y1)) - new_pt[1] = p[1] + r; - if (dim > 2 && (dir & DIY_Z0)) - new_pt[2] = p[2] - r; - if (dim > 2 && (dir & DIY_Z1)) - new_pt[2] = p[2] + r; - if (dim > 3 && (dir & DIY_T0)) - new_pt[3] = p[3] - r; - if (dim > 3 && (dir & DIY_T1)) - new_pt[3] = p[3] + r; } diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/proxy.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/proxy.hpp index 5ea2d463184..0160e060567 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/proxy.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/proxy.hpp @@ -19,7 +19,7 @@ namespace diy int gid() const { return gid_; } - //! Enqueue data whose size can be determined automatically + //! Enqueue data whose size can be determined automatically, e.g., an STL vector. template void enqueue(const BlockID& to, //!< target block (gid,proc) const T& x, //!< data (eg. STL vector) @@ -27,7 +27,7 @@ namespace diy ) const { OutgoingQueues& out = *outgoing_; save(out[to], x); } - //! Enqueue an array of data whose size is given explicitly + //! Enqueue data whose size is given explicitly by the user, e.g., an array. template void enqueue(const BlockID& to, //!< target block (gid,proc) const T* x, //!< pointer to the data (eg. address of start of vector) @@ -35,8 +35,9 @@ namespace diy void (*save)(BinaryBuffer&, const T&) = &::diy::save //!< optional serialization function ) const; - //! Dequeue data whose size can be determined automatically. - //! Diy will allocate the receive buffer. + //! Dequeue data whose size can be determined automatically (e.g., STL vector) and that was + //! previously enqueued so that diy knows its size when it is received. + //! In this case, diy will allocate the receive buffer; the user does not need to do so. template void dequeue(int from, //!< target block gid T& x, //!< data (eg. STL vector) @@ -44,8 +45,8 @@ namespace diy ) const { IncomingQueues& in = *incoming_; load(in[from], x); } - //! Dequeue an array of data whose size is given explicitly. - //! The user needs to allocate the receive buffer. + //! Dequeue an array of data whose size is given explicitly by the user. + //! In this case, the user needs to allocate the receive buffer prior to calling dequeue. template void dequeue(int from, //!< target block gid T* x, //!< pointer to the data (eg. address of start of vector) @@ -65,17 +66,37 @@ namespace diy OutgoingQueues* outgoing() const { return outgoing_; } MemoryBuffer& outgoing(const BlockID& to) const { return (*outgoing_)[to]; } - //! Post an all-reduce collective +/** + * \ingroup Communication + * \brief Post an all-reduce collective using an existing communication proxy. + * Available operators are: + * maximum, minimum, std::plus, std::multiplies, std::logical_and, and + * std::logical_or. + */ template - inline void all_reduce(const T& in, Op op) const; + inline void all_reduce(const T& in, //!< local value being reduced + Op op //!< operator + ) const; +/** + * \ingroup Communication + * \brief Return the result of a proxy collective without popping it off the collectives list (same result would be returned multiple times). The list can be cleared with collectives()->clear(). + */ template inline T read() const; +/** + * \ingroup Communication + * \brief Return the result of a proxy collective; result is popped off the collectives list. + */ template inline T get() const; template inline void scratch(const T& in) const; +/** + * \ingroup Communication + * \brief Return the list of proxy collectives (values and operations) + */ CollectivesList* collectives() const { return collectives_; } Master* master() const { return master_; } diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/reduce-operations.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/reduce-operations.hpp index 30c4570a6ae..b1e45a58061 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/reduce-operations.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/reduce-operations.hpp @@ -21,7 +21,8 @@ all_to_all(Master& master, //!< block owner int k = 2 //!< reduction fanout ) { - RegularSwapPartners partners(1, assigner.nblocks(), k, false); + RegularDecomposer decomposer(1, interval(0,assigner.nblocks()-1), assigner.nblocks()); + RegularSwapPartners partners(decomposer, k, false); reduce(master, assigner, partners, detail::AllToAllReduce(op, assigner), detail::SkipIntermediate(partners.rounds())); } diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/reduce.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/reduce.hpp index e7be78129b5..4810942ff1c 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/reduce.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/reduce.hpp @@ -104,11 +104,11 @@ namespace detail * */ template -void reduce(Master& master, - const Assigner& assigner, - const Partners& partners, - const Reduce& reduce, - const Skip& skip) +void reduce(Master& master, //!< master object + const Assigner& assigner, //!< assigner object + const Partners& partners, //!< partners object + const Reduce& reduce, //!< reduction callback function + const Skip& skip) //!< object determining whether a block should be skipped { int original_expected = master.expected(); @@ -121,7 +121,7 @@ void reduce(Master& master, master.execute(); int expected = 0; - for (int i = 0; i < master.size(); ++i) + for (unsigned i = 0; i < master.size(); ++i) { if (partners.active(round + 1, master.gid(i), master)) { @@ -142,11 +142,17 @@ void reduce(Master& master, master.set_expected(original_expected); } +/** + * \ingroup Communication + * \brief Implementation of the reduce communication pattern (includes + * swap-reduce, merge-reduce, and any other global communication). + * + */ template -void reduce(Master& master, - const Assigner& assigner, - const Partners& partners, - const Reduce& reducer) +void reduce(Master& master, //!< master object + const Assigner& assigner, //!< assigner object + const Partners& partners, //!< partners object + const Reduce& reducer) //!< reduction callback function { reduce(master, assigner, partners, reducer, detail::ReduceNeverSkip()); } @@ -174,8 +180,8 @@ namespace detail // touch the outgoing queues to make sure they exist Master::OutgoingQueues& outgoing = *cp.outgoing(); - if (outgoing.size() < rp.out_link().size()) - for (unsigned j = 0; j < rp.out_link().size(); ++j) + if (outgoing.size() < (size_t) rp.out_link().size()) + for (int j = 0; j < rp.out_link().size(); ++j) outgoing[rp.out_link().target(j)]; // touch the outgoing queue, creating it if necessary } diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/serialization.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/serialization.hpp index 4bb89fe15ec..6a1a3defae3 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/serialization.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/serialization.hpp @@ -11,6 +11,7 @@ #if __cplusplus > 199711L // C++11 #include #include +#include #include // this is used for a safety check for default serialization #endif #endif @@ -333,6 +334,33 @@ namespace diy } }; + // save/load for std::unordered_set + template + struct Serialization< std::unordered_set > + { + typedef std::unordered_set Set; + + static void save(BinaryBuffer& bb, const Set& m) + { + size_t s = m.size(); + diy::save(bb, s); + for (auto& x : m) + diy::save(bb, x); + } + + static void load(BinaryBuffer& bb, Set& m) + { + size_t s; + diy::load(bb, s); + for (size_t i = 0; i < s; ++i) + { + T p; + diy::load(bb, p); + m.emplace(std::move(p)); + } + } + }; + // save/load for std::tuple<...> // TODO: this ought to be default (copying) serialization // if all arguments are default diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/thread.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/thread.hpp index 95377d29550..4208ccff74c 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/thread.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/thread.hpp @@ -4,9 +4,30 @@ #ifdef DIY_NO_THREADS #include "no-thread.hpp" #else -#include "thread/tinythread.h" + #include "thread/fast_mutex.h" +#if __cplusplus > 199711L // C++11 +#include +#include + +namespace diy +{ + using std::thread; + using std::mutex; + using std::recursive_mutex; + namespace this_thread = std::this_thread; + + // TODO: replace with our own implementation using std::atomic_flag + using fast_mutex = tthread::fast_mutex; + + template + using lock_guard = std::unique_lock; +} + +#else +#include "thread/tinythread.h" + namespace diy { using tthread::thread; @@ -17,6 +38,7 @@ namespace diy namespace this_thread = tthread::this_thread; } #endif +#endif #include "critical-resource.hpp" diff --git a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/types.hpp b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/types.hpp index 83db2d8fd67..7ce19d5a7f6 100644 --- a/ThirdParty/diy2/vtkdiy2/include/vtkdiy/types.hpp +++ b/ThirdParty/diy2/vtkdiy2/include/vtkdiy/types.hpp @@ -12,7 +12,29 @@ namespace diy typedef bb_d_t DiscreteBounds; typedef bb_c_t ContinuousBounds; - typedef dir_t Direction; + //! Helper to create a 1-dimensional discrete domain with the specified extents + diy::DiscreteBounds + interval(int from, int to) { DiscreteBounds domain; domain.min[0] = from; domain.max[0] = to; return domain; } + + struct Direction: public dir_t + { + Direction() { for (int i = 0; i < DIY_MAX_DIM; ++i) x[i] = 0; } + + int operator[](int i) const { return x[i]; } + int& operator[](int i) { return x[i]; } + + // lexicographic comparison + bool + operator<(const diy::Direction& y) const + { + for (int i = 0; i < DIY_MAX_DIM; ++i) + { + if ((*this)[i] < y[i]) return true; + if ((*this)[i] > y[i]) return false; + } + return false; + } + }; // Selector of bounds value type template diff --git a/ThirdParty/hdf5/CMakeLists.txt b/ThirdParty/hdf5/CMakeLists.txt index 44eb16e8454..5fa2500290d 100644 --- a/ThirdParty/hdf5/CMakeLists.txt +++ b/ThirdParty/hdf5/CMakeLists.txt @@ -62,6 +62,10 @@ if(HDF5_ENABLE_Z_LIB_SUPPORT) set(H5_ZLIB_HEADER "vtk_zlib.h") endif() +# Ensure that the proper headers are included. Without this, static MSVC builds +# do not compile. +set(H5_STDC_HEADERS "On") + add_subdirectory(vtkhdf5) foreach(lib diff --git a/ThirdParty/hdf5/vtkhdf5/config/cmake/ConversionTests.c b/ThirdParty/hdf5/vtkhdf5/config/cmake/ConversionTests.c index 1290c9f1f4a..581924398ee 100644 --- a/ThirdParty/hdf5/vtkhdf5/config/cmake/ConversionTests.c +++ b/ThirdParty/hdf5/vtkhdf5/config/cmake/ConversionTests.c @@ -1,6 +1,19 @@ +/* This file performs several undefined behaviors, suppress Undefined + * Behavior Sanitizer (UBSan) from warning. + */ +#if defined(__clang__) + #if __has_attribute(no_sanitize) + #define HDF_NO_UBSAN __attribute__((no_sanitize("undefined"))) + #else + #define HDF_NO_UBSAN + #endif +#else + #define HDF_NO_UBSAN +#endif + #ifdef H5_FP_TO_INTEGER_OVERFLOW_WORKS_TEST -int main(void) +int main(void) HDF_NO_UBSAN { float f = 2147483648.0f; int i; @@ -15,7 +28,7 @@ int main(void) #ifdef H5_FP_TO_ULLONG_ACCURATE_TEST -int main(void) +int main(void) HDF_NO_UBSAN { float f = 111.60f; double d = 222.55L; @@ -35,7 +48,7 @@ int main(void) #endif #ifdef H5_FP_TO_ULLONG_RIGHT_MAXIMUM_TEST -int main(void) +int main(void) HDF_NO_UBSAN { float f = 9701917572145405952.00f; double d1 = 9701917572145405952.00L; @@ -66,7 +79,7 @@ int main(void) #include #include -int main(void) +int main(void) HDF_NO_UBSAN { void *align; long double ld = 9701917572145405952.00L; @@ -90,7 +103,7 @@ int main(void) #endif #ifdef H5_LDOUBLE_TO_LLONG_ACCURATE_TEST -int main(void) +int main(void) HDF_NO_UBSAN { long double ld = 20041683600089727.779961L; long long ll; @@ -131,7 +144,7 @@ int main(void) #endif #ifdef H5_LDOUBLE_TO_UINT_ACCURATE_TEST -int main(void) +int main(void) HDF_NO_UBSAN { long double ld = 2733248032.9183987530L; unsigned int i; @@ -147,7 +160,7 @@ int main(void) #endif #ifdef H5_LLONG_TO_LDOUBLE_CORRECT_TEST -int main(void) +int main(void) HDF_NO_UBSAN { long double ld; long long ll; @@ -213,7 +226,7 @@ int FC_DUMMY_MAIN() #endif #endif int -main () +main () HDF_NO_UBSAN { char *chp = "beefs"; @@ -255,7 +268,7 @@ main () #include #include -int main(void) +int main(void) HDF_NO_UBSAN { /* General variables */ int endian; @@ -331,7 +344,7 @@ int main(void) #ifdef H5_ULONG_TO_FLOAT_ACCURATE_TEST -int main(void) +int main(void) HDF_NO_UBSAN { int ret = 0; unsigned long l1; @@ -366,7 +379,7 @@ int main(void) #include -int main(void) +int main(void) HDF_NO_UBSAN { unsigned long l1; unsigned long l2; diff --git a/ThirdParty/hdf5/vtkhdf5/src/H5detect.c b/ThirdParty/hdf5/vtkhdf5/src/H5detect.c index c202303c215..a21c13ee057 100644 --- a/ThirdParty/hdf5/vtkhdf5/src/H5detect.c +++ b/ThirdParty/hdf5/vtkhdf5/src/H5detect.c @@ -58,6 +58,20 @@ static const char *FileHeader = "\n\ #include "H5Tpublic.h" #include "H5Rpublic.h" +/* This file performs several undefined behaviors, suppress Undefined + * Behavior Sanitizer (UBSan) from warning. + */ +#if defined(__clang__) + #if __has_attribute(no_sanitize) + #define HDF_NO_UBSAN __attribute__((no_sanitize("undefined"))) + #else + #define HDF_NO_UBSAN + #endif +#else + #define HDF_NO_UBSAN +#endif + + #define MAXDETECT 64 /* The ALIGNMENT test code may generate the SIGBUS, SIGSEGV, or SIGILL signals. @@ -1351,7 +1365,7 @@ bit.\n"; *------------------------------------------------------------------------- */ static void -detect_C89_integers(void) +detect_C89_integers(void) HDF_NO_UBSAN { DETECT_BYTE(signed char, SCHAR, d_g[nd_g]); nd_g++; DETECT_BYTE(unsigned char, UCHAR, d_g[nd_g]); nd_g++; @@ -1379,7 +1393,7 @@ detect_C89_integers(void) *------------------------------------------------------------------------- */ static void -detect_C89_floats(void) +detect_C89_floats(void) HDF_NO_UBSAN { DETECT_F(float, FLOAT, d_g[nd_g]); nd_g++; DETECT_F(double, DOUBLE, d_g[nd_g]); nd_g++; @@ -1401,7 +1415,7 @@ detect_C89_floats(void) *------------------------------------------------------------------------- */ static void -detect_C99_integers8(void) +detect_C99_integers8(void) HDF_NO_UBSAN { #if H5_SIZEOF_INT8_T>0 #if H5_SIZEOF_INT8_T==1 @@ -1463,7 +1477,7 @@ detect_C99_integers8(void) *------------------------------------------------------------------------- */ static void -detect_C99_integers16(void) +detect_C99_integers16(void) HDF_NO_UBSAN { #if H5_SIZEOF_INT16_T>0 DETECT_I(int16_t, INT16, d_g[nd_g]); nd_g++; @@ -1501,7 +1515,7 @@ detect_C99_integers16(void) *------------------------------------------------------------------------- */ static void -detect_C99_integers32(void) +detect_C99_integers32(void) HDF_NO_UBSAN { #if H5_SIZEOF_INT32_T>0 DETECT_I(int32_t, INT32, d_g[nd_g]); nd_g++; @@ -1539,7 +1553,7 @@ detect_C99_integers32(void) *------------------------------------------------------------------------- */ static void -detect_C99_integers64(void) +detect_C99_integers64(void) HDF_NO_UBSAN { #if H5_SIZEOF_INT64_T>0 DETECT_I(int64_t, INT64, d_g[nd_g]); nd_g++; @@ -1590,7 +1604,7 @@ detect_C99_integers64(void) *------------------------------------------------------------------------- */ static void -detect_C99_integers(void) +detect_C99_integers(void) HDF_NO_UBSAN { /* break it down to more subroutines so that each module subroutine */ /* is smaller and takes less time to compile with optimization on. */ @@ -1616,7 +1630,7 @@ detect_C99_integers(void) *------------------------------------------------------------------------- */ static void -detect_C99_floats(void) +detect_C99_floats(void) HDF_NO_UBSAN { #if H5_SIZEOF_DOUBLE == H5_SIZEOF_LONG_DOUBLE /* @@ -1647,7 +1661,7 @@ detect_C99_floats(void) *------------------------------------------------------------------------- */ static void -detect_alignments(void) +detect_alignments(void) HDF_NO_UBSAN { /* Detect structure alignment for pointers, hvl_t, hobj_ref_t, hdset_reg_ref_t */ DETECT_M(void *, POINTER, m_g[na_g]); na_g++; @@ -1664,7 +1678,14 @@ detect_alignments(void) * Return 0 for success, -1 for failure. */ static int verify_signal_handlers(int signum, void (*handler)(int)) -{ +{ + /* Under Address Sanitizer, don't raise any signals. */ +#if defined(__has_feature) +#if __has_feature(address_sanitizer) + return 0; +#endif +#endif + void (*save_handler)(int) = HDsignal(signum, handler); int i, val; int ntries=5; @@ -1729,7 +1750,7 @@ static int verify_signal_handlers(int signum, void (*handler)(int)) *------------------------------------------------------------------------- */ int -main(void) +main(void) HDF_NO_UBSAN { #if defined(H5_HAVE_SETSYSINFO) && defined(SSI_NVPAIRS) diff --git a/ThirdParty/libproj4/update.sh b/ThirdParty/libproj4/update.sh index dd130234fd1..8f22cdb497c 100755 --- a/ThirdParty/libproj4/update.sh +++ b/ThirdParty/libproj4/update.sh @@ -14,7 +14,6 @@ AUTHORS ChangeLog cmake/*.cmake cmake/*.cmake.in -cmake/CMakeLists.txt CMakeLists.txt COPYING src/CMakeLists.txt diff --git a/ThirdParty/libproj4/vtklibproj4/.notused b/ThirdParty/libproj4/vtklibproj4/.notused deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/ThirdParty/libproj4/vtklibproj4/CMakeLists.txt b/ThirdParty/libproj4/vtklibproj4/CMakeLists.txt index 040cfb27ada..907f3585c4f 100644 --- a/ThirdParty/libproj4/vtklibproj4/CMakeLists.txt +++ b/ThirdParty/libproj4/vtklibproj4/CMakeLists.txt @@ -86,5 +86,5 @@ include_directories(${PROJ4_SOURCE_DIR}/src) message(STATUS "") add_subdirectory(src) -add_subdirectory(cmake) + diff --git a/ThirdParty/libproj4/vtklibproj4/cmake/CMakeLists.txt b/ThirdParty/libproj4/vtklibproj4/cmake/CMakeLists.txt deleted file mode 100644 index 742da0e9986..00000000000 --- a/ThirdParty/libproj4/vtklibproj4/cmake/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -# proj-config.cmake for the install tree. It's installed in -# ${INSTALL_CMAKE_DIR} and @PROJECT_ROOT_DIR@ is the relative -# path to the root from there. (Note that the whole install tree can -# be relocated.) -if (NOT WIN32) - set (INSTALL_CMAKE_DIR "share/cmake/${PROJECT_NAME}") - set (PROJECT_ROOT_DIR "../../..") -else () - set (INSTALL_CMAKE_DIR "cmake") - set (PROJECT_ROOT_DIR "..") -endif () - -string(TOLOWER "${PROJECT_NAME}" PROJECT_NAME_LOWER) -configure_file (project-config.cmake.in project-config.cmake @ONLY) -configure_file (project-config-version.cmake.in - project-config-version.cmake @ONLY) -install (FILES - "${CMAKE_CURRENT_BINARY_DIR}/project-config.cmake" - DESTINATION "${INSTALL_CMAKE_DIR}" - RENAME "${PROJECT_NAME_LOWER}-config.cmake") -install (FILES - "${CMAKE_CURRENT_BINARY_DIR}/project-config-version.cmake" - DESTINATION "${INSTALL_CMAKE_DIR}" - RENAME "${PROJECT_NAME_LOWER}-config-version.cmake") -# Make information about the cmake targets (the library and the tools) -# available. -install (EXPORT targets - FILE ${PROJECT_NAME_LOWER}-targets.cmake - DESTINATION "${INSTALL_CMAKE_DIR}") diff --git a/ThirdParty/libproj4/vtklibproj4/cmake/Proj4InstallPath.cmake b/ThirdParty/libproj4/vtklibproj4/cmake/Proj4InstallPath.cmake index da1491c0412..36a74aa5950 100644 --- a/ThirdParty/libproj4/vtklibproj4/cmake/Proj4InstallPath.cmake +++ b/ThirdParty/libproj4/vtklibproj4/cmake/Proj4InstallPath.cmake @@ -1,23 +1,6 @@ #---------------------------------------------- # installation path settings #---------------------------------------------- -if(WIN32) - if(DEFINED ENV{OSGEO4W_ROOT}) - set(OSGEO4W_ROOT_DIR $ENV{OSGEO4W_ROOT}) - else() - set(OSGEO4W_ROOT_DIR c:/OSGeo4W) - endif() - set(DEFAULT_PROJ_ROOT_DIR ${OSGEO4W_ROOT_DIR}) -endif() -if(UNIX) - set(DEFAULT_PROJ_ROOT_DIR "/usr/local/") -endif(UNIX) - - -IF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - SET(CMAKE_INSTALL_PREFIX ${DEFAULT_PROJ_ROOT_DIR} CACHE PATH "Foo install - prefix" FORCE) -ENDIF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) #TODO # for data install testing the PROJ_LIB envVar diff --git a/ThirdParty/libproj4/vtklibproj4/src/lib_proj.cmake b/ThirdParty/libproj4/vtklibproj4/src/lib_proj.cmake index dc1eb82e1bb..1ba757f1e8c 100644 --- a/ThirdParty/libproj4/vtklibproj4/src/lib_proj.cmake +++ b/ThirdParty/libproj4/vtklibproj4/src/lib_proj.cmake @@ -255,22 +255,6 @@ if(LIBPROJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT AND BUILD_SH endif(LIBPROJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT AND BUILD_SHARED_LIBS) -############################################## -# install -############################################## -if(NOT VTK_INSTALL_NO_DEVELOPMENT) - install(TARGETS ${PROJ_CORE_TARGET} - EXPORT targets - RUNTIME DESTINATION ${LIBPROJ_BINDIR} - LIBRARY DESTINATION ${VTK_INSTALL_LIBRARY_DIR} - ARCHIVE DESTINATION ${LIBPROJ_LIBDIR} - FRAMEWORK DESTINATION ${FRAMEWORKDIR}) - if(NOT BUILD_FRAMEWORKS_AND_BUNDLE) - install(FILES ${ALL_LIBPROJ_HEADERS} - DESTINATION ${VTK_INSTALL_INCLUDE_DIR}/vtklibproj4) - endif(NOT BUILD_FRAMEWORKS_AND_BUNDLE) -endif(NOT VTK_INSTALL_NO_DEVELOPMENT) - ############################################## # Core configuration summary ############################################## diff --git a/ThirdParty/libxml2/vtklibxml2/include/libxml/SAX.h b/ThirdParty/libxml2/vtklibxml2/include/libxml/SAX.h index 39bcfc66485..e95c12390e7 100644 --- a/ThirdParty/libxml2/vtklibxml2/include/libxml/SAX.h +++ b/ThirdParty/libxml2/vtklibxml2/include/libxml/SAX.h @@ -111,9 +111,6 @@ XMLPUBFUN void XMLCALL XMLPUBFUN void XMLCALL endElement (void *ctx, const xmlChar *name); -XMLPUBFUN void XMLCALL - reference (void *ctx, - const xmlChar *name); XMLPUBFUN void XMLCALL characters (void *ctx, const xmlChar *ch, diff --git a/ThirdParty/libxml2/vtklibxml2/include/libxml/vtk_libxml2_mangle.h b/ThirdParty/libxml2/vtklibxml2/include/libxml/vtk_libxml2_mangle.h index 3050a9f3f61..0bd0ac1b2e8 100644 --- a/ThirdParty/libxml2/vtklibxml2/include/libxml/vtk_libxml2_mangle.h +++ b/ThirdParty/libxml2/vtklibxml2/include/libxml/vtk_libxml2_mangle.h @@ -169,7 +169,6 @@ nm libxml2.a |grep " [TRD] " #define notationDecl vtk_libxml2_notationDecl #define oldXMLWDcompatibility vtk_libxml2_oldXMLWDcompatibility #define processingInstruction vtk_libxml2_processingInstruction -#define reference vtk_libxml2_reference #define resolveEntity vtk_libxml2_resolveEntity #define setDocumentLocator vtk_libxml2_setDocumentLocator #define setNamespace vtk_libxml2_setNamespace diff --git a/ThirdParty/libxml2/vtklibxml2/legacy.c b/ThirdParty/libxml2/vtklibxml2/legacy.c index 817d2ead331..80742af12c8 100644 --- a/ThirdParty/libxml2/vtklibxml2/legacy.c +++ b/ThirdParty/libxml2/vtklibxml2/legacy.c @@ -1154,21 +1154,6 @@ endElement(void *ctx, const xmlChar * name ATTRIBUTE_UNUSED) xmlSAX2EndElement(ctx, name); } -/** - * reference: - * @ctx: the user data (XML parser context) - * @name: The entity name - * - * called when an entity reference is detected. - * DEPRECATED: use xmlSAX2Reference() - */ -void -reference(void *ctx, const xmlChar * name) -{ - DEPRECATED("reference") - xmlSAX2Reference(ctx, name); -} - /** * characters: * @ctx: the user data (XML parser context) diff --git a/ThirdParty/update-common.sh b/ThirdParty/update-common.sh index 6aeeccd1b1d..3b8358e0114 100644 --- a/ThirdParty/update-common.sh +++ b/ThirdParty/update-common.sh @@ -155,8 +155,14 @@ popd if [ -n "$basehash" ]; then git merge --log -s recursive "-Xsubtree=$subtree/" --no-commit "upstream-$name" else + unrelated_histories_flag="" + if git merge --help | grep -q -e allow-unrelated-histories; then + unrelated_histories_flag="--allow-unrelated-histories " + fi + readonly unrelated_histories_flag + git fetch "$extractdir" "upstream-$name:upstream-$name" - git merge --log -s ours --no-commit "upstream-$name" + git merge --log -s ours --no-commit $unrelated_histories_flag "upstream-$name" git read-tree -u --prefix="$subtree/" "upstream-$name" fi git commit --no-edit diff --git a/ThirdParty/xdmf3/CMakeLists.txt b/ThirdParty/xdmf3/CMakeLists.txt index 5c55ce8091e..8e264d184c8 100644 --- a/ThirdParty/xdmf3/CMakeLists.txt +++ b/ThirdParty/xdmf3/CMakeLists.txt @@ -1,5 +1,7 @@ find_package(Boost REQUIRED) include_directories(${Boost_INCLUDE_DIRS}) +set(${vtk-module}_SYSTEM_INCLUDE_DIRS + ${Boost_INCLUDE_DIRS}) vtk_module_third_party(xdmf3 LIBRARIES vtkxdmf3 @@ -18,8 +20,24 @@ endif() ######################################################################### # Set Xdmf build environment options the way VTK wants them - -#? +set(REQUESTED_PYTHON_VERSION ${VTK_PYTHON_VERSION}) +set(XDMF_BUILD_CORE_ONLY OFF CACHE INTERNAL "") +set(XDMF_BUILD_DOCUMENTATION OFF CACHE INTERNAL "") +set(XDMF_BUILD_DSM OFF CACHE INTERNAL "") +set(XDMF_BUILD_TESTING OFF CACHE INTERNAL "") +set(XDMF_BUILD_UTILS OFF CACHE INTERNAL "") +set(XDMF_LIBNAME "vtkxdmf3" CACHE INTERNAL "") +set(XDMF_NO_REALPATH ON CACHE INTERNAL "") +set(XDMF_WRAP_JAVA OFF CACHE INTERNAL "") +set(XDMF_WRAP_PYTHON OFF CACHE INTERNAL "") +set(HDF5_LIBRARIES ${vtkhdf5_LIBRARIES}) +set(HDF5_hdf5_LIBRARY_RELEASE ${vtkhdf5_LIBRARIES}) +set(HDF5_INCLUDE_DIRS ${vtkhdf5_INCLUDE_DIRS}) +set(HDF5_C_INCLUDE_DIR ${vtkhdf5_INCLUDE_DIRS}) +set(HDF5_FOUND TRUE) +set(LIBXML2_LIBRARIES ${vtklibxml2_LIBRARIES}) +set(LIBXML2_INCLUDE_DIR ${vtklibxml2_INCLUDE_DIRS}) +set(LIBXML2_FOUND TRUE) ######################################################################### # Setup cmake to pull the library into place as a vtk module diff --git a/ThirdParty/xdmf3/update.sh b/ThirdParty/xdmf3/update.sh new file mode 100755 index 00000000000..0b385dd8eb1 --- /dev/null +++ b/ThirdParty/xdmf3/update.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash + +set -e +set -x +shopt -s dotglob + +readonly name="xdmf3" +readonly ownership="XDMF Upstream " +readonly subtree="ThirdParty/$name/vtk$name" +readonly repo="git://xdmf.org/Xdmf.git" +readonly tag="master" +readonly paths=" +CMake +CMakeLists.txt +CTestConfig.cmake +Copyright.txt +Xdmf.hpp +XdmfAttribute.cpp +XdmfAttribute.hpp +XdmfAttributeCenter.cpp +XdmfAttributeCenter.hpp +XdmfAttributeType.cpp +XdmfAttributeType.hpp +XdmfConfig.cmake.in +XdmfCurvilinearGrid.cpp +XdmfCurvilinearGrid.hpp +XdmfDomain.cpp +XdmfDomain.hpp +XdmfGeometry.cpp +XdmfGeometry.hpp +XdmfGeometryType.cpp +XdmfGeometryType.hpp +XdmfGraph.cpp +XdmfGraph.hpp +XdmfGrid.cpp +XdmfGrid.hpp +XdmfGridCollection.cpp +XdmfGridCollection.hpp +XdmfGridCollectionType.cpp +XdmfGridCollectionType.hpp +XdmfItemFactory.cpp +XdmfItemFactory.hpp +XdmfMap.cpp +XdmfMap.hpp +XdmfReader.cpp +XdmfReader.hpp +XdmfRectilinearGrid.cpp +XdmfRectilinearGrid.hpp +XdmfRegularGrid.cpp +XdmfRegularGrid.hpp +XdmfSet.cpp +XdmfSet.hpp +XdmfSetType.cpp +XdmfSetType.hpp +XdmfTime.cpp +XdmfTime.hpp +XdmfTopology.cpp +XdmfTopology.hpp +XdmfTopologyType.cpp +XdmfTopologyType.hpp +XdmfUnstructuredGrid.cpp +XdmfUnstructuredGrid.hpp +core/CMakeLists.txt +core/XdmfArray.cpp +core/XdmfArray.hpp +core/XdmfArray.tpp +core/XdmfArrayReference.cpp +core/XdmfArrayReference.hpp +core/XdmfArrayType.cpp +core/XdmfArrayType.hpp +core/XdmfBinaryController.cpp +core/XdmfBinaryController.hpp +core/XdmfConfig.hpp.in +core/XdmfCore.hpp +core/XdmfCoreConfig.hpp.in +core/XdmfCoreItemFactory.cpp +core/XdmfCoreItemFactory.hpp +core/XdmfCoreReader.cpp +core/XdmfCoreReader.hpp +core/XdmfError.cpp +core/XdmfError.hpp +core/XdmfFunction.cpp +core/XdmfFunction.hpp +core/XdmfHDF5Controller.cpp +core/XdmfHDF5Controller.hpp +core/XdmfHDF5Writer.cpp +core/XdmfHDF5Writer.hpp +core/XdmfHeavyDataController.cpp +core/XdmfHeavyDataController.hpp +core/XdmfHeavyDataWriter.cpp +core/XdmfHeavyDataWriter.hpp +core/XdmfInformation.cpp +core/XdmfInformation.hpp +core/XdmfItem.cpp +core/XdmfItem.hpp +core/XdmfItemProperty.cpp +core/XdmfItemProperty.hpp +core/XdmfSharedPtr.hpp +core/XdmfSparseMatrix.cpp +core/XdmfSparseMatrix.hpp +core/XdmfSubset.cpp +core/XdmfSubset.hpp +core/XdmfSystemUtils.cpp +core/XdmfSystemUtils.hpp +core/XdmfVisitor.cpp +core/XdmfVisitor.hpp +core/XdmfWriter.cpp +core/XdmfWriter.hpp +core/loki +core/dsm/CMakeLists.txt +core/dsm/XdmfDSM.hpp +core/dsm/XdmfDSMBuffer.cpp +core/dsm/XdmfDSMBuffer.hpp +core/dsm/XdmfDSMCommMPI.cpp +core/dsm/XdmfDSMCommMPI.hpp +core/dsm/XdmfDSMDriver.cpp +core/dsm/XdmfDSMDriver.hpp +core/dsm/XdmfDSMManager.cpp +core/dsm/XdmfDSMManager.hpp +core/dsm/XdmfHDF5ControllerDSM.cpp +core/dsm/XdmfHDF5ControllerDSM.hpp +core/dsm/XdmfHDF5WriterDSM.cpp +core/dsm/XdmfHDF5WriterDSM.hpp +" + +extract_source () { + git_archive +} + +. "${BASH_SOURCE%/*}/../update-common.sh" diff --git a/ThirdParty/xdmf3/vtkxdmf3/CMake/FindMPI4PY.cmake b/ThirdParty/xdmf3/vtkxdmf3/CMake/FindMPI4PY.cmake new file mode 100644 index 00000000000..dc28ddffa2d --- /dev/null +++ b/ThirdParty/xdmf3/vtkxdmf3/CMake/FindMPI4PY.cmake @@ -0,0 +1,34 @@ +# - FindMPI4PY +# Find mpi4py includes and library +# This module defines: +# MPI4PY_INCLUDE_DIR, where to find mpi4py.h, etc. +# MPI4PY_FOUND + +# https://compacc.fnal.gov/projects/repositories/entry/synergia2/CMake/FindMPI4PY.cmake?rev=c147eafb60728606af4fe7b1b161a660df142e9a + +if(NOT MPI4PY_INCLUDE_DIR) + execute_process(COMMAND + "${PYTHON_EXECUTABLE}" "-c" "import mpi4py; print mpi4py.get_include()" + OUTPUT_VARIABLE MPI4PY_INCLUDE_DIR + RESULT_VARIABLE MPI4PY_COMMAND_RESULT + OUTPUT_STRIP_TRAILING_WHITESPACE) + if(MPI4PY_COMMAND_RESULT) + message("jfa: mpi4py not found") + set(MPI4PY_FOUND FALSE) + else(MPI4PY_COMMAND_RESULT) + if (MPI4PY_INCLUDE_DIR MATCHES "Traceback") + message("jfa: mpi4py matches traceback") + ## Did not successfully include MPI4PY + set(MPI4PY_FOUND FALSE) + else (MPI4PY_INCLUDE_DIR MATCHES "Traceback") + ## successful + set(MPI4PY_FOUND TRUE) + set(MPI4PY_INCLUDE_DIR ${MPI4PY_INCLUDE_DIR} CACHE STRING "mpi4py include path") + endif (MPI4PY_INCLUDE_DIR MATCHES "Traceback") + endif(MPI4PY_COMMAND_RESULT) +else(NOT MPI4PY_INCLUDE_DIR) + set(MPI4PY_FOUND TRUE) +endif(NOT MPI4PY_INCLUDE_DIR) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(MPI4PY DEFAULT_MSG MPI4PY_INCLUDE_DIR) diff --git a/ThirdParty/xdmf3/vtkxdmf3/CMake/TestingSuite/AddTestsJava.cmake b/ThirdParty/xdmf3/vtkxdmf3/CMake/TestingSuite/AddTestsJava.cmake index 8ee75aacdb8..5c7ff37f0ee 100644 --- a/ThirdParty/xdmf3/vtkxdmf3/CMake/TestingSuite/AddTestsJava.cmake +++ b/ThirdParty/xdmf3/vtkxdmf3/CMake/TestingSuite/AddTestsJava.cmake @@ -42,7 +42,7 @@ MACRO(ADD_TEST_JAVA_CLASSPATH cp) SET_PROPERTY(GLOBAL PROPERTY JAVA_TEST_CLASSPATH "${classpath}${sep}${cp}" ) - ENDIF() + ENDIF() ENDMACRO() # Java Add LDPath Macro @@ -56,7 +56,7 @@ MACRO(ADD_TEST_JAVA_LDPATH ld) SET_PROPERTY(GLOBAL PROPERTY JAVA_TEST_LDPATH "${ldpath}${sep}${ld}" ) - ENDIF() + ENDIF() ENDMACRO() # Java Add Path Macro @@ -110,7 +110,7 @@ MACRO(ADD_TEST_JAVA executable) IF("${java_path}" STREQUAL "") SET(java_path ${java_ldpath}) ENDIF() - ENDIF() + ENDIF() SET_CORE("${java_binary_dir}") ADD_TEST(Java${is_core}_${executable}${dup} ${CMAKE_COMMAND} diff --git a/ThirdParty/xdmf3/vtkxdmf3/CMakeLists.txt b/ThirdParty/xdmf3/vtkxdmf3/CMakeLists.txt index 2db7d394e0c..ea2a25ab5e6 100644 --- a/ThirdParty/xdmf3/vtkxdmf3/CMakeLists.txt +++ b/ThirdParty/xdmf3/vtkxdmf3/CMakeLists.txt @@ -12,6 +12,8 @@ if(MSVC10) SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}) endif() +set(XDMF_LIBNAME "Xdmf" CACHE STRING "Name for this xdmf library to avoid collision") +option(BUILD_SHARED_LIBS "Build Shared Libraries" OFF) if(BUILD_SHARED_LIBS) set(LIBTYPE SHARED) set(BUILD_SHARED 1) @@ -22,13 +24,23 @@ configure_file(${CMAKE_CURRENT_SOURCE_DIR}/XdmfConfig.hpp.in ${CMAKE_CURRENT_BINARY_DIR}/XdmfConfig.hpp) +# Enable CMake testing +option(XDMF_BUILD_TESTING "Build Tests" OFF) +if(XDMF_BUILD_TESTING) + enable_testing() + include(CTest) +endif() + include_directories(${CMAKE_CURRENT_SOURCE_DIR}) include_directories(${CMAKE_CURRENT_BINARY_DIR}) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/CMake -# ${CMAKE_SOURCE_DIR}/CMake/TestingSuite ${CMAKE_CURRENT_SOURCE_DIR}/CMake/VersionSuite) +if(XDMF_BUILD_TESTING) + list(APPEND CMAKE_MODULE_PATH + ${CMAKE_CURRENT_SOURCE_DIR}/CMake/TestingSuite) +endif() include(XdmfFunctions) @@ -42,17 +54,10 @@ get_filename_component(CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}" ABSOLUTE) #set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) # Should we build with documentation -#option(XDMF_BUILD_DOCUMENTATION OFF) -#if(XDMF_BUILD_DOCUMENTATION) -# add_subdirectory(doc) -#endif() - -# Enable CMake testing -#option(BUILD_TESTING "Build Tests" OFF) -#if(BUILD_TESTING) -# enable_testing() -# include(CTest) -#endif() +option(XDMF_BUILD_DOCUMENTATION OFF) +if(XDMF_BUILD_DOCUMENTATION) + add_subdirectory(doc) +endif() # Wrapper Setup #option(XDMF_WRAP_PYTHON OFF) @@ -93,8 +98,8 @@ endif() # If we are wrapping python, let's include it in the top level if(XDMF_WRAP_PYTHON) - find_package(PythonInterp ${VTK_PYTHON_VERSION} REQUIRED) - find_package(PythonLibs ${VTK_PYTHON_VERSION} REQUIRED) + find_package(PythonInterp ${REQUESTED_PYTHON_VERSION} REQUIRED) + find_package(PythonLibs ${REQUESTED_PYTHON_VERSION} REQUIRED) if (XDMF_BUILD_DSM) find_package (MPI4PY REQUIRED) if (MPI4PY_FOUND) @@ -291,22 +296,24 @@ if(NOT XDMF_BUILD_CORE_ONLY) XdmfTopologyType XdmfUnstructuredGrid) - add_library(vtkxdmf3 ${LIBTYPE} ${XdmfSources}) + add_library(${XDMF_LIBNAME} ${LIBTYPE} ${XdmfSources}) if(XDMF_BUILD_DSM) - target_link_libraries(vtkxdmf3 XdmfCore XdmfDSM) + target_link_libraries(${XDMF_LIBNAME} XdmfCore XdmfDSM) else() - target_link_libraries(vtkxdmf3 XdmfCore) + target_link_libraries(${XDMF_LIBNAME} XdmfCore) + endif() + if (COMMAND vtk_target_install) + vtk_target_install(${XDMF_LIBNAME}) endif() - vtk_target_install(vtkxdmf3) if(WIN32) if (BUILD_SHARED_LIBS) - set_target_properties(vtkxdmf3 PROPERTIES - DEFINE_SYMBOL vtkxdmf3_EXPORTS) + set_target_properties(${XDMF_LIBNAME} PROPERTIES + DEFINE_SYMBOL XDMF_EXPORTS) endif() if(NOT MSVC10) - set_target_properties(vtkxdmf3 PROPERTIES + set_target_properties(${XDMF_LIBNAME} PROPERTIES PREFIX ../ IMPORT_PREFIX ../ RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} @@ -316,33 +323,33 @@ if(NOT XDMF_BUILD_CORE_ONLY) endif() if(XDMF_WRAP_JAVA) - XDMF_SWIG_JAVA(Xdmf Compiled_XdmfCore_Jar) + XDMF_SWIG_JAVA(${XDMF_LIBNAME} Compiled_XdmfCore_Jar) endif() if(XDMF_WRAP_PYTHON) - XDMF_SWIG_PYTHON(Xdmf XdmfCore XdmfDSM) + XDMF_SWIG_PYTHON(${XDMF_LIBNAME} XdmfCore XdmfDSM) set(XDMF_PYTHON_INSTALL_DIR ${CMAKE_INSTALL_PREFIX}/lib/python/) endif() -# if(BUILD_TESTING) -# add_subdirectory(tests) -# endif() + if(XDMF_BUILD_TESTING) + add_subdirectory(tests) + endif() - #option(XDMF_BUILD_UTILS OFF) - #if(XDMF_BUILD_UTILS) - # add_subdirectory(utils) - #endif() + option(XDMF_BUILD_UTILS OFF) + if(XDMF_BUILD_UTILS) + add_subdirectory(utils) + endif() if(WIN32) - set(XDMF_LIBRARY ${CMAKE_INSTALL_PREFIX}/lib/vtkxdmf3.lib) + set(XDMF_LIBRARY ${CMAKE_INSTALL_PREFIX}/lib/${XDMF_LIBNAME}.lib) endif() if(UNIX) - set(XDMF_LIBRARY ${CMAKE_INSTALL_PREFIX}/lib/libvtkxdmf3.so) + set(XDMF_LIBRARY ${CMAKE_INSTALL_PREFIX}/lib/lib${XDMF_LIBNAME}.so) endif() if(APPLE) - set(XDMF_LIBRARY ${CMAKE_INSTALL_PREFIX}/lib/libvtkxdmf3.dylib) + set(XDMF_LIBRARY ${CMAKE_INSTALL_PREFIX}/lib/lib${XDMF_LIBNAME}.dylib) endif() file(GLOB XdmfHeaders @@ -353,7 +360,7 @@ if(NOT XDMF_BUILD_CORE_ONLY) "${CMAKE_CURRENT_BINARY_DIR}/*.hpp" ) install(FILES ${XdmfHeaders} DESTINATION include) - install(TARGETS vtkxdmf3 + install(TARGETS ${XDMF_LIBNAME} RUNTIME DESTINATION bin LIBRARY DESTINATION lib ARCHIVE DESTINATION lib) diff --git a/ThirdParty/xdmf3/vtkxdmf3/Xdmf.hpp b/ThirdParty/xdmf3/vtkxdmf3/Xdmf.hpp index 10730c6f715..331dda89131 100644 --- a/ThirdParty/xdmf3/vtkxdmf3/Xdmf.hpp +++ b/ThirdParty/xdmf3/vtkxdmf3/Xdmf.hpp @@ -149,13 +149,13 @@ # undef XDMFDSM_TEMPLATE # define XDMFDSM_TEMPLATE extern -# ifdef vtkxdmf3_EXPORTS +# ifdef XDMF_EXPORTS # define XDMF_EXPORT __declspec(dllexport) # define XDMF_TEMPLATE -# else /* vtkxdmf3_EXPORTS */ +# else /* XDMF_EXPORTS */ # define XDMF_EXPORT __declspec(dllimport) # define XDMF_TEMPLATE extern -# endif /* vtkxdmf3_EXPORTS */ +# endif /* XDMF_EXPORTS */ #endif /* Compiler Warnings */ diff --git a/ThirdParty/xdmf3/vtkxdmf3/core/CMakeLists.txt b/ThirdParty/xdmf3/vtkxdmf3/core/CMakeLists.txt index c63a5397412..a733524e936 100644 --- a/ThirdParty/xdmf3/vtkxdmf3/core/CMakeLists.txt +++ b/ThirdParty/xdmf3/vtkxdmf3/core/CMakeLists.txt @@ -155,7 +155,9 @@ add_library(XdmfCore ${LIBTYPE} ${XdmfCoreSources}) link_directories(${XDMF_LIBRARY_DIRS}) target_link_libraries(XdmfCore ${XDMF_LIBRARIES}) -vtk_target_install(XdmfCore) +if (COMMAND vtk_target_install) + vtk_target_install(XdmfCore) +endif() if(WIN32) add_definitions(-D_HDF5USEDLL_ -D_HDF5USEHLDLL_) @@ -211,6 +213,7 @@ install(TARGETS XdmfCore set(XdmfCore_INCLUDE_DIRS ${Boost_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_BINARY_DIR} ${HDF5_INCLUDE_DIR} ${LIBXML2_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} @@ -225,9 +228,9 @@ if(XDMF_BUILD_DSM) add_subdirectory(dsm) endif() -#if(BUILD_TESTING) -# add_subdirectory(tests) -#endif() +if(XDMF_BUILD_TESTING) + add_subdirectory(tests) +endif() set(XDMF_LIBRARIES ${XDMF_LIBRARIES} PARENT_SCOPE) set(XDMF_BINARIES ${XDMF_BINARIES} PARENT_SCOPE) diff --git a/ThirdParty/xdmf3/vtkxdmf3/core/XdmfCoreConfig.hpp.in b/ThirdParty/xdmf3/vtkxdmf3/core/XdmfCoreConfig.hpp.in index 2b15c4b0638..9880a735f8c 100644 --- a/ThirdParty/xdmf3/vtkxdmf3/core/XdmfCoreConfig.hpp.in +++ b/ThirdParty/xdmf3/vtkxdmf3/core/XdmfCoreConfig.hpp.in @@ -32,4 +32,6 @@ # define XDMFSTATIC #endif +#cmakedefine XDMF_NO_REALPATH + #endif /* XDMFCORECONFIG_HPP_ */ diff --git a/ThirdParty/xdmf3/vtkxdmf3/core/XdmfItem.hpp b/ThirdParty/xdmf3/vtkxdmf3/core/XdmfItem.hpp index f95e77aa623..6e80caf42d5 100644 --- a/ThirdParty/xdmf3/vtkxdmf3/core/XdmfItem.hpp +++ b/ThirdParty/xdmf3/vtkxdmf3/core/XdmfItem.hpp @@ -30,7 +30,7 @@ class XdmfInformation; class XdmfVisitor; // Includes -#undef reference //stop VTK's libXM2 mangle of "reference" from causing havoc +#undef reference //stop libXML2 mangle of "reference" from causing havoc #include #include #include diff --git a/ThirdParty/xdmf3/vtkxdmf3/core/XdmfSystemUtils.cpp b/ThirdParty/xdmf3/vtkxdmf3/core/XdmfSystemUtils.cpp index d2c9f1d267d..7f218153278 100644 --- a/ThirdParty/xdmf3/vtkxdmf3/core/XdmfSystemUtils.cpp +++ b/ThirdParty/xdmf3/vtkxdmf3/core/XdmfSystemUtils.cpp @@ -25,6 +25,7 @@ #include #include #include "XdmfSystemUtils.hpp" +#include "XdmfCoreConfig.hpp" #include XdmfSystemUtils::XdmfSystemUtils() @@ -35,6 +36,14 @@ XdmfSystemUtils::~XdmfSystemUtils() { } +#ifdef XDMF_NO_REALPATH +//allows symbolic links +std::string +XdmfSystemUtils::getRealPath(const std::string & path) +{ + return path; +} +#else std::string XdmfSystemUtils::getRealPath(const std::string & path) { @@ -44,5 +53,6 @@ XdmfSystemUtils::getRealPath(const std::string & path) char realPath[PATH_MAX]; char *rp = realpath(ref->path, realPath); xmlFreeURI(ref); - return path; + return std::string(rp); } +#endif diff --git a/ThirdParty/xdmf3/vtkxdmf3/core/dsm/CMakeLists.txt b/ThirdParty/xdmf3/vtkxdmf3/core/dsm/CMakeLists.txt index 842b4716494..b69abf126d4 100644 --- a/ThirdParty/xdmf3/vtkxdmf3/core/dsm/CMakeLists.txt +++ b/ThirdParty/xdmf3/vtkxdmf3/core/dsm/CMakeLists.txt @@ -150,6 +150,6 @@ endif() include_directories(${XdmfCore_INCLUDE_DIRS} ${XdmfDSM_INCLUDE_DIRS}) -if(BUILD_TESTING) +if(XDMF_BUILD_TESTING) add_subdirectory(tests) endif() diff --git a/Utilities/Benchmarks/TimingTests.cxx b/Utilities/Benchmarks/TimingTests.cxx index 35457ea7f14..7a13f452599 100644 --- a/Utilities/Benchmarks/TimingTests.cxx +++ b/Utilities/Benchmarks/TimingTests.cxx @@ -47,6 +47,9 @@ int main( int argc, char *argv[] ) a.TestsToRun.push_back(new volumeTest("Volume", false)); a.TestsToRun.push_back(new volumeTest("VolumeWithShading", true)); + a.TestsToRun.push_back(new depthPeelingTest("DepthPeeling", false)); + a.TestsToRun.push_back(new depthPeelingTest("DepthPeelingWithNormals", true)); + // process them return a.ParseCommandLineArguments(argc, argv); } diff --git a/Utilities/Benchmarks/vtkRenderTimingTests.h b/Utilities/Benchmarks/vtkRenderTimingTests.h index 448ae213146..ab77616d1c6 100644 --- a/Utilities/Benchmarks/vtkRenderTimingTests.h +++ b/Utilities/Benchmarks/vtkRenderTimingTests.h @@ -513,4 +513,133 @@ class volumeTest : public vtkRTTest bool WithShading; }; +/*========================================================================= +Define a test for depth peeling transluscent geometry. +=========================================================================*/ +#include "vtkParametricTorus.h" +#include "vtkParametricFunctionSource.h" +#include "vtkProperty.h" +#include "vtkTransform.h" + +class depthPeelingTest : public vtkRTTest +{ + public: + depthPeelingTest(const char *name, bool withNormals) + : vtkRTTest(name), + WithNormals(withNormals) + { + } + + const char *GetSummaryResultName() { return "subsequent frame time"; } + + const char *GetSecondSummaryResultName() { return "first frame time"; } + + virtual vtkRTTestResult Run(vtkRTTestSequence *ats, + int /*argc*/, char * /* argv */[]) + { + int ures, vres; + ats->GetSequenceNumbers(ures,vres); + + // ------------------------------------------------------------ + // Create surface + // ------------------------------------------------------------ + vtkNew PB; + vtkNew PFS; + PFS->SetParametricFunction(PB.Get()); + if (this->WithNormals == false) + { + PFS->GenerateNormalsOff(); + } + PFS->SetUResolution(ures * 50); + PFS->SetVResolution(vres * 100); + PFS->Update(); + + vtkNew mapper; + mapper->SetInputConnection(PFS->GetOutputPort()); + mapper->SetScalarRange(0.0, 360.0); + + // create a rendering window and renderer + vtkNew ren1; + vtkNew renWindow; + renWindow->SetMultiSamples(0); + renWindow->SetAlphaBitPlanes(1); + renWindow->AddRenderer(ren1.Get()); + + // Setup depth peeling to render an exact scene: + ren1->UseDepthPeelingOn(); + ren1->SetMaximumNumberOfPeels(100); + ren1->SetOcclusionRatio(0.); + + // Create a set of 10 colored translucent actors at slight offsets: + const int NUM_ACTORS = 10; + const unsigned char colors[NUM_ACTORS][4] = { { 255, 0, 0, 32 }, + { 0, 255, 0, 32 }, + { 0, 0, 255, 32 }, + { 128, 128, 0, 32 }, + { 0, 128, 128, 32 }, + { 128, 0, 128, 32 }, + { 128, 64, 64, 32 }, + { 64, 128, 64, 32 }, + { 64, 64, 128, 32 }, + { 64, 64, 64, 32 } }; + + for (int i = 0; i < NUM_ACTORS; ++i) + { + vtkNew actor; + actor->SetMapper(mapper.Get()); + actor->GetProperty()->SetColor(colors[i][0] / 255., + colors[i][1] / 255., + colors[i][2] / 255.); + actor->GetProperty()->SetOpacity(colors[i][3] / 255.); + + vtkNew xform; + xform->Identity(); + xform->RotateX(i * (180. / static_cast(NUM_ACTORS))); + actor->SetUserTransform(xform.Get()); + + ren1->AddActor(actor.Get()); + } + + // set the size/color of our window + renWindow->SetSize(500, 500); + ren1->SetBackground(0.2, 0.3, 0.5); + + // draw the resulting scene + double startTime = vtkTimerLog::GetUniversalTime(); + renWindow->Render(); + double firstFrameTime = vtkTimerLog::GetUniversalTime() - startTime; + ren1->GetActiveCamera()->Azimuth(90); + ren1->ResetCameraClippingRange(); + + int frameCount = 80; + for (int i = 0; i < frameCount; i++) + { + renWindow->Render(); + ren1->GetActiveCamera()->Azimuth(1); + ren1->GetActiveCamera()->Elevation(1); + if ((vtkTimerLog::GetUniversalTime() - startTime - firstFrameTime) > + this->TargetTime * 1.5) + { + frameCount = i + 1; + break; + } + } + double subsequentFrameTime = (vtkTimerLog::GetUniversalTime() - startTime - + firstFrameTime) / frameCount; + double numTris = PFS->GetOutput()->GetPolys()->GetNumberOfCells(); + numTris *= NUM_ACTORS; + + vtkRTTestResult result; + result.Results["first frame time"] = firstFrameTime; + result.Results["subsequent frame time"] = subsequentFrameTime; + result.Results["FPS"] = 1. / subsequentFrameTime; + result.Results["triangles"] = numTris; + + return result; + } + + protected: + bool WithNormals; +}; + #endif diff --git a/Utilities/DICOMParser/DICOMAppHelper.cxx b/Utilities/DICOMParser/DICOMAppHelper.cxx index 3e12087c966..d3954b63e68 100644 --- a/Utilities/DICOMParser/DICOMAppHelper.cxx +++ b/Utilities/DICOMParser/DICOMAppHelper.cxx @@ -705,7 +705,7 @@ void DICOMAppHelper::TransferSyntaxCallback(DICOMParser *parser, { #ifdef DEBUG_DICOM_APP_HELPER -#ifdef WIN32 +#ifdef _WIN32 char platformByteOrder = 'L'; #else char platformByteOrder = 'B'; diff --git a/Utilities/Doxygen/doc_index.stop b/Utilities/Doxygen/doc_index.stop index 3fa4be2d175..800357ca78c 100644 --- a/Utilities/Doxygen/doc_index.stop +++ b/Utilities/Doxygen/doc_index.stop @@ -727,5 +727,3 @@ ymax ymin zmax zmin -ETX -BTX \ No newline at end of file diff --git a/Utilities/Doxygen/doc_readme.txt b/Utilities/Doxygen/doc_readme.txt index 100ea0e7013..3a10b9292de 100644 --- a/Utilities/Doxygen/doc_readme.txt +++ b/Utilities/Doxygen/doc_readme.txt @@ -28,7 +28,7 @@ process. Thus, you might browse or download a pre-built documentation here: Nevertheless, Doxygen might still be useful to generate additional PDF, Postscript or plain LaTeX output. -This package is made of he following Perl scripts: +This package is made of the following Perl scripts: - doc_header2doxygen.pl: convert the VTK headers to the Doxygen format - doc_version.pl: extract the VTK version and add it to the documentation set diff --git a/Utilities/EncodeString/vtkEncodeString.cxx b/Utilities/EncodeString/vtkEncodeString.cxx index 00a7d23b957..d3d3c5e10bf 100644 --- a/Utilities/EncodeString/vtkEncodeString.cxx +++ b/Utilities/EncodeString/vtkEncodeString.cxx @@ -91,7 +91,7 @@ class Output { } Output(const Output&); - void operator=(const Output&); + Output& operator=(const Output&); ~Output() { } diff --git a/Utilities/KWSys/vtksys/CommandLineArguments.cxx b/Utilities/KWSys/vtksys/CommandLineArguments.cxx index 36368368bf5..f713294da0e 100644 --- a/Utilities/KWSys/vtksys/CommandLineArguments.cxx +++ b/Utilities/KWSys/vtksys/CommandLineArguments.cxx @@ -20,6 +20,7 @@ #if 0 # include "CommandLineArguments.hxx.in" # include "Configure.hxx.in" +# include "String.hxx.in" #endif #include diff --git a/Utilities/KWSys/vtksys/Configure.h.in b/Utilities/KWSys/vtksys/Configure.h.in index 70cf8442beb..cd2d965199f 100644 --- a/Utilities/KWSys/vtksys/Configure.h.in +++ b/Utilities/KWSys/vtksys/Configure.h.in @@ -115,6 +115,11 @@ # pragma warning (disable: 4710) /* function not inlined */ # pragma warning (disable: 4786) /* identifier truncated in debug info */ # endif +# if defined(__BORLANDC__) && !defined(__cplusplus) + /* Code has no effect; raised by winnt.h in C (not C++) when ignoring an + unused parameter using "(param)" syntax (i.e. no cast to void). */ +# pragma warn -8019 +# endif #endif /* MSVC 6.0 in release mode will warn about code it produces with its diff --git a/Utilities/KWSys/vtksys/FStream.cxx b/Utilities/KWSys/vtksys/FStream.cxx index 018652c84e7..5a30997d670 100644 --- a/Utilities/KWSys/vtksys/FStream.cxx +++ b/Utilities/KWSys/vtksys/FStream.cxx @@ -34,6 +34,7 @@ BOM ReadBOM(std::istream& in) in.read(reinterpret_cast(bom), 2); if(!in.good()) { + in.clear(); in.seekg(orig); return BOM_None; } @@ -68,6 +69,7 @@ BOM ReadBOM(std::istream& in) in.seekg(p); return BOM_UTF16LE; } + in.clear(); in.seekg(orig); return BOM_None; } diff --git a/Utilities/KWSys/vtksys/MD5.c b/Utilities/KWSys/vtksys/MD5.c index a1470572d7a..b75acb2f09e 100644 --- a/Utilities/KWSys/vtksys/MD5.c +++ b/Utilities/KWSys/vtksys/MD5.c @@ -29,7 +29,7 @@ it in a single source file instead of a separate header and implementation file. */ -#if defined(__clang__) +#if defined(__clang__) && !defined(__INTEL_COMPILER) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wcast-align" #endif @@ -254,7 +254,7 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ #define F(x, y, z) (((x) & (y)) | (~(x) & (z))) #define SET(a, b, c, d, k, s, Ti)\ - t = a + F(b,c,d) + X[k] + Ti;\ + t = a + F(b,c,d) + X[k] + (Ti);\ a = ROTATE_LEFT(t, s) + b /* Do the following 16 operations. */ SET(a, b, c, d, 0, 7, T1); @@ -280,7 +280,7 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ #define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) #define SET(a, b, c, d, k, s, Ti)\ - t = a + G(b,c,d) + X[k] + Ti;\ + t = a + G(b,c,d) + X[k] + (Ti);\ a = ROTATE_LEFT(t, s) + b /* Do the following 16 operations. */ SET(a, b, c, d, 1, 5, T17); @@ -306,7 +306,7 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ #define H(x, y, z) ((x) ^ (y) ^ (z)) #define SET(a, b, c, d, k, s, Ti)\ - t = a + H(b,c,d) + X[k] + Ti;\ + t = a + H(b,c,d) + X[k] + (Ti);\ a = ROTATE_LEFT(t, s) + b /* Do the following 16 operations. */ SET(a, b, c, d, 5, 4, T33); @@ -332,7 +332,7 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ #define I(x, y, z) ((y) ^ ((x) | ~(z))) #define SET(a, b, c, d, k, s, Ti)\ - t = a + I(b,c,d) + X[k] + Ti;\ + t = a + I(b,c,d) + X[k] + (Ti);\ a = ROTATE_LEFT(t, s) + b /* Do the following 16 operations. */ SET(a, b, c, d, 0, 6, T49); @@ -433,7 +433,7 @@ static void md5_finish(md5_state_t *pms, md5_byte_t digest[16]) digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); } -#if defined(__clang__) +#if defined(__clang__) && !defined(__INTEL_COMPILER) # pragma clang diagnostic pop #endif diff --git a/Utilities/KWSys/vtksys/ProcessUNIX.c b/Utilities/KWSys/vtksys/ProcessUNIX.c index b0ddf5a1382..74029553b61 100644 --- a/Utilities/KWSys/vtksys/ProcessUNIX.c +++ b/Utilities/KWSys/vtksys/ProcessUNIX.c @@ -505,6 +505,8 @@ void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout) { cp->Timeout = 0; } + // Force recomputation of TimeoutTime. + cp->TimeoutTime.tv_sec = -1; } /*--------------------------------------------------------------------------*/ @@ -1595,12 +1597,12 @@ static void kwsysProcessVolatileFree(volatile void* p) { /* clang has made it impossible to free memory that points to volatile without first using special pragmas to disable a warning... */ -#if defined(__clang__) +#if defined(__clang__) && !defined(__INTEL_COMPILER) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wcast-qual" #endif free((void*)p); /* The cast will silence most compilers, but not clang. */ -#if defined(__clang__) +#if defined(__clang__) && !defined(__INTEL_COMPILER) # pragma clang diagnostic pop #endif } diff --git a/Utilities/KWSys/vtksys/ProcessWin32.c b/Utilities/KWSys/vtksys/ProcessWin32.c index 1f8749fbeaf..a18ea2748ff 100644 --- a/Utilities/KWSys/vtksys/ProcessWin32.c +++ b/Utilities/KWSys/vtksys/ProcessWin32.c @@ -17,7 +17,7 @@ duplicate the above list of headers. */ #if 0 # include "Process.h.in" -# include "Encoding_c.h.in" +# include "Encoding.h.in" #endif /* @@ -698,6 +698,8 @@ void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout) { cp->Timeout = 0; } + // Force recomputation of TimeoutTime. + cp->TimeoutTime.QuadPart = -1; } /*--------------------------------------------------------------------------*/ diff --git a/Utilities/KWSys/vtksys/SharedForward.h.in b/Utilities/KWSys/vtksys/SharedForward.h.in index f22fa580a21..f80ef84703d 100644 --- a/Utilities/KWSys/vtksys/SharedForward.h.in +++ b/Utilities/KWSys/vtksys/SharedForward.h.in @@ -74,6 +74,12 @@ # endif #endif +#if defined(__BORLANDC__) && !defined(__cplusplus) + /* Code has no effect; raised by winnt.h in C (not C++) when ignoring an + unused parameter using "(param)" syntax (i.e. no cast to void). */ +# pragma warn -8019 +#endif + /*--------------------------------------------------------------------------*/ /* Full path to the directory in which this executable is built. Do diff --git a/Utilities/KWSys/vtksys/SystemInformation.cxx b/Utilities/KWSys/vtksys/SystemInformation.cxx index cddcc8dcb6e..1d8723cbaa5 100644 --- a/Utilities/KWSys/vtksys/SystemInformation.cxx +++ b/Utilities/KWSys/vtksys/SystemInformation.cxx @@ -43,7 +43,6 @@ #if 0 # include "SystemInformation.hxx.in" # include "Process.h.in" -# include "Configure.hxx.in" #endif #include @@ -177,13 +176,13 @@ typedef struct rlimit ResourceLimitType; # if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG) # define iostreamLongLong(x) (x) # else -# define iostreamLongLong(x) ((long)x) +# define iostreamLongLong(x) ((long)(x)) # endif #elif defined(KWSYS_USE___INT64) # if defined(KWSYS_IOS_HAS_OSTREAM___INT64) # define iostreamLongLong(x) (x) # else -# define iostreamLongLong(x) ((long)x) +# define iostreamLongLong(x) ((long)(x)) # endif #else # error "No Long Long" @@ -861,7 +860,7 @@ void SystemInformation::RunMemoryCheck() // -------------------------------------------------------------- // SystemInformationImplementation starts here -#define STORE_TLBCACHE_INFO(x,y) x = (x < y) ? y : x +#define STORE_TLBCACHE_INFO(x,y) x = (x < (y)) ? (y) : x #define TLBCACHE_INFO_UNITS (15) #define CLASSICAL_CPU_FREQ_LOOP 10000000 #define RDTSC_INSTRUCTION _asm _emit 0x0f _asm _emit 0x31 @@ -3570,33 +3569,44 @@ SystemInformationImplementation::GetHostMemoryUsed() return (statex.ullTotalPhys - statex.ullAvailPhys)/1024; # endif #elif defined(__linux) - const char *names[3]={"MemTotal:","MemFree:",NULL}; - SystemInformation::LongLong values[2]={SystemInformation::LongLong(0)}; - int ierr=GetFieldsFromFile("/proc/meminfo",names,values); + // First try to use MemAvailable, but it only works on newer kernels + const char *names2[3]={"MemTotal:","MemAvailable:",NULL}; + SystemInformation::LongLong values2[2]={SystemInformation::LongLong(0)}; + int ierr=GetFieldsFromFile("/proc/meminfo",names2,values2); if (ierr) { - return ierr; - } - SystemInformation::LongLong &memTotal=values[0]; - SystemInformation::LongLong &memFree=values[1]; - return memTotal - memFree; + const char *names4[5]={"MemTotal:","MemFree:","Buffers:","Cached:",NULL}; + SystemInformation::LongLong values4[4]={SystemInformation::LongLong(0)}; + ierr=GetFieldsFromFile("/proc/meminfo",names4,values4); + if(ierr) + { + return ierr; + } + SystemInformation::LongLong &memTotal=values4[0]; + SystemInformation::LongLong &memFree=values4[1]; + SystemInformation::LongLong &memBuffers=values4[2]; + SystemInformation::LongLong &memCached=values4[3]; + return memTotal - memFree - memBuffers - memCached; + } + SystemInformation::LongLong &memTotal=values2[0]; + SystemInformation::LongLong &memAvail=values2[1]; + return memTotal - memAvail; #elif defined(__APPLE__) SystemInformation::LongLong psz=getpagesize(); if (psz<1) { return -1; } - const char *names[4]={"Pages active:","Pages inactive:","Pages wired down:",NULL}; - SystemInformation::LongLong values[3]={SystemInformation::LongLong(0)}; + const char *names[3]={"Pages wired down:","Pages active:",NULL}; + SystemInformation::LongLong values[2]={SystemInformation::LongLong(0)}; int ierr=GetFieldsFromCommand("vm_stat", names, values); if (ierr) { return -1; } - SystemInformation::LongLong &vmActive=values[0]; - SystemInformation::LongLong &vmInactive=values[1]; - SystemInformation::LongLong &vmWired=values[2]; - return ((vmActive+vmInactive+vmWired)*psz)/1024; + SystemInformation::LongLong &vmWired=values[0]; + SystemInformation::LongLong &vmActive=values[1]; + return ((vmActive+vmWired)*psz)/1024; #else return 0; #endif @@ -4622,7 +4632,7 @@ std::string SystemInformationImplementation::RunProcess(std::vector double timeout = 255; int pipe; // pipe id as returned by kwsysProcess_WaitForData() - while( ( pipe = kwsysProcess_WaitForData(gp,&data,&length,&timeout), + while( ( static_cast(pipe = kwsysProcess_WaitForData(gp,&data,&length,&timeout)), (pipe == kwsysProcess_Pipe_STDOUT || pipe == kwsysProcess_Pipe_STDERR) ) ) // wait for 1s { buffer.append(data, length); diff --git a/Utilities/KWSys/vtksys/SystemTools.cxx b/Utilities/KWSys/vtksys/SystemTools.cxx index 82087f0608d..0c7f4194f4d 100644 --- a/Utilities/KWSys/vtksys/SystemTools.cxx +++ b/Utilities/KWSys/vtksys/SystemTools.cxx @@ -35,10 +35,12 @@ #include #include #include +#include // Work-around CMake dependency scanning limitation. This must // duplicate the above list of headers. #if 0 +# include "RegularExpression.hxx.in" # include "SystemTools.hxx.in" # include "Directory.hxx.in" # include "FStream.hxx.in" @@ -87,6 +89,7 @@ // Windows API. #if defined(_WIN32) # include +# include # ifndef INVALID_FILE_ATTRIBUTES # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) # endif @@ -2754,6 +2757,106 @@ std::string SystemTools::GetLastSystemError() return strerror(e); } +#ifdef _WIN32 + +static bool IsJunction(const std::wstring& source) +{ +#ifdef FSCTL_GET_REPARSE_POINT + const DWORD JUNCTION_ATTRS = FILE_ATTRIBUTE_DIRECTORY | + FILE_ATTRIBUTE_REPARSE_POINT; + DWORD attrs = GetFileAttributesW(source.c_str()); + if (attrs == INVALID_FILE_ATTRIBUTES) + { + return false; + } + if ((attrs & JUNCTION_ATTRS) != JUNCTION_ATTRS) + { + return false; + } + + // Adjust privileges so that we can succefully open junction points. + HANDLE token; + TOKEN_PRIVILEGES privs; + OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token); + LookupPrivilegeValue(NULL, SE_BACKUP_NAME, &privs.Privileges[0].Luid); + privs.PrivilegeCount = 1; + privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL, NULL); + CloseHandle(token); + + HANDLE dir = CreateFileW(source.c_str(), GENERIC_READ, + 0, NULL, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL); + if (dir == INVALID_HANDLE_VALUE) + { + return false; + } + + // Query whether this is a reparse point or not. + BYTE buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; + REPARSE_GUID_DATA_BUFFER *reparse_buffer = + (REPARSE_GUID_DATA_BUFFER*) buffer; + DWORD sentinel; + + BOOL success = DeviceIoControl( + dir, FSCTL_GET_REPARSE_POINT, + NULL, 0, + reparse_buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, + &sentinel, NULL); + + CloseHandle(dir); + + return (success && (reparse_buffer->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)); +#else + return false; +#endif +} + +static bool DeleteJunction(const std::wstring& source) +{ +#ifdef FSCTL_DELETE_REPARSE_POINT + // Adjust privileges so that we can succefully open junction points as + // read/write. + HANDLE token; + TOKEN_PRIVILEGES privs; + OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token); + LookupPrivilegeValue(NULL, SE_RESTORE_NAME, &privs.Privileges[0].Luid); + privs.PrivilegeCount = 1; + privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; + AdjustTokenPrivileges(token, FALSE, &privs, sizeof(TOKEN_PRIVILEGES), NULL, NULL); + CloseHandle(token); + + HANDLE dir = CreateFileW(source.c_str(), GENERIC_READ | GENERIC_WRITE, + 0, NULL, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL); + if (dir == INVALID_HANDLE_VALUE) + { + return false; + } + + // Set up the structure so that we can delete the junction. + std::vector buffer(REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, 0); + REPARSE_GUID_DATA_BUFFER *reparse_buffer = + (REPARSE_GUID_DATA_BUFFER*) &buffer[0]; + DWORD sentinel; + + reparse_buffer->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; + + BOOL success = DeviceIoControl( + dir, FSCTL_DELETE_REPARSE_POINT, + reparse_buffer, REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, + NULL, 0, + &sentinel, NULL); + + CloseHandle(dir); + + return !!success; +#else + return false; +#endif +} +#endif + bool SystemTools::RemoveFile(const std::string& source) { #ifdef _WIN32 @@ -2781,6 +2884,10 @@ bool SystemTools::RemoveFile(const std::string& source) SetLastError(err); return false; } + if (IsJunction(ws) && !DeleteJunction(ws)) + { + return false; + } if (DeleteFileW(ws.c_str()) || GetLastError() == ERROR_FILE_NOT_FOUND || GetLastError() == ERROR_PATH_NOT_FOUND) @@ -4491,36 +4598,27 @@ bool SystemTools::FileIsFullPath(const char* in_name, size_t len) bool SystemTools::GetShortPath(const std::string& path, std::string& shortPath) { #if defined(_WIN32) && !defined(__CYGWIN__) - const int size = int(path.size()) +1; // size of return - char *tempPath = new char[size]; // create a buffer - DWORD ret; + std::string tempPath = path; // create a buffer // if the path passed in has quotes around it, first remove the quotes if (!path.empty() && path[0] == '"' && *path.rbegin() == '"') { - strcpy(tempPath,path.c_str()+1); - tempPath[size-2] = '\0'; - } - else - { - strcpy(tempPath,path.c_str()); + tempPath = path.substr(1, path.length()-2); } std::wstring wtempPath = Encoding::ToWide(tempPath); - std::vector buffer(wtempPath.size()+1); - buffer[0] = 0; + DWORD ret = GetShortPathNameW(wtempPath.c_str(), NULL, 0); + std::vector buffer(ret); ret = GetShortPathNameW(wtempPath.c_str(), - &buffer[0], static_cast(wtempPath.size())); + &buffer[0], static_cast(buffer.size())); - if(buffer[0] == 0 || ret > wtempPath.size()) + if (ret == 0) { - delete [] tempPath; return false; } else { shortPath = Encoding::ToNarrow(&buffer[0]); - delete [] tempPath; return true; } #else @@ -4660,8 +4758,9 @@ bool SystemTools::GetLineFromStream(std::istream& is, // been reached. Clear the fail bit just before reading. while(!haveNewline && leftToRead != 0 && - (is.clear(is.rdstate() & ~std::ios::failbit), - is.getline(buffer, bufferSize), is.gcount() > 0)) + (static_cast(is.clear(is.rdstate() & ~std::ios::failbit)), + static_cast(is.getline(buffer, bufferSize)), + is.gcount() > 0)) { // We have read at least one byte. haveData = true; diff --git a/Utilities/KWSys/vtksys/testDynamicLoader.cxx b/Utilities/KWSys/vtksys/testDynamicLoader.cxx index 695a134d24d..7c58769695d 100644 --- a/Utilities/KWSys/vtksys/testDynamicLoader.cxx +++ b/Utilities/KWSys/vtksys/testDynamicLoader.cxx @@ -53,7 +53,7 @@ static std::string GetLibName(const char* lname) * r2: should GetSymbolAddress succeed ? * r3: should CloseLibrary succeed ? */ -int TestDynamicLoader(const char* libname, const char* symbol, int r1, int r2, int r3) +static int TestDynamicLoader(const char* libname, const char* symbol, int r1, int r2, int r3) { std::cerr << "Testing: " << libname << std::endl; kwsys::DynamicLoader::LibraryHandle l diff --git a/Utilities/KWSys/vtksys/testFStream.cxx b/Utilities/KWSys/vtksys/testFStream.cxx index ac5220ac06b..5e537258f80 100644 --- a/Utilities/KWSys/vtksys/testFStream.cxx +++ b/Utilities/KWSys/vtksys/testFStream.cxx @@ -41,8 +41,13 @@ static int testNoFile() return 0; } -static kwsys::FStream::BOM expected_bom[5] = +static const int num_test_files = 7; +static const int max_test_file_size = 45; + +static kwsys::FStream::BOM expected_bom[num_test_files] = { + kwsys::FStream::BOM_None, + kwsys::FStream::BOM_None, kwsys::FStream::BOM_UTF8, kwsys::FStream::BOM_UTF16LE, kwsys::FStream::BOM_UTF16BE, @@ -50,8 +55,10 @@ static kwsys::FStream::BOM expected_bom[5] = kwsys::FStream::BOM_UTF32BE }; -static unsigned char expected_bom_data[5][5] = +static unsigned char expected_bom_data[num_test_files][5] = { + {0}, + {0}, {3, 0xEF, 0xBB, 0xBF}, {2, 0xFF, 0xFE}, {2, 0xFE, 0xFF}, @@ -59,8 +66,10 @@ static unsigned char expected_bom_data[5][5] = {4, 0x00, 0x00, 0xFE, 0xFF}, }; -static unsigned char file_data[5][45] = +static unsigned char file_data[num_test_files][max_test_file_size] = { + {1, 'H'}, + {11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}, {11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}, {22, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x20, 0x00, 0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64, 0x00}, @@ -80,7 +89,7 @@ static unsigned char file_data[5][45] = static int testBOM() { // test various encodings in binary mode - for(int i=0; i<5; i++) + for(int i=0; i(expected_bom_data[0]+1), - *expected_bom_data[0]); - out << "Hello World"; - } - - kwsys::ifstream in("bom.txt"); - kwsys::FStream::BOM bom = kwsys::FStream::ReadBOM(in); - if(bom != kwsys::FStream::BOM_UTF8) - { - std::cout << "Unexpected BOM for utf-8 case" << std::endl; - return 1; - } - char data[45]; - in.read(data, file_data[0][0]); - if(!in.good()) - { - std::cout << "Unable to read data for utf-8 case" << std::endl; - return 1; - } - - if(memcmp(data, file_data[0]+1, file_data[0][0]) != 0) - { - std::cout << "Incorrect read data for utf-8 case" << std::endl; - return 1; - } - } - return 0; } diff --git a/Utilities/KWSys/vtksys/testHashSTL.cxx b/Utilities/KWSys/vtksys/testHashSTL.cxx index ab1f83e7802..ae66cebead0 100644 --- a/Utilities/KWSys/vtksys/testHashSTL.cxx +++ b/Utilities/KWSys/vtksys/testHashSTL.cxx @@ -18,7 +18,6 @@ #if 0 # include "hash_map.hxx.in" # include "hash_set.hxx.in" -# include "hashtable.hxx.in" #endif #include diff --git a/Utilities/KWSys/vtksys/testIOS.cxx b/Utilities/KWSys/vtksys/testIOS.cxx index 396a09d47d0..5ff7955bfa7 100644 --- a/Utilities/KWSys/vtksys/testIOS.cxx +++ b/Utilities/KWSys/vtksys/testIOS.cxx @@ -18,6 +18,12 @@ #include #include /* strlen */ +// Work-around CMake dependency scanning limitation. This must +// duplicate the above list of headers. +#if 0 +# include "Configure.hxx.in" +#endif + int testIOS(int, char*[]) { std::ostringstream ostr; diff --git a/Utilities/MetaIO/vtkmetaio/localMetaConfiguration.h b/Utilities/MetaIO/vtkmetaio/localMetaConfiguration.h index 48df5f6ec66..edb39df4348 100644 --- a/Utilities/MetaIO/vtkmetaio/localMetaConfiguration.h +++ b/Utilities/MetaIO/vtkmetaio/localMetaConfiguration.h @@ -55,7 +55,7 @@ #include #include - #if (defined(_WIN32) || defined(WIN32)) && defined(vtkmetaio_BUILD_SHARED_LIBS) + #if defined(_WIN32) && defined(vtkmetaio_BUILD_SHARED_LIBS) #ifdef vtkmetaio_EXPORTS #define METAIO_EXPORT __declspec(dllexport) #define METAIO_EXTERN diff --git a/Utilities/ParseOGLExt/ParseOGLExt.cxx b/Utilities/ParseOGLExt/ParseOGLExt.cxx index 3672f26c98d..9654ee3d324 100644 --- a/Utilities/ParseOGLExt/ParseOGLExt.cxx +++ b/Utilities/ParseOGLExt/ParseOGLExt.cxx @@ -76,7 +76,7 @@ class Extension { switch (itype) { case WGL: - out << "#ifdef WIN32" << endl; + out << "#ifdef _WIN32" << endl; break; case GLX: out << "#ifdef VTK_USE_X" << endl; diff --git a/Utilities/Python/vtkPython.h b/Utilities/Python/vtkPython.h index 3a656f802d8..4053e99c49c 100644 --- a/Utilities/Python/vtkPython.h +++ b/Utilities/Python/vtkPython.h @@ -87,7 +87,7 @@ they are system headers. Do NOT add any #undef lines here. */ #endif #ifdef VTK_PYTHON_UNDEF_DEBUG -# define _DEBUG +# define _DEBUG 1 # undef VTK_PYTHON_UNDEF_DEBUG #endif diff --git a/Utilities/PythonInterpreter/vtkPythonInteractiveInterpreter.h b/Utilities/PythonInterpreter/vtkPythonInteractiveInterpreter.h index c80a6855cd9..a71e7a50965 100644 --- a/Utilities/PythonInterpreter/vtkPythonInteractiveInterpreter.h +++ b/Utilities/PythonInterpreter/vtkPythonInteractiveInterpreter.h @@ -76,7 +76,6 @@ class VTKPYTHONINTERPRETER_EXPORT vtkPythonInteractiveInterpreter : public vtkOb void* GetInteractiveConsolePyObject(); void* GetInteractiveConsoleLocalsPyObject(); -//BTX protected: vtkPythonInteractiveInterpreter(); ~vtkPythonInteractiveInterpreter(); @@ -89,7 +88,7 @@ class VTKPYTHONINTERPRETER_EXPORT vtkPythonInteractiveInterpreter : public vtkOb class vtkInternals; vtkInternals* Internals; -//ETX + }; #endif diff --git a/Utilities/PythonInterpreter/vtkPythonInterpreter.h b/Utilities/PythonInterpreter/vtkPythonInterpreter.h index e8b9d744527..70175fe38f0 100644 --- a/Utilities/PythonInterpreter/vtkPythonInterpreter.h +++ b/Utilities/PythonInterpreter/vtkPythonInterpreter.h @@ -113,7 +113,6 @@ class VTKPYTHONINTERPRETER_EXPORT vtkPythonInterpreter : public vtkObject static void SetCaptureStdin(bool); static bool GetCaptureStdin(); -//BTX protected: vtkPythonInterpreter(); ~vtkPythonInterpreter(); @@ -142,7 +141,7 @@ class VTKPYTHONINTERPRETER_EXPORT vtkPythonInterpreter : public vtkObject // Accumulate here output printed to console by the python interpreter. static std::string StdErrBuffer; static std::string StdOutBuffer; -//ETX + }; #endif diff --git a/Utilities/Upgrading/README.WindowsMangling.txt b/Utilities/Upgrading/README.WindowsMangling.txt index b2f9aacdb41..432b6676d21 100644 --- a/Utilities/Upgrading/README.WindowsMangling.txt +++ b/Utilities/Upgrading/README.WindowsMangling.txt @@ -89,10 +89,8 @@ of whether windows.h has been included before it: #ifdef VTK_WORKAROUND_WINDOWS_MANGLE # undef GetClassNameW # undef GetClassNameA - //BTX const char* GetClassNameA() const; const char* GetClassNameW() const; - //ETX #endif The method GetClassName has three cases. If windows.h is not included @@ -103,9 +101,7 @@ preprocessor will not recursively expand a macro, so replacement stops there and the GetClassName method is declared. When UNICODE is defined the same process occurs but through GetClassNameW instead. The methods GetClassNameA and GetClassNameW are not mangled so they -can be provided directly. They are surrounded by a BTX/ETX pair -because they should not be wrapped since scripting language code will -not be mangled by windows.h. +can be provided directly. Now that all three names are provided we can address the fact that GetClassName is supposed to be a virtual function. When a subclass diff --git a/Views/Context2D/vtkContextInteractorStyle.h b/Views/Context2D/vtkContextInteractorStyle.h index 97b748ac5ee..558c791a6b4 100644 --- a/Views/Context2D/vtkContextInteractorStyle.h +++ b/Views/Context2D/vtkContextInteractorStyle.h @@ -12,12 +12,12 @@ PURPOSE. See the above copyright notice for more information. =========================================================================*/ -// .NAME vtkContextInteractorStyle - An interactor for chart views +// .NAME vtkContextInteractorStyle - An interactor for chart views. +// +// .SECTION Description // It observes the user events (mouse events) and propagates them // to the scene. If the scene doesn't eat the event, it is propagated // to the interactor style superclass. -// -// .SECTION Description #ifndef vtkContextInteractorStyle_h #define vtkContextInteractorStyle_h diff --git a/Views/Core/vtkConvertSelectionDomain.cxx b/Views/Core/vtkConvertSelectionDomain.cxx index 699fd91525f..b856719115d 100644 --- a/Views/Core/vtkConvertSelectionDomain.cxx +++ b/Views/Core/vtkConvertSelectionDomain.cxx @@ -61,7 +61,7 @@ static void vtkConvertSelectionDomainFindDomains( { if (dsa->GetAbstractArray("domain")) { - vtkStringArray* domainArr = vtkStringArray::SafeDownCast( + vtkStringArray* domainArr = vtkArrayDownCast( dsa->GetAbstractArray("domain")); if (!domainArr) { diff --git a/Views/Core/vtkDataRepresentation.h b/Views/Core/vtkDataRepresentation.h index a5b53f3d8e9..bd9e3c352c4 100644 --- a/Views/Core/vtkDataRepresentation.h +++ b/Views/Core/vtkDataRepresentation.h @@ -238,13 +238,11 @@ class VTKVIEWSCORE_EXPORT vtkDataRepresentation : public vtkPassInputTypeAlgorit // If a VALUES selection, the array names used in the selection. vtkStringArray* SelectionArrayNames; - //BTX friend class vtkView; friend class vtkRenderView; class Command; friend class Command; Command* Observer; - //ETX // ------------------------------------------------------------------------ // Methods to override in subclasses @@ -275,10 +273,9 @@ class VTKVIEWSCORE_EXPORT vtkDataRepresentation : public vtkPassInputTypeAlgorit vtkDataRepresentation(const vtkDataRepresentation&); // Not implemented. void operator=(const vtkDataRepresentation&); // Not implemented. - //BTX class Internals; Internals* Implementation; - //ETX + }; #endif diff --git a/Views/Core/vtkEmptyRepresentation.h b/Views/Core/vtkEmptyRepresentation.h index 6c1da03144f..7023178c8fe 100644 --- a/Views/Core/vtkEmptyRepresentation.h +++ b/Views/Core/vtkEmptyRepresentation.h @@ -55,9 +55,8 @@ class VTKVIEWSCORE_EXPORT vtkEmptyRepresentation : public vtkDataRepresentation vtkEmptyRepresentation(const vtkEmptyRepresentation&); // Not implemented void operator=(const vtkEmptyRepresentation&); // Not implemented -//BTX vtkSmartPointer ConvertDomains; -//ETX + }; #endif diff --git a/Views/Core/vtkView.h b/Views/Core/vtkView.h index 88580fe2752..59301d051fc 100644 --- a/Views/Core/vtkView.h +++ b/Views/Core/vtkView.h @@ -129,7 +129,6 @@ class VTKVIEWSCORE_EXPORT vtkView : public vtkObject // Apply a theme to the view. virtual void ApplyViewTheme(vtkViewTheme* vtkNotUsed(theme)) { } - //BTX // Description: // Returns the observer that the subclasses can use to listen to additional // events. Additionally these subclasses should override @@ -165,7 +164,6 @@ class VTKVIEWSCORE_EXPORT vtkView : public vtkObject double GetProgress() const { return this->Progress; } }; - //ETX // Description: // Meant for use by subclasses and vtkRepresentation subclasses. @@ -181,7 +179,6 @@ class VTKVIEWSCORE_EXPORT vtkView : public vtkObject // Unregister objects previously registered with RegisterProgress. void UnRegisterProgress(vtkObject* algorithm); -//BTX protected: vtkView(); ~vtkView(); @@ -227,7 +224,7 @@ class VTKVIEWSCORE_EXPORT vtkView : public vtkObject class vtkInternal; vtkInternal* Internal; -//ETX + }; #endif diff --git a/Views/Geovis/Testing/Cxx/TestGeoView2DPopulation.cxx b/Views/Geovis/Testing/Cxx/TestGeoView2DPopulation.cxx index 7ee276a7692..0da60e23e98 100644 --- a/Views/Geovis/Testing/Cxx/TestGeoView2DPopulation.cxx +++ b/Views/Geovis/Testing/Cxx/TestGeoView2DPopulation.cxx @@ -127,7 +127,7 @@ int TestGeoView2DPopulation(int argc, char* argv[]) colorArray->SetName("Colors"); colorArray->SetNumberOfTuples(numRows); - priority = vtkIntArray::SafeDownCast(table->GetColumnByName("Priority")); + priority = vtkArrayDownCast(table->GetColumnByName("Priority")); for(i = 0; i < numRows; i++) { diff --git a/Views/Infovis/Testing/Data/Baseline/TestGraphLayoutView.png.md5 b/Views/Infovis/Testing/Data/Baseline/TestGraphLayoutView.png.md5 index d832e142c49..aebb60a3285 100644 --- a/Views/Infovis/Testing/Data/Baseline/TestGraphLayoutView.png.md5 +++ b/Views/Infovis/Testing/Data/Baseline/TestGraphLayoutView.png.md5 @@ -1 +1 @@ -657c5e78352f4d8b1eaa8de3f9653ce6 +131439b242766b6820e4c8c89bc132dc diff --git a/Views/Infovis/Testing/Data/Baseline/TestParallelCoordinatesView.png.md5 b/Views/Infovis/Testing/Data/Baseline/TestParallelCoordinatesView.png.md5 index f0bc23818d3..416ab051e6a 100644 --- a/Views/Infovis/Testing/Data/Baseline/TestParallelCoordinatesView.png.md5 +++ b/Views/Infovis/Testing/Data/Baseline/TestParallelCoordinatesView.png.md5 @@ -1 +1 @@ -7a2159150d8a6ef37db06affa929b2c1 +b6388cefac4a46cf1edc1df2d83e996c diff --git a/Views/Infovis/Testing/Data/Baseline/TestParallelCoordinatesView_2.png.md5 b/Views/Infovis/Testing/Data/Baseline/TestParallelCoordinatesView_2.png.md5 index 500fe14e203..f08b5101eb9 100644 --- a/Views/Infovis/Testing/Data/Baseline/TestParallelCoordinatesView_2.png.md5 +++ b/Views/Infovis/Testing/Data/Baseline/TestParallelCoordinatesView_2.png.md5 @@ -1 +1 @@ -81c8d5be8e823133170e11b7951aa50c +24cb4563ff257028f275d6fcbc6a07d3 diff --git a/Views/Infovis/Testing/Data/Baseline/TestTreeRingView.png.md5 b/Views/Infovis/Testing/Data/Baseline/TestTreeRingView.png.md5 index a542714166a..4c80df4f8a7 100644 --- a/Views/Infovis/Testing/Data/Baseline/TestTreeRingView.png.md5 +++ b/Views/Infovis/Testing/Data/Baseline/TestTreeRingView.png.md5 @@ -1 +1 @@ -1d0017d41fd423b046b5e649506e4fd5 +3b795e0990b158b4780871bace77761c diff --git a/Views/Infovis/vtkApplyColors.cxx b/Views/Infovis/vtkApplyColors.cxx index d31a5a3f5a6..46dda9b09d5 100644 --- a/Views/Infovis/vtkApplyColors.cxx +++ b/Views/Infovis/vtkApplyColors.cxx @@ -257,7 +257,7 @@ int vtkApplyColors::RequestData( { continue; } - colorArr1->GetTupleValue(list1->GetValue(i), prev); + colorArr1->GetTypedTuple(list1->GetValue(i), prev); if (hasColor) { curColor[0] = annColor[0]; @@ -279,7 +279,7 @@ int vtkApplyColors::RequestData( { curColor[3] = prev[3]; } - colorArr1->SetTupleValue(list1->GetValue(i), curColor); + colorArr1->SetTypedTuple(list1->GetValue(i), curColor); } numIds = list2->GetNumberOfTuples(); for (vtkIdType i = 0; i < numIds; ++i) @@ -288,7 +288,7 @@ int vtkApplyColors::RequestData( { continue; } - colorArr2->GetTupleValue(list2->GetValue(i), prev); + colorArr2->GetTypedTuple(list2->GetValue(i), prev); if (hasColor) { curColor[0] = annColor[0]; @@ -310,7 +310,7 @@ int vtkApplyColors::RequestData( { curColor[3] = prev[3]; } - colorArr2->SetTupleValue(list2->GetValue(i), curColor); + colorArr2->SetTypedTuple(list2->GetValue(i), curColor); } } if (vtkAnnotation* ann = layers->GetCurrentAnnotation()) @@ -371,7 +371,7 @@ int vtkApplyColors::RequestData( { continue; } - colorArr1->SetTupleValue(list1->GetValue(i), color1); + colorArr1->SetTypedTuple(list1->GetValue(i), color1); } numIds = list2->GetNumberOfTuples(); for (vtkIdType i = 0; i < numIds; ++i) @@ -380,7 +380,7 @@ int vtkApplyColors::RequestData( { continue; } - colorArr2->SetTupleValue(list2->GetValue(i), color2); + colorArr2->SetTypedTuple(list2->GetValue(i), color2); } } } // end if (layers) @@ -438,7 +438,7 @@ void vtkApplyColors::ProcessColorArray( // Combine the opacity of the lookup table with the // default color opacity. myColor[3] = static_cast((color[3]/255.0)*mappedColor[3]); - colorArr->SetTupleValue(i, myColor); + colorArr->SetTypedTuple(i, myColor); } } else @@ -446,7 +446,7 @@ void vtkApplyColors::ProcessColorArray( // If no lookup table, use default color. for (vtkIdType i = 0; i < colorArr->GetNumberOfTuples(); ++i) { - colorArr->SetTupleValue(i, color); + colorArr->SetTypedTuple(i, color); } } } diff --git a/Views/Infovis/vtkApplyIcons.h b/Views/Infovis/vtkApplyIcons.h index 05514e9c7c9..c6759273f09 100644 --- a/Views/Infovis/vtkApplyIcons.h +++ b/Views/Infovis/vtkApplyIcons.h @@ -106,7 +106,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkApplyIcons : public vtkPassInputTypeAlgorithm vtkSetStringMacro(IconOutputArrayName); vtkGetStringMacro(IconOutputArrayName); - //BTX enum { SELECTED_ICON, @@ -114,7 +113,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkApplyIcons : public vtkPassInputTypeAlgorithm ANNOTATION_ICON, IGNORE_SELECTION }; - //ETX // Description: // Changes the behavior of the icon to use for selected items. @@ -164,10 +162,8 @@ class VTKVIEWSINFOVIS_EXPORT vtkApplyIcons : public vtkPassInputTypeAlgorithm int SelectionMode; int AttributeType; - //BTX class Internals; Internals* Implementation; - //ETX private: vtkApplyIcons(const vtkApplyIcons&); // Not implemented. diff --git a/Views/Infovis/vtkDendrogramItem.cxx b/Views/Infovis/vtkDendrogramItem.cxx index c564b75dbb6..d1873991241 100644 --- a/Views/Infovis/vtkDendrogramItem.cxx +++ b/Views/Infovis/vtkDendrogramItem.cxx @@ -428,7 +428,7 @@ void vtkDendrogramItem::PaintBuffers(vtkContext2D *painter) double targetPoint[3]; int numberOfCollapsedSubTrees = 0; - vtkUnsignedIntArray *vertexIsPruned = vtkUnsignedIntArray::SafeDownCast( + vtkUnsignedIntArray *vertexIsPruned = vtkArrayDownCast( this->Tree->GetVertexData()->GetArray("VertexIsPruned")); int orientation = this->GetOrientation(); @@ -689,7 +689,7 @@ void vtkDendrogramItem::PaintBuffers(vtkContext2D *painter) } // get array of node names from the tree - vtkStringArray *vertexNames = vtkStringArray::SafeDownCast( + vtkStringArray *vertexNames = vtkArrayDownCast( this->LayoutTree->GetVertexData()->GetAbstractArray( this->VertexNameArrayName)); @@ -873,9 +873,9 @@ vtkIdType vtkDendrogramItem::GetClickedCollapsedSubTree(double x, double y) { // iterate over all the collapsed subtrees to see if this click refers // to one of them. - vtkUnsignedIntArray *vertexIsPruned = vtkUnsignedIntArray::SafeDownCast( + vtkUnsignedIntArray *vertexIsPruned = vtkArrayDownCast( this->Tree->GetVertexData()->GetArray("VertexIsPruned")); - vtkIdTypeArray *originalIdArray = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray *originalIdArray = vtkArrayDownCast( this->PrunedTree->GetVertexData()->GetArray("OriginalId")); int orientation = this->GetOrientation(); @@ -1008,7 +1008,7 @@ void vtkDendrogramItem::CollapseSubTree(vtkIdType vertex) } // look up the original ID of the vertex that's being collapsed. - vtkIdTypeArray *originalIdArray = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray *originalIdArray = vtkArrayDownCast( this->PrunedTree->GetVertexData()->GetArray("OriginalId")); vtkIdType originalId = originalIdArray->GetValue(vertex); @@ -1031,7 +1031,7 @@ void vtkDendrogramItem::CollapseSubTree(vtkIdType vertex) return; } - vtkUnsignedIntArray *vertexIsPruned = vtkUnsignedIntArray::SafeDownCast( + vtkUnsignedIntArray *vertexIsPruned = vtkArrayDownCast( this->Tree->GetVertexData()->GetArray("VertexIsPruned")); vertexIsPruned->SetValue(originalId, numLeavesCollapsed); @@ -1048,7 +1048,7 @@ void vtkDendrogramItem::CollapseSubTree(vtkIdType vertex) void vtkDendrogramItem::ExpandSubTree(vtkIdType vertex) { // mark this vertex as "not pruned" - vtkUnsignedIntArray *vertexIsPruned = vtkUnsignedIntArray::SafeDownCast( + vtkUnsignedIntArray *vertexIsPruned = vtkArrayDownCast( this->Tree->GetVertexData()->GetArray("VertexIsPruned")); vtkIdType vertexOriginalId = this->GetOriginalId(vertex); vertexIsPruned->SetValue(vertexOriginalId, 0); @@ -1065,7 +1065,7 @@ void vtkDendrogramItem::ExpandSubTree(vtkIdType vertex) { // Find PrunedTree's vertex that corresponds to this originalId. // Use this to re-collapse the subtrees that were not just expanded. - vtkIdTypeArray *originalIdArray = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray *originalIdArray = vtkArrayDownCast( this->PrunedTree->GetVertexData()->GetArray("OriginalId")); for (vtkIdType prunedId = 0; prunedId < originalIdArray->GetNumberOfTuples(); ++prunedId) @@ -1083,7 +1083,7 @@ void vtkDendrogramItem::ExpandSubTree(vtkIdType vertex) //----------------------------------------------------------------------------- vtkIdType vtkDendrogramItem::GetOriginalId(vtkIdType vertex) { - vtkIdTypeArray *originalIdArray = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray *originalIdArray = vtkArrayDownCast( this->PrunedTree->GetVertexData()->GetArray("OriginalId")); return originalIdArray->GetValue(vertex); } @@ -1091,7 +1091,7 @@ vtkIdType vtkDendrogramItem::GetOriginalId(vtkIdType vertex) //----------------------------------------------------------------------------- vtkIdType vtkDendrogramItem::GetPrunedIdForOriginalId(vtkIdType originalId) { - vtkIdTypeArray *originalIdArray = vtkIdTypeArray::SafeDownCast( + vtkIdTypeArray *originalIdArray = vtkArrayDownCast( this->PrunedTree->GetVertexData()->GetArray("OriginalId")); for (vtkIdType i = 0; i < originalIdArray->GetNumberOfTuples(); ++i) { @@ -1124,7 +1124,7 @@ void vtkDendrogramItem::CollapseToNumberOfLeafNodes(unsigned int n) std::vector, vtkDendrogramItem::CompareWeightedVertices> queue; std::vector verticesToCollapse; - vtkDoubleArray *nodeWeights = vtkDoubleArray::SafeDownCast( + vtkDoubleArray *nodeWeights = vtkArrayDownCast( this->Tree->GetVertexData()->GetAbstractArray(this->DistanceArrayName)); // initially, the priority queue contains the children of the root node. @@ -1209,7 +1209,7 @@ void vtkDendrogramItem::CollapseToNumberOfLeafNodes(unsigned int n) //----------------------------------------------------------------------------- void vtkDendrogramItem::SetColorArray(const char *arrayName) { - this->ColorArray = vtkDoubleArray::SafeDownCast( + this->ColorArray = vtkArrayDownCast( this->Tree->GetVertexData()->GetArray(arrayName)); if (!this->ColorArray) { @@ -1336,7 +1336,7 @@ void vtkDendrogramItem::SetOrientation(int orientation) //----------------------------------------------------------------------------- void vtkDendrogramItem::SetOrientation(vtkTree *tree, int orientation) { - vtkIntArray *existingArray = vtkIntArray::SafeDownCast( + vtkIntArray *existingArray = vtkArrayDownCast( tree->GetFieldData()->GetArray("orientation")); if (existingArray) { @@ -1362,7 +1362,7 @@ void vtkDendrogramItem::SetOrientation(vtkTree *tree, int orientation) //----------------------------------------------------------------------------- int vtkDendrogramItem::GetOrientation() { - vtkIntArray *orientationArray = vtkIntArray::SafeDownCast( + vtkIntArray *orientationArray = vtkArrayDownCast( this->Tree->GetFieldData()->GetArray("orientation")); if (orientationArray) { @@ -1473,7 +1473,7 @@ void vtkDendrogramItem::ComputeLabelWidth(vtkContext2D *painter) painter->GetTextProp()->SetOrientation(0.0); // get array of node names from the tree - vtkStringArray *vertexNames = vtkStringArray::SafeDownCast( + vtkStringArray *vertexNames = vtkArrayDownCast( this->LayoutTree->GetVertexData()->GetAbstractArray( this->VertexNameArrayName)); @@ -1495,7 +1495,7 @@ void vtkDendrogramItem::ComputeLabelWidth(vtkContext2D *painter) bool vtkDendrogramItem::GetPositionOfVertex(std::string vertexName, double position[2]) { - vtkStringArray *vertexNames = vtkStringArray::SafeDownCast( + vtkStringArray *vertexNames = vtkArrayDownCast( this->LayoutTree->GetVertexData()->GetAbstractArray( this->VertexNameArrayName)); diff --git a/Views/Infovis/vtkDendrogramItem.h b/Views/Infovis/vtkDendrogramItem.h index bc3a5399bfe..d21893616a1 100644 --- a/Views/Infovis/vtkDendrogramItem.h +++ b/Views/Infovis/vtkDendrogramItem.h @@ -213,7 +213,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkDendrogramItem : public vtkContextItem } }; - //BTX // Description: // Enum for Orientation. enum @@ -232,7 +231,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkDendrogramItem : public vtkContextItem // Collapse or expand a subtree when the user double clicks on an // internal node. virtual bool MouseDoubleClickEvent( const vtkContextMouseEvent &event); - //ETX protected: vtkDendrogramItem(); diff --git a/Views/Infovis/vtkHeatmapItem.cxx b/Views/Infovis/vtkHeatmapItem.cxx index 1988412d523..8e4ff6a98fd 100644 --- a/Views/Infovis/vtkHeatmapItem.cxx +++ b/Views/Infovis/vtkHeatmapItem.cxx @@ -109,11 +109,11 @@ void vtkHeatmapItem::SetTable(vtkTable *table) this->Table = table; // get the row names for this table - vtkStringArray *rowNames = vtkStringArray::SafeDownCast( + vtkStringArray *rowNames = vtkArrayDownCast( this->Table->GetColumnByName(this->NameColumn)); if (rowNames == NULL) { - rowNames = vtkStringArray::SafeDownCast( + rowNames = vtkArrayDownCast( this->Table->GetColumn(0)); } if (rowNames == NULL) @@ -182,9 +182,9 @@ void vtkHeatmapItem::RebuildBuffers() this->InitializeLookupTables(); - this->CollapsedRowsArray = vtkBitArray::SafeDownCast( + this->CollapsedRowsArray = vtkArrayDownCast( this->Table->GetFieldData()->GetArray("collapsed rows")); - this->CollapsedColumnsArray = vtkBitArray::SafeDownCast( + this->CollapsedColumnsArray = vtkArrayDownCast( this->Table->GetFieldData()->GetArray("collapsed columns")); this->HeatmapBuildTime = this->Table->GetMTime(); @@ -267,7 +267,7 @@ void vtkHeatmapItem::GenerateContinuousDataLookupTable() //----------------------------------------------------------------------------- void vtkHeatmapItem::AccumulateProminentCategoricalDataValues(vtkIdType column) { - vtkStringArray *stringColumn = vtkStringArray::SafeDownCast( + vtkStringArray *stringColumn = vtkArrayDownCast( this->Table->GetColumn(column)); // search for values that occur more than once @@ -895,7 +895,7 @@ std::string vtkHeatmapItem::GetTooltipText(float x, float y) //----------------------------------------------------------------------------- void vtkHeatmapItem::SetOrientation(int orientation) { - vtkIntArray *existingArray = vtkIntArray::SafeDownCast( + vtkIntArray *existingArray = vtkArrayDownCast( this->Table->GetFieldData()->GetArray("orientation")); if (existingArray) { @@ -918,7 +918,7 @@ void vtkHeatmapItem::SetOrientation(int orientation) //----------------------------------------------------------------------------- int vtkHeatmapItem::GetOrientation() { - vtkIntArray *orientationArray = vtkIntArray::SafeDownCast( + vtkIntArray *orientationArray = vtkArrayDownCast( this->Table->GetFieldData()->GetArray("orientation")); if (orientationArray) { @@ -1159,7 +1159,7 @@ bool vtkHeatmapItem::MouseDoubleClickEvent(const vtkContextMouseEvent &event) { // categorical data // generate an array of distinct values from this column - vtkStringArray *stringColumn = vtkStringArray::SafeDownCast( + vtkStringArray *stringColumn = vtkArrayDownCast( this->Table->GetColumn(column)); this->CategoryLegendValues->Reset(); this->CategoryLegendValues->Squeeze(); diff --git a/Views/Infovis/vtkHeatmapItem.h b/Views/Infovis/vtkHeatmapItem.h index 98353c89338..0706650a3b0 100644 --- a/Views/Infovis/vtkHeatmapItem.h +++ b/Views/Infovis/vtkHeatmapItem.h @@ -127,8 +127,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkHeatmapItem : public vtkContextItem vtkGetMacro(RowLabelWidth, float); vtkGetMacro(ColumnLabelWidth, float); - //BTX - // Description: // Enum for Orientation. enum @@ -151,8 +149,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkHeatmapItem : public vtkContextItem // Display a legend for a column of data. virtual bool MouseDoubleClickEvent(const vtkContextMouseEvent &event); - //ETX - protected: vtkHeatmapItem(); ~vtkHeatmapItem(); diff --git a/Views/Infovis/vtkInteractorStyleAreaSelectHover.cxx b/Views/Infovis/vtkInteractorStyleAreaSelectHover.cxx index 70c75bf9a1e..6d84f67bccc 100644 --- a/Views/Infovis/vtkInteractorStyleAreaSelectHover.cxx +++ b/Views/Infovis/vtkInteractorStyleAreaSelectHover.cxx @@ -212,13 +212,13 @@ void vtkInteractorStyleAreaSelectHover::OnMouseMove() if (absArray != NULL && id > -1 ) { vtkStdString str; - if (vtkStringArray::SafeDownCast(absArray)) + if (vtkArrayDownCast(absArray)) { - str = vtkStringArray::SafeDownCast(absArray)->GetValue(id); + str = vtkArrayDownCast(absArray)->GetValue(id); } - if (vtkDataArray::SafeDownCast(absArray)) + if (vtkArrayDownCast(absArray)) { - str = vtkVariant(vtkDataArray::SafeDownCast(absArray)->GetTuple(id)[0]).ToString(); + str = vtkVariant(vtkArrayDownCast(absArray)->GetTuple(id)[0]).ToString(); } this->Balloon->SetBalloonText(str); double z = 0.02; diff --git a/Views/Infovis/vtkInteractorStyleTreeMapHover.cxx b/Views/Infovis/vtkInteractorStyleTreeMapHover.cxx index 87d2586919b..626cd63aa1c 100644 --- a/Views/Infovis/vtkInteractorStyleTreeMapHover.cxx +++ b/Views/Infovis/vtkInteractorStyleTreeMapHover.cxx @@ -250,13 +250,13 @@ void vtkInteractorStyleTreeMapHover::OnMouseMove() if (absArray != NULL && id > -1) { vtkStdString str; - if (vtkStringArray::SafeDownCast(absArray)) + if (vtkArrayDownCast(absArray)) { - str = vtkStringArray::SafeDownCast(absArray)->GetValue(id); + str = vtkArrayDownCast(absArray)->GetValue(id); } - if (vtkDataArray::SafeDownCast(absArray)) + if (vtkArrayDownCast(absArray)) { - str = vtkVariant(vtkDataArray::SafeDownCast(absArray)->GetTuple(id)[0]).ToString(); + str = vtkVariant(vtkArrayDownCast(absArray)->GetTuple(id)[0]).ToString(); } this->Balloon->SetBalloonText(str); vtkTree* tree = this->Layout->GetOutput(); @@ -359,7 +359,7 @@ void vtkInteractorStyleTreeMapHover::OnLeftButtonUp() "PedigreeVertexId"); if (absArray) { - vtkIdTypeArray* idArray = vtkIdTypeArray::SafeDownCast(absArray); + vtkIdTypeArray* idArray = vtkArrayDownCast(absArray); if (idArray) { id = idArray->GetValue(this->CurrentSelectedId); diff --git a/Views/Infovis/vtkParallelCoordinatesHistogramRepresentation.cxx b/Views/Infovis/vtkParallelCoordinatesHistogramRepresentation.cxx index 97bc0dd2416..37ff23a7f6d 100644 --- a/Views/Infovis/vtkParallelCoordinatesHistogramRepresentation.cxx +++ b/Views/Infovis/vtkParallelCoordinatesHistogramRepresentation.cxx @@ -276,7 +276,7 @@ int vtkParallelCoordinatesHistogramRepresentation::PlaceSelection(vtkPolyData* p vtkTable* data, vtkSelectionNode* selectionNode) { - vtkIdTypeArray* selectedIds = vtkIdTypeArray::SafeDownCast(selectionNode->GetSelectionList()); + vtkIdTypeArray* selectedIds = vtkArrayDownCast(selectionNode->GetSelectionList()); if (!selectedIds) return 1; @@ -313,10 +313,10 @@ int vtkParallelCoordinatesHistogramRepresentation::PlaceHistogramLineQuads(vtkPo numberOfQuads,0); vtkPoints* points = polyData->GetPoints(); - float* pointsp = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float* pointsp = vtkArrayDownCast(points->GetData())->GetPointer(0); - vtkDoubleArray* scalars = vtkDoubleArray::SafeDownCast(polyData->GetCellData()->GetScalars()); - double* scalarsp = scalars->GetPointer(0);//vtkDoubleArray::SafeDownCast(polyData->GetCellData()->GetScalars()); + vtkDoubleArray* scalars = vtkArrayDownCast(polyData->GetCellData()->GetScalars()); + double* scalarsp = scalars->GetPointer(0);//vtkArrayDownCast(polyData->GetCellData()->GetScalars()); // for each histogram, draw a quad for each bin. vtkIdType ptId=0; @@ -392,9 +392,9 @@ int vtkParallelCoordinatesHistogramRepresentation::PlaceHistogramCurveQuads(vtkP numberOfStrips,0); vtkPoints *points = polyData->GetPoints(); - float* pointsp = vtkFloatArray::SafeDownCast(points->GetData())->GetPointer(0); + float* pointsp = vtkArrayDownCast(points->GetData())->GetPointer(0); - vtkDoubleArray* scalars = vtkDoubleArray::SafeDownCast(polyData->GetCellData()->GetScalars()); + vtkDoubleArray* scalars = vtkArrayDownCast(polyData->GetCellData()->GetScalars()); double* scalarsp = scalars->GetPointer(0); // build the default spline diff --git a/Views/Infovis/vtkParallelCoordinatesHistogramRepresentation.h b/Views/Infovis/vtkParallelCoordinatesHistogramRepresentation.h index f3641950590..7d0b7e49378 100644 --- a/Views/Infovis/vtkParallelCoordinatesHistogramRepresentation.h +++ b/Views/Infovis/vtkParallelCoordinatesHistogramRepresentation.h @@ -89,13 +89,11 @@ class VTKVIEWSINFOVIS_EXPORT vtkParallelCoordinatesHistogramRepresentation : pub vtkSetVector2Macro(HistogramLookupTableRange,double); vtkGetVector2Macro(HistogramLookupTableRange,double); - //BTX // Description: // The number of histogram bins on either side of each pair of axes. void SetNumberOfHistogramBins(int,int); void SetNumberOfHistogramBins(int*); vtkGetVector2Macro(NumberOfHistogramBins,int); - //ETX // Description: // Target maximum number of outliers to be drawn, although not guaranteed. @@ -137,10 +135,8 @@ class VTKVIEWSINFOVIS_EXPORT vtkParallelCoordinatesHistogramRepresentation : pub // How many bins are used during the 2D histogram computation int NumberOfHistogramBins[2]; - //BTX vtkSmartPointer HistogramFilter; vtkSmartPointer HistogramLookupTable; - //ETX // Description: // Whether or not to draw outlier lines @@ -150,12 +146,10 @@ class VTKVIEWSINFOVIS_EXPORT vtkParallelCoordinatesHistogramRepresentation : pub // How many outlier lines to draw, approximately. int PreferredNumberOfOutliers; - //BTX vtkSmartPointer OutlierFilter; vtkSmartPointer OutlierData; vtkSmartPointer OutlierMapper; vtkSmartPointer OutlierActor; - //ETX // Description: // Correctly forwards the superclass call to draw lines to the internal diff --git a/Views/Infovis/vtkParallelCoordinatesRepresentation.cxx b/Views/Infovis/vtkParallelCoordinatesRepresentation.cxx index 074981c76f0..cc8da1c2b6a 100644 --- a/Views/Infovis/vtkParallelCoordinatesRepresentation.cxx +++ b/Views/Infovis/vtkParallelCoordinatesRepresentation.cxx @@ -437,7 +437,7 @@ int vtkParallelCoordinatesRepresentation::RequestData( vtkTable* inputTitles = vtkTable::SafeDownCast(inTitleInfo->Get(vtkDataObject::DATA_OBJECT())); if (inputTitles && inputTitles->GetNumberOfColumns() > 0) { - titles = vtkStringArray::SafeDownCast(inputTitles->GetColumn(0)); + titles = vtkArrayDownCast(inputTitles->GetColumn(0)); } } // build the input array table. This is convenience table that gets used @@ -504,7 +504,7 @@ int vtkParallelCoordinatesRepresentation::RequestData( vtkIdTypeArray* unselectedRows = NULL; if (this->InverseSelection->GetNode(0)) - unselectedRows = vtkIdTypeArray::SafeDownCast(this->InverseSelection->GetNode(0)->GetSelectionList()); + unselectedRows = vtkArrayDownCast(this->InverseSelection->GetNode(0)->GetSelectionList()); if (this->UseCurves) { @@ -776,7 +776,7 @@ int vtkParallelCoordinatesRepresentation::ComputeDataProperties() // compute axis ranges for (int i=0; iInputArrayTable->GetColumn(i)); + vtkDataArray* array = vtkArrayDownCast(this->InputArrayTable->GetColumn(i)); double *r = array->GetRange(0); this->Mins[i] = r[0]; this->Maxs[i] = r[1]; @@ -1054,7 +1054,7 @@ int vtkParallelCoordinatesRepresentation::AllocatePolyData(vtkPolyData* polyData if (numCellScalars) { vtkDoubleArray* scalars = - vtkDoubleArray::SafeDownCast(polyData->GetCellData()->GetScalars()); + vtkArrayDownCast(polyData->GetCellData()->GetScalars()); if (!scalars) { @@ -1079,7 +1079,7 @@ int vtkParallelCoordinatesRepresentation::AllocatePolyData(vtkPolyData* polyData if (numPointScalars) { vtkDoubleArray* scalars = - vtkDoubleArray::SafeDownCast(polyData->GetPointData()->GetScalars()); + vtkArrayDownCast(polyData->GetPointData()->GetScalars()); if (!scalars) { @@ -1138,7 +1138,7 @@ int vtkParallelCoordinatesRepresentation::PlaceLines(vtkPolyData* polyData, // get the relevant array information // vtkDataArray* array = this->GetInputArrayAtPosition(position); - vtkDataArray* array = vtkDataArray::SafeDownCast(data->GetColumn(position)); + vtkDataArray* array = vtkArrayDownCast(data->GetColumn(position)); if (!array) return 0; @@ -1202,7 +1202,7 @@ int vtkParallelCoordinatesRepresentation::PlaceCurves(vtkPolyData* polyData, // get the relevant array information // vtkDataArray* array = this->GetInputArrayAtPosition(position); - vtkDataArray* array = vtkDataArray::SafeDownCast(data->GetColumn(position)); + vtkDataArray* array = vtkArrayDownCast(data->GetColumn(position)); if (!array) { return 0; @@ -1291,7 +1291,7 @@ int vtkParallelCoordinatesRepresentation::PlaceSelection(vtkPolyData* polyData, vtkTable* data, vtkSelectionNode* selectionNode) { - vtkIdTypeArray* selectedIds = vtkIdTypeArray::SafeDownCast(selectionNode->GetSelectionList()); + vtkIdTypeArray* selectedIds = vtkArrayDownCast(selectionNode->GetSelectionList()); if (!selectedIds) return 0; @@ -1825,7 +1825,7 @@ void vtkParallelCoordinatesRepresentation::SelectRows(vtkIdType brushClass, node = selection->GetNode(brushClass); } - vtkIdTypeArray* oldSelectedIds = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkIdTypeArray* oldSelectedIds = vtkArrayDownCast(node->GetSelectionList()); // no selection list yet? that shouldn't be possible...it was allocated above if (!oldSelectedIds) @@ -1921,7 +1921,7 @@ void vtkParallelCoordinatesRepresentation::BuildInverseSelection() for (int j=0; jGetNode(j)->GetSelectionList()); + vtkIdTypeArray* a = vtkArrayDownCast(selection->GetNode(j)->GetSelectionList()); if (!a || idxs[j] >= a->GetNumberOfTuples()) { continue; diff --git a/Views/Infovis/vtkParallelCoordinatesRepresentation.h b/Views/Infovis/vtkParallelCoordinatesRepresentation.h index 594b886d744..092b31b5fc8 100644 --- a/Views/Infovis/vtkParallelCoordinatesRepresentation.h +++ b/Views/Infovis/vtkParallelCoordinatesRepresentation.h @@ -183,14 +183,12 @@ class VTKVIEWSINFOVIS_EXPORT vtkParallelCoordinatesRepresentation : public vtkRe virtual void FunctionSelect(int brushClass, int brushOperator, double *p1, double *p2, double *q1, double *q2); virtual void RangeSelect(int brushClass, int brushOperator, double *p1, double *p2); -//BTX enum InputPorts { INPUT_DATA=0, INPUT_TITLES, NUM_INPUT_PORTS }; -//ETX protected: vtkParallelCoordinatesRepresentation(); @@ -283,8 +281,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkParallelCoordinatesRepresentation : public vtkRe vtkPolyDataMapper2D* GetSelectionMapper(int idx); int GetNumberOfSelections(); - - //BTX vtkSmartPointer PlotData; vtkSmartPointer PlotMapper; vtkSmartPointer PlotActor; @@ -298,7 +294,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkParallelCoordinatesRepresentation : public vtkRe class Internals; Internals* I; - //ETX int NumberOfAxes; int NumberOfAxisLabels; @@ -319,11 +314,9 @@ class VTKVIEWSINFOVIS_EXPORT vtkParallelCoordinatesRepresentation : public vtkRe double* MinOffsets; double* MaxOffsets; - //BTX vtkSmartPointer* Axes; vtkSmartPointer InputArrayTable; vtkSmartPointer AxisTitles; - //ETX vtkTimeStamp BuildTime; diff --git a/Views/Infovis/vtkParallelCoordinatesView.h b/Views/Infovis/vtkParallelCoordinatesView.h index 5a4c76061f2..529b507c1f4 100644 --- a/Views/Infovis/vtkParallelCoordinatesView.h +++ b/Views/Infovis/vtkParallelCoordinatesView.h @@ -55,11 +55,9 @@ class VTKVIEWSINFOVIS_EXPORT vtkParallelCoordinatesView : public vtkRenderView static vtkParallelCoordinatesView *New(); void PrintSelf(ostream &os, vtkIndent indent); - //BTX enum {VTK_BRUSH_LASSO=0,VTK_BRUSH_ANGLE,VTK_BRUSH_FUNCTION,VTK_BRUSH_AXISTHRESHOLD,VTK_BRUSH_MODECOUNT}; enum {VTK_BRUSHOPERATOR_ADD=0,VTK_BRUSHOPERATOR_SUBTRACT,VTK_BRUSHOPERATOR_INTERSECT,VTK_BRUSHOPERATOR_REPLACE,VTK_BRUSHOPERATOR_MODECOUNT}; enum {VTK_INSPECT_MANIPULATE_AXES=0, VTK_INSPECT_SELECT_DATA, VTK_INSPECT_MODECOUNT}; - //ETX void SetBrushMode(int); void SetBrushModeToLasso() { this->SetBrushMode(VTK_BRUSH_LASSO); } @@ -93,12 +91,11 @@ class VTKVIEWSINFOVIS_EXPORT vtkParallelCoordinatesView : public vtkRenderView virtual ~vtkParallelCoordinatesView(); int SelectedAxisPosition; - //BTX + enum {VTK_HIGHLIGHT_CENTER=0,VTK_HIGHLIGHT_MIN,VTK_HIGHLIGHT_MAX}; vtkSmartPointer HighlightSource; vtkSmartPointer HighlightMapper; vtkSmartPointer HighlightActor; - //ETX int InspectMode; int BrushMode; @@ -106,11 +103,10 @@ class VTKVIEWSINFOVIS_EXPORT vtkParallelCoordinatesView : public vtkRenderView int MaximumNumberOfBrushPoints; int NumberOfBrushPoints; int CurrentBrushClass; - //BTX + vtkSmartPointer BrushData; vtkSmartPointer BrushMapper; vtkSmartPointer BrushActor; - //ETX int FirstFunctionBrushLineDrawn; int AxisHighlightPosition; diff --git a/Views/Infovis/vtkRenderView.h b/Views/Infovis/vtkRenderView.h index 6eec1fa4048..06c6db8b3cf 100644 --- a/Views/Infovis/vtkRenderView.h +++ b/Views/Infovis/vtkRenderView.h @@ -79,14 +79,13 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderView : public vtkRenderViewBase // description of vtkRenderViewBase. virtual void SetRenderWindow(vtkRenderWindow *win); - //BTX enum { INTERACTION_MODE_2D, INTERACTION_MODE_3D, INTERACTION_MODE_UNKNOWN }; - //ETX + void SetInteractionMode(int mode); vtkGetMacro(InteractionMode, int); @@ -120,12 +119,10 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderView : public vtkRenderViewBase vtkGetMacro(DisplayHoverText, bool); vtkBooleanMacro(DisplayHoverText, bool); - //BTX enum { SURFACE = 0, FRUSTUM = 1 }; - //ETX // Description: // Sets the selection mode for the render view. @@ -165,13 +162,11 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderView : public vtkRenderViewBase int* GetDisplaySize(); void GetDisplaySize(int &dsx, int &dsy); - //BTX enum { NO_OVERLAP, ALL }; - //ETX // Description: // Label placement mode. @@ -186,13 +181,11 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderView : public vtkRenderViewBase virtual void SetLabelPlacementModeToAll() { this->SetLabelPlacementMode(ALL); } - //BTX enum { FREETYPE, QT }; - //ETX // Description: // Label render mode. @@ -260,14 +253,12 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderView : public vtkRenderViewBase int InteractionMode; bool RenderOnMouseMove; - //BTX vtkSmartPointer LabelRenderer; vtkSmartPointer Balloon; vtkSmartPointer LabelPlacementMapper; vtkSmartPointer LabelActor; vtkSmartPointer HoverWidget; vtkSmartPointer Selector; - //ETX private: vtkRenderView(const vtkRenderView&); // Not implemented. diff --git a/Views/Infovis/vtkRenderedGraphRepresentation.cxx b/Views/Infovis/vtkRenderedGraphRepresentation.cxx index fc01c3eefda..4ad820d0790 100644 --- a/Views/Infovis/vtkRenderedGraphRepresentation.cxx +++ b/Views/Infovis/vtkRenderedGraphRepresentation.cxx @@ -1344,7 +1344,7 @@ void vtkRenderedGraphRepresentation::ComputeSelectedGraphBounds(double bounds[6] if (list) { // Append the selection list to the selection - vtkIdTypeArray* curList = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vtkIdTypeArray* curList = vtkArrayDownCast(node->GetSelectionList()); if (curList) { int inverse = node->GetProperties()->Get(vtkSelectionNode::INVERSE()); diff --git a/Views/Infovis/vtkRenderedGraphRepresentation.h b/Views/Infovis/vtkRenderedGraphRepresentation.h index 500a1e047dc..b67c21fc9f9 100644 --- a/Views/Infovis/vtkRenderedGraphRepresentation.h +++ b/Views/Infovis/vtkRenderedGraphRepresentation.h @@ -376,7 +376,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderedGraphRepresentation : public vtkRendered vtkInformationVector** inputVector, vtkInformationVector* outputVector); - //BTX // Description: // Internal filter classes. vtkSmartPointer ApplyColors; @@ -407,7 +406,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderedGraphRepresentation : public vtkRendered vtkSmartPointer VertexIconGlyph; vtkSmartPointer VertexIconMapper; vtkSmartPointer VertexIconActor; - //ETX char* VertexHoverArrayName; char* EdgeHoverArrayName; diff --git a/Views/Infovis/vtkRenderedHierarchyRepresentation.h b/Views/Infovis/vtkRenderedHierarchyRepresentation.h index 736118260ea..095d738ae8c 100644 --- a/Views/Infovis/vtkRenderedHierarchyRepresentation.h +++ b/Views/Infovis/vtkRenderedHierarchyRepresentation.h @@ -127,10 +127,8 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderedHierarchyRepresentation : public vtkRend virtual void ApplyViewTheme(vtkViewTheme* theme); - //BTX class Internals; Internals* Implementation; - //ETX private: vtkRenderedHierarchyRepresentation(const vtkRenderedHierarchyRepresentation&); // Not implemented diff --git a/Views/Infovis/vtkRenderedRepresentation.h b/Views/Infovis/vtkRenderedRepresentation.h index 45eb6eddf5d..cd12f5040e1 100644 --- a/Views/Infovis/vtkRenderedRepresentation.h +++ b/Views/Infovis/vtkRenderedRepresentation.h @@ -80,11 +80,9 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderedRepresentation : public vtkDataRepresent // Representations may add their own pre-render logic here. virtual void PrepareForRendering(vtkRenderView* view); - //BTX friend class vtkRenderView; class Internals; Internals* Implementation; - //ETX int LabelRenderMode; diff --git a/Views/Infovis/vtkRenderedTreeAreaRepresentation.cxx b/Views/Infovis/vtkRenderedTreeAreaRepresentation.cxx index 986218500da..5b47e65793c 100644 --- a/Views/Infovis/vtkRenderedTreeAreaRepresentation.cxx +++ b/Views/Infovis/vtkRenderedTreeAreaRepresentation.cxx @@ -790,7 +790,7 @@ vtkSelection* vtkRenderedTreeAreaRepresentation::ConvertSelection( if (prop == this->AreaActor.GetPointer()) { vtkSmartPointer vertexIds; - vertexIds = vtkIdTypeArray::SafeDownCast(node->GetSelectionList()); + vertexIds = vtkArrayDownCast(node->GetSelectionList()); // If we are in single select mode, make sure to select only the vertex // that is being hovered over. @@ -855,7 +855,7 @@ vtkSelection* vtkRenderedTreeAreaRepresentation::ConvertSelection( vtkGraph* g = vtkGraph::SafeDownCast(this->GetInternalOutputPort(1, static_cast(k))->GetProducer()->GetOutputDataObject(0)); vtkAbstractArray* arr2 = g->GetVertexData()->GetPedigreeIds(); - vtkStringArray* domainArr = vtkStringArray::SafeDownCast(g->GetVertexData()->GetAbstractArray("domain")); + vtkStringArray* domainArr = vtkArrayDownCast(g->GetVertexData()->GetAbstractArray("domain")); for(vtkIdType j=0; jGetNumberOfTuples(); ++j) { vtkIdType id = arr2->LookupValue(arr->GetVariantValue(j)); diff --git a/Views/Infovis/vtkRenderedTreeAreaRepresentation.h b/Views/Infovis/vtkRenderedTreeAreaRepresentation.h index 69380716584..f077300a93a 100644 --- a/Views/Infovis/vtkRenderedTreeAreaRepresentation.h +++ b/Views/Infovis/vtkRenderedTreeAreaRepresentation.h @@ -248,12 +248,9 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderedTreeAreaRepresentation : public vtkRende virtual vtkUnicodeString GetHoverTextInternal(vtkSelection* sel); - //BTX class Internals; Internals* Implementation; - //ETX - //BTX vtkSmartPointer Picker; vtkSmartPointer ApplyColors; vtkSmartPointer TreeLevels; @@ -271,7 +268,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkRenderedTreeAreaRepresentation : public vtkRende vtkSmartPointer EdgeScalarBar; vtkSmartPointer AreaLabelHierarchy; vtkSmartPointer EmptyPolyData; - //ETX vtkSetStringMacro(AreaSizeArrayNameInternal); vtkGetStringMacro(AreaSizeArrayNameInternal); diff --git a/Views/Infovis/vtkTanglegramItem.cxx b/Views/Infovis/vtkTanglegramItem.cxx index f536b9811e6..1b4f372daf1 100644 --- a/Views/Infovis/vtkTanglegramItem.cxx +++ b/Views/Infovis/vtkTanglegramItem.cxx @@ -104,7 +104,7 @@ void vtkTanglegramItem::SetTable(vtkTable *table) this->Table = table; - this->SourceNames = vtkStringArray::SafeDownCast(this->Table->GetColumn(0)); + this->SourceNames = vtkArrayDownCast(this->Table->GetColumn(0)); this->GenerateLookupTable(); this->TreeReordered = false; } @@ -155,11 +155,11 @@ void vtkTanglegramItem::RefreshBuffers(vtkContext2D *painter) this->Dendrogram2->GetBounds(this->Tree2Bounds); this->LabelWidth2 = this->Dendrogram2->GetLabelWidth(); - this->Tree1Names = vtkStringArray::SafeDownCast( + this->Tree1Names = vtkArrayDownCast( this->Dendrogram1->GetPrunedTree()->GetVertexData()-> GetAbstractArray("node name")); - this->Tree2Names = vtkStringArray::SafeDownCast( + this->Tree2Names = vtkArrayDownCast( this->Dendrogram2->GetPrunedTree()->GetVertexData()-> GetAbstractArray("node name")); } @@ -523,7 +523,7 @@ void vtkTanglegramItem::ReorderTree() vtkTree *tree = this->Dendrogram2->GetTree(); - this->Tree2Names = vtkStringArray::SafeDownCast( + this->Tree2Names = vtkArrayDownCast( tree->GetVertexData()-> GetAbstractArray("node name")); vtkNew bfsIterator; @@ -610,7 +610,7 @@ double vtkTanglegramItem::GetPositionScoreForVertex(vtkIdType vertex, std::string tree2Name = this->Tree2Names->GetValue(v); // find where this name appears in the correspondence table - vtkDoubleArray *column = vtkDoubleArray::SafeDownCast( + vtkDoubleArray *column = vtkArrayDownCast( this->Table->GetColumnByName(tree2Name.c_str())); if (column == NULL) diff --git a/Views/Infovis/vtkTanglegramItem.h b/Views/Infovis/vtkTanglegramItem.h index fd70377edc6..fb956ee034d 100644 --- a/Views/Infovis/vtkTanglegramItem.h +++ b/Views/Infovis/vtkTanglegramItem.h @@ -108,8 +108,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkTanglegramItem : public vtkContextItem float GetTreeLineWidth(); void SetTreeLineWidth(float width); - // BTX - // Description: // Returns true if the transform is interactive, false otherwise. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -119,8 +117,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkTanglegramItem : public vtkContextItem // subtrees should be collapsed or expanded. virtual bool MouseDoubleClickEvent(const vtkContextMouseEvent &event); - //ETX - protected: vtkTanglegramItem(); ~vtkTanglegramItem(); diff --git a/Views/Infovis/vtkTreeHeatmapItem.cxx b/Views/Infovis/vtkTreeHeatmapItem.cxx index 3697c121ff7..87c32508d1d 100644 --- a/Views/Infovis/vtkTreeHeatmapItem.cxx +++ b/Views/Infovis/vtkTreeHeatmapItem.cxx @@ -105,7 +105,7 @@ void vtkTreeHeatmapItem::SetTable(vtkTable *table) // add an array to this table's field data to keep track of collapsed rows // (unless it already has the array) - vtkBitArray *existingRowsArray = vtkBitArray::SafeDownCast( + vtkBitArray *existingRowsArray = vtkArrayDownCast( this->GetTable()->GetFieldData()->GetArray("collapsed rows")); if (existingRowsArray) { @@ -129,7 +129,7 @@ void vtkTreeHeatmapItem::SetTable(vtkTable *table) // add an array to this table's field data to keep track of collapsed columns // (unless it already has the array) - vtkBitArray *existingColumnsArray = vtkBitArray::SafeDownCast( + vtkBitArray *existingColumnsArray = vtkArrayDownCast( this->GetTable()->GetFieldData()->GetArray("collapsed columns")); if (existingColumnsArray) { @@ -245,7 +245,7 @@ void vtkTreeHeatmapItem::ReorderTable() } // get the names of the vertices in our tree. - vtkStringArray *vertexNames = vtkStringArray::SafeDownCast( + vtkStringArray *vertexNames = vtkArrayDownCast( this->GetTree()->GetVertexData()->GetAbstractArray("node name")); @@ -434,10 +434,10 @@ bool vtkTreeHeatmapItem::MouseDoubleClickEvent( //----------------------------------------------------------------------------- void vtkTreeHeatmapItem::CollapseHeatmapRows() { - vtkBitArray *collapsedRowsArray = vtkBitArray::SafeDownCast( + vtkBitArray *collapsedRowsArray = vtkArrayDownCast( this->GetTable()->GetFieldData()->GetArray("collapsed rows")); - vtkStringArray *vertexNames = vtkStringArray::SafeDownCast( + vtkStringArray *vertexNames = vtkArrayDownCast( this->Dendrogram->GetPrunedTree()->GetVertexData() ->GetAbstractArray("node name")); @@ -466,10 +466,10 @@ void vtkTreeHeatmapItem::CollapseHeatmapRows() //----------------------------------------------------------------------------- void vtkTreeHeatmapItem::CollapseHeatmapColumns() { - vtkBitArray *collapsedColumnsArray = vtkBitArray::SafeDownCast( + vtkBitArray *collapsedColumnsArray = vtkArrayDownCast( this->GetTable()->GetFieldData()->GetArray("collapsed columns")); - vtkStringArray *vertexNames = vtkStringArray::SafeDownCast( + vtkStringArray *vertexNames = vtkArrayDownCast( this->ColumnDendrogram->GetPrunedTree()->GetVertexData() ->GetAbstractArray("node name")); diff --git a/Views/Infovis/vtkTreeHeatmapItem.h b/Views/Infovis/vtkTreeHeatmapItem.h index daf5f2d7dbc..2fac67219bf 100644 --- a/Views/Infovis/vtkTreeHeatmapItem.h +++ b/Views/Infovis/vtkTreeHeatmapItem.h @@ -158,8 +158,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkTreeHeatmapItem : public vtkContextItem // instead. void SetTreeColorArray(const char *arrayName); - //BTX - // Description: // Returns true if the transform is interactive, false otherwise. virtual bool Hit(const vtkContextMouseEvent &mouse); @@ -169,8 +167,6 @@ class VTKVIEWSINFOVIS_EXPORT vtkTreeHeatmapItem : public vtkContextItem // subtrees should be collapsed or expanded. virtual bool MouseDoubleClickEvent(const vtkContextMouseEvent &event); - //ETX - protected: vtkTreeHeatmapItem(); ~vtkTreeHeatmapItem(); diff --git a/Views/Infovis/vtkTreeMapView.h b/Views/Infovis/vtkTreeMapView.h index 341368a681f..e06bdbc6586 100644 --- a/Views/Infovis/vtkTreeMapView.h +++ b/Views/Infovis/vtkTreeMapView.h @@ -59,11 +59,9 @@ class VTKVIEWSINFOVIS_EXPORT vtkTreeMapView : public vtkTreeAreaView vtkTreeMapView(); ~vtkTreeMapView(); - //BTX vtkSmartPointer BoxLayout; vtkSmartPointer SliceAndDiceLayout; vtkSmartPointer SquarifyLayout; - //ETX private: vtkTreeMapView(const vtkTreeMapView&); // Not implemented. diff --git a/Views/Infovis/vtkViewUpdater.h b/Views/Infovis/vtkViewUpdater.h index c56abde48f6..c969d6981fe 100644 --- a/Views/Infovis/vtkViewUpdater.h +++ b/Views/Infovis/vtkViewUpdater.h @@ -54,10 +54,9 @@ class VTKVIEWSINFOVIS_EXPORT vtkViewUpdater : public vtkObject vtkViewUpdater(const vtkViewUpdater&); // Not implemented. void operator=(const vtkViewUpdater&); // Not implemented. -//BTX class vtkViewUpdaterInternals; vtkViewUpdaterInternals* Internals; -//ETX + }; #endif diff --git a/Web/Core/vtkDataEncoder.h b/Web/Core/vtkDataEncoder.h index d9923e1f21e..c7ecfbd216e 100644 --- a/Web/Core/vtkDataEncoder.h +++ b/Web/Core/vtkDataEncoder.h @@ -81,7 +81,6 @@ class VTKWEBCORE_EXPORT vtkDataEncoder : public vtkObject // Take an image data and synchronously convert it to a base-64 encoded jpg. const char* EncodeAsBase64Jpg(vtkImageData* img, int quality=50); -//BTX protected: vtkDataEncoder(); ~vtkDataEncoder(); @@ -92,7 +91,7 @@ class VTKWEBCORE_EXPORT vtkDataEncoder : public vtkObject class vtkInternals; vtkInternals* Internals; -//ETX + }; #endif diff --git a/Web/Core/vtkObjectIdMap.h b/Web/Core/vtkObjectIdMap.h index 862d1c55bae..0fd54cef102 100644 --- a/Web/Core/vtkObjectIdMap.h +++ b/Web/Core/vtkObjectIdMap.h @@ -52,7 +52,6 @@ class VTKWEBCORE_EXPORT vtkObjectIdMap : public vtkObject // Remove any internal reference count due to internal Id/Object mapping void FreeObject(vtkObject* obj); -//BTX protected: vtkObjectIdMap(); ~vtkObjectIdMap(); @@ -63,7 +62,7 @@ class VTKWEBCORE_EXPORT vtkObjectIdMap : public vtkObject struct vtkInternals; vtkInternals* Internals; -//ETX + }; #endif diff --git a/Web/Core/vtkWebApplication.h b/Web/Core/vtkWebApplication.h index 434b465bd55..39be61b5415 100644 --- a/Web/Core/vtkWebApplication.h +++ b/Web/Core/vtkWebApplication.h @@ -96,7 +96,6 @@ class VTKWEBCORE_EXPORT vtkWebApplication : public vtkObject vtkObjectIdMap* GetObjectIdMap(); -//BTX protected: vtkWebApplication(); ~vtkWebApplication(); @@ -112,7 +111,6 @@ class VTKWEBCORE_EXPORT vtkWebApplication : public vtkObject class vtkInternals; vtkInternals* Internals; -//ETX }; #endif diff --git a/Web/Core/vtkWebInteractionEvent.h b/Web/Core/vtkWebInteractionEvent.h index d4c47a207a7..58692d1cfec 100644 --- a/Web/Core/vtkWebInteractionEvent.h +++ b/Web/Core/vtkWebInteractionEvent.h @@ -71,7 +71,7 @@ class VTKWEBCORE_EXPORT vtkWebInteractionEvent : public vtkObject // Handle double click vtkSetMacro(RepeatCount, int); vtkGetMacro(RepeatCount, int); -//BTX + protected: vtkWebInteractionEvent(); ~vtkWebInteractionEvent(); @@ -87,7 +87,7 @@ class VTKWEBCORE_EXPORT vtkWebInteractionEvent : public vtkObject private: vtkWebInteractionEvent(const vtkWebInteractionEvent&); // Not implemented void operator=(const vtkWebInteractionEvent&); // Not implemented -//ETX + }; #endif diff --git a/Web/Core/vtkWebUtilities.h b/Web/Core/vtkWebUtilities.h index d62ebaed78a..5851889ee48 100644 --- a/Web/Core/vtkWebUtilities.h +++ b/Web/Core/vtkWebUtilities.h @@ -44,7 +44,7 @@ class VTKWEBCORE_EXPORT vtkWebUtilities : public vtkObject // background without locking the main one. static void ProcessRMIs(); static void ProcessRMIs(int reportError, int dont_loop=0); -//BTX + protected: vtkWebUtilities(); ~vtkWebUtilities(); @@ -52,7 +52,7 @@ class VTKWEBCORE_EXPORT vtkWebUtilities : public vtkObject private: vtkWebUtilities(const vtkWebUtilities&); // Not implemented void operator=(const vtkWebUtilities&); // Not implemented -//ETX + }; #endif diff --git a/Web/Python/vtk/web/wamp.py b/Web/Python/vtk/web/wamp.py index 685bf8e5ec4..1542760b7d6 100644 --- a/Web/Python/vtk/web/wamp.py +++ b/Web/Python/vtk/web/wamp.py @@ -375,7 +375,7 @@ def onClose(self, wasClean, code, reason): self.renderLoop = False def connectionLost(self, reason): - self.viewToCapture = [] + self.viewToCapture = {} self.renderLoop = False def startRenderLoop(self): diff --git a/Web/WebGLExporter/vtkWebGLDataSet.h b/Web/WebGLExporter/vtkWebGLDataSet.h index f3cbb0ea4cd..7fe7013a331 100644 --- a/Web/WebGLExporter/vtkWebGLDataSet.h +++ b/Web/WebGLExporter/vtkWebGLDataSet.h @@ -46,9 +46,7 @@ class VTKWEBGLEXPORTER_EXPORT vtkWebGLDataSet : public vtkObject void GenerateBinaryData(); bool HasChanged(); - //BTX std::string GetMD5(); - //ETX protected: vtkWebGLDataSet(); diff --git a/Web/WebGLExporter/vtkWebGLExporter.h b/Web/WebGLExporter/vtkWebGLExporter.h index d6191f6a1c4..639659838da 100644 --- a/Web/WebGLExporter/vtkWebGLExporter.h +++ b/Web/WebGLExporter/vtkWebGLExporter.h @@ -63,7 +63,6 @@ class VTKWEBGLEXPORTER_EXPORT vtkWebGLExporter : public vtkObject void SetMaxAllowedSize(int mesh, int lines); void SetMaxAllowedSize(int size); - //BTX static void ComputeMD5(const unsigned char* content, int size, std::string &hash); protected: vtkWebGLExporter(); @@ -96,7 +95,7 @@ class VTKWEBGLEXPORTER_EXPORT vtkWebGLExporter : public vtkObject class vtkInternal; vtkInternal* Internal; - //ETX + }; #endif diff --git a/Web/WebGLExporter/vtkWebGLObject.h b/Web/WebGLExporter/vtkWebGLObject.h index 6b6ac11d316..9100593db66 100644 --- a/Web/WebGLExporter/vtkWebGLObject.h +++ b/Web/WebGLExporter/vtkWebGLObject.h @@ -67,10 +67,10 @@ class VTKWEBGLEXPORTER_EXPORT vtkWebGLObject : public vtkObject bool isWidget(); bool HasTransparency(); bool InteractAtServer(); - //BTX + std::string GetMD5(); std::string GetId(); - //ETX + size_t GetRendererId(); int GetLayer(); diff --git a/Wrapping/Java/vtkJavaAwt.h b/Wrapping/Java/vtkJavaAwt.h index 8f0e83adad0..e78fba8318e 100644 --- a/Wrapping/Java/vtkJavaAwt.h +++ b/Wrapping/Java/vtkJavaAwt.h @@ -32,7 +32,7 @@ #endif #endif -#if defined(_WIN32) || defined(WIN32) +#if defined(_WIN32) #define WIN32_JAWT_LOCK_HACK #endif @@ -108,7 +108,7 @@ Java_vtk_vtkPanel_RenderCreate(JNIEnv *env, jobject canvas, jobject id0) } // Here is the win32 drawing code -#if defined(_WIN32) || defined(WIN32) +#if defined(_WIN32) temp0->Finalize(); JAWT_Win32DrawingSurfaceInfo* dsi_win; dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo; @@ -209,7 +209,7 @@ Java_vtk_rendering_awt_vtkInternalAwtComponent_RenderCreate(JNIEnv *env, jobject } // Here is the win32 drawing code -#if defined(_WIN32) || defined(WIN32) +#if defined(_WIN32) temp0->Finalize(); JAWT_Win32DrawingSurfaceInfo* dsi_win; dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo; diff --git a/Wrapping/Python/CMakeLists.txt b/Wrapping/Python/CMakeLists.txt index ff9706e8927..6b5c0141116 100644 --- a/Wrapping/Python/CMakeLists.txt +++ b/Wrapping/Python/CMakeLists.txt @@ -29,21 +29,143 @@ macro(vtk_include_recurse module) include_directories(${${module}_PYTHON_INCLUDE_DIRS}) endmacro() -# Loop through all modules that should be wrapped, and wrap them. -foreach(module ${VTK_PYTHON_MODULES}) - vtk_module_load(${module}) - vtk_module_headers_load(${module}) - vtk_include_recurse(${module}) - vtk_add_python_wrapping(${module}) -endforeach() + +set(VTK_PYTHON_MODULES_AND_KITS ${VTK_PYTHON_MODULES}) +set(_vtk_python_modules_only ${VTK_PYTHON_MODULES}) + +if(VTK_ENABLE_KITS) + set(_vtk_kits_with_suffix) + set(VTK_KIT_SUFFIX "Kit") # Required to avoid conflict with targets like vtkFiltersPython + # Create list of module that do not belong to any kits + foreach(kit IN LISTS vtk_kits) + # XXX Variable '_${kit}_modules' is set in vtkModuleTop.cmake + list(REMOVE_ITEM _vtk_python_modules_only ${_${kit}_modules}) + list(APPEND _vtk_kits_with_suffix ${kit}${VTK_KIT_SUFFIX}) + endforeach() + set(VTK_PYTHON_MODULES_AND_KITS ${_vtk_kits_with_suffix} ${_vtk_python_modules_only}) + + # Create dependency lists for kits (suffix: _DEPENDS). The function + # vtk_add_python_wrapping_libary uses these lists. + # + # Additionally, create subsets of the full dependency lists that contain only + # Python-wrapped kits and modules (suffix: _PYTHON_DEPENDS). These lists are + # used to topologically sort the dependency graph. + foreach(kit IN LISTS vtk_kits) + set(_module_depends) + foreach(module IN LISTS _${kit}_modules) + vtk_module_load(${module}) + list(APPEND _module_depends ${${module}_DEPENDS}) + endforeach() + + set(_kit_depends) + foreach(dep IN LISTS _module_depends) + if(${dep}_KIT) + list(APPEND _kit_depends ${${dep}_KIT}${VTK_KIT_SUFFIX}) + else() + list(APPEND _kit_depends ${dep}) + endif() + endforeach() + list(REMOVE_DUPLICATES _kit_depends) + set(${kit}${VTK_KIT_SUFFIX}_DEPENDS ${_kit_depends}) + + set(_kit_python_depends) + foreach(module IN LISTS ${kit}${VTK_KIT_SUFFIX}_DEPENDS) + list(FIND VTK_PYTHON_MODULES_AND_KITS ${module} _module_index) + if (_module_index GREATER -1) + list(APPEND _kit_python_depends ${module}) + endif() + endforeach() + list(REMOVE_DUPLICATES _kit_python_depends) + set(${kit}${VTK_KIT_SUFFIX}_PYTHON_DEPENDS ${_kit_python_depends}) + endforeach() + + # Create dependency lists for modules that also consider any dependent kits + # (suffix: _DEPENDS_WITH_KITS). These lists are used to override + # _DEPENDS when calling vtk_add_python_wrapping_library. + # + # Additionally, create subsets of the full dependency lists that contain only + # Python-wrapped kits and modules (suffix: _PYTHON_DEPENDS). These lists are + # used to topologically sort the dependency graph. + foreach(module IN LISTS _vtk_python_modules_only) + vtk_module_load(${module}) + set(_saved_${module}_DEPENDS ${${module}_DEPENDS}) + + set(_module_depends_with_kits) + foreach(dep IN LISTS ${module}_DEPENDS) + if(${dep}_KIT) + list(APPEND _module_depends_with_kits ${${dep}_KIT}${VTK_KIT_SUFFIX}) + else() + list(APPEND _module_depends_with_kits ${dep}) + endif() + endforeach() + list(REMOVE_DUPLICATES _module_depends_with_kits) + set(${module}_DEPENDS_WITH_KITS ${_module_depends_with_kits}) + + set(_module_python_depends) + foreach(module IN LISTS ${module}_DEPENDS_WITH_KITS) + list(FIND VTK_PYTHON_MODULES_AND_KITS ${module} _module_index) + if (_module_index GREATER -1) + list(APPEND _module_python_depends ${module}) + endif() + endforeach() + list(REMOVE_DUPLICATES _module_python_depends) + set(${module}_PYTHON_DEPENDS ${_module_python_depends}) + endforeach() + + # Create list of kits and modules to wrap, ordered to satisfy dependencies. + include(${VTK_CMAKE_DIR}/TopologicalSort.cmake) + set(_vtk_python_wrapping_work_list ${VTK_PYTHON_MODULES_AND_KITS}) + topological_sort(_vtk_python_wrapping_work_list "" _PYTHON_DEPENDS) + + # Wrap kits and modules. + foreach(target IN LISTS _vtk_python_wrapping_work_list) + # Determine whether target is a kit or module + string(REGEX REPLACE "(.+)${VTK_KIT_SUFFIX}\$" "\\1" _stripped_target ${target}) + if(_${_stripped_target}_is_kit) + # Wrap kit + set(kit ${_stripped_target}) + set(kit_srcs) + foreach(module IN LISTS _${kit}_modules) + vtk_module_headers_load(${module}) + vtk_include_recurse(${module}) + endforeach() + vtk_add_python_wrapping("${_${kit}_modules}" kit_srcs ${kit}${VTK_KIT_SUFFIX}) + vtk_add_python_wrapping_library(${kit}${VTK_KIT_SUFFIX} kit_srcs ${_${kit}_modules}) + else() + # Wrap module + set(module ${_stripped_target}) + vtk_module_headers_load(${module}) + vtk_include_recurse(${module}) + vtk_add_python_wrapping(${module} module_srcs) + # Override module dependency list for vtk_add_python_wrapping_library + set(${module}_DEPENDS ${${module}_DEPENDS_WITH_KITS}) + vtk_add_python_wrapping_library(${module} module_srcs ${module}) + set(${module}_DEPENDS ${_saved_${module}_DEPENDS}) + endif() + endforeach() + + # Ensure that original module dependency lists are restored + foreach(module IN LISTS _vtk_python_modules_only) + set(${module}_DEPENDS ${_saved_${module}_DEPENDS}) + unset(_saved_${module}_DEPENDS) + endforeach() + +else(VTK_ENABLE_KITS) + # Loop through all modules that should be wrapped, and wrap them. + foreach(module IN LISTS _vtk_python_modules_only) + vtk_module_load(${module}) + vtk_module_headers_load(${module}) + vtk_include_recurse(${module}) + vtk_add_python_wrapping(${module} module_srcs) + vtk_add_python_wrapping_library(${module} module_srcs ${module}) + endforeach() +endif(VTK_ENABLE_KITS) + option(VTK_ENABLE_VTKPYTHON "Enable vtkpython and pvtkpython binaries" ON) mark_as_advanced(VTK_ENABLE_VTKPYTHON) if(VTK_ENABLE_VTKPYTHON) -# Now to build the vtkPython executable, configure the .py files etc. -get_property(VTK_PYTHON_MODULES GLOBAL PROPERTY VTK_PYTHON_WRAPPED) - vtk_module_load(vtkWrappingPythonCore) vtk_module_load(vtkPython) include_directories(${CMAKE_CURRENT_BINARY_DIR} @@ -166,7 +288,7 @@ if(PYTHON_EXECUTABLE) # Wrapping/Python/vtk/*.py unset(VTK_PYTHON_FILES) unset(VTK_PYTHON_IMPORT_ALL) - foreach(module ${VTK_PYTHON_MODULES}) + foreach(module IN LISTS VTK_PYTHON_MODULES_AND_KITS) set(VTK_PYTHON_IMPORT_ALL "${VTK_PYTHON_IMPORT_ALL}from .${module} import *\n") configure_file(vtk/module.py.in vtk/${module}.py @ONLY) @@ -177,6 +299,17 @@ if(PYTHON_EXECUTABLE) list(APPEND VTK_PYTHON_FILES "${CMAKE_CURRENT_BINARY_DIR}/vtk/__init__.py") +# Kit module adapters + foreach(kit IN LISTS vtk_kits) + set(_module_kit ${kit}${VTK_KIT_SUFFIX}) + foreach(dep IN LISTS _${kit}_modules) + configure_file(vtk/kit_module__init__.py.in vtk/${dep}.py @ONLY) + list(APPEND VTK_PYTHON_FILES + "${CMAKE_CURRENT_BINARY_DIR}/vtk/${dep}.py") + endforeach() + endforeach() + unset(_module_kit) + # vtk.util package list(APPEND VTK_PYTHON_FILES vtk/util/__init__ @@ -295,7 +428,7 @@ if(PYTHON_EXECUTABLE) # Install python extension library that backs the modules if (BUILD_SHARED_LIBS AND NOT VTK_INSTALL_NO_LIBRARIES) - foreach(module ${VTK_PYTHON_MODULES}) + foreach(module IN LISTS VTK_PYTHON_MODULES_AND_KITS) install(TARGETS ${module}Python RUNTIME DESTINATION ${VTK_INSTALL_RUNTIME_DIR} COMPONENT RuntimeLibraries LIBRARY DESTINATION ${VTK_INSTALL_PYTHON_MODULE_DIR}/vtk COMPONENT RuntimeLibraries diff --git a/Wrapping/Python/vtk/kit_module__init__.py.in b/Wrapping/Python/vtk/kit_module__init__.py.in new file mode 100644 index 00000000000..1ae93aba41f --- /dev/null +++ b/Wrapping/Python/vtk/kit_module__init__.py.in @@ -0,0 +1,15 @@ +""" +This module is an adapter for scripts that explicitly import from named +submodules as opposed to from the top-level vtk module. This is necessary +because the specific submodules might not exist when VTK_ENABLE_KITS is enabled. +""" + +from __future__ import absolute_import + +try: + # use relative import for installed modules + from .@_module_kit@Python import * +except ImportError: + # during build and testing, the modules will be elsewhere, + # e.g. in lib directory or Release/Debug config directories + from @_module_kit@Python import * diff --git a/Wrapping/PythonCore/vtkPythonArgs.cxx b/Wrapping/PythonCore/vtkPythonArgs.cxx index e4e0c93cd31..18c0e054715 100644 --- a/Wrapping/PythonCore/vtkPythonArgs.cxx +++ b/Wrapping/PythonCore/vtkPythonArgs.cxx @@ -227,24 +227,20 @@ static bool vtkPythonGetValue( reinterpret_cast(p), &s, "p_void"); #ifdef VTK_PY3K Py_DECREF(bytes); -#endif - if (s >= 0) - { - return true; - } - if (s == -1) + if (s != 0) { - char buf[128]; - sprintf(buf, "value is %.80s, required type is p_void", - reinterpret_cast(p)); - PyErr_SetString(PyExc_TypeError, buf); + PyErr_SetString(PyExc_TypeError, "requires a _addr_p_void string"); return false; } - else +#else + if (s == -1) { - PyErr_SetString(PyExc_TypeError, "cannot get a void pointer"); - return false; + // matched _addr_ but not p_void, assume it isn't a swig ptr string: + // use the buffer's pointer as the argument + a = p; } +#endif + return true; } else if (p && sz >= 0) { diff --git a/Wrapping/PythonCore/vtkPythonUtil.cxx b/Wrapping/PythonCore/vtkPythonUtil.cxx index 7882ee09cda..71fd8642684 100644 --- a/Wrapping/PythonCore/vtkPythonUtil.cxx +++ b/Wrapping/PythonCore/vtkPythonUtil.cxx @@ -354,11 +354,7 @@ PyVTKSpecialType *vtkPythonUtil::FindSpecialType(const char *classname) //-------------------------------------------------------------------- void vtkPythonUtil::AddObjectToMap(PyObject *obj, vtkObjectBase *ptr) { - if (vtkPythonMap == NULL) - { - vtkPythonMap = new vtkPythonUtil(); - Py_AtExit(vtkPythonUtilDelete); - } + vtkPythonUtilCreateIfNeeded(); #ifdef VTKPYTHONDEBUG vtkGenericWarningMacro("Adding an object to map ptr = " << ptr); @@ -441,7 +437,7 @@ PyObject *vtkPythonUtil::GetObjectFromPointer(vtkObjectBase *ptr) { PyObject *obj = NULL; - if (ptr) + if (ptr && vtkPythonMap) { vtkPythonObjectMap::iterator i = vtkPythonMap->ObjectMap->find(ptr); @@ -781,6 +777,12 @@ PyObject *vtkPythonUtil::GetObjectFromObject( void *vtkPythonUtil::GetPointerFromSpecialObject( PyObject *obj, const char *result_type, PyObject **newobj) { + if (vtkPythonMap == NULL) + { + PyErr_SetString(PyExc_TypeError, "method requires a vtkPythonMap"); + return NULL; + } + const char *object_type = vtkPythonUtil::StripModule(Py_TYPE(obj)->tp_name); @@ -865,11 +867,7 @@ void vtkPythonUtil::AddNamespaceToMap(PyObject *module) return; } - if (vtkPythonMap == NULL) - { - vtkPythonMap = new vtkPythonUtil(); - Py_AtExit(vtkPythonUtilDelete); - } + vtkPythonUtilCreateIfNeeded(); const char *name = PyVTKNamespace_GetName(module); // let's make sure it isn't already there @@ -921,11 +919,7 @@ PyObject *vtkPythonUtil::FindNamespace(const char *name) //-------------------------------------------------------------------- void vtkPythonUtil::AddEnumToMap(PyTypeObject *enumtype) { - if (vtkPythonMap == NULL) - { - vtkPythonMap = new vtkPythonUtil(); - Py_AtExit(vtkPythonUtilDelete); - } + vtkPythonUtilCreateIfNeeded(); // Only add to map if it isn't already there const char *enumname = vtkPythonUtil::StripModule(enumtype->tp_name); diff --git a/Wrapping/Tcl/vtkTclUtil.h b/Wrapping/Tcl/vtkTclUtil.h index e196067367c..45db3c0b4a0 100644 --- a/Wrapping/Tcl/vtkTclUtil.h +++ b/Wrapping/Tcl/vtkTclUtil.h @@ -20,7 +20,7 @@ #include "vtkCommand.h" #include "vtkTcl.h" -#ifdef WIN32 +#ifdef _WIN32 #define VTKTCL_EXPORT __declspec( dllexport ) #else #define VTKTCL_EXPORT diff --git a/Wrapping/Tools/lex.yy.c b/Wrapping/Tools/lex.yy.c index 2844180c695..aa38dc8e093 100644 --- a/Wrapping/Tools/lex.yy.c +++ b/Wrapping/Tools/lex.yy.c @@ -2305,16 +2305,10 @@ YY_RULE_SETUP case 4: YY_RULE_SETUP -{ - if (!IgnoreBTX) { - skip_ahead_until("//ETX"); - } - } YY_BREAK case 5: YY_RULE_SETUP -/* eat mismatched ETX */ YY_BREAK case 6: YY_RULE_SETUP diff --git a/Wrapping/Tools/vtkParse.h b/Wrapping/Tools/vtkParse.h index 8d0ab4693cc..cae45ec835c 100644 --- a/Wrapping/Tools/vtkParse.h +++ b/Wrapping/Tools/vtkParse.h @@ -49,11 +49,6 @@ void vtkParse_IncludeDirectory(const char *dirname); */ const char *vtkParse_FindIncludeFile(const char *filename); -/** - * Ignore BTX/ETX markers - */ -void vtkParse_SetIgnoreBTX(int option); - /** * Set the command name, for error reporting and diagnostics. */ diff --git a/Wrapping/Tools/vtkParse.l b/Wrapping/Tools/vtkParse.l index 637be62447c..f727799b532 100644 --- a/Wrapping/Tools/vtkParse.l +++ b/Wrapping/Tools/vtkParse.l @@ -99,14 +99,6 @@ ID [a-zA-Z_\x80-\xff][0-9a-zA-Z_\x80-\xff]* "/*" { skip_comment(); } -^[\t ]*"//BTX".* { - if (!IgnoreBTX) { - skip_ahead_until("//ETX"); - } - } - -^[\t ]*"//ETX".* /* eat mismatched ETX */ - ^[\t ]*("@interface"|"@implementation") { skip_ahead_until("@end"); } diff --git a/Wrapping/Tools/vtkParse.tab.c b/Wrapping/Tools/vtkParse.tab.c index b9565500f0c..dc5ddee3ffe 100644 --- a/Wrapping/Tools/vtkParse.tab.c +++ b/Wrapping/Tools/vtkParse.tab.c @@ -126,6 +126,12 @@ order to eliminate shift/reduce conflicts in the parser. However, this means that this parser will only recognize "scope::*" as valid if it is preceded by "(", e.g. as part of a member function pointer specification. +Variables that are initialized via constructor arguments, for example +"someclass variablename(arglist)", must take a literals as the first +argument. If an identifier is used as the first argument, then the +parser will interpret the variable declaration as a function declaration, +since the parser will assume the identifier names a type. + An odd bit of C++ ambiguity is that y(x); can be interpreted variously as declaration of variable "x" of type "y", as a function call if "y" is the name of a function, or as a constructor if "y" is the name of @@ -213,6 +219,18 @@ static unsigned int vtkParseTypeMap[] = #define VTK_PARSE_FLOAT32 vtkParseTypeMap[VTK_TYPE_FLOAT32] #define VTK_PARSE_FLOAT64 vtkParseTypeMap[VTK_TYPE_FLOAT64] +/* Define the kinds of [[attributes]] to collect */ +enum + { + VTK_PARSE_ATTRIB_NONE, + VTK_PARSE_ATTRIB_DECL, /* modify a declaration */ + VTK_PARSE_ATTRIB_ID, /* modify an id */ + VTK_PARSE_ATTRIB_REF, /* modify *, &, or && */ + VTK_PARSE_ATTRIB_FUNC, /* modify a function or method */ + VTK_PARSE_ATTRIB_ARRAY, /* modify an array size specifier */ + VTK_PARSE_ATTRIB_CLASS /* modify class, struct, union, or enum */ + }; + #define vtkParseDebug(s1, s2) \ if ( parseDebug ) { fprintf(stderr, " %s %s\n", s1, s2); } @@ -235,7 +253,6 @@ int NumberOfDefinitions = 0; const char **Definitions; /* options that can be set by the programs that use the parser */ -int IgnoreBTX = 0; int Recursive = 0; const char *CommandName = NULL; @@ -284,6 +301,7 @@ void handle_complex_type(ValueInfo *val, unsigned int datatype, unsigned int extra, const char *funcSig); void handle_function_type(ValueInfo *param, const char *name, const char *funcSig); +void handle_attribute(const char *att, int pack); void add_legacy_parameter(FunctionInfo *func, ValueInfo *param); void outputSetVectorMacro(const char *var, unsigned int paramType, @@ -1231,6 +1249,23 @@ const char *copySig() return vtkstrdup(cp); } +/* cut the sig from the mark to the current location, and clear the mark */ +const char *cutSig() +{ + const char *cp = NULL; + if (sigMarkDepth > 0) + { + sigMarkDepth--; + } + if (signature) + { + sigLength = sigMark[sigMarkDepth]; + cp = vtkstrdup(&signature[sigLength]); + signature[sigLength] = 0; + } + return cp; +} + /* swap the signature text using the mark as the radix */ void swapSig() { @@ -1633,6 +1668,30 @@ FunctionInfo *getFunction() return functionStack[functionDepth+1]; } +/*---------------------------------------------------------------- + * Attributes + */ + +int attributeRole = 0; + +/* Set kind of attributes to collect in attribute_specifier_seq */ +void setAttributeRole(int x) +{ + attributeRole = x; +} + +/* Get the current kind of attribute */ +int getAttributeRole() +{ + return attributeRole; +} + +/* Ignore attributes until further notice */ +void clearAttributeRole() +{ + attributeRole = 0; +} + /*---------------------------------------------------------------- * Utility methods */ @@ -2000,7 +2059,8 @@ static YYSTYPE yyval_default; #ifndef YY_ATTRIBUTE # if (defined __GNUC__) \ - || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C + || defined __SUNPRO_C \ + && 0x5110 <= __SUNPRO_C # define YY_ATTRIBUTE(Spec) __attribute__(Spec) # else # define YY_ATTRIBUTE(Spec) /* empty */ @@ -2058,16 +2118,16 @@ static YYSTYPE yyval_default; /* YYFINAL -- State number of the termination state. */ #define YYFINAL 3 /* YYLAST -- Last index in YYTABLE. */ -#define YYLAST 9170 +#define YYLAST 8723 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 158 /* YYNNTS -- Number of nonterminals. */ -#define YYNNTS 275 +#define YYNNTS 294 /* YYNRULES -- Number of rules. */ -#define YYNRULES 704 +#define YYNRULES 731 /* YYNRULES -- Number of states. */ -#define YYNSTATES 1185 +#define YYNSTATES 1217 /* YYMAXRHS -- Maximum number of symbols on right-hand side of rule. */ #define YYMAXRHS 10 /* YYMAXLEFT -- Maximum number of symbols to the left of a handle @@ -2129,77 +2189,80 @@ static const unsigned char yytranslate[] = /* YYRLINE[YYN] -- source line where rule number YYN was defined. */ static const unsigned short int yyrline[] = { - 0, 1912, 1912, 1914, 1916, 1915, 1926, 1927, 1928, 1929, - 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, - 1940, 1941, 1942, 1943, 1946, 1947, 1948, 1949, 1950, 1951, - 1954, 1955, 1962, 1969, 1970, 1970, 1974, 1981, 1982, 1985, - 1986, 1987, 1990, 1991, 1994, 1994, 2009, 2008, 2014, 2020, - 2019, 2024, 2030, 2031, 2032, 2035, 2037, 2039, 2042, 2043, - 2046, 2047, 2049, 2051, 2050, 2059, 2063, 2064, 2065, 2068, - 2069, 2070, 2071, 2072, 2073, 2074, 2075, 2076, 2077, 2078, - 2079, 2080, 2081, 2082, 2083, 2086, 2087, 2088, 2089, 2090, - 2093, 2094, 2095, 2096, 2099, 2100, 2103, 2105, 2108, 2113, - 2114, 2117, 2118, 2121, 2122, 2123, 2134, 2135, 2136, 2140, - 2141, 2145, 2145, 2158, 2164, 2172, 2173, 2174, 2177, 2178, - 2178, 2182, 2183, 2185, 2186, 2187, 2187, 2195, 2199, 2200, - 2203, 2205, 2207, 2208, 2211, 2212, 2220, 2221, 2224, 2225, - 2227, 2229, 2231, 2235, 2237, 2238, 2241, 2244, 2245, 2248, - 2249, 2248, 2253, 2294, 2297, 2298, 2299, 2301, 2303, 2305, - 2309, 2312, 2312, 2344, 2347, 2346, 2364, 2366, 2365, 2370, - 2372, 2370, 2374, 2376, 2374, 2378, 2381, 2378, 2392, 2393, - 2396, 2397, 2399, 2400, 2403, 2403, 2413, 2414, 2422, 2423, - 2424, 2425, 2428, 2431, 2432, 2433, 2436, 2437, 2438, 2441, - 2442, 2443, 2447, 2448, 2449, 2450, 2453, 2454, 2455, 2459, - 2464, 2458, 2476, 2480, 2480, 2492, 2491, 2500, 2504, 2507, - 2516, 2517, 2520, 2520, 2521, 2522, 2528, 2533, 2534, 2535, - 2538, 2541, 2542, 2544, 2545, 2548, 2548, 2556, 2557, 2558, - 2561, 2563, 2564, 2568, 2567, 2580, 2581, 2580, 2600, 2600, - 2604, 2605, 2608, 2609, 2612, 2618, 2619, 2619, 2622, 2623, - 2623, 2625, 2627, 2631, 2633, 2631, 2657, 2658, 2661, 2661, - 2663, 2663, 2671, 2674, 2744, 2745, 2747, 2748, 2748, 2751, - 2754, 2755, 2759, 2770, 2770, 2789, 2791, 2791, 2809, 2809, - 2811, 2815, 2816, 2817, 2816, 2822, 2824, 2825, 2826, 2827, - 2828, 2829, 2832, 2833, 2837, 2838, 2842, 2843, 2846, 2847, - 2851, 2852, 2853, 2854, 2857, 2858, 2861, 2861, 2864, 2865, - 2868, 2868, 2872, 2873, 2873, 2880, 2881, 2884, 2885, 2886, - 2887, 2888, 2891, 2893, 2895, 2899, 2901, 2903, 2905, 2907, - 2909, 2911, 2911, 2916, 2919, 2922, 2925, 2925, 2933, 2933, - 2942, 2943, 2944, 2945, 2946, 2947, 2948, 2949, 2950, 2951, - 2952, 2953, 2954, 2955, 2956, 2957, 2958, 2959, 2960, 2961, - 2962, 2969, 2970, 2971, 2972, 2973, 2974, 2975, 2981, 2982, - 2985, 2986, 2988, 2989, 2992, 2993, 2996, 2997, 2998, 2999, - 3002, 3003, 3004, 3005, 3006, 3010, 3011, 3012, 3015, 3016, - 3019, 3020, 3028, 3031, 3031, 3033, 3033, 3037, 3038, 3040, - 3044, 3045, 3047, 3047, 3049, 3051, 3055, 3058, 3058, 3060, - 3060, 3064, 3067, 3067, 3069, 3069, 3073, 3074, 3076, 3078, - 3080, 3082, 3084, 3088, 3089, 3092, 3093, 3094, 3095, 3096, - 3097, 3098, 3099, 3100, 3101, 3102, 3103, 3104, 3105, 3106, - 3107, 3108, 3109, 3110, 3111, 3112, 3115, 3116, 3117, 3118, - 3119, 3120, 3121, 3122, 3123, 3124, 3125, 3126, 3127, 3128, - 3129, 3149, 3150, 3151, 3152, 3155, 3159, 3163, 3163, 3167, - 3168, 3183, 3184, 3200, 3201, 3204, 3204, 3204, 3211, 3211, - 3221, 3222, 3222, 3221, 3231, 3231, 3241, 3241, 3250, 3250, - 3250, 3283, 3282, 3293, 3294, 3294, 3293, 3303, 3321, 3321, - 3326, 3326, 3331, 3331, 3336, 3336, 3341, 3341, 3346, 3346, - 3351, 3351, 3356, 3356, 3361, 3361, 3378, 3378, 3392, 3429, - 3467, 3504, 3505, 3512, 3513, 3514, 3515, 3516, 3517, 3518, - 3519, 3520, 3521, 3522, 3523, 3526, 3527, 3528, 3529, 3530, - 3531, 3532, 3533, 3534, 3535, 3536, 3537, 3538, 3539, 3540, - 3541, 3542, 3543, 3544, 3545, 3546, 3547, 3548, 3549, 3550, - 3551, 3552, 3553, 3554, 3555, 3556, 3557, 3558, 3559, 3562, - 3563, 3564, 3565, 3566, 3567, 3568, 3569, 3570, 3571, 3572, - 3573, 3574, 3575, 3576, 3577, 3578, 3579, 3580, 3581, 3582, - 3583, 3584, 3585, 3586, 3587, 3588, 3589, 3590, 3593, 3594, - 3595, 3596, 3597, 3598, 3599, 3600, 3601, 3608, 3609, 3612, - 3613, 3614, 3615, 3615, 3616, 3619, 3620, 3623, 3624, 3625, - 3626, 3656, 3656, 3657, 3658, 3659, 3660, 3683, 3684, 3687, - 3688, 3689, 3690, 3693, 3694, 3695, 3698, 3699, 3701, 3702, - 3704, 3705, 3708, 3709, 3712, 3713, 3714, 3718, 3717, 3731, - 3732, 3735, 3735, 3737, 3737, 3741, 3741, 3743, 3743, 3745, - 3745, 3749, 3749, 3754, 3755, 3757, 3758, 3761, 3762, 3765, - 3766, 3769, 3770, 3771, 3772, 3773, 3774, 3775, 3776, 3776, - 3776, 3776, 3776, 3777, 3778, 3779, 3780, 3781, 3784, 3787, - 3788, 3791, 3794, 3794, 3794 + 0, 1972, 1972, 1974, 1976, 1975, 1986, 1987, 1988, 1989, + 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, + 2000, 2001, 2002, 2003, 2006, 2007, 2008, 2009, 2010, 2011, + 2014, 2015, 2022, 2029, 2030, 2030, 2034, 2041, 2042, 2045, + 2046, 2047, 2050, 2051, 2054, 2054, 2069, 2068, 2074, 2080, + 2079, 2084, 2090, 2091, 2092, 2095, 2097, 2099, 2102, 2103, + 2106, 2107, 2109, 2111, 2110, 2119, 2123, 2124, 2125, 2128, + 2129, 2130, 2131, 2132, 2133, 2134, 2135, 2136, 2137, 2138, + 2139, 2140, 2141, 2142, 2143, 2146, 2147, 2148, 2149, 2150, + 2153, 2154, 2155, 2156, 2159, 2160, 2163, 2165, 2168, 2173, + 2174, 2177, 2178, 2181, 2182, 2183, 2194, 2195, 2196, 2200, + 2201, 2205, 2205, 2218, 2224, 2232, 2233, 2234, 2237, 2238, + 2238, 2242, 2243, 2245, 2246, 2247, 2247, 2255, 2259, 2260, + 2263, 2265, 2267, 2268, 2271, 2272, 2280, 2281, 2284, 2285, + 2287, 2289, 2291, 2295, 2297, 2298, 2301, 2304, 2305, 2308, + 2309, 2308, 2313, 2354, 2357, 2358, 2359, 2361, 2363, 2365, + 2369, 2372, 2372, 2404, 2407, 2406, 2424, 2426, 2425, 2430, + 2432, 2430, 2434, 2436, 2434, 2438, 2441, 2438, 2452, 2453, + 2456, 2457, 2459, 2460, 2463, 2463, 2473, 2474, 2482, 2483, + 2484, 2485, 2488, 2491, 2492, 2493, 2496, 2497, 2498, 2501, + 2502, 2503, 2507, 2508, 2509, 2510, 2513, 2514, 2515, 2519, + 2525, 2518, 2536, 2540, 2540, 2552, 2551, 2560, 2564, 2567, + 2576, 2577, 2580, 2580, 2581, 2582, 2588, 2593, 2594, 2595, + 2598, 2601, 2602, 2604, 2605, 2608, 2608, 2616, 2617, 2618, + 2621, 2623, 2624, 2628, 2627, 2641, 2642, 2641, 2661, 2661, + 2665, 2666, 2669, 2670, 2673, 2679, 2680, 2680, 2683, 2684, + 2684, 2686, 2688, 2692, 2694, 2692, 2718, 2719, 2722, 2722, + 2724, 2724, 2726, 2726, 2731, 2732, 2732, 2740, 2743, 2813, + 2814, 2816, 2817, 2817, 2820, 2823, 2824, 2828, 2840, 2839, + 2858, 2860, 2860, 2878, 2878, 2880, 2884, 2885, 2886, 2885, + 2891, 2893, 2894, 2895, 2896, 2897, 2898, 2901, 2902, 2906, + 2907, 2911, 2912, 2915, 2916, 2920, 2921, 2922, 2923, 2926, + 2927, 2930, 2930, 2933, 2934, 2937, 2937, 2941, 2942, 2942, + 2949, 2950, 2953, 2954, 2955, 2956, 2957, 2960, 2962, 2964, + 2968, 2970, 2972, 2974, 2976, 2978, 2980, 2980, 2985, 2988, + 2991, 2994, 2994, 3002, 3002, 3011, 3012, 3013, 3014, 3015, + 3016, 3017, 3018, 3019, 3020, 3021, 3022, 3023, 3024, 3025, + 3026, 3027, 3028, 3029, 3030, 3031, 3038, 3039, 3040, 3041, + 3042, 3043, 3044, 3050, 3051, 3054, 3055, 3057, 3058, 3061, + 3062, 3065, 3066, 3067, 3068, 3071, 3072, 3073, 3074, 3075, + 3079, 3080, 3081, 3084, 3085, 3088, 3089, 3097, 3100, 3100, + 3102, 3102, 3106, 3107, 3109, 3113, 3114, 3116, 3116, 3119, + 3121, 3125, 3128, 3128, 3130, 3130, 3134, 3137, 3137, 3139, + 3139, 3143, 3144, 3146, 3148, 3150, 3152, 3154, 3158, 3159, + 3162, 3163, 3164, 3165, 3166, 3167, 3168, 3169, 3170, 3171, + 3172, 3173, 3174, 3175, 3176, 3177, 3178, 3179, 3180, 3181, + 3182, 3185, 3186, 3187, 3188, 3189, 3190, 3191, 3192, 3193, + 3194, 3195, 3196, 3197, 3198, 3199, 3219, 3220, 3221, 3222, + 3225, 3229, 3233, 3233, 3237, 3238, 3253, 3254, 3279, 3279, + 3283, 3283, 3287, 3287, 3291, 3291, 3295, 3295, 3299, 3299, + 3302, 3303, 3306, 3308, 3309, 3310, 3311, 3314, 3314, 3318, + 3319, 3322, 3323, 3326, 3327, 3335, 3335, 3345, 3346, 3346, + 3345, 3355, 3355, 3365, 3365, 3374, 3374, 3374, 3407, 3406, + 3417, 3418, 3418, 3417, 3427, 3445, 3445, 3450, 3450, 3455, + 3455, 3460, 3460, 3465, 3465, 3470, 3470, 3475, 3475, 3480, + 3480, 3485, 3485, 3502, 3502, 3516, 3553, 3591, 3628, 3629, + 3636, 3637, 3638, 3639, 3640, 3641, 3642, 3643, 3644, 3645, + 3646, 3647, 3650, 3651, 3652, 3653, 3654, 3655, 3656, 3657, + 3658, 3659, 3660, 3661, 3662, 3663, 3664, 3665, 3666, 3667, + 3668, 3669, 3670, 3671, 3672, 3673, 3674, 3675, 3676, 3677, + 3678, 3679, 3680, 3681, 3682, 3683, 3686, 3687, 3688, 3689, + 3690, 3691, 3692, 3693, 3694, 3695, 3696, 3697, 3698, 3699, + 3700, 3701, 3702, 3703, 3704, 3705, 3706, 3707, 3708, 3709, + 3710, 3711, 3712, 3713, 3714, 3717, 3718, 3719, 3720, 3721, + 3722, 3723, 3724, 3725, 3732, 3733, 3736, 3737, 3738, 3739, + 3739, 3740, 3743, 3744, 3747, 3748, 3749, 3750, 3780, 3780, + 3781, 3782, 3783, 3784, 3807, 3808, 3811, 3812, 3813, 3814, + 3817, 3818, 3819, 3822, 3823, 3825, 3826, 3828, 3829, 3832, + 3833, 3836, 3837, 3838, 3842, 3841, 3855, 3856, 3859, 3859, + 3861, 3861, 3865, 3865, 3867, 3867, 3869, 3869, 3873, 3873, + 3878, 3879, 3881, 3882, 3885, 3886, 3889, 3890, 3893, 3894, + 3895, 3896, 3897, 3898, 3899, 3900, 3900, 3900, 3900, 3900, + 3901, 3902, 3903, 3904, 3905, 3908, 3911, 3912, 3915, 3918, + 3918, 3918 }; #endif @@ -2273,172 +2336,181 @@ static const char *const yytname[] = "mem_initializer_list", "mem_initializer", "parameter_declaration_clause", "$@32", "parameter_list", "$@33", "parameter_declaration", "$@34", "$@35", "opt_initializer", - "initializer", "$@36", "$@37", "variable_declaration", - "init_declarator_id", "opt_declarator_list", "declarator_list_cont", - "$@38", "init_declarator", "opt_ptr_operator_seq", - "direct_abstract_declarator", "$@39", "direct_declarator", "$@40", - "lp_or_la", "$@41", "opt_array_or_parameters", "$@42", "$@43", - "function_qualifiers", "abstract_declarator", "declarator", - "opt_declarator_id", "declarator_id", "bitfield_size", - "opt_array_decorator_seq", "array_decorator_seq", "$@44", - "array_decorator_seq_impl", "array_decorator", "$@45", - "array_size_specifier", "$@46", "id_expression", "unqualified_id", - "qualified_id", "nested_name_specifier", "$@47", "tilde_sig", - "identifier_sig", "scope_operator_sig", "template_id", "$@48", - "decltype_specifier", "$@49", "simple_id", "identifier", - "opt_decl_specifier_seq", "decl_specifier2", "decl_specifier_seq", - "decl_specifier", "storage_class_specifier", "function_specifier", - "cv_qualifier", "cv_qualifier_seq", "store_type", "store_type_specifier", - "$@50", "$@51", "type_specifier", "trailing_type_specifier", "$@52", - "trailing_type_specifier_seq", "trailing_type_specifier_seq2", "$@53", - "$@54", "tparam_type", "tparam_type_specifier2", "$@55", "$@56", + "initializer", "$@36", "$@37", "$@38", "constructor_args", "$@39", + "variable_declaration", "init_declarator_id", "opt_declarator_list", + "declarator_list_cont", "$@40", "init_declarator", + "opt_ptr_operator_seq", "direct_abstract_declarator", "$@41", + "direct_declarator", "$@42", "lp_or_la", "$@43", + "opt_array_or_parameters", "$@44", "$@45", "function_qualifiers", + "abstract_declarator", "declarator", "opt_declarator_id", + "declarator_id", "bitfield_size", "opt_array_decorator_seq", + "array_decorator_seq", "$@46", "array_decorator_seq_impl", + "array_decorator", "$@47", "array_size_specifier", "$@48", + "id_expression", "unqualified_id", "qualified_id", + "nested_name_specifier", "$@49", "tilde_sig", "identifier_sig", + "scope_operator_sig", "template_id", "$@50", "decltype_specifier", + "$@51", "simple_id", "identifier", "opt_decl_specifier_seq", + "decl_specifier2", "decl_specifier_seq", "decl_specifier", + "storage_class_specifier", "function_specifier", "cv_qualifier", + "cv_qualifier_seq", "store_type", "store_type_specifier", "$@52", "$@53", + "type_specifier", "trailing_type_specifier", "$@54", + "trailing_type_specifier_seq", "trailing_type_specifier_seq2", "$@55", + "$@56", "tparam_type", "tparam_type_specifier2", "$@57", "$@58", "tparam_type_specifier", "simple_type_specifier", "type_name", "primitive_type", "ptr_operator_seq", "reference", "rvalue_reference", - "pointer", "$@57", "ptr_cv_qualifier_seq", "pointer_seq", - "attribute_specifier_seq", "attribute_specifier", "$@58", "$@59", - "declaration_macro", "$@60", "$@61", "$@62", "$@63", "$@64", "$@65", - "$@66", "$@67", "$@68", "$@69", "$@70", "$@71", "$@72", "$@73", "$@74", - "$@75", "$@76", "$@77", "$@78", "$@79", "$@80", "$@81", "opt_comma", - "operator_id", "operator_id_no_delim", "keyword", "literal", - "constant_expression", "constant_expression_item", "$@82", + "pointer", "$@59", "ptr_cv_qualifier_seq", "pointer_seq", + "decl_attribute_specifier_seq", "$@60", "id_attribute_specifier_seq", + "$@61", "ref_attribute_specifier_seq", "$@62", + "func_attribute_specifier_seq", "$@63", "array_attribute_specifier_seq", + "$@64", "class_attribute_specifier_seq", "$@65", + "attribute_specifier_seq", "attribute_specifier", "attribute_list", + "attribute", "$@66", "attribute_pack", "attribute_sig", + "attribute_token", "declaration_macro", "$@67", "$@68", "$@69", "$@70", + "$@71", "$@72", "$@73", "$@74", "$@75", "$@76", "$@77", "$@78", "$@79", + "$@80", "$@81", "$@82", "$@83", "$@84", "$@85", "$@86", "$@87", "$@88", + "opt_comma", "operator_id", "operator_id_no_delim", "keyword", "literal", + "constant_expression", "constant_expression_item", "$@89", "common_bracket_item", "common_bracket_item_no_scope_operator", "any_bracket_contents", "bracket_pitem", "any_bracket_item", "braces_item", "angle_bracket_contents", "braces_contents", "angle_bracket_pitem", "angle_bracket_item", "angle_brackets_sig", - "$@83", "right_angle_bracket", "brackets_sig", "$@84", "$@85", - "parentheses_sig", "$@86", "$@87", "$@88", "braces_sig", "$@89", + "$@90", "right_angle_bracket", "brackets_sig", "$@91", "$@92", + "parentheses_sig", "$@93", "$@94", "$@95", "braces_sig", "$@96", "ignored_items", "ignored_expression", "ignored_item", "ignored_item_no_semi", "ignored_item_no_angle", "ignored_braces", "ignored_brackets", "ignored_parentheses", "ignored_left_parenthesis", YY_NULLPTR }; #endif -#define YYPACT_NINF (-1052) -#define YYTABLE_NINF (-658) +#define YYPACT_NINF -1011 +#define YYTABLE_NINF -685 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const short int yypact[] = { - -1052, 87, 99, -1052, -1052, 7093, 147, 154, 159, 175, - 182, 193, 202, -52, -40, 198, -1052, -1052, -1052, -1052, - 415, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - 73, -1052, 4481, -1052, -1052, 8724, 243, 7577, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, 241, 248, 249, 267, 271, 274, - 281, 288, 309, 332, 339, -32, -10, 0, 9, 104, - 118, 135, 140, 151, 158, 166, 171, 185, 190, 201, - 203, 227, 232, 246, 263, 273, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, 285, -1052, -1052, -1052, -1052, -1052, -1052, - 8394, -1052, 24, 24, 24, 24, -1052, 290, 8724, -1052, - 93, -1052, 308, 7698, 9058, 367, 7874, 206, 220, -1052, - 313, 8504, -1052, -1052, -1052, -1052, 225, 16, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, 323, 4946, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, 7, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, 65, - 7874, 23, 153, 155, 178, 192, 216, 221, 449, -1052, - -1052, -1052, -1052, -1052, 7921, 367, 367, 8724, 225, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, 330, 23, 153, - 155, 178, 192, 216, 221, -1052, -1052, -1052, 7874, 7874, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, 344, 346, -1052, 7698, 7874, 367, 367, 6916, -1052, - -1052, -1052, 6916, 6916, -1052, 6916, 6916, 6916, 6916, 6916, - 6916, 6916, 6916, 6916, 6916, 6916, 6916, 6916, 6916, 7319, - 374, 8103, 7319, -1052, 1834, 360, 7874, -1052, -1052, -1052, - -1052, -1052, -1052, 8394, -1052, -1052, 8614, 225, 381, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, 8724, -1052, - -1052, 501, -1052, -1052, -1052, -1052, 387, 367, 367, 367, - -1052, -1052, -1052, -1052, 313, -1052, -1052, -1052, -1052, 501, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, 7698, -1052, - -1052, 501, -1052, -1052, -1052, 7945, -1052, 186, 95, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, 316, -1052, 501, - 501, 5876, -1052, -1052, 2311, 2466, -1052, -1052, 312, -1052, - 2621, 3706, 2776, -1052, -1052, -1052, -1052, -1052, -1052, 8294, - 8213, 8294, 7687, -1052, -1052, -1052, -1052, -1052, -1052, 7992, - -1052, 2931, 641, 394, -1052, 398, -1052, 72, -1052, -1052, - 6806, 7698, -1052, -1052, -1052, -1052, -1052, -1052, -1052, 399, - 6916, 6916, 6916, 403, 404, 6916, 405, 407, 408, 409, - 412, 413, 414, 416, 420, 421, 425, 392, 396, 428, - -1052, -1052, 435, -1052, 225, -1052, -1052, -1052, -1052, -1052, - -1052, 56, -1052, 8966, 429, 367, 367, 443, 6916, -1052, - -1052, -1052, 363, -1052, 7762, 8614, 7945, 7874, 444, 3086, - 437, 8355, 481, 381, -1052, -1052, -1052, -1052, -1052, 7319, - 8213, 7319, 7687, -1052, -1052, 501, -1052, 491, -1052, -1052, - -1052, 2082, -1052, -1052, 440, -1052, 7698, 131, -1052, -1052, - -1052, 450, 7992, -1052, 451, 225, 501, 501, 501, -1052, - -1052, 8482, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, 447, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, 460, 3861, -1052, -1052, - 453, -1052, -1052, -1052, -1052, 84, -1052, 8834, 52, 555, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, 501, 469, -1052, - 225, 57, 471, -6, 8294, 8294, 134, 170, -1052, -1052, - -1052, -1052, 473, 367, -1052, -1052, -1052, 606, 466, 467, - 13, -1052, -1052, 472, -1052, 474, -1052, -1052, -1052, -1052, - -1052, -1052, 478, 482, 483, -1052, -1052, 480, 8724, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, 7874, -1052, 486, -1052, 501, 124, 7566, -1052, -1052, - 489, 501, -1052, 367, 367, 8966, -1052, 235, -1052, 492, - 8724, 496, 501, -1052, 7698, 493, -1052, 70, -1052, -1052, - 494, 551, -1052, 367, -1052, 437, 6031, 502, 63, 504, - 363, 8482, -1052, 491, -1052, -1052, 34, 59, -1052, -1052, - 507, 49, -1052, -1052, -1052, -1052, -1052, 6341, -1052, -1052, - -1052, 491, -1052, -1052, -1052, 495, -1052, -1052, -1052, -1052, - -1052, 7874, 7874, 7874, -1052, 367, 367, 8724, 225, 16, - -1052, -1052, -1052, -1052, 225, 52, 5101, 5256, 5411, -1052, - 514, -1052, -1052, -1052, 520, 521, -1052, 16, -1052, 31, - -1052, 522, 8724, -1052, 512, 513, -1052, -1052, -1052, -1052, - 8724, -1052, -1052, -1052, 8724, 8724, -1052, 518, 8724, 8724, - 8724, 8724, 8724, 8724, 8724, 8724, 8724, 8724, 523, -1052, - -1052, -1052, -1052, -1052, 525, -1052, -1052, -1052, 463, 527, - -1052, 624, 578, -1052, 501, -1052, -1052, 6916, -1052, -1052, - -1052, 275, 7874, 578, 3241, -1052, -1052, 529, -1052, 8724, - -1052, -1052, 528, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, 530, -1052, 59, -1052, -1052, -1052, - -1052, -1052, -1052, 55, -1052, 65, -1052, -1052, -1052, -1052, - 507, -1052, 575, -1052, 37, 16, -1052, 6186, -1052, 6341, - -1052, -1052, -1052, 251, -1052, 5566, 4636, 5721, -1052, 312, - -1052, -1052, -1052, -1052, 7992, -1052, -1052, -1052, -1052, -1052, - 225, -1052, -1052, -1052, -1052, -1052, -1052, 437, -1052, 225, - -1052, -1052, 531, 8724, -1052, 532, 8724, -1052, 533, 534, - 536, 537, 539, 541, 542, 544, 548, 552, -1052, 553, - 6960, -1052, 7874, -1052, -1052, -1052, 7874, -1052, 7566, 501, - -1052, 6341, -1052, 558, -1052, -1052, -1052, -1052, 501, 610, - 225, 59, -1052, -1052, -1052, -1052, 437, 65, 8944, -1052, - -1052, -1052, -1052, 554, -1052, -1052, -1052, -1052, -1052, -1052, - 437, -1052, 6651, -1052, -1052, -1052, -1052, 556, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, 251, -1052, 559, 125, 8482, - 559, -1052, 560, 563, -1052, -1052, 565, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, 687, 690, -1052, - 7226, 76, 7809, 70, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, 2165, -1052, 24, -1052, - -1052, -1052, 571, 387, 7698, 7341, 225, -1052, 578, 1580, - 578, 527, 6341, 4791, -1052, 660, -1052, -1052, -1052, -1052, - -1052, 501, 6031, 566, -1052, 8944, -1052, -1052, 16, 567, - 6341, 572, -1052, 437, -1052, 8482, -1052, -1052, -1052, -1052, - -1052, 573, 225, -1052, 559, -1052, -1052, 576, -1052, 581, - 582, 583, -1052, -1052, -1052, 766, 24, 387, 7456, 578, - -1052, -1052, -1052, -1052, 2165, -1052, -1052, 7456, -1052, -1052, - -1052, -1052, 7698, 7945, -1052, -1052, -1052, 70, 59, -1052, - 186, -1052, -1052, -1052, -1052, -1052, -1052, 6341, -1052, 586, - 6496, -1052, -1052, -1052, -1052, -1052, 4016, -1052, -1052, -1052, - 8056, -1052, -1052, 766, -1052, -1052, 7945, 7456, 32, -1052, - -1052, 577, -1052, -1052, 501, -1052, 8482, 501, 501, -1052, - 6496, -1052, 251, 326, -1052, -1052, -1052, 69, -1052, 8056, - -1052, 8175, -1052, 39, -1052, 8482, 501, -1052, -1052, -1052, - -1052, 70, 70, 3396, 4171, 258, 46, 8175, 83, -1052, - -1052, 3551, -1052, -1052, -1052, -1052, -1052, -1052, 48, 258, - -1052, 326, 4326, -1052, -1052 + -1011, 99, 124, -1011, -1011, 6666, -1011, 144, 154, 174, + 205, 225, 259, 282, 194, 286, 289, -1011, -1011, -1011, + 236, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + 72, -1011, 4209, -1011, -1011, 8256, 74, 7254, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, 291, 312, 319, 344, 346, 360, + 373, 374, 386, 391, 393, -7, 8, 31, 58, 109, + 193, 217, 224, 237, 241, 249, 260, 267, 301, 309, + 310, 326, 333, 345, 357, 359, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, 170, -1011, -1011, -1011, -1011, -1011, -1011, + 7926, -1011, 50, 50, 50, 50, -1011, 364, 8256, -1011, + 242, -1011, 398, 7275, 8611, 399, 7531, 130, 190, -1011, + 410, 8036, -1011, -1011, -1011, -1011, 135, 126, -1011, -1011, + -1011, -1011, -1011, -1011, 518, -1011, -1011, 411, 4674, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, 10, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, 91, 7531, + -26, 19, 25, 45, 71, 139, 158, 543, -1011, -1011, + -1011, -1011, -1011, 7578, 399, 399, 8256, 135, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, 424, -26, 19, 25, + 45, 71, 139, 158, -1011, -1011, -1011, 7531, 7531, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + 434, 436, -1011, 7275, 7531, 399, 399, 6489, -1011, -1011, + -1011, 6489, 6489, -1011, 6489, 6489, 6489, 6489, 6489, 6489, + 6489, 6489, 6489, 6489, 6489, 6489, 6489, 6489, 2135, 437, + 7724, -1011, 2135, -1011, 7304, 432, 7531, -1011, -1011, -1011, + -1011, -1011, -1011, 7926, -1011, -1011, 8146, 135, 442, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, 8256, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, 444, 399, 399, 399, + -1011, -1011, -1011, -1011, 410, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, 7275, -1011, + -1011, -1011, -1011, -1011, -1011, 7602, -1011, 405, 79, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, 133, -1011, -1011, + -1011, 36, -1011, -1011, -1011, 1829, 2054, -1011, -1011, 330, + -1011, 2349, 3434, 2504, -1011, -1011, -1011, -1011, -1011, -1011, + 6892, 7834, 6892, 7419, -1011, -1011, -1011, -1011, -1011, -1011, + 7649, -1011, 2659, 877, 447, -1011, 452, -1011, 458, -1011, + -1011, -1011, 6379, 7275, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, 450, 6489, 6489, 6489, 457, 462, 6489, 465, 470, + 471, 472, 473, 474, 475, 482, 488, 489, 490, 491, + 493, 496, -1011, -1011, 502, -1011, 135, -1011, -1011, -1011, + -1011, -1011, -1011, 55, -1011, 8498, 896, 399, 399, 518, + 503, 6489, -1011, -1011, -1011, 277, -1011, 7531, 8146, 7602, + 7531, 507, 2814, 497, 8590, 812, 442, -1011, -1011, -1011, + -1011, -1011, 2135, 7834, 2135, 7419, -1011, -1011, -1011, -1011, + 337, -1011, -1011, -1011, 1550, -1011, -1011, 500, -1011, 7275, + 137, -1011, -1011, -1011, 509, 505, 7649, -1011, 508, 135, + -1011, -1011, -1011, -1011, -1011, -1011, 1692, 159, -1011, 812, + 515, 3589, -1011, -1011, 510, -1011, -1011, -1011, -1011, 118, + -1011, 8366, 121, 610, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, 521, -1011, 135, 62, 526, -25, 6892, 6892, + 187, 248, -1011, -1011, -1011, -1011, 527, 399, -1011, -1011, + -1011, 518, 650, 519, 520, 24, -1011, -1011, 524, -1011, + 522, -1011, -1011, -1011, -1011, -1011, -1011, 529, 528, 537, + -1011, -1011, 531, 8256, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, 7531, -1011, 538, -1011, + -1011, 76, 2236, -1011, -1011, 541, -1011, -1011, 399, 399, + 8498, -1011, 210, -1011, 545, 8256, 546, -1011, -1011, 7275, + 548, -1011, 116, -1011, -1011, 556, 606, -1011, 399, -1011, + 497, 5604, 567, 70, 569, 277, 1692, -1011, 337, -1011, + -1011, 564, 122, -1011, -1011, 562, 153, -1011, -1011, -1011, + -1011, -1011, 5914, -1011, -1011, 1246, -1011, -1011, 518, 337, + 198, 565, 399, -1011, 623, 91, -1011, -1011, -1011, -1011, + -1011, 7531, 7531, 7531, -1011, 399, 399, 8256, 135, 126, + -1011, -1011, -1011, -1011, 135, 121, 4829, 4984, 5139, -1011, + 571, -1011, -1011, -1011, 574, 577, -1011, 126, -1011, 576, + -1011, 579, 8256, -1011, 572, 573, -1011, -1011, -1011, -1011, + 8256, -1011, -1011, -1011, 8256, 8256, -1011, 578, 8256, 8256, + 8256, 8256, 8256, 8256, 8256, 8256, 8256, 8256, 589, -1011, + -1011, -1011, -1011, -1011, 591, -1011, -1011, -1011, 549, 592, + -1011, 694, 651, -1011, -1011, -1011, -1011, 6489, -1011, -1011, + -1011, 203, 7531, 651, 2969, -1011, -1011, 594, -1011, -1011, + -1011, -1011, 597, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, 601, -1011, + 122, -1011, -1011, -1011, -1011, -1011, -1011, 214, -1011, 91, + -1011, -1011, -1011, -1011, 562, -1011, 536, -1011, 600, 126, + -1011, 5759, -1011, 5914, -1011, -1011, -1011, -1011, 293, -1011, + 287, -1011, -1011, -1011, 812, -1011, -1011, -1011, 330, -1011, + -1011, -1011, -1011, 7649, -1011, -1011, -1011, -1011, -1011, 135, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, 497, -1011, 135, -1011, -1011, 602, + 8256, -1011, 608, 8256, -1011, 611, 617, 621, 624, 625, + 627, 630, 631, 603, 612, -1011, 632, 6533, -1011, 7531, + -1011, -1011, -1011, 7531, -1011, 2236, -1011, -1011, 5914, -1011, + 607, -1011, -1011, -1011, -1011, -1011, -1011, 664, 8256, 122, + -1011, -1011, -1011, -1011, -1011, -1011, 497, 91, 8476, -1011, + -1011, -1011, -1011, 620, -1011, -1011, -1011, -1011, -1011, -1011, + 497, -1011, 6224, -1011, 4364, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, 325, -1011, 613, 79, 1692, 613, -1011, + 633, 642, -1011, -1011, 638, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, 766, 767, -1011, 6914, 96, + 7466, 116, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, 6799, -1011, 50, -1011, -1011, -1011, + 646, 444, 7275, 7029, 135, -1011, 651, 2236, 651, 592, + 5914, 4519, -1011, 735, -1011, 518, -1011, -1011, 135, -1011, + -1011, 5294, 5604, 5449, 644, -1011, 8476, -1011, -1011, 126, + 645, 5914, 649, -1011, -1011, -1011, -1011, -1011, 5914, 497, + 1692, -1011, -1011, -1011, -1011, -1011, 654, 135, -1011, 613, + -1011, -1011, 655, -1011, 658, 659, 661, -1011, -1011, -1011, + 1484, 50, 444, 7144, 651, -1011, -1011, -1011, -1011, 6799, + -1011, -1011, 7144, -1011, -1011, -1011, -1011, 7275, 7602, -1011, + -1011, -1011, 116, 122, -1011, -1011, 660, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, 5914, -1011, 5914, 668, 6069, -1011, + -1011, -1011, -1011, -1011, 3744, -1011, -1011, -1011, 7713, -1011, + -1011, 1484, -1011, -1011, 7602, 7144, 671, -1011, -1011, 675, + -1011, 405, -1011, -1011, -1011, 1692, -1011, -1011, -1011, -1011, + 6069, -1011, 416, 404, -1011, -1011, -1011, 110, -1011, 7713, + -1011, 7762, -1011, 677, -1011, -1011, 1692, 518, -1011, -1011, + -1011, -1011, -1011, 116, 127, 3124, 3899, 354, 61, 7762, + 112, -1011, -1011, 3279, -1011, -1011, -1011, -1011, -1011, -1011, + 83, 354, -1011, 404, 4054, -1011, -1011 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. @@ -2446,191 +2518,198 @@ static const short int yypact[] = means the default is an error. */ static const unsigned short int yydefact[] = { - 3, 0, 4, 1, 483, 0, 439, 440, 441, 435, - 436, 437, 438, 443, 444, 442, 485, 53, 52, 54, - 115, 398, 399, 390, 393, 394, 396, 397, 395, 389, - 391, 218, 0, 348, 412, 0, 0, 0, 345, 456, - 457, 458, 459, 460, 465, 466, 467, 468, 461, 462, - 463, 464, 469, 470, 455, 445, 446, 447, 448, 449, - 450, 451, 452, 453, 454, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 23, 343, 5, 19, - 20, 13, 11, 12, 9, 37, 17, 378, 44, 483, - 10, 16, 378, 0, 483, 14, 136, 7, 6, 8, + 3, 0, 4, 1, 488, 0, 500, 444, 445, 446, + 440, 441, 442, 443, 448, 449, 447, 53, 52, 54, + 115, 403, 404, 395, 398, 399, 401, 402, 400, 394, + 396, 218, 0, 353, 417, 0, 0, 0, 350, 461, + 462, 463, 464, 465, 470, 471, 472, 473, 466, 467, + 468, 469, 474, 475, 460, 450, 451, 452, 453, 454, + 455, 456, 457, 458, 459, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 23, 348, 5, 19, + 20, 13, 11, 12, 9, 37, 17, 383, 44, 498, + 10, 16, 383, 0, 498, 14, 136, 7, 6, 8, 0, 18, 0, 0, 0, 0, 206, 0, 0, 15, - 0, 325, 483, 0, 0, 0, 0, 483, 411, 327, - 344, 0, 483, 386, 387, 388, 178, 280, 403, 407, - 410, 483, 483, 484, 21, 637, 117, 116, 392, 0, - 439, 440, 441, 435, 436, 437, 438, 703, 704, 614, - 609, 610, 611, 608, 612, 613, 615, 616, 443, 444, - 442, 673, 582, 581, 583, 601, 585, 587, 586, 588, - 589, 590, 593, 594, 592, 591, 597, 600, 584, 602, - 603, 595, 580, 579, 599, 598, 555, 556, 596, 606, - 605, 604, 607, 557, 558, 559, 687, 560, 561, 562, - 568, 569, 563, 564, 565, 566, 567, 570, 571, 572, - 573, 574, 575, 576, 577, 578, 685, 684, 697, 455, - 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, - 673, 691, 688, 692, 702, 164, 673, 551, 552, 546, - 690, 545, 547, 548, 549, 550, 553, 554, 689, 696, - 695, 686, 693, 694, 675, 681, 683, 682, 673, 0, - 0, 439, 440, 441, 435, 436, 437, 438, 391, 378, - 483, 378, 483, 483, 0, 483, 411, 0, 178, 371, - 373, 372, 376, 377, 375, 374, 673, 34, 352, 350, - 351, 355, 356, 354, 353, 359, 358, 357, 0, 0, - 370, 360, 361, 362, 363, 364, 365, 366, 367, 368, - 369, 0, 483, 326, 0, 0, 328, 329, 0, 490, - 494, 496, 0, 0, 503, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 280, - 0, 51, 280, 111, 118, 0, 0, 27, 38, 24, - 483, 26, 28, 0, 25, 29, 0, 178, 250, 239, - 673, 188, 238, 190, 191, 189, 209, 483, 0, 212, - 22, 415, 341, 196, 194, 245, 332, 0, 328, 329, - 330, 59, 331, 58, 0, 335, 333, 334, 336, 414, - 337, 346, 378, 483, 378, 483, 137, 207, 0, 483, - 405, 384, 288, 290, 179, 0, 276, 266, 178, 483, - 483, 483, 402, 281, 471, 472, 481, 473, 378, 434, - 433, 486, 3, 675, 0, 0, 660, 659, 169, 163, - 0, 0, 0, 667, 669, 665, 349, 483, 392, 280, - 51, 280, 118, 332, 378, 378, 152, 148, 144, 0, - 147, 0, 0, 0, 155, 0, 153, 0, 157, 156, - 0, 0, 352, 350, 351, 355, 356, 354, 353, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 383, 382, 0, 276, 178, 483, 380, 381, 62, 40, - 49, 408, 483, 0, 0, 59, 0, 0, 123, 107, - 119, 114, 483, 483, 0, 0, 0, 0, 0, 0, - 256, 0, 0, 250, 248, 338, 339, 340, 648, 280, - 51, 280, 118, 197, 195, 385, 378, 479, 208, 213, - 483, 0, 192, 220, 314, 483, 0, 0, 268, 273, - 267, 0, 0, 304, 0, 178, 476, 475, 477, 474, - 482, 404, 663, 642, 626, 671, 644, 631, 645, 640, - 661, 641, 632, 636, 635, 0, 630, 633, 634, 639, - 625, 643, 638, 627, 628, 629, 4, 0, 678, 680, - 0, 674, 677, 679, 698, 0, 166, 0, 0, 0, - 699, 31, 676, 701, 637, 637, 637, 413, 0, 144, - 178, 408, 0, 483, 280, 280, 0, 314, 483, 328, - 329, 33, 0, 0, 3, 160, 161, 0, 555, 556, - 0, 540, 539, 0, 537, 0, 538, 217, 544, 159, - 158, 488, 0, 0, 0, 498, 501, 0, 0, 508, - 512, 516, 520, 510, 514, 518, 522, 524, 526, 528, - 529, 0, 42, 275, 279, 379, 63, 0, 61, 39, - 48, 57, 483, 59, 0, 0, 109, 0, 121, 124, - 0, 113, 409, 483, 0, 251, 252, 0, 673, 237, - 0, 263, 408, 0, 246, 256, 0, 0, 408, 0, - 483, 406, 400, 480, 289, 220, 0, 233, 285, 315, - 0, 308, 198, 193, 483, 272, 277, 0, 271, 286, - 305, 479, 637, 650, 637, 0, 32, 30, 700, 167, - 165, 0, 0, 0, 429, 428, 427, 0, 178, 280, - 422, 426, 180, 181, 178, 0, 0, 0, 0, 139, - 143, 146, 141, 113, 0, 0, 138, 280, 149, 308, - 36, 4, 0, 543, 0, 0, 542, 541, 533, 534, - 0, 491, 495, 497, 0, 0, 504, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 531, 66, - 67, 68, 45, 483, 0, 103, 104, 105, 101, 50, - 94, 99, 178, 46, 55, 483, 112, 123, 125, 120, - 106, 327, 0, 178, 0, 483, 262, 257, 258, 0, - 342, 220, 0, 655, 656, 657, 653, 654, 649, 652, - 347, 43, 41, 110, 113, 401, 233, 215, 226, 224, - 222, 230, 235, 0, 221, 228, 229, 219, 234, 320, - 317, 318, 0, 243, 0, 280, 624, 621, 622, 269, - 617, 619, 620, 291, 478, 0, 0, 0, 487, 169, - 430, 431, 432, 424, 306, 170, 483, 421, 378, 173, - 178, 668, 670, 666, 140, 142, 145, 256, 35, 178, - 535, 536, 0, 0, 499, 0, 0, 507, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 532, 0, - 0, 65, 0, 102, 483, 100, 0, 96, 0, 56, - 122, 0, 675, 0, 129, 253, 254, 241, 210, 259, - 178, 233, 483, 648, 108, 214, 256, 0, 0, 225, - 231, 232, 227, 323, 319, 311, 312, 313, 310, 309, - 256, 278, 0, 618, 292, 287, 295, 0, 647, 672, - 646, 651, 662, 168, 378, 291, 307, 182, 178, 423, - 182, 176, 0, 0, 489, 492, 0, 502, 505, 509, - 513, 517, 521, 511, 515, 519, 523, 0, 0, 530, - 0, 391, 0, 0, 84, 80, 71, 77, 64, 79, - 73, 72, 76, 74, 69, 70, 0, 78, 0, 203, - 204, 75, 0, 325, 0, 0, 178, 81, 178, 0, - 178, 47, 126, 128, 127, 240, 220, 261, 263, 264, - 247, 249, 0, 0, 223, 0, 417, 236, 280, 0, - 0, 0, 623, 256, 664, 425, 282, 184, 171, 183, - 302, 0, 178, 174, 182, 150, 162, 0, 675, 0, - 0, 0, 92, 483, 90, 0, 0, 0, 0, 178, - 82, 85, 87, 88, 0, 86, 89, 0, 199, 83, - 483, 205, 0, 0, 97, 95, 98, 0, 233, 260, - 266, 658, 483, 419, 378, 416, 483, 324, 483, 0, - 0, 283, 303, 177, 296, 493, 0, 506, 525, 527, - 0, 483, 91, 0, 93, 483, 0, 0, 0, 483, - 202, 0, 211, 265, 216, 378, 418, 321, 244, 483, - 185, 186, 291, 151, 500, 673, 675, 408, 132, 0, - 483, 0, 200, 0, 673, 420, 293, 187, 284, 298, - 297, 0, 301, 0, 0, 0, 60, 0, 408, 133, - 201, 0, 296, 299, 300, 675, 135, 130, 60, 0, - 242, 294, 0, 131, 134 + 0, 330, 488, 0, 0, 0, 0, 488, 416, 332, + 349, 0, 488, 391, 392, 393, 178, 285, 408, 412, + 415, 488, 488, 21, 489, 117, 116, 397, 0, 444, + 445, 446, 440, 441, 442, 443, 730, 731, 641, 636, + 637, 638, 635, 639, 640, 642, 643, 448, 449, 447, + 700, 609, 608, 610, 628, 612, 614, 613, 615, 616, + 617, 620, 621, 619, 618, 624, 627, 611, 629, 630, + 622, 607, 606, 626, 625, 582, 583, 623, 633, 632, + 631, 634, 584, 585, 586, 714, 587, 588, 589, 595, + 596, 590, 591, 592, 593, 594, 597, 598, 599, 600, + 601, 602, 603, 604, 605, 712, 711, 724, 460, 450, + 451, 452, 453, 454, 455, 456, 457, 458, 459, 700, + 718, 715, 719, 729, 164, 700, 578, 579, 573, 717, + 572, 574, 575, 576, 577, 580, 581, 716, 723, 722, + 713, 720, 721, 702, 708, 710, 709, 700, 0, 0, + 444, 445, 446, 440, 441, 442, 443, 396, 383, 498, + 383, 498, 488, 0, 488, 416, 0, 178, 376, 378, + 377, 381, 382, 380, 379, 700, 34, 357, 355, 356, + 360, 361, 359, 358, 364, 363, 362, 0, 0, 375, + 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, + 0, 490, 331, 0, 0, 333, 334, 0, 517, 521, + 523, 0, 0, 530, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 285, 0, + 51, 500, 285, 111, 118, 0, 0, 27, 38, 24, + 498, 26, 28, 0, 25, 29, 0, 178, 250, 239, + 700, 188, 238, 190, 191, 189, 209, 498, 0, 212, + 22, 420, 346, 196, 194, 245, 337, 0, 333, 334, + 335, 59, 336, 58, 0, 340, 338, 339, 341, 419, + 342, 351, 383, 498, 383, 498, 137, 207, 0, 488, + 410, 389, 293, 295, 179, 0, 281, 266, 178, 492, + 492, 492, 407, 286, 476, 477, 486, 478, 383, 439, + 438, 507, 501, 3, 702, 0, 0, 687, 686, 169, + 163, 0, 0, 0, 694, 696, 692, 354, 488, 397, + 285, 51, 285, 118, 337, 383, 383, 152, 148, 144, + 0, 147, 0, 0, 0, 155, 0, 153, 0, 500, + 157, 156, 0, 0, 357, 355, 356, 360, 361, 359, + 358, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 388, 387, 0, 281, 178, 488, 385, 386, + 62, 40, 49, 413, 488, 0, 0, 59, 0, 499, + 0, 123, 107, 119, 114, 488, 490, 0, 0, 0, + 0, 0, 0, 256, 0, 0, 250, 248, 343, 344, + 345, 675, 285, 51, 285, 118, 197, 195, 390, 383, + 484, 208, 213, 490, 0, 192, 220, 319, 490, 0, + 0, 268, 278, 267, 0, 0, 0, 309, 0, 178, + 481, 500, 480, 482, 479, 487, 409, 0, 504, 0, + 4, 0, 705, 707, 0, 701, 704, 706, 725, 0, + 166, 0, 0, 0, 726, 31, 703, 728, 664, 664, + 664, 418, 0, 144, 178, 413, 0, 488, 285, 285, + 0, 319, 490, 333, 334, 33, 0, 0, 3, 160, + 161, 491, 0, 582, 583, 0, 567, 566, 0, 564, + 0, 565, 217, 571, 159, 158, 515, 0, 0, 0, + 525, 528, 0, 0, 535, 539, 543, 547, 537, 541, + 545, 549, 551, 553, 555, 556, 0, 42, 280, 284, + 384, 63, 0, 61, 39, 48, 57, 488, 59, 0, + 0, 109, 0, 121, 124, 0, 113, 414, 488, 0, + 251, 252, 0, 700, 237, 0, 488, 413, 0, 246, + 256, 0, 0, 413, 0, 488, 411, 405, 485, 294, + 220, 0, 233, 290, 320, 0, 313, 198, 193, 490, + 277, 282, 0, 698, 271, 0, 291, 310, 493, 484, + 507, 0, 513, 349, 509, 511, 32, 30, 727, 167, + 165, 0, 0, 0, 434, 433, 432, 0, 178, 285, + 427, 431, 180, 181, 178, 0, 0, 0, 0, 139, + 143, 146, 141, 113, 0, 0, 138, 285, 149, 313, + 36, 4, 0, 570, 0, 0, 569, 568, 560, 561, + 0, 518, 522, 524, 0, 0, 531, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 558, 66, + 67, 68, 45, 488, 0, 103, 104, 105, 101, 50, + 94, 99, 178, 46, 55, 488, 112, 123, 125, 120, + 106, 332, 0, 178, 0, 494, 262, 257, 258, 263, + 347, 220, 0, 690, 653, 682, 658, 683, 684, 688, + 659, 663, 662, 657, 660, 661, 680, 652, 681, 676, + 679, 352, 654, 655, 656, 43, 41, 110, 113, 406, + 233, 215, 226, 224, 222, 230, 235, 0, 221, 228, + 229, 219, 234, 325, 322, 323, 0, 243, 0, 285, + 651, 648, 649, 269, 644, 646, 647, 677, 0, 274, + 296, 483, 506, 502, 0, 510, 508, 512, 169, 435, + 436, 437, 429, 311, 170, 492, 426, 383, 173, 178, + 669, 671, 672, 695, 667, 668, 666, 670, 665, 697, + 693, 140, 142, 145, 256, 35, 178, 562, 563, 0, + 0, 526, 0, 0, 534, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 559, 0, 0, 65, 0, + 102, 488, 100, 0, 96, 0, 56, 122, 0, 702, + 0, 129, 253, 254, 241, 210, 500, 259, 0, 233, + 494, 664, 675, 664, 108, 214, 256, 0, 0, 225, + 231, 232, 227, 328, 324, 316, 317, 318, 315, 314, + 256, 283, 0, 645, 0, 275, 273, 297, 292, 300, + 514, 168, 383, 296, 312, 182, 178, 428, 182, 176, + 0, 0, 516, 519, 0, 529, 532, 536, 540, 544, + 548, 538, 542, 546, 550, 0, 0, 557, 0, 396, + 0, 0, 84, 80, 71, 77, 64, 79, 73, 72, + 76, 74, 69, 70, 0, 78, 0, 203, 204, 75, + 0, 330, 0, 0, 178, 81, 178, 0, 178, 47, + 126, 128, 127, 240, 220, 495, 261, 488, 178, 247, + 249, 0, 0, 0, 0, 223, 0, 422, 236, 285, + 0, 0, 0, 650, 674, 699, 673, 678, 0, 256, + 430, 287, 184, 171, 183, 307, 0, 178, 174, 182, + 150, 162, 0, 702, 0, 0, 0, 92, 498, 90, + 0, 0, 0, 0, 178, 82, 85, 87, 88, 0, + 86, 89, 0, 199, 83, 490, 205, 0, 0, 97, + 95, 98, 0, 233, 260, 264, 0, 685, 689, 494, + 424, 383, 421, 496, 329, 494, 276, 0, 0, 288, + 308, 177, 301, 520, 0, 533, 552, 554, 0, 498, + 91, 0, 93, 498, 0, 0, 0, 490, 202, 0, + 211, 266, 691, 216, 383, 423, 326, 500, 244, 494, + 185, 186, 296, 151, 527, 700, 702, 413, 132, 0, + 498, 0, 200, 0, 700, 265, 425, 497, 298, 187, + 289, 303, 302, 0, 306, 0, 0, 0, 60, 0, + 413, 133, 201, 0, 301, 304, 305, 702, 135, 130, + 60, 0, 242, 299, 0, 131, 134 }; /* YYPGOTO[NTERM-NUM]. */ static const short int yypgoto[] = { - -1052, -1052, -393, -1052, -1052, 715, -191, -1052, -1052, -1052, - -1052, -856, -100, -1, -34, -1052, -1052, -1052, -1052, 152, - -416, -108, -780, -1052, -1052, -1052, -1052, -188, -1052, -194, - -289, -1052, -1052, -67, -178, -175, -33, -1052, -1052, -2, - -476, -1052, -1052, -71, -1052, -1052, -1052, -328, -1051, -172, - -125, -408, 130, -17, -1052, -1052, -1052, -1052, 132, -167, - -1052, -1052, 14, -1052, 25, -1052, -1052, -1052, -124, -1052, - -1052, -1052, -1052, -1052, -1052, 838, 1, -837, -1052, -1052, - -1052, 752, -1052, -1052, -1052, -162, -241, 17, 92, -1052, - -1052, -277, -508, -1052, -1052, -1052, -313, -270, -543, -679, - -1052, -1052, -1052, -1052, -818, -1052, -1052, -90, -1052, -1052, - -1052, -1052, -115, -1052, -1052, -1052, -1052, 228, -1052, -59, - -676, -1052, -1052, -1052, -273, -1052, -1052, -334, -1052, -1052, - -1052, 30, 268, -310, 277, -1052, -94, -58, -714, -1052, - -257, -1052, -710, -1052, -930, -1052, -1052, -396, -1052, -1052, - -1052, -433, -1052, -1052, -485, -1052, -1052, -83, -1052, -1052, - -1052, 1291, 985, 1028, 15, -1052, -1052, 319, 874, -5, - -1052, 45, -1052, 503, -31, 315, -1052, 22, 767, -1052, - -1052, -506, -1052, 1313, 91, -1052, -1052, 196, -880, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, 176, - 181, 333, -403, 358, -1052, 362, -1052, 64, -1052, 910, - -1052, -1052, -1052, -123, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, - -1052, -1052, -1052, -1052, -1052, -1052, -1052, -1052, -15, 35, - 71, -878, -832, -1052, -469, -166, -477, -1052, -69, -1052, - -133, -1052, -1018, -1052, -692, -1052, -593, -1052, -1052, -1052, - -260, -1052, -1052, -1052, 250, -1052, -156, -415, -1052, -420, - 33, -9, -1052, -690, -1052 + -1011, -1011, -388, -1011, -1011, 808, -114, -1011, -1011, -1011, + -1011, -834, -104, 2, -34, -1011, -1011, -1011, -1011, 56, + -411, -100, -914, -1011, -1011, -1011, -1011, -109, -1011, -116, + -217, -1011, -1011, 37, -101, -99, -33, -1011, -1011, 34, + -474, -1011, -1011, 26, -1011, -1011, -1011, -261, -824, -97, + -123, -397, 239, 86, -1011, -1011, -1011, -1011, 240, -92, + -1011, -1011, 6, -1011, -1, -1011, -1011, -1011, -42, -1011, + -1011, -1011, -1011, -1011, -1011, -113, 102, -911, -1011, -1011, + -1011, 843, -1011, -1011, -1011, -87, -164, 32, -11, -1011, + -1011, -266, -484, -1011, -1011, -1011, -309, -293, -550, -673, + -1011, -1011, -1011, -1011, -815, -1011, -1011, -95, -1011, -1011, + -1011, -1011, -120, -1011, -1011, -1011, -1011, 320, -1011, 43, + -659, -1011, -1011, -1011, -200, -1011, -1011, -303, -1011, -1011, + -1011, -1011, -1011, -1011, 7, 358, -300, 361, -1011, -4, + -43, -696, -1011, -241, -1011, -682, -1011, -944, -1011, -1011, + -337, -1011, -1011, -1011, -450, -1011, -1011, -281, -1011, -1011, + 5, -1011, -1011, -1011, 1018, 349, 1009, 48, -1011, -1011, + 311, 334, -5, -1011, 29, -1011, 1152, -31, 343, -1011, + 33, 609, -1011, -1011, -496, -1011, 799, 196, -1011, -1011, + -55, -897, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, 281, 206, 251, -403, 446, -1011, 448, -1011, + 155, -1011, 9, -1011, -517, -1011, -392, -1011, -913, -1011, + -1011, -1011, -44, -1011, -330, -1011, -1011, 156, -1011, -1011, + -1011, -1011, -58, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, -1011, + -1011, -1011, -1011, -1011, -1011, -1011, -1011, 35, 165, 77, + -878, -810, -1011, -307, -93, -557, -1011, -91, -1011, -75, + -1011, -1010, -1011, -674, -1011, -556, -1011, -1011, -1011, -242, + -1011, -1011, -1011, 332, -1011, -195, -418, -1011, -420, 60, + 87, -1011, -657, -1011 }; /* YYDEFGOTO[NTERM-NUM]. */ static const short int yydefgoto[] = { - -1, 1, 2, 4, 88, 357, 90, 91, 92, 463, - 93, 94, 95, 359, 97, 350, 98, 928, 677, 377, - 511, 512, 680, 676, 803, 804, 1008, 1082, 1010, 809, - 810, 926, 922, 811, 100, 101, 102, 518, 103, 360, - 521, 690, 687, 688, 931, 361, 933, 1074, 1148, 105, - 106, 618, 626, 619, 456, 457, 897, 1114, 458, 107, - 321, 108, 362, 772, 363, 438, 605, 879, 606, 607, - 977, 608, 980, 609, 1064, 884, 754, 1058, 1059, 1110, - 1140, 364, 112, 113, 114, 1085, 1018, 1019, 116, 530, - 1036, 117, 548, 715, 549, 946, 550, 118, 552, 717, - 854, 947, 855, 856, 857, 858, 948, 371, 372, 1035, - 553, 960, 1020, 533, 831, 385, 705, 528, 695, 696, - 700, 701, 827, 1038, 828, 829, 1100, 559, 560, 727, - 561, 365, 416, 502, 557, 865, 503, 504, 885, 1142, - 417, 873, 418, 547, 965, 1053, 1172, 1143, 1061, 564, - 975, 554, 959, 718, 966, 720, 860, 861, 953, 1049, - 1050, 812, 121, 283, 284, 532, 124, 125, 126, 285, - 538, 286, 269, 129, 130, 349, 505, 378, 132, 133, - 134, 135, 713, 1026, 137, 428, 546, 138, 139, 270, - 1047, 1048, 1104, 1135, 748, 749, 888, 974, 750, 140, - 141, 142, 423, 424, 425, 426, 731, 714, 427, 692, - 143, 145, 585, 144, 780, 480, 903, 1067, 481, 482, - 784, 986, 785, 485, 906, 1069, 788, 792, 789, 793, - 790, 794, 791, 795, 796, 797, 919, 647, 586, 587, - 588, 869, 870, 962, 589, 590, 431, 591, 592, 971, - 706, 876, 837, 838, 872, 943, 439, 593, 734, 732, - 594, 616, 614, 615, 595, 733, 434, 441, 601, 602, - 603, 265, 266, 267, 268 + -1, 1, 2, 4, 88, 357, 90, 91, 92, 464, + 93, 94, 95, 359, 97, 349, 98, 945, 662, 377, + 513, 514, 665, 661, 793, 794, 1026, 1107, 1028, 799, + 800, 943, 939, 801, 100, 101, 102, 521, 103, 360, + 524, 675, 672, 673, 948, 361, 950, 1099, 1178, 105, + 106, 602, 610, 603, 457, 458, 914, 1142, 459, 107, + 320, 108, 362, 762, 363, 439, 589, 888, 590, 591, + 995, 592, 998, 593, 1089, 893, 744, 1083, 1084, 1138, + 1170, 364, 112, 113, 114, 1110, 1036, 1037, 116, 533, + 1054, 117, 551, 700, 552, 966, 553, 118, 555, 702, + 858, 967, 859, 860, 861, 862, 968, 371, 372, 1053, + 556, 980, 1038, 536, 821, 385, 690, 531, 680, 681, + 685, 686, 817, 1057, 818, 958, 1161, 562, 563, 712, + 564, 565, 878, 1078, 365, 416, 504, 560, 869, 505, + 506, 894, 1172, 417, 880, 418, 550, 988, 1079, 1204, + 1173, 1086, 568, 993, 557, 979, 703, 989, 705, 864, + 865, 973, 1070, 1071, 802, 121, 282, 283, 535, 124, + 125, 126, 284, 541, 285, 268, 129, 130, 348, 507, + 378, 132, 133, 134, 135, 698, 1044, 137, 428, 549, + 138, 139, 269, 1068, 1069, 1131, 1164, 738, 739, 897, + 992, 740, 140, 141, 142, 423, 424, 425, 426, 719, + 699, 427, 677, 6, 468, 469, 570, 571, 955, 956, + 1166, 1167, 350, 351, 144, 432, 577, 578, 579, 886, + 724, 725, 143, 770, 482, 920, 1092, 483, 484, 774, + 1004, 775, 487, 923, 1094, 778, 782, 779, 783, 780, + 784, 781, 785, 786, 787, 936, 632, 833, 834, 835, + 873, 874, 982, 875, 837, 746, 907, 908, 1077, 691, + 984, 838, 839, 876, 962, 440, 842, 963, 961, 843, + 600, 598, 599, 844, 877, 435, 442, 585, 586, 587, + 264, 265, 266, 267 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If @@ -2638,1793 +2717,1601 @@ static const short int yydefgoto[] = number is the opposite. If YYTABLE_NINF, syntax error. */ static const short int yytable[] = { - 127, 279, 281, 104, 96, 297, 406, 823, 384, 446, - 358, 469, 740, 723, 839, 565, 390, 261, 597, 109, - 123, 612, 115, 373, 374, 375, 627, 131, 945, 832, - 110, 460, 326, 282, 621, 119, 846, 963, 886, 596, - 889, 712, 517, 622, 886, 1056, 691, 468, 722, 678, - 128, 678, 324, 1032, 470, 16, 16, 287, 16, 678, - 678, 16, 848, 16, 1006, 264, 678, 262, 1046, 719, - 368, 436, 678, 16, 949, 443, 444, 776, 752, 422, - 157, 158, 327, -359, 435, 148, 678, 3, 448, -359, - 440, 849, 1141, 394, 419, -358, 16, 402, 404, -2, - 1169, -358, 753, 263, 850, 412, 413, 851, -371, 328, - 950, 951, 442, 840, 1177, 702, 1169, 149, 388, 391, - 149, 326, 1157, 1040, 708, 123, 852, 115, 1183, 405, - -118, 329, 366, 520, 261, 412, 413, 756, 757, 758, - 461, 330, 719, 1063, 1072, 551, 408, 763, 436, 16, - 331, 723, 941, 799, 800, 801, 437, 99, 650, 369, - 370, 563, 777, 420, 421, 1103, -371, 1152, 389, 392, - 862, 327, 1107, 419, 1170, 847, 981, 612, 863, 414, - 886, 679, 433, 842, 262, 983, 722, 280, 862, 886, - 863, 679, -60, -60, 649, -60, -60, 853, 842, -60, - 963, 470, -60, 419, 679, -60, 445, 845, -60, 414, - 636, 244, 1158, 259, 529, 383, 764, 765, 842, -60, - 263, 982, -60, 407, 739, 712, 1039, 1113, 380, 707, - 886, 709, -371, 437, 844, 412, 413, 836, -373, -373, - -372, 771, 420, 421, -372, 332, 289, 290, 291, 292, - 293, 294, 295, 454, 455, 875, 551, 877, 871, 333, - -376, 802, 99, -376, 1060, 326, 725, -377, 886, 766, - 1043, 726, 420, 421, 767, 963, 334, -377, -375, 388, - 1132, 335, -352, 403, 1051, 282, 551, -374, -352, -350, - -371, 38, 336, 544, -351, -350, -373, -373, -372, 337, - -351, -375, -372, 326, 326, 38, -374, 338, 730, 414, - -355, 768, 339, 1080, -316, 327, -355, -356, -376, 388, - 326, -376, -270, -356, 558, -377, 340, 410, -354, 389, - 259, 341, 402, -357, -354, -377, -375, -353, -172, -357, - 471, -328, 342, -353, 343, -374, 515, -328, 1112, 326, - 839, 326, 886, 327, 327, -329, -175, 1098, 1159, -375, - 1160, -329, -172, 460, -374, 260, 513, 1165, 344, 389, - 327, 1161, 816, 345, 1162, 817, -370, 1109, 123, 296, - 115, 408, -370, -360, -361, 525, 1165, 346, 1179, -360, - -361, 620, 964, 620, 1145, -316, 516, 1146, 1179, 327, - 871, 327, -362, 388, 347, 682, -363, 1131, -362, -364, - 326, 240, -363, 932, 348, -364, -365, 352, 839, 261, - 261, 353, -365, -366, 551, 261, 261, 261, 394, -366, - 556, 376, 289, 290, 291, 292, 293, 294, 295, 280, - 146, 147, 387, -326, -367, 515, 261, 326, 839, 1101, - -367, 976, 38, 389, 629, 648, 401, 633, 407, 432, - 327, 448, 871, 420, 421, 513, 388, -368, 462, 262, - 262, 1173, 1174, -368, -369, 262, 262, 262, 33, 466, - -369, -154, 260, 410, 289, 290, 291, 292, 293, 294, - 295, 402, 805, 806, 807, 516, 262, 327, -118, -118, - 543, 394, 520, 245, 630, 263, 263, 516, 683, 633, - 508, 263, 263, 263, 261, 280, 389, 1033, 403, 326, - 527, 326, 326, 21, 22, 16, 515, 703, 534, 685, - 634, 394, 263, 635, 669, 515, 648, 326, 670, 651, - 408, 694, 824, 655, 656, 658, 513, 659, 660, 661, - 1130, 388, 662, 663, 664, 513, 665, 629, 684, 516, - 666, 667, 410, 871, 262, 668, 620, 620, 671, 327, - 672, 327, 327, 836, 410, 1062, 516, 815, 686, -255, - 698, 871, 261, 1130, -316, 516, 575, 327, 955, 956, - 957, 958, 735, 729, 449, 952, 451, 736, 738, 355, - 263, 389, 745, 387, 759, 743, 762, 630, 770, 773, - 774, 775, 583, 612, 778, 259, 259, 407, 781, 779, - 786, 259, 259, 259, 782, 783, 726, 393, 813, 747, - 818, 820, 262, 822, 755, 826, 825, 841, 871, 843, - 878, 836, 259, 387, 289, 290, 291, 292, 293, 294, - 295, 859, 746, 1116, 767, 894, 895, 900, 901, 898, - 907, 925, 414, 918, 921, 944, 326, 924, 263, 939, - 942, 836, 326, 984, 987, 989, 990, 280, 991, 992, - 683, 993, 507, 994, 995, 507, 996, 1044, 997, 388, - 33, 887, 998, 1034, 1037, 999, 612, 1057, 1066, -322, - 1070, 1054, 1065, 1071, 1147, 1068, 1089, 1097, 1102, 620, - 259, 1090, 1106, 1154, 1108, 1111, 327, 539, 1115, 541, - 89, 410, 327, 1117, 1118, 1119, 38, 387, 1139, 1005, - 684, 1164, 1009, 1166, 1031, 1168, 326, 326, 326, 389, - 1095, 923, 1011, 571, 612, 1012, 930, 1122, 1013, 760, - 896, 1178, 761, 1014, 551, 973, 890, 111, 1017, 1076, - 1182, 704, 612, 935, 584, 1099, 1133, 260, 260, 624, - 625, 961, 674, 260, 260, 260, 1181, 954, 259, 1129, - 673, 819, 507, 751, 507, 569, 327, 327, 327, 570, - 387, 17, 18, 19, 260, 874, 1052, 1027, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 970, 278, 261, - 1042, 728, 934, 0, 0, 0, 0, 326, 0, 0, - 0, 0, 551, 551, 0, 0, 0, 0, 0, 0, - 0, 479, 387, 0, 0, 483, 484, 0, 486, 487, - 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, - 498, 499, 0, 394, 393, 0, 551, 0, 0, 262, - 0, 711, 260, 0, 0, 0, 0, 327, 0, 0, - 0, 0, 507, 0, 507, 387, 0, 0, 0, 629, - 0, 0, 0, 0, 0, 0, 0, 583, 0, 0, - 0, 0, 0, 0, 0, 263, 0, 0, 409, 0, - 406, 0, 0, 0, 507, 0, 0, 0, 583, 0, - 1091, 325, 0, 0, 5, 127, 358, 326, 104, 1007, - 0, 326, 0, 326, 0, 0, 0, 0, 1088, 630, - 260, 0, 0, 0, 1015, 1024, 0, 583, 583, 583, - 0, 0, 1025, 883, 0, 1016, 0, 0, 0, 0, - 1021, 0, 0, 393, 0, 0, 0, 507, 507, 0, - 0, 0, 0, 1091, 0, 128, 0, 327, 0, 0, - 1045, 327, 1091, 327, 415, 358, 0, 0, 0, 0, - 0, 0, 0, 652, 653, 654, 1124, 0, 657, 1163, - 1105, 402, 404, 0, 0, 127, 0, 326, 1171, 395, - 0, 398, 400, 0, 387, 259, 0, 0, 0, 351, - 0, 127, 1091, 387, 354, 1081, 393, 324, 261, 388, - 127, 689, 1078, 405, 326, 1075, 0, 0, 0, 0, - 1083, 1024, 381, 122, 393, 0, 0, 399, 1087, 584, - 1092, 1084, 411, 393, 507, 128, 1086, 327, 0, 0, - 583, 429, 430, 402, 409, 0, 583, 583, 583, 0, - 584, 128, 394, 0, 0, 323, 0, 0, 262, 389, - 128, 0, 99, 127, 327, 0, 0, 0, 0, 127, - 0, 0, 127, 1081, 0, 0, 0, 388, 629, 584, - 584, 584, 0, 402, 0, 394, 0, 1123, 1083, 1024, - 0, 261, 1092, 0, 263, 0, 1127, 0, 386, 1084, - 0, 396, 583, 0, 1086, 515, 506, 407, 0, 506, - 0, 629, 127, 128, 0, 0, 459, 0, 0, 128, - 0, 0, 128, 409, 0, 513, 0, 389, 630, 0, - 0, 0, 1092, 583, 515, 409, 515, 0, 261, 261, - 0, 262, 1073, 0, 397, 0, 261, 260, 0, 398, - 400, 0, 515, 0, 513, 516, 513, 261, 99, 0, - 407, 630, 128, 0, 0, 0, 0, 403, 0, 407, - 0, 0, 513, 0, 0, 0, 0, 263, 393, 0, - 450, 0, 452, 381, 516, 399, 516, 821, 262, 262, - 398, 400, 584, 979, 0, 526, 262, 0, 584, 584, - 584, 0, 516, 583, 259, 0, 506, 262, 506, 407, - 0, 410, 0, 583, 0, 514, 0, 1121, 0, 0, - 1125, 583, 467, 0, 263, 263, 280, 0, 0, 403, - 0, 0, 263, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 263, 0, 0, 562, 0, 0, 0, - 0, 535, 536, 537, 584, 0, 0, 0, 0, 453, - 524, 0, 0, 0, 410, 1150, 0, 0, 0, 280, - 0, 0, 0, 410, 0, 0, 0, 531, 583, 1055, - 0, 583, 409, 0, 0, 584, 120, 259, 323, 0, - 0, 0, 0, 0, 0, 0, 506, 0, 506, 453, - 396, 0, 507, 540, 0, 542, 0, 0, 136, 545, - 689, 583, 0, 410, 514, 0, 0, 0, 322, 566, - 567, 568, 0, 0, 0, 0, 323, 323, 506, 0, - 0, 0, 562, 387, 259, 259, 0, 0, 288, 0, - 0, 0, 259, 397, 0, 0, 0, 617, 0, 0, - 0, 0, 0, 259, 0, 584, 260, 0, 0, 0, - 0, 0, 0, 0, 0, 584, 0, 0, 0, 0, - 0, 0, 323, 584, 323, 0, 0, 0, 507, 398, - 400, 506, 506, 386, 0, 0, 0, 0, 0, 0, - 555, 0, 0, 562, 0, 514, 0, 0, 0, 0, - 0, 387, 0, 0, 514, 675, 0, 0, 0, 1136, - 0, 0, 681, 367, 0, 0, 0, 0, 0, 0, - 0, 379, 0, 467, 0, 0, 0, 0, 0, 0, - 584, 0, 0, 584, 628, 0, 0, 0, 0, 260, - 1155, 0, 0, 0, 0, 0, 453, 0, 459, 0, - 716, 0, 0, 0, 0, 721, 0, 0, 0, 507, - 0, 0, 0, 584, 0, 0, 0, 0, 506, 0, - 323, 0, 0, 0, 0, 0, 0, 0, 507, 0, - 632, 0, 0, 0, 0, 0, 260, 260, 0, 0, - 0, 0, 0, 0, 260, 0, 0, 398, 0, 0, - 0, 555, 0, 0, 409, 260, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 769, 0, - 0, 724, 0, 0, 0, 0, 0, 628, 0, 0, - 0, 0, 323, 0, 0, 323, 0, 536, 537, 0, - 0, 447, 0, 0, 0, 0, 0, 0, 0, 0, - 323, 0, 0, 0, 0, 0, 0, 830, 0, 0, - 0, 0, 0, 298, 299, 300, 301, 302, 303, 304, - 0, 0, 814, 0, 0, 0, 0, 0, 0, 464, - 465, 305, 306, 307, 16, 0, 0, 0, 0, 805, - 806, 807, 0, 0, 0, 0, 0, 808, 0, 398, - 400, 0, 0, 393, 0, 0, 0, 0, 0, 33, - 0, 0, 0, 0, 864, 744, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 522, 0, 523, 0, 0, - 927, 0, 393, 0, 393, 0, 0, 0, 0, 0, - 0, 936, 0, 0, 0, 38, 0, 0, 0, 0, - 393, 0, 0, 0, 0, 0, 367, 0, 0, 724, - 0, 0, 310, 311, 312, 313, 314, 315, 316, 317, - 318, 319, 320, 0, 0, 0, 0, 0, 0, 323, - 0, 0, 0, 0, 0, 323, 0, 0, 0, 0, - 0, 0, 0, 920, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 929, 87, 0, 0, 0, - 0, 0, 0, 0, 0, 938, 0, 0, 0, 0, - 0, 0, 0, 623, 0, 0, 506, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 323, - 323, 323, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 379, 0, 0, 0, 0, 0, 0, - 0, 0, 409, 0, 0, 0, 978, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 409, 0, 0, 693, 0, 0, 697, 0, - 0, 0, 506, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 710, 1029, 0, 0, 298, 299, 300, - 301, 302, 303, 304, 0, 409, 0, 0, 0, 0, - 323, 0, 1041, 0, 409, 305, 306, 307, 16, 0, - 0, 0, 0, 0, 1093, 0, 1094, 0, 1096, 628, - 0, 0, 0, 0, 0, 0, 325, 0, 0, 0, - 0, 0, 0, 33, 0, 0, 0, 0, 0, 0, - 409, 0, 0, 0, 409, 0, 0, 0, 0, 0, - 0, 0, 0, 506, 0, 1023, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 1126, 0, 38, - 0, 0, 506, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 310, 311, 312, 313, - 314, 315, 316, 317, 318, 319, 320, 0, 122, 0, - 323, 0, 0, 0, 323, 0, 323, 0, 0, 0, - 0, 0, 798, 0, 0, 0, 0, 0, 0, 519, - 0, 787, 0, 520, 0, 0, 0, 0, 0, 0, - 87, 0, 0, 1120, 0, 1077, 0, 0, 0, 0, - 0, 0, 0, 0, 514, 0, 0, 0, 0, 0, - 1128, 1077, 0, 0, 0, 0, 0, 0, 0, 453, - 1077, 0, 1134, 0, 0, 0, 1137, 0, 1138, 0, - 0, 0, 0, 514, 0, 514, 0, 0, 0, 0, - 323, 1149, 880, 881, 882, 1151, 0, 0, 0, 1153, - 0, 514, 0, 0, 0, 0, 0, 0, 0, 1156, - 0, 0, 0, 0, 0, 0, 0, 323, 0, 0, - 1167, 0, 0, 1077, 0, 0, 0, 0, 0, 1077, - 0, 0, 1077, 0, 0, 0, 0, 453, 555, 0, - 0, 0, 0, 0, 0, 899, 0, 0, 0, 0, - 0, 0, 0, 902, 637, 0, 0, 904, 905, 0, - 0, 908, 909, 910, 911, 912, 913, 914, 915, 916, - 917, 724, 1077, 697, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 638, 639, 0, 0, - 0, 0, 940, 203, 204, 205, 640, 207, 208, 209, - 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, - 220, 221, 222, 223, 224, 225, 0, 0, 6, 7, - 8, 9, 10, 11, 12, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 13, 14, 15, 0, - 17, 18, 19, 20, 0, 0, 0, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 0, 278, 31, 355, - 0, 1022, 0, 1028, 33, 34, 985, 1030, 356, 988, - 641, 0, 642, 643, 0, 644, 645, 0, 247, 248, - 249, 646, 251, 252, 253, 254, 255, 256, 257, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 38, 0, 39, 40, 41, 42, 43, 44, 45, 46, - 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, - 57, 58, 59, 60, 61, 62, 63, 64, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 322, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 87, 0, 1079, 150, 151, 152, 153, 154, 155, - 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 226, 227, 228, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 598, 240, 0, 241, - 242, 243, 244, 0, 599, 246, 600, 247, 248, 249, - 250, 251, 252, 253, 254, 255, 256, 257, 258, 150, - 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 171, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 226, 227, 228, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 598, 240, 604, 241, 242, 243, 244, 0, 599, - 246, 0, 247, 248, 249, 250, 251, 252, 253, 254, - 255, 256, 257, 258, 150, 151, 152, 153, 154, 155, - 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, + 127, 278, 280, 384, 110, 296, 358, 96, 406, 708, + 611, 109, 119, 5, 471, 569, 581, 840, 373, 374, + 375, 519, 596, 415, 390, 813, 447, 850, 572, 573, + 472, 822, 325, 730, 128, 965, 701, 115, 131, 104, + 605, 706, 747, 748, 436, 580, 461, 1060, 898, 1081, + 441, 676, 520, 123, 697, 606, 895, 470, 663, -376, + 354, 99, 895, 983, 663, 663, 326, 260, 286, 281, + 1050, 1067, 443, 663, 437, 707, 410, 288, 289, 290, + 291, 292, 293, 294, 147, 323, 663, 1088, 766, 412, + 413, 279, 263, 394, 422, 759, 368, 402, 404, 3, + 462, 444, 445, 1024, -378, 789, 790, 791, 449, 262, + -377, -118, 383, 663, 523, 663, 148, -376, 388, 391, + 407, 325, 554, 687, -2, 852, 156, 157, 1171, 708, + -381, 381, 693, 753, 327, 841, 399, 156, 157, 621, + 148, 411, 115, 366, 1059, 412, 413, 742, 959, 328, + 429, 430, 389, 392, 853, 326, -382, 419, 123, 438, + 1189, 596, -378, 414, 635, 405, 99, 854, -377, 1130, + 855, 743, 329, 767, 460, 532, -503, 567, 1141, 408, + 472, -503, 437, 260, 1097, 369, 370, 403, -381, 856, + 664, -60, 868, 1134, -60, 707, 664, 261, -60, 330, + 1136, -60, 849, 999, 419, 846, -60, 634, 434, -60, + 295, 754, 755, 792, -382, 38, 1163, 895, 846, 414, + 1001, 848, 1168, 697, -380, 262, 420, 421, 1190, -376, + 761, 410, 446, 969, 895, 451, 554, 453, 258, -378, + 983, 718, 692, -379, 694, 664, -60, 846, -60, -60, + 331, -60, 455, 456, 529, 1000, 1188, 243, 729, -377, + 857, 145, 146, 1197, 325, -333, 554, 438, 243, 970, + 971, -333, 710, 420, 421, 38, 704, 711, 388, -357, + 420, 421, -380, 259, 1197, -357, 1211, -376, 547, -355, + -381, 381, 866, 399, 867, -355, 1211, -378, 326, 720, + 1085, -379, 325, 325, 721, 566, 353, 1064, 1160, -356, + -382, 410, 389, 261, 895, -356, 527, -377, 388, 325, + 281, 1072, 756, 410, 983, -334, 983, 757, 717, -364, + 704, -334, 402, 534, 332, -364, 326, 326, -505, 239, + -360, 949, 279, -505, -380, 517, -360, 806, -381, 325, + 807, 325, 389, 326, 258, 407, -172, 1201, 333, 543, + -361, 545, 1125, 461, 1105, 334, -361, -379, -382, 21, + 22, 324, 473, 1209, -175, 1201, 895, 380, 335, 518, + -172, 1123, 336, 326, 836, 326, 554, 1215, 840, 758, + 337, 1140, -321, 566, -359, 115, 528, 546, 515, 259, + -359, 338, -380, 388, 1061, 895, 1063, 604, 339, 604, + 325, 123, -118, -118, 408, 667, 523, -358, 548, 279, + 1137, -363, 403, -358, -362, -379, -375, -363, 987, 394, + -362, -321, -375, 985, 387, 986, 1191, 389, 1192, 906, + 906, 906, 340, 994, 326, 352, 517, -365, 325, 1193, + 341, 342, 1194, -365, -366, 613, 566, 601, 617, 395, + -366, 398, 400, 559, 840, 1159, 987, 343, 388, -321, + 260, 260, 386, 410, 344, 396, 260, 260, 260, -367, + 518, -368, 326, 887, 38, -367, 345, -368, 814, 614, + 1175, 460, 518, 1176, 402, -369, 840, 260, 346, 515, + 347, -369, 389, 996, 394, 376, 1127, 633, -370, -371, + 668, 617, 262, 262, -370, -371, 660, 407, 262, 262, + 262, -372, 325, 666, 325, 325, -373, -372, -374, 517, + 688, 1051, -373, -331, -374, 394, 1205, 1206, 517, 262, + 325, -270, 431, 561, 669, 518, -272, 433, 723, 975, + 976, 977, 978, 401, 388, 449, 326, 987, 326, 326, + -321, 613, 463, 518, 670, 604, 604, 260, 1158, 467, + 805, -154, 518, 510, 326, 244, 408, 679, 795, 796, + 797, 530, 515, 618, 279, 537, 735, 619, 389, 633, + 636, 515, 745, 1087, 387, 614, 620, 640, 1156, 509, + 261, 261, 641, 509, 1158, 643, 261, 261, 261, 262, + 644, 645, 646, 647, 648, 649, 260, 972, 398, 400, + 736, 450, 650, 452, 737, 733, 1055, 261, 651, 652, + 653, 596, 454, 654, 387, 655, 656, 657, 671, -255, + 1183, 258, 258, 683, -321, 713, 715, 258, 258, 258, + 716, 325, 726, 763, 355, 728, 749, 325, 262, 398, + 400, 752, 760, 764, 765, 668, 768, 769, 258, 771, + 772, 776, 454, 396, 388, 1144, 804, 906, 711, 773, + 803, 810, 892, 808, 516, 326, 259, 259, 812, 944, + 816, 326, 259, 259, 259, 819, 896, 261, 815, 669, + 953, 509, 845, 509, 847, 851, 863, 885, 389, 911, + 883, 757, 912, 259, 604, 866, 915, 917, 918, 387, + 924, 538, 539, 540, 596, 1065, 325, 325, 325, 935, + 938, 942, 941, 1115, 957, 414, 964, 1177, 258, 960, + 409, 867, 1052, 1015, 1002, 542, 261, 544, 1056, 554, + 1005, 1082, 1016, 1007, 906, 836, 906, 386, 1196, 1008, + 326, 326, 326, 1009, 558, -327, 1010, 1011, 1198, 1012, + 1200, 576, 1013, 1014, 1017, 1090, 596, 1091, 1093, 1095, + 1096, 1114, 1122, 259, 387, 516, 1129, 258, 1210, 1214, + 1133, 1135, 879, 509, 596, 509, 1139, 1143, 608, 609, + 1145, 1146, 937, 1147, 136, 1162, 1182, 325, 1157, 612, + 1169, 1184, 1202, 89, 946, 288, 289, 290, 291, 292, + 293, 294, 454, 1023, 554, 554, 387, 509, 1027, 1049, + 1120, 836, 259, 947, 287, 940, 1029, 1187, 1030, 1150, + 1031, 326, 750, 913, 751, 1032, 991, 899, 111, 260, + 1035, 398, 400, 723, 1101, 952, 689, 1124, 1185, 509, + 509, 554, 394, 836, 659, 981, 658, 1213, 516, 974, + 387, 809, 741, 574, 881, 575, 882, 516, 558, 1045, + 288, 289, 290, 291, 292, 293, 294, 1062, 613, 1073, + 722, 262, 696, 1076, 0, 409, 714, 831, 951, 288, + 289, 290, 291, 292, 293, 294, 0, 0, 709, 367, + 0, 0, 0, 0, 0, 612, 0, 379, 831, 0, + 406, 0, 614, 1116, 0, 0, 33, 0, 0, 0, + 358, 1118, 127, 1119, 325, 1121, 1034, 0, 325, 1025, + 325, 1113, 832, 1033, 1039, 33, 0, 509, 0, 0, + 1047, 398, 831, 831, 831, 0, 0, 508, 0, 0, + 0, 508, 38, 832, 0, 0, 128, 0, 326, 0, + 1043, 104, 326, 0, 326, 409, 0, 0, 0, 261, + 1195, 387, 0, 1116, 0, 1042, 0, 409, 410, 1203, + 387, 1154, 1116, 99, 0, 0, 358, 832, 832, 832, + 0, 1066, 539, 540, 0, 0, 1152, 0, 0, 402, + 404, 0, 0, 127, 122, 325, 0, 1100, 0, 0, + 258, 0, 820, 120, 0, 0, 1132, 0, 709, 127, + 0, 0, 407, 1109, 0, 1116, 1106, 388, 127, 0, + 1108, 1111, 325, 0, 0, 0, 322, 128, 410, 326, + 0, 1103, 0, 0, 1148, 321, 884, 410, 0, 508, + 0, 508, 0, 128, 0, 259, 819, 1112, 323, 398, + 400, 389, 128, 0, 1098, 0, 326, 405, 402, 831, + 0, 0, 1042, 0, 0, 0, 260, 394, 0, 0, + 99, 1117, 407, 0, 0, 0, 0, 0, 127, 403, + 410, 407, 0, 0, 127, 1179, 0, 127, 1109, 1181, + 0, 1106, 388, 613, 0, 1108, 1111, 0, 0, 0, + 0, 402, 0, 394, 832, 0, 0, 0, 262, 0, + 0, 0, 128, 1151, 0, 397, 1199, 409, 128, 0, + 0, 128, 1155, 517, 407, 0, 389, 614, 0, 613, + 127, 508, 0, 508, 831, 0, 1149, 1042, 0, 1153, + 1117, 0, 367, 0, 0, 279, 0, 0, 403, 0, + 0, 0, 0, 0, 517, 0, 517, 518, 0, 260, + 0, 0, 0, 614, 128, 508, 0, 0, 831, 0, + 831, 0, 0, 0, 517, 990, 515, 0, 0, 832, + 0, 0, 0, 1117, 0, 0, 0, 1180, 518, 0, + 518, 279, 0, 0, 0, 0, 261, 508, 508, 0, + 0, 262, 0, 0, 0, 0, 0, 515, 518, 515, + 260, 260, 0, 832, 0, 832, 0, 0, 260, 0, + 997, 0, 612, 0, 0, 0, 0, 515, 509, 260, + 0, 0, 0, 0, 0, 0, 831, 258, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 831, 831, 831, + 0, 379, 262, 262, 0, 0, 393, 831, 322, 0, + 262, 0, 0, 0, 831, 0, 1041, 448, 0, 0, + 0, 262, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 832, 259, 0, 0, 508, 0, 0, 0, 261, + 0, 0, 832, 832, 832, 0, 322, 322, 0, 0, + 0, 0, 832, 0, 0, 465, 466, 0, 0, 832, + 0, 509, 0, 397, 0, 1080, 0, 0, 0, 0, + 831, 0, 831, 0, 831, 0, 409, 0, 0, 0, + 258, 0, 0, 387, 324, 0, 0, 0, 0, 0, + 261, 261, 0, 322, 0, 322, 0, 1102, 261, 0, + 0, 0, 525, 0, 526, 0, 831, 0, 0, 261, + 0, 0, 0, 1102, 0, 832, 0, 832, 0, 832, + 0, 454, 1102, 0, 0, 259, 0, 0, 0, 0, + 0, 258, 258, 0, 0, 0, 0, 0, 0, 258, + 0, 0, 0, 0, 0, 0, 509, 0, 0, 0, + 258, 832, 0, 0, 0, 0, 0, 0, 387, 0, + 0, 0, 0, 0, 0, 0, 0, 509, 0, 0, + 0, 0, 777, 0, 0, 0, 259, 259, 0, 0, + 0, 0, 1102, 0, 259, 0, 0, 0, 1102, 0, + 0, 1102, 322, 0, 0, 259, 454, 558, 0, 0, + 0, 607, 616, 0, 1165, 0, 0, 0, 0, 481, + 0, 0, 516, 485, 486, 0, 488, 489, 490, 491, + 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, + 0, 0, 393, 709, 1102, 0, 0, 1186, 0, 17, + 18, 19, 0, 516, 0, 516, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 0, 277, 0, 0, 0, + 0, 0, 0, 516, 0, 0, 322, 0, 0, 322, + 0, 0, 0, 0, 0, 678, 0, 0, 682, 0, + 0, 0, 0, 0, 322, 0, 0, 0, 0, 0, + 0, 916, 622, 695, 0, 0, 0, 0, 0, 919, + 0, 0, 0, 921, 922, 0, 0, 925, 926, 927, + 928, 929, 930, 931, 932, 933, 934, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 734, 0, 0, 393, 623, 624, 508, 0, 0, 0, + 0, 202, 203, 204, 625, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 226, 227, 228, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 598, 240, 0, 241, - 242, 243, 244, 0, 599, 246, 610, 247, 248, 249, - 250, 251, 252, 253, 254, 255, 256, 257, 258, 150, - 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 171, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 226, 227, 228, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 598, 240, 0, 241, 242, 243, 244, 613, 599, - 246, 0, 247, 248, 249, 250, 251, 252, 253, 254, - 255, 256, 257, 258, 150, 151, 152, 153, 154, 155, - 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 226, 227, 228, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 598, 240, 631, 241, - 242, 243, 244, 0, 599, 246, 0, 247, 248, 249, - 250, 251, 252, 253, 254, 255, 256, 257, 258, 150, - 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 171, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 226, 227, 228, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 598, 240, 699, 241, 242, 243, 244, 0, 599, - 246, 0, 247, 248, 249, 250, 251, 252, 253, 254, - 255, 256, 257, 258, 150, 151, 152, 153, 154, 155, - 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 226, 227, 228, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 598, 240, 937, 241, - 242, 243, 244, 0, 599, 246, 0, 247, 248, 249, - 250, 251, 252, 253, 254, 255, 256, 257, 258, 150, - 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 171, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 226, 227, 228, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 598, 240, 1175, 241, 242, 243, 244, 0, 599, - 246, 0, 247, 248, 249, 250, 251, 252, 253, 254, - 255, 256, 257, 258, 150, 151, 152, 153, 154, 155, - 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 226, 227, 228, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 598, 240, 1180, 241, - 242, 243, 244, 0, 599, 246, 0, 247, 248, 249, - 250, 251, 252, 253, 254, 255, 256, 257, 258, 150, - 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 171, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 226, 227, 228, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 611, 240, 0, 241, 242, 243, 244, 0, 599, - 246, 0, 247, 248, 249, 250, 251, 252, 253, 254, - 255, 256, 257, 258, 150, 151, 152, 153, 154, 155, - 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 226, 227, 228, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 737, 240, 0, 241, - 242, 243, 244, 0, 599, 246, 0, 247, 248, 249, - 250, 251, 252, 253, 254, 255, 256, 257, 258, 150, - 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 171, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 226, 227, 228, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 240, 0, 241, 242, 243, 244, 1144, 599, - 246, 0, 247, 248, 249, 250, 251, 252, 253, 254, - 255, 256, 257, 258, 150, 151, 152, 153, 154, 155, - 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 226, 227, 228, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 1176, 240, 0, 241, - 242, 243, 244, 0, 599, 246, 0, 247, 248, 249, - 250, 251, 252, 253, 254, 255, 256, 257, 258, 150, - 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 171, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 226, 227, 228, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1184, 240, 0, 241, 242, 243, 244, 0, 599, - 246, 0, 247, 248, 249, 250, 251, 252, 253, 254, - 255, 256, 257, 258, 150, 151, 152, 153, 154, 155, - 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 226, 227, 228, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 240, 0, 241, - 242, 243, 244, 0, 245, 246, 0, 247, 248, 249, - 250, 251, 252, 253, 254, 255, 256, 257, 258, 150, - 151, 152, 153, 154, 155, 156, 443, 444, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 572, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 573, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 0, 574, 0, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 968, 575, 969, 576, 577, 578, 445, 0, 579, - 580, 0, 247, 248, 249, 581, 251, 252, 253, 254, - 255, 256, 257, 582, 150, 151, 152, 153, 154, 155, - 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 226, 227, 228, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 240, 0, 241, - 242, 243, 244, 0, 599, 246, 0, 247, 248, 249, - 250, 251, 252, 253, 254, 255, 256, 257, 258, 150, - 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 171, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 226, 227, 228, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 240, 0, 241, 242, 243, 244, 0, 0, - 246, 0, 247, 248, 249, 250, 251, 252, 253, 254, - 255, 256, 257, 258, 150, 151, 152, 153, 154, 155, - 156, 443, 444, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 572, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 573, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 0, 574, 0, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 575, 0, 576, - 577, 578, 445, 891, 579, 580, 0, 247, 248, 249, - 581, 251, 252, 253, 254, 255, 256, 257, 582, 150, - 151, 152, 153, 154, 155, 156, 443, 444, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 572, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 573, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 0, 574, 0, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 575, 0, 576, 577, 578, 445, 892, 579, - 580, 0, 247, 248, 249, 581, 251, 252, 253, 254, - 255, 256, 257, 582, 150, 151, 152, 153, 154, 155, - 156, 443, 444, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 572, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 573, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 0, 574, 0, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 575, 0, 576, - 577, 578, 445, 893, 579, 580, 0, 247, 248, 249, - 581, 251, 252, 253, 254, 255, 256, 257, 582, 150, - 151, 152, 153, 154, 155, 156, 443, 444, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 572, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 573, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 0, 574, 0, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 575, 0, 576, 577, 578, 445, 0, 579, - 580, 967, 247, 248, 249, 581, 251, 252, 253, 254, - 255, 256, 257, 582, 150, 151, 152, 153, 154, 155, - 156, 443, 444, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 572, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 573, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 0, 574, 0, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 575, 0, 576, - 577, 578, 445, 0, 579, 580, 972, 247, 248, 249, - 581, 251, 252, 253, 254, 255, 256, 257, 582, 150, - 151, 152, 153, 154, 155, 156, 443, 444, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 572, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 573, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 0, 574, 0, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 575, 0, 576, 577, 578, 445, 0, 579, - 580, 0, 247, 248, 249, 581, 251, 252, 253, 254, - 255, 256, 257, 582, 150, 151, 152, 153, 154, 155, - 156, 443, 444, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 572, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 436, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 0, 574, 0, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 575, 0, 833, - 577, 834, 445, 0, 835, 580, 0, 247, 248, 249, - 437, 251, 252, 253, 254, 255, 256, 257, 582, -621, - -621, -621, -621, -621, -621, -621, -621, -621, -621, -621, - -621, -621, -621, -621, -621, -621, -621, -621, -621, -621, - -621, -621, -621, -621, -621, -621, -621, -621, -621, 0, - 0, -621, -621, -621, -621, -621, -621, 0, -621, -621, - -621, -621, 0, 0, -621, -621, -621, -621, -621, -621, - -621, -621, -621, -621, -621, -621, -621, -621, -621, -621, - -621, -621, -621, -621, -621, -621, -621, -621, -621, -621, - -621, -621, -621, -621, -621, -621, -621, -621, -621, -621, - 0, -621, 0, -621, -621, -621, -621, -621, -621, -621, - -621, -621, -621, -621, -621, -621, -621, -621, -621, -621, - -621, -621, -621, -621, -621, -621, -621, -621, -621, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, -621, 0, -657, -621, -621, -621, 0, -621, - -621, 0, -621, -621, -621, -621, -621, -621, -621, -621, - -621, -621, -621, -621, 150, 151, 152, 153, 154, 155, - 156, 443, 444, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 572, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 866, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 0, 574, 0, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 575, 0, 0, - 577, 0, 445, 0, 867, 580, 0, 247, 248, 249, - 868, 251, 252, 253, 254, 255, 256, 257, 582, 150, - 151, 152, 153, 154, 155, 156, 443, 444, 159, 160, - 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, - 572, 172, 173, 174, 175, 176, 177, 178, 179, 0, - 0, 180, 181, 182, 183, 184, 185, 0, 186, 187, - 188, 189, 0, 0, 190, 191, 192, 193, 194, 195, - 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, - 0, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 0, 574, 0, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 575, 0, 0, 577, 0, 445, 0, 835, - 580, 0, 247, 248, 249, 0, 251, 252, 253, 254, - 255, 256, 257, 582, 150, 151, 152, 153, 154, 155, - 156, 443, 444, 159, 160, 161, 162, 163, 164, 165, - 166, 167, 168, 169, 170, 572, 172, 173, 174, 175, - 176, 177, 178, 179, 0, 0, 180, 181, 182, 183, - 184, 185, 0, 186, 187, 188, 189, 0, 0, 190, - 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, - 201, 202, 203, 204, 205, 0, 207, 208, 209, 210, - 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, - 221, 222, 223, 224, 225, 0, 0, 0, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 229, 230, 231, 232, 233, 234, 235, - 236, 237, 238, 239, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 575, 0, 0, - 577, 0, 445, 0, 0, 580, 0, 247, 248, 249, - 0, 251, 252, 253, 254, 255, 256, 257, 582, 271, - 272, 273, 274, 275, 276, 277, 0, 0, 637, 0, - 0, 0, 0, 0, 0, 0, 0, 168, 169, 170, - 0, 17, 18, 19, 20, 0, 0, 0, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 0, 278, 0, - 0, 0, 0, 0, 0, 33, 34, 0, 0, 0, - 638, 639, 0, 0, 0, 0, 0, 203, 204, 205, - 640, 207, 208, 209, 210, 211, 212, 213, 214, 215, - 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, - 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 229, 230, - 231, 232, 233, 234, 235, 236, 237, 238, 239, 472, - 473, 474, 475, 476, 477, 478, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 305, 306, 307, - 0, 0, 0, 0, 641, 0, 642, 643, 0, 644, - 645, 0, 247, 248, 249, 646, 251, 252, 253, 254, - 255, 256, 257, 6, 7, 8, 9, 10, 11, 12, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 13, 14, 15, 16, 17, 18, 19, 20, 0, - 0, 0, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 1000, 1001, 31, 32, 0, 0, 0, 0, 33, - 34, 35, 0, 1002, 0, 0, 0, 0, 310, 311, - 312, 313, 314, 315, 316, 317, 318, 319, 320, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 38, 0, 39, 40, 41, - 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, - 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, - 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, - 82, 83, 84, 85, 1003, 1004, 6, 7, 8, 9, - 10, 11, 12, 0, 0, 0, 87, 0, 0, 0, - 0, 0, 0, 0, 13, 14, 15, 16, 17, 18, - 19, 20, 0, 0, 0, 21, 22, 23, 24, 25, - 26, 27, 28, 29, 0, 30, 31, 32, 0, 0, - 0, 0, 33, 34, 35, 36, 37, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 221, 222, 223, 224, 637, 638, 639, 0, 0, 642, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 409, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 322, 0, 393, 0, 0, + 0, 322, 0, 674, 788, 409, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 393, 0, 626, 508, + 627, 628, 0, 629, 630, 393, 246, 247, 248, 631, + 250, 251, 252, 253, 254, 255, 256, 0, 0, 0, + 0, 0, 409, 0, 0, 0, 0, 0, 0, 1003, + 0, 409, 1006, 0, 21, 22, 23, 24, 25, 26, + 27, 28, 29, 502, 277, 0, 0, 0, 0, 0, + 322, 322, 322, 503, 0, 0, 0, 0, 0, 889, + 890, 891, 0, 0, 0, 0, 0, 1058, 0, 0, + 409, 0, 0, 0, 409, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 508, 0, 0, 0, 0, 39, + 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, + 50, 51, 52, 53, 0, 508, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1104, 0, 0, + 0, 322, 393, 0, 0, 0, 0, 0, 0, 0, + 682, 811, 149, 150, 151, 152, 153, 154, 155, 156, + 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 122, 0, 322, 0, + 0, 0, 322, 0, 322, 1040, 0, 1046, 0, 674, + 0, 1048, 0, 0, 582, 239, 0, 240, 241, 242, + 243, 0, 583, 245, 584, 246, 247, 248, 249, 250, + 251, 252, 253, 254, 255, 256, 257, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 322, + 0, 0, 0, 0, 0, 0, 0, 0, 321, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 322, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, + 227, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 502, 277, 0, 0, + 0, 0, 0, 0, 0, 0, 503, 0, 0, 582, + 239, 588, 240, 241, 242, 243, 0, 583, 245, 0, + 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, + 256, 257, 0, 419, 0, 0, 0, 0, 0, 0, + 0, 0, 39, 40, 41, 42, 43, 44, 45, 46, + 47, 48, 49, 50, 51, 52, 53, 0, 0, 297, + 298, 299, 300, 301, 302, 303, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 304, 305, 306, + 0, 0, 0, 0, 0, 795, 796, 797, 0, 0, + -279, 0, 0, 798, 0, 0, 0, 0, 0, 0, + 0, 0, 420, 421, 0, 33, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 393, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 393, 0, 393, 0, 0, 0, 0, 309, 310, + 311, 312, 313, 314, 315, 316, 317, 318, 319, 0, + 0, 393, 149, 150, 151, 152, 153, 154, 155, 156, + 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 87, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 582, 239, 0, 240, 241, 242, + 243, 0, 583, 245, 594, 246, 247, 248, 249, 250, + 251, 252, 253, 254, 255, 256, 257, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, + 227, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 582, + 239, 0, 240, 241, 242, 243, 597, 583, 245, 0, + 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, + 256, 257, 149, 150, 151, 152, 153, 154, 155, 156, + 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 582, 239, 615, 240, 241, 242, + 243, 0, 583, 245, 0, 246, 247, 248, 249, 250, + 251, 252, 253, 254, 255, 256, 257, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, + 227, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 582, + 239, 684, 240, 241, 242, 243, 0, 583, 245, 0, + 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, + 256, 257, 149, 150, 151, 152, 153, 154, 155, 156, + 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 582, 239, 954, 240, 241, 242, + 243, 0, 583, 245, 0, 246, 247, 248, 249, 250, + 251, 252, 253, 254, 255, 256, 257, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, + 227, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 582, + 239, 1207, 240, 241, 242, 243, 0, 583, 245, 0, + 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, + 256, 257, 149, 150, 151, 152, 153, 154, 155, 156, + 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 582, 239, 1212, 240, 241, 242, + 243, 0, 583, 245, 0, 246, 247, 248, 249, 250, + 251, 252, 253, 254, 255, 256, 257, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, + 227, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 595, + 239, 0, 240, 241, 242, 243, 0, 583, 245, 0, + 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, + 256, 257, 149, 150, 151, 152, 153, 154, 155, 156, + 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 727, 239, 0, 240, 241, 242, + 243, 0, 583, 245, 0, 246, 247, 248, 249, 250, + 251, 252, 253, 254, 255, 256, 257, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, + 227, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 239, 0, 240, 241, 242, 243, 1174, 583, 245, 0, + 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, + 256, 257, 149, 150, 151, 152, 153, 154, 155, 156, + 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 1208, 239, 0, 240, 241, 242, + 243, 0, 583, 245, 0, 246, 247, 248, 249, 250, + 251, 252, 253, 254, 255, 256, 257, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, + 227, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1216, + 239, 0, 240, 241, 242, 243, 0, 583, 245, 0, + 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, + 256, 257, 149, 150, 151, 152, 153, 154, 155, 156, + 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 239, 0, 240, 241, 242, + 243, 0, 244, 245, 0, 246, 247, 248, 249, 250, + 251, 252, 253, 254, 255, 256, 257, 149, 150, 151, + 152, 153, 154, 155, 444, 445, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 823, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 900, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 0, 824, + 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1074, + 713, 1075, 901, 826, 902, 446, 0, 904, 829, 0, + 246, 247, 248, 905, 250, 251, 252, 253, 254, 255, + 256, 830, 149, 150, 151, 152, 153, 154, 155, 156, + 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 225, 226, 227, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 239, 0, 240, 241, 242, + 243, 0, 583, 245, 0, 246, 247, 248, 249, 250, + 251, 252, 253, 254, 255, 256, 257, 149, 150, 151, + 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, + 227, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 239, 0, 240, 241, 242, 243, 0, 0, 245, 0, + 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, + 256, 257, 149, 150, 151, 152, 153, 154, 155, 444, + 445, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 823, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 900, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 0, 824, 0, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 713, 0, 901, 826, 902, + 446, 903, 904, 829, 0, 246, 247, 248, 905, 250, + 251, 252, 253, 254, 255, 256, 830, 149, 150, 151, + 152, 153, 154, 155, 444, 445, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 823, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 900, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 0, 824, + 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 713, 0, 901, 826, 902, 446, 909, 904, 829, 0, + 246, 247, 248, 905, 250, 251, 252, 253, 254, 255, + 256, 830, 149, 150, 151, 152, 153, 154, 155, 444, + 445, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 823, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 900, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 0, 824, 0, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 713, 0, 901, 826, 902, + 446, 910, 904, 829, 0, 246, 247, 248, 905, 250, + 251, 252, 253, 254, 255, 256, 830, 149, 150, 151, + 152, 153, 154, 155, 444, 445, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 823, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 900, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 0, 824, + 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 713, 0, 901, 826, 902, 446, 0, 904, 829, 1126, + 246, 247, 248, 905, 250, 251, 252, 253, 254, 255, + 256, 830, 149, 150, 151, 152, 153, 154, 155, 444, + 445, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 823, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 900, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 0, 824, 0, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 713, 0, 901, 826, 902, + 446, 0, 904, 829, 1128, 246, 247, 248, 905, 250, + 251, 252, 253, 254, 255, 256, 830, 149, 150, 151, + 152, 153, 154, 155, 444, 445, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 823, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 437, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 0, 824, + 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 713, 0, 825, 826, 827, 446, 0, 828, 829, 0, + 246, 247, 248, 438, 250, 251, 252, 253, 254, 255, + 256, 830, -648, -648, -648, -648, -648, -648, -648, -648, + -648, -648, -648, -648, -648, -648, -648, -648, -648, -648, + -648, -648, -648, -648, -648, -648, -648, -648, -648, -648, + -648, -648, 0, 0, -648, -648, -648, -648, -648, -648, + 0, -648, -648, -648, -648, 0, 0, -648, -648, -648, + -648, -648, -648, -648, -648, -648, -648, -648, -648, -648, + -648, -648, -648, -648, -648, -648, -648, -648, -648, -648, + -648, -648, -648, -648, -648, -648, -648, -648, -648, -648, + -648, -648, -648, 0, -648, 0, -648, -648, -648, -648, + -648, -648, -648, -648, -648, -648, -648, -648, -648, -648, + -648, -648, -648, -648, -648, -648, -648, -648, -648, -648, + -648, -648, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, -648, 0, -684, -648, -648, + -648, 0, -648, -648, 0, -648, -648, -648, -648, -648, + -648, -648, -648, -648, -648, -648, -648, 149, 150, 151, + 152, 153, 154, 155, 444, 445, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 823, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 870, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 0, 824, + 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 713, 0, 0, 826, 0, 446, 0, 871, 829, 0, + 246, 247, 248, 872, 250, 251, 252, 253, 254, 255, + 256, 830, 149, 150, 151, 152, 153, 154, 155, 444, + 445, 158, 159, 160, 161, 162, 163, 164, 165, 166, + 167, 168, 169, 823, 171, 172, 173, 174, 175, 176, + 177, 178, 0, 0, 179, 180, 181, 182, 183, 184, + 0, 185, 186, 187, 188, 0, 0, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, + 202, 203, 204, 0, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 0, 824, 0, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 713, 0, 0, 826, 0, + 446, 0, 828, 829, 0, 246, 247, 248, 0, 250, + 251, 252, 253, 254, 255, 256, 830, 149, 150, 151, + 152, 153, 154, 155, 444, 445, 158, 159, 160, 161, + 162, 163, 164, 165, 166, 167, 168, 169, 823, 171, + 172, 173, 174, 175, 176, 177, 178, 0, 0, 179, + 180, 181, 182, 183, 184, 0, 185, 186, 187, 188, + 0, 0, 189, 190, 191, 192, 193, 194, 195, 196, + 197, 198, 199, 200, 201, 202, 203, 204, 0, 206, + 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, + 217, 218, 219, 220, 221, 222, 223, 224, 0, 0, + 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 228, 229, 230, 231, + 232, 233, 234, 235, 236, 237, 238, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 713, 0, 0, 826, 0, 446, 0, 0, 829, 0, + 246, 247, 248, 0, 250, 251, 252, 253, 254, 255, + 256, 830, 270, 271, 272, 273, 274, 275, 276, 0, + 0, 622, 0, 0, 0, 0, 0, 0, 0, 0, + 167, 168, 169, 0, 17, 18, 19, 20, 0, 0, + 0, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 0, 277, 0, 0, 0, 0, 0, 0, 33, 34, + 0, 0, 0, 623, 624, 0, 0, 0, 0, 0, + 202, 203, 204, 625, 206, 207, 208, 209, 210, 211, + 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, + 222, 223, 224, 0, 38, 0, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 228, 229, 230, 231, 232, 233, 234, 235, 236, + 237, 238, 474, 475, 476, 477, 478, 479, 480, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 304, 305, 306, 0, 0, 0, 0, 626, 0, 627, + 628, 0, 629, 630, 0, 246, 247, 248, 631, 250, + 251, 252, 253, 254, 255, 256, 7, 8, 9, 10, + 11, 12, 13, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 14, 15, 16, 0, 17, 18, + 19, 20, 0, 0, 0, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 1018, 1019, 31, 32, 0, 0, + 0, 0, 33, 34, 35, 0, 1020, 0, 0, 0, + 0, 309, 310, 311, 312, 313, 314, 315, 316, 317, + 318, 319, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 0, 86, 6, - 7, 8, 9, 10, 11, 12, 0, 0, 0, 87, - 0, 0, 0, 0, 0, 0, 0, 13, 14, 15, + 79, 80, 81, 82, 83, 84, 85, 1021, 1022, 7, + 8, 9, 10, 11, 12, 13, 0, 0, 0, 87, + 0, 0, 0, 0, 0, 0, 0, 14, 15, 16, 0, 17, 18, 19, 20, 0, 0, 0, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 0, 278, 31, - 355, 0, 0, 0, 0, 33, 34, 0, 0, 0, + 23, 24, 25, 26, 27, 28, 29, 0, 30, 31, + 32, 0, 0, 0, 0, 33, 34, 35, 36, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, 64, 0, - 0, 0, 0, 0, 6, 7, 8, 9, 10, 11, - 12, 21, 22, 23, 24, 25, 26, 27, 28, 29, - 500, 278, 13, 14, 15, 0, 17, 18, 19, 20, - 501, 0, 87, 21, 22, 23, 24, 25, 26, 27, - 28, 29, 0, 278, 31, 0, 0, 0, 0, 0, - 33, 34, 35, 0, 0, 0, 0, 419, 0, 0, - 0, 0, 0, 0, 0, 0, 39, 40, 41, 42, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 0, 86, 7, 8, 9, 10, 11, 12, 13, 0, + 0, 0, 87, 0, 0, 0, 0, 0, 0, 0, + 14, 15, 16, 0, 17, 18, 19, 20, 0, 0, + 0, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 0, 277, 31, 355, 0, 0, 0, 0, 33, 34, + 0, 0, 356, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, - 53, 0, 0, 0, 0, 0, 38, 0, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, - 61, 62, 63, 64, -274, 0, 0, 0, 0, 6, - 7, 8, 9, 10, 11, 12, 420, 421, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 13, 14, 15, - 0, 17, 18, 19, 20, 0, 0, 87, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 0, 278, 31, - 0, 0, 0, 0, 0, 33, 34, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, 64, 298, - 299, 300, 301, 302, 303, 304, 0, 0, 0, 0, - 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, - 0, 0, 0, 0, 0, 805, 806, 807, 305, 306, - 307, 0, 87, 808, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 33, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 33, 308, 0, 309, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 38, 0, 0, 0, 0, 0, 310, 311, - 312, 313, 314, 315, 316, 317, 318, 319, 320, 310, - 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, - 298, 299, 300, 301, 302, 303, 304, 0, 0, 0, - 0, 298, 299, 300, 301, 302, 303, 304, 305, 306, - 307, 16, 87, 0, 0, 0, 0, 0, 0, 305, - 306, 307, 0, 87, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 33, 0, 0, 0, - 0, 31, 382, 0, 0, 0, 0, 33, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 298, 299, 300, 301, 302, - 303, 304, 38, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 305, 306, 307, 16, 0, 0, 310, - 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, - 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, - 320, 33, 298, 299, 300, 301, 302, 303, 304, 0, - 0, 0, 0, 0, 0, 0, 520, 0, 0, 0, - 305, 306, 307, 87, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 87, 0, 0, 38, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 33, 308, - 0, 0, 0, 0, 310, 311, 312, 313, 314, 315, - 316, 317, 318, 319, 320, 0, 0, 298, 299, 300, - 301, 302, 303, 304, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 38, 305, 306, 307, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 87, 0, - 0, 310, 311, 312, 313, 314, 315, 316, 317, 318, - 319, 320, 0, 33, 298, 299, 300, 301, 302, 303, - 304, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 305, 306, 307, 0, 0, 0, 298, 299, - 300, 301, 302, 303, 304, 87, 0, 0, 0, 38, - 0, 0, 0, 0, 0, 382, 305, 306, 307, 0, - 33, 0, 0, 0, 0, 0, 310, 311, 312, 313, - 314, 315, 316, 317, 318, 319, 320, 0, 31, 0, - 0, 0, 0, 0, 33, 298, 299, 300, 301, 302, - 303, 304, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 305, 306, 307, 0, 0, 0, 0, - 87, 0, 0, 310, 311, 312, 313, 314, 315, 316, - 317, 318, 319, 320, 0, 0, 0, 0, 0, 0, - 0, 33, 0, 0, 0, 0, 0, 310, 311, 312, - 313, 314, 315, 316, 317, 318, 319, 320, 0, 298, - 299, 300, 301, 302, 303, 304, 0, 87, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 305, 306, 307, - 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 87, 0, 0, 310, 311, 312, 313, 314, 315, - 316, 317, 318, 319, 320, 33, 298, 299, 300, 301, - 302, 303, 304, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 305, 306, 307, 16, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 87, 0, - 0, 38, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 33, 0, 0, 0, 0, 0, 310, 311, - 312, 313, 314, 315, 316, 317, 318, 319, 320, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 298, 299, - 300, 301, 302, 303, 304, 0, 0, 0, 38, 0, - 0, 509, 1145, 0, 0, 1146, 305, 306, 307, 16, - 0, 0, 0, 0, 0, 310, 311, 312, 313, 314, - 315, 316, 317, 318, 319, 320, 298, 299, 300, 301, - 302, 303, 304, 0, 33, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 305, 306, 307, 16, 509, 0, - 0, 0, 510, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 38, 0, 33, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 310, 311, 312, - 313, 314, 315, 316, 317, 318, 319, 320, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1145, 0, 0, 1146, 310, 311, 312, 313, 314, - 315, 316, 317, 318, 319, 320, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 500, 278, 0, 0, 0, - 0, 0, 0, 0, 0, 501, 0, 0, 0, 0, - 0, 0, 510, 0, 0, 0, 0, 0, 298, 299, - 300, 301, 302, 303, 304, 0, 0, 0, 0, 0, - 0, 0, 419, 0, 0, 0, 305, 306, 307, 16, - 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 0, 271, 272, 273, - 274, 275, 276, 277, 33, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 168, 169, 170, 0, 17, - 18, 19, 20, 0, 0, 0, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 0, 278, 31, 355, 0, - 38, 420, 421, 33, 34, 0, 0, 356, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 310, 311, 312, - 313, 314, 315, 316, 317, 318, 319, 320, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, - 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 229, 230, 231, 232, - 233, 234, 235, 236, 237, 238, 239, 271, 272, 273, - 274, 275, 276, 277, 21, 22, 23, 24, 25, 26, - 27, 28, 29, 500, 278, 168, 169, 170, 0, 17, - 18, 19, 20, 501, 0, 0, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 0, 278, 31, 0, 0, - 0, 0, 0, 33, 34, 35, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, + 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, + 63, 64, 0, 0, 0, 0, 0, 7, 8, 9, + 10, 11, 12, 13, 21, 22, 23, 24, 25, 26, + 27, 28, 29, 502, 277, 14, 15, 16, 0, 17, + 18, 19, 20, 503, 0, 87, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 0, 277, 31, 355, 0, + 0, 0, 0, 33, 34, 0, 0, 0, 0, 0, + 419, 0, 0, 0, 0, 0, 0, 0, 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 0, 0, 0, 0, 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 229, 230, 231, 232, - 233, 234, 235, 236, 237, 238, 239, 271, 272, 273, - 274, 275, 276, 277, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 168, 169, 170, 0, 17, - 18, 19, 20, 0, 0, 0, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 0, 278, 31, 0, 0, - 0, 0, 0, 33, 34, 0, 0, 0, 0, 0, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62, 63, 64, 0, 0, 0, + 0, 0, 7, 8, 9, 10, 11, 12, 13, 420, + 421, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 14, 15, 16, 0, 17, 18, 19, 20, 0, 0, + 87, 21, 22, 23, 24, 25, 26, 27, 28, 29, + 0, 277, 31, 0, 0, 0, 0, 0, 33, 34, + 35, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, - 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 229, 230, 231, 232, - 233, 234, 235, 236, 237, 238, 239, 271, 272, 273, - 274, 275, 276, 277, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 168, 169, 170, 0, 17, - 18, 19, 20, 0, 0, 0, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 0, 278, 0, 0, 0, + 0, 0, 0, 0, 38, 0, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, + 63, 64, 0, 0, 0, 0, 0, 7, 8, 9, + 10, 11, 12, 13, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 14, 15, 16, 0, 17, + 18, 19, 20, 0, 0, 87, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 0, 277, 31, 0, 0, 0, 0, 0, 33, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 229, 230, 231, 232, - 233, 234, 235, 236, 237, 238, 239, 271, 272, 273, - 274, 275, 276, 277, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 168, 169, 170, 0, 741, - 0, 742, 20, 0, 0, 0, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 0, 278, 0, 0, 0, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, + 58, 59, 60, 61, 62, 63, 64, 297, 298, 299, + 300, 301, 302, 303, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 304, 305, 306, 297, 298, + 299, 300, 301, 302, 303, 0, 0, 0, 0, 0, + 87, 0, 0, 0, 0, 0, 304, 305, 306, 0, + 0, 0, 0, 33, 307, 0, 308, 297, 298, 299, + 300, 301, 302, 303, 0, 0, 0, 0, 31, 382, + 0, 0, 0, 0, 33, 304, 305, 306, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 33, 0, 0, 309, 310, 311, 312, + 313, 314, 315, 316, 317, 318, 319, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 309, 310, 311, + 312, 313, 314, 315, 316, 317, 318, 319, 0, 38, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 87, 0, 0, 0, 0, 0, 309, 310, 311, 312, + 313, 314, 315, 316, 317, 318, 319, 0, 0, 0, + 0, 87, 297, 298, 299, 300, 301, 302, 303, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 522, + 304, 305, 306, 523, 0, 0, 0, 0, 0, 0, + 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 33, 297, + 298, 299, 300, 301, 302, 303, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 304, 305, 306, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 38, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 33, 307, 0, 0, 0, + 0, 309, 310, 311, 312, 313, 314, 315, 316, 317, + 318, 319, 0, 0, 297, 298, 299, 300, 301, 302, + 303, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 38, 304, 305, 306, 0, 0, 0, 523, 0, + 0, 0, 0, 0, 0, 87, 0, 0, 309, 310, + 311, 312, 313, 314, 315, 316, 317, 318, 319, 0, + 33, 297, 298, 299, 300, 301, 302, 303, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 304, + 305, 306, 0, 0, 0, 297, 298, 299, 300, 301, + 302, 303, 87, 0, 0, 0, 38, 0, 0, 0, + 0, 0, 382, 304, 305, 306, 0, 33, 0, 0, + 0, 0, 0, 309, 310, 311, 312, 313, 314, 315, + 316, 317, 318, 319, 0, 31, 0, 0, 0, 0, + 0, 33, 297, 298, 299, 300, 301, 302, 303, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 304, 305, 306, 0, 0, 0, 0, 87, 0, 0, + 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, + 319, 0, 0, 0, 0, 0, 0, 0, 33, 0, + 0, 0, 0, 0, 309, 310, 311, 312, 313, 314, + 315, 316, 317, 318, 319, 0, 297, 298, 299, 300, + 301, 302, 303, 0, 87, 0, 0, 297, 298, 299, + 300, 301, 302, 303, 304, 305, 306, 0, 0, 0, + 0, 0, 0, 0, 0, 304, 305, 306, 87, 0, + 0, 309, 310, 311, 312, 313, 314, 315, 316, 317, + 318, 319, 33, 0, 0, 297, 298, 299, 300, 301, + 302, 303, 0, 33, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 304, 305, 306, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 87, 0, 0, 38, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, + 0, 33, 0, 0, 0, 309, 310, 311, 312, 313, + 314, 315, 316, 317, 318, 319, 309, 310, 311, 312, + 313, 314, 315, 316, 317, 318, 319, 297, 298, 299, + 300, 301, 302, 303, 0, 0, 0, 38, 511, 1175, + 0, 0, 1176, 0, 0, 304, 305, 306, 0, 511, + 0, 0, 0, 512, 309, 310, 311, 312, 313, 314, + 315, 316, 317, 318, 319, 0, 0, 0, 0, 0, 0, 0, 0, 33, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1175, 0, + 0, 1176, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 270, + 271, 272, 273, 274, 275, 276, 309, 310, 311, 312, + 313, 314, 315, 316, 317, 318, 319, 167, 168, 169, + 0, 17, 18, 19, 20, 0, 0, 0, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 0, 277, 31, + 355, 0, 0, 512, 0, 33, 34, 0, 0, 356, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, - 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 229, 230, 231, 232, - 233, 234, 235, 236, 237, 238, 239, 271, 272, 273, - 274, 275, 276, 277, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 168, 169, 170, 0, 298, - 299, 300, 301, 302, 303, 304, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 0, 278, 305, 306, 307, - 0, 0, 0, 33, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 382, 0, 0, 0, 0, 33, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 38, - 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, - 48, 49, 50, 51, 52, 53, 229, 230, 231, 232, - 233, 234, 235, 236, 237, 238, 239, 0, 0, 0, - 0, 298, 299, 300, 301, 302, 303, 304, 310, 311, - 312, 313, 314, 315, 316, 317, 318, 319, 320, 305, - 306, 307, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, 228, 229, + 230, 231, 232, 233, 234, 235, 236, 237, 238, 270, + 271, 272, 273, 274, 275, 276, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 167, 168, 169, + 0, 17, 18, 19, 20, 0, 0, 0, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 0, 277, 31, + 0, 0, 0, 0, 0, 33, 34, 35, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 33, 0, 0, + 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, 228, 229, + 230, 231, 232, 233, 234, 235, 236, 237, 238, 270, + 271, 272, 273, 274, 275, 276, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 167, 168, 169, + 0, 17, 18, 19, 20, 0, 0, 0, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 0, 277, 31, + 0, 0, 0, 0, 0, 33, 34, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, 228, 229, + 230, 231, 232, 233, 234, 235, 236, 237, 238, 270, + 271, 272, 273, 274, 275, 276, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 167, 168, 169, + 0, 17, 18, 19, 20, 0, 0, 0, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 0, 277, 0, + 0, 0, 0, 0, 0, 33, 34, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, 228, 229, + 230, 231, 232, 233, 234, 235, 236, 237, 238, 270, + 271, 272, 273, 274, 275, 276, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 167, 168, 169, + 0, 731, 0, 732, 20, 0, 0, 0, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 0, 277, 0, + 0, 0, 0, 0, 0, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, 228, 229, + 230, 231, 232, 233, 234, 235, 236, 237, 238, 270, + 271, 272, 273, 274, 275, 276, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 167, 168, 169, + 0, 297, 298, 299, 300, 301, 302, 303, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 0, 277, 304, + 305, 306, 0, 0, 0, 33, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 382, 0, 0, 0, 0, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, - 320 + 0, 38, 0, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, 228, 229, + 230, 231, 232, 233, 234, 235, 236, 237, 238, 0, + 0, 0, 0, 297, 298, 299, 300, 301, 302, 303, + 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, + 319, 304, 305, 306, 297, 298, 299, 300, 301, 302, + 303, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 304, 305, 306, 0, 0, 0, 0, 33, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 38, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 309, 310, 311, 312, 313, 314, 315, 316, + 317, 318, 319, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 309, 310, 311, 312, 313, 314, 315, + 316, 317, 318, 319 }; static const short int yycheck[] = { - 5, 35, 35, 5, 5, 36, 131, 697, 123, 269, - 110, 324, 605, 556, 706, 418, 124, 32, 433, 5, - 5, 441, 5, 113, 114, 115, 459, 5, 846, 705, - 5, 288, 37, 35, 450, 5, 715, 869, 748, 432, - 754, 547, 352, 451, 754, 975, 522, 324, 556, 3, - 5, 3, 37, 931, 324, 24, 24, 35, 24, 3, - 3, 24, 3, 24, 920, 32, 3, 32, 948, 554, - 46, 64, 3, 24, 19, 10, 11, 64, 26, 137, - 10, 11, 37, 135, 240, 12, 3, 0, 12, 141, - 246, 32, 1110, 124, 78, 135, 24, 131, 131, 0, - 1151, 141, 50, 32, 45, 10, 11, 48, 85, 141, - 55, 56, 268, 706, 1165, 531, 1167, 44, 123, 124, - 44, 126, 1140, 941, 540, 110, 67, 110, 1179, 131, - 136, 141, 110, 139, 149, 10, 11, 614, 615, 616, - 296, 141, 627, 980, 1000, 415, 131, 623, 64, 24, - 141, 694, 831, 29, 30, 31, 149, 5, 471, 135, - 136, 418, 149, 147, 148, 1045, 143, 135, 123, 124, - 139, 126, 1050, 78, 135, 141, 890, 597, 141, 84, - 890, 135, 149, 135, 149, 899, 694, 35, 139, 899, - 141, 135, 136, 136, 471, 139, 139, 138, 135, 136, - 1032, 471, 139, 78, 135, 136, 141, 713, 139, 84, - 138, 141, 1142, 32, 370, 123, 624, 625, 135, 136, - 149, 897, 139, 131, 140, 731, 940, 1064, 135, 539, - 940, 541, 85, 149, 710, 10, 11, 706, 85, 85, - 85, 634, 147, 148, 85, 141, 3, 4, 5, 6, - 7, 8, 9, 287, 287, 732, 526, 734, 727, 141, - 85, 137, 110, 85, 978, 270, 135, 85, 978, 135, - 946, 140, 147, 148, 140, 1107, 141, 85, 85, 284, - 1098, 141, 135, 131, 960, 287, 556, 85, 141, 135, - 143, 85, 141, 408, 135, 141, 143, 143, 143, 141, - 141, 85, 143, 308, 309, 85, 85, 141, 565, 84, - 135, 141, 141, 1003, 144, 270, 141, 135, 143, 324, - 325, 143, 136, 141, 138, 143, 141, 131, 135, 284, - 149, 141, 366, 135, 141, 143, 143, 135, 26, 141, - 325, 135, 141, 141, 141, 143, 351, 141, 1062, 354, - 1042, 356, 1062, 308, 309, 135, 44, 1036, 32, 143, - 34, 141, 50, 620, 143, 32, 351, 1147, 141, 324, - 325, 45, 137, 141, 48, 140, 135, 1053, 363, 136, - 363, 366, 141, 135, 135, 363, 1166, 141, 1168, 141, - 141, 449, 141, 451, 136, 144, 351, 139, 1178, 354, - 869, 356, 135, 408, 141, 513, 135, 1097, 141, 135, - 415, 136, 141, 138, 141, 141, 135, 102, 1110, 434, - 435, 136, 141, 135, 694, 440, 441, 442, 459, 141, - 415, 141, 3, 4, 5, 6, 7, 8, 9, 287, - 25, 26, 123, 135, 135, 450, 461, 452, 1140, 1042, - 141, 884, 85, 408, 459, 470, 143, 462, 366, 136, - 415, 12, 931, 147, 148, 450, 471, 135, 138, 434, - 435, 1161, 1162, 141, 135, 440, 441, 442, 49, 135, - 141, 135, 149, 287, 3, 4, 5, 6, 7, 8, - 9, 525, 29, 30, 31, 450, 461, 452, 135, 136, - 408, 532, 139, 143, 459, 434, 435, 462, 513, 514, - 136, 440, 441, 442, 529, 363, 471, 932, 366, 524, - 139, 526, 527, 32, 33, 24, 531, 532, 141, 514, - 136, 562, 461, 135, 142, 540, 551, 542, 142, 140, - 525, 526, 698, 140, 140, 140, 531, 140, 140, 140, - 1093, 556, 140, 140, 140, 540, 140, 562, 513, 514, - 140, 140, 366, 1032, 529, 140, 624, 625, 140, 524, - 135, 526, 527, 1042, 378, 978, 531, 685, 135, 142, - 136, 1050, 597, 1126, 144, 540, 136, 542, 13, 14, - 15, 16, 145, 142, 279, 855, 281, 137, 145, 44, - 529, 556, 607, 284, 135, 607, 135, 562, 135, 3, - 144, 144, 431, 1033, 142, 434, 435, 525, 140, 145, - 140, 440, 441, 442, 142, 142, 140, 124, 139, 607, - 138, 135, 597, 140, 609, 84, 142, 135, 1107, 135, - 145, 1110, 461, 324, 3, 4, 5, 6, 7, 8, - 9, 144, 607, 1068, 140, 135, 135, 145, 145, 137, - 142, 37, 84, 140, 139, 135, 671, 140, 597, 140, - 142, 1140, 677, 142, 142, 142, 142, 525, 142, 142, - 685, 142, 349, 142, 142, 352, 142, 947, 140, 694, - 49, 749, 140, 135, 84, 142, 1116, 138, 135, 145, - 13, 145, 142, 13, 1120, 140, 135, 47, 142, 767, - 529, 1024, 145, 136, 142, 142, 671, 402, 142, 404, - 5, 525, 677, 142, 142, 142, 85, 408, 142, 920, - 685, 1146, 920, 1149, 928, 1151, 741, 742, 743, 694, - 1029, 808, 920, 428, 1164, 920, 817, 1075, 920, 619, - 767, 1167, 620, 920, 1024, 879, 755, 5, 920, 1000, - 1175, 533, 1182, 822, 431, 1038, 1100, 434, 435, 454, - 455, 865, 504, 440, 441, 442, 1172, 860, 597, 1092, - 503, 690, 449, 607, 451, 427, 741, 742, 743, 427, - 471, 25, 26, 27, 461, 731, 962, 920, 32, 33, - 34, 35, 36, 37, 38, 39, 40, 876, 42, 824, - 943, 561, 821, -1, -1, -1, -1, 822, -1, -1, - -1, -1, 1092, 1093, -1, -1, -1, -1, -1, -1, - -1, 328, 513, -1, -1, 332, 333, -1, 335, 336, - 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, - 347, 348, -1, 884, 351, -1, 1126, -1, -1, 824, - -1, 546, 529, -1, -1, -1, -1, 822, -1, -1, - -1, -1, 539, -1, 541, 556, -1, -1, -1, 884, - -1, -1, -1, -1, -1, -1, -1, 706, -1, -1, - -1, -1, -1, -1, -1, 824, -1, -1, 131, -1, - 1025, -1, -1, -1, 571, -1, -1, -1, 727, -1, - 1025, 37, -1, -1, 4, 920, 1016, 922, 920, 920, - -1, 926, -1, 928, -1, -1, -1, -1, 1018, 884, - 597, -1, -1, -1, 920, 920, -1, 756, 757, 758, - -1, -1, 920, 747, -1, 920, -1, -1, -1, -1, - 920, -1, -1, 450, -1, -1, -1, 624, 625, -1, - -1, -1, -1, 1078, -1, 920, -1, 922, -1, -1, - 948, 926, 1087, 928, 136, 1075, -1, -1, -1, -1, - -1, -1, -1, 480, 481, 482, 1076, -1, 485, 1145, - 1048, 1025, 1025, -1, -1, 1000, -1, 1002, 1154, 125, - -1, 127, 128, -1, 685, 824, -1, -1, -1, 99, - -1, 1016, 1127, 694, 104, 1016, 513, 1002, 1033, 1024, - 1025, 518, 1000, 1025, 1029, 1000, -1, -1, -1, -1, - 1016, 1016, 122, 5, 531, -1, -1, 127, 1016, 706, - 1025, 1016, 132, 540, 711, 1000, 1016, 1002, -1, -1, - 869, 141, 142, 1087, 287, -1, 875, 876, 877, -1, - 727, 1016, 1093, -1, -1, 37, -1, -1, 1033, 1024, - 1025, -1, 920, 1078, 1029, -1, -1, -1, -1, 1084, - -1, -1, 1087, 1084, -1, -1, -1, 1092, 1093, 756, - 757, 758, -1, 1127, -1, 1126, -1, 1075, 1084, 1084, - -1, 1116, 1087, -1, 1033, -1, 1084, -1, 123, 1084, - -1, 126, 931, -1, 1084, 1120, 349, 1025, -1, 352, - -1, 1126, 1127, 1078, -1, -1, 288, -1, -1, 1084, - -1, -1, 1087, 366, -1, 1120, -1, 1092, 1093, -1, - -1, -1, 1127, 962, 1149, 378, 1151, -1, 1163, 1164, - -1, 1116, 1000, -1, 126, -1, 1171, 824, -1, 285, - 286, -1, 1167, -1, 1149, 1120, 1151, 1182, 1016, -1, - 1078, 1126, 1127, -1, -1, -1, -1, 1025, -1, 1087, - -1, -1, 1167, -1, -1, -1, -1, 1116, 685, -1, - 280, -1, 282, 283, 1149, 285, 1151, 694, 1163, 1164, - 326, 327, 869, 888, -1, 367, 1171, -1, 875, 876, - 877, -1, 1167, 1032, 1033, -1, 449, 1182, 451, 1127, - -1, 1025, -1, 1042, -1, 351, -1, 1075, -1, -1, - 1078, 1050, 322, -1, 1163, 1164, 1084, -1, -1, 1087, - -1, -1, 1171, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 1182, -1, -1, 418, -1, -1, -1, - -1, 387, 388, 389, 931, -1, -1, -1, -1, 284, - 360, -1, -1, -1, 1078, 1123, -1, -1, -1, 1127, - -1, -1, -1, 1087, -1, -1, -1, 377, 1107, 974, - -1, 1110, 525, -1, -1, 962, 5, 1116, 270, -1, - -1, -1, -1, -1, -1, -1, 539, -1, 541, 324, - 325, -1, 979, 403, -1, 405, -1, -1, 5, 409, - 817, 1140, -1, 1127, 450, -1, -1, -1, 37, 419, - 420, 421, -1, -1, -1, -1, 308, 309, 571, -1, - -1, -1, 504, 1024, 1163, 1164, -1, -1, 35, -1, - -1, -1, 1171, 325, -1, -1, -1, 447, -1, -1, - -1, -1, -1, 1182, -1, 1032, 1033, -1, -1, -1, - -1, -1, -1, -1, -1, 1042, -1, -1, -1, -1, - -1, -1, 354, 1050, 356, -1, -1, -1, 1055, 515, - 516, 624, 625, 408, -1, -1, -1, -1, -1, -1, - 415, -1, -1, 565, -1, 531, -1, -1, -1, -1, - -1, 1092, -1, -1, 540, 505, -1, -1, -1, 1104, - -1, -1, 512, 110, -1, -1, -1, -1, -1, -1, - -1, 118, -1, 523, -1, -1, -1, -1, -1, -1, - 1107, -1, -1, 1110, 459, -1, -1, -1, -1, 1116, - 1135, -1, -1, -1, -1, -1, 471, -1, 620, -1, - 550, -1, -1, -1, -1, 555, -1, -1, -1, 1136, - -1, -1, -1, 1140, -1, -1, -1, -1, 711, -1, - 452, -1, -1, -1, -1, -1, -1, -1, 1155, -1, - 462, -1, -1, -1, -1, -1, 1163, 1164, -1, -1, - -1, -1, -1, -1, 1171, -1, -1, 633, -1, -1, - -1, 526, -1, -1, 747, 1182, -1, -1, -1, -1, + 5, 35, 35, 123, 5, 36, 110, 5, 131, 559, + 460, 5, 5, 4, 323, 418, 434, 691, 113, 114, + 115, 351, 442, 136, 124, 682, 268, 700, 420, 421, + 323, 690, 37, 589, 5, 850, 553, 5, 5, 5, + 451, 558, 599, 600, 239, 433, 287, 960, 744, 993, + 245, 525, 352, 5, 550, 452, 738, 323, 3, 85, + 104, 5, 744, 873, 3, 3, 37, 32, 35, 35, + 948, 968, 267, 3, 64, 559, 131, 3, 4, 5, + 6, 7, 8, 9, 12, 37, 3, 998, 64, 10, + 11, 35, 32, 124, 137, 612, 46, 131, 131, 0, + 295, 10, 11, 937, 85, 29, 30, 31, 12, 32, + 85, 136, 123, 3, 139, 3, 44, 143, 123, 124, + 131, 126, 415, 534, 0, 3, 10, 11, 1138, 679, + 85, 122, 543, 607, 141, 691, 127, 10, 11, 469, + 44, 132, 110, 110, 959, 10, 11, 26, 821, 141, + 141, 142, 123, 124, 32, 126, 85, 78, 110, 149, + 1170, 581, 143, 84, 473, 131, 110, 45, 143, 1066, + 48, 50, 141, 149, 287, 370, 140, 418, 1089, 131, + 473, 145, 64, 148, 1018, 135, 136, 131, 143, 67, + 135, 136, 709, 1071, 139, 679, 135, 32, 136, 141, + 1078, 139, 698, 899, 78, 135, 136, 473, 148, 139, + 136, 608, 609, 137, 143, 85, 1129, 899, 135, 84, + 916, 695, 1135, 719, 85, 148, 147, 148, 1172, 85, + 618, 286, 141, 19, 916, 279, 529, 281, 32, 85, + 1050, 571, 542, 85, 544, 135, 136, 135, 136, 139, + 141, 139, 286, 286, 367, 914, 1169, 141, 140, 85, + 138, 25, 26, 1177, 269, 135, 559, 149, 141, 55, + 56, 141, 135, 147, 148, 85, 557, 140, 283, 135, + 147, 148, 143, 32, 1198, 141, 1200, 143, 408, 135, + 85, 282, 139, 284, 141, 141, 1210, 143, 269, 140, + 996, 143, 307, 308, 145, 418, 136, 966, 1123, 135, + 85, 366, 283, 148, 996, 141, 360, 143, 323, 324, + 286, 980, 135, 378, 1134, 135, 1136, 140, 569, 135, + 611, 141, 366, 377, 141, 141, 307, 308, 140, 136, + 135, 138, 286, 145, 85, 350, 141, 137, 143, 354, + 140, 356, 323, 324, 148, 366, 26, 1181, 141, 403, + 135, 405, 1058, 604, 1021, 141, 141, 85, 143, 32, + 33, 37, 324, 1197, 44, 1199, 1058, 135, 141, 350, + 50, 1054, 141, 354, 691, 356, 679, 1211, 1062, 141, + 141, 1087, 144, 506, 135, 363, 363, 408, 350, 148, + 141, 141, 143, 408, 961, 1087, 963, 450, 141, 452, + 415, 363, 135, 136, 366, 515, 139, 135, 409, 363, + 1079, 135, 366, 141, 135, 143, 135, 141, 141, 460, + 141, 144, 141, 140, 123, 142, 32, 408, 34, 746, + 747, 748, 141, 893, 415, 102, 451, 135, 453, 45, + 141, 141, 48, 141, 135, 460, 569, 448, 463, 125, + 141, 127, 128, 415, 1138, 1122, 141, 141, 473, 144, + 435, 436, 123, 528, 141, 126, 441, 442, 443, 135, + 451, 135, 453, 725, 85, 141, 141, 141, 683, 460, + 136, 604, 463, 139, 528, 135, 1170, 462, 141, 451, + 141, 141, 473, 895, 535, 141, 1062, 472, 135, 135, + 515, 516, 435, 436, 141, 141, 507, 528, 441, 442, + 443, 135, 527, 514, 529, 530, 135, 141, 135, 534, + 535, 949, 141, 135, 141, 566, 1193, 1194, 543, 462, + 545, 136, 24, 138, 515, 516, 141, 136, 579, 13, + 14, 15, 16, 143, 559, 12, 527, 141, 529, 530, + 144, 566, 138, 534, 516, 608, 609, 532, 1118, 135, + 670, 135, 543, 136, 545, 143, 528, 529, 29, 30, + 31, 139, 534, 136, 528, 141, 591, 135, 559, 554, + 140, 543, 593, 996, 283, 566, 138, 140, 1115, 348, + 435, 436, 140, 352, 1154, 140, 441, 442, 443, 532, + 140, 140, 140, 140, 140, 140, 581, 859, 284, 285, + 591, 278, 140, 280, 591, 591, 956, 462, 140, 140, + 140, 1051, 283, 142, 323, 142, 140, 135, 135, 142, + 1157, 435, 436, 136, 144, 136, 141, 441, 442, 443, + 142, 656, 137, 3, 44, 145, 135, 662, 581, 325, + 326, 135, 135, 144, 144, 670, 142, 145, 462, 140, + 142, 140, 323, 324, 679, 1093, 667, 984, 140, 142, + 139, 135, 737, 138, 350, 656, 435, 436, 140, 802, + 84, 662, 441, 442, 443, 686, 739, 532, 142, 670, + 813, 450, 135, 452, 135, 141, 144, 84, 679, 135, + 145, 140, 135, 462, 757, 139, 137, 145, 145, 408, + 142, 387, 388, 389, 1144, 967, 731, 732, 733, 140, + 139, 37, 140, 1042, 140, 84, 135, 1148, 532, 142, + 131, 141, 135, 140, 142, 402, 581, 404, 84, 1042, + 142, 138, 140, 142, 1061, 1062, 1063, 408, 1176, 142, + 731, 732, 733, 142, 415, 145, 142, 142, 1179, 142, + 1181, 428, 142, 142, 142, 142, 1196, 135, 140, 13, + 13, 135, 47, 532, 473, 451, 142, 581, 1199, 1207, + 145, 142, 715, 542, 1214, 544, 142, 142, 455, 456, + 142, 142, 793, 142, 5, 145, 135, 812, 1117, 460, + 142, 136, 135, 5, 805, 3, 4, 5, 6, 7, + 8, 9, 473, 937, 1117, 1118, 515, 576, 937, 945, + 1047, 1138, 581, 807, 35, 798, 937, 1167, 937, 1100, + 937, 812, 603, 757, 604, 937, 888, 745, 5, 814, + 937, 517, 518, 884, 1018, 812, 536, 1057, 1161, 608, + 609, 1154, 893, 1170, 506, 869, 505, 1204, 534, 864, + 559, 675, 591, 427, 719, 427, 720, 543, 529, 937, + 3, 4, 5, 6, 7, 8, 9, 962, 893, 982, + 579, 814, 549, 984, -1, 286, 564, 691, 811, 3, + 4, 5, 6, 7, 8, 9, -1, -1, 559, 110, + -1, -1, -1, -1, -1, 566, -1, 118, 712, -1, + 1043, -1, 893, 1043, -1, -1, 49, -1, -1, -1, + 1034, 1044, 937, 1046, 939, 1048, 937, -1, 943, 937, + 945, 1036, 691, 937, 937, 49, -1, 696, -1, -1, + 941, 617, 746, 747, 748, -1, -1, 348, -1, -1, + -1, 352, 85, 712, -1, -1, 937, -1, 939, -1, + 937, 937, 943, -1, 945, 366, -1, -1, -1, 814, + 1175, 670, -1, 1103, -1, 937, -1, 378, 1043, 1184, + 679, 1104, 1112, 937, -1, -1, 1100, 746, 747, 748, + -1, 968, 668, 669, -1, -1, 1101, -1, -1, 1043, + 1043, -1, -1, 1018, 5, 1020, -1, 1018, -1, -1, + 814, -1, 688, 5, -1, -1, 1069, -1, 679, 1034, + -1, -1, 1043, 1034, -1, 1155, 1034, 1042, 1043, -1, + 1034, 1034, 1047, -1, -1, -1, 37, 1018, 1103, 1020, + -1, 1018, -1, -1, 1098, 37, 722, 1112, -1, 450, + -1, 452, -1, 1034, -1, 814, 1057, 1034, 1020, 735, + 736, 1042, 1043, -1, 1018, -1, 1047, 1043, 1112, 873, + -1, -1, 1034, -1, -1, -1, 1051, 1118, -1, -1, + 1034, 1043, 1103, -1, -1, -1, -1, -1, 1103, 1043, + 1155, 1112, -1, -1, 1109, 1149, -1, 1112, 1109, 1153, + -1, 1109, 1117, 1118, -1, 1109, 1109, -1, -1, -1, + -1, 1155, -1, 1154, 873, -1, -1, -1, 1051, -1, + -1, -1, 1103, 1100, -1, 126, 1180, 528, 1109, -1, + -1, 1112, 1109, 1148, 1155, -1, 1117, 1118, -1, 1154, + 1155, 542, -1, 544, 948, -1, 1100, 1109, -1, 1103, + 1112, -1, 363, -1, -1, 1109, -1, -1, 1112, -1, + -1, -1, -1, -1, 1179, -1, 1181, 1148, -1, 1144, + -1, -1, -1, 1154, 1155, 576, -1, -1, 982, -1, + 984, -1, -1, -1, 1199, 884, 1148, -1, -1, 948, + -1, -1, -1, 1155, -1, -1, -1, 1151, 1179, -1, + 1181, 1155, -1, -1, -1, -1, 1051, 608, 609, -1, + -1, 1144, -1, -1, -1, -1, -1, 1179, 1199, 1181, + 1195, 1196, -1, 982, -1, 984, -1, -1, 1203, -1, + 897, -1, 893, -1, -1, -1, -1, 1199, 997, 1214, + -1, -1, -1, -1, -1, -1, 1050, 1051, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 1061, 1062, 1063, + -1, 472, 1195, 1196, -1, -1, 124, 1071, 269, -1, + 1203, -1, -1, -1, 1078, -1, 937, 269, -1, -1, + -1, 1214, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 1050, 1051, -1, -1, 696, -1, -1, -1, 1144, + -1, -1, 1061, 1062, 1063, -1, 307, 308, -1, -1, + -1, -1, 1071, -1, -1, 307, 308, -1, -1, 1078, + -1, 1080, -1, 324, -1, 992, -1, -1, -1, -1, + 1134, -1, 1136, -1, 1138, -1, 737, -1, -1, -1, + 1144, -1, -1, 1042, 1020, -1, -1, -1, -1, -1, + 1195, 1196, -1, 354, -1, 356, -1, 1018, 1203, -1, + -1, -1, 354, -1, 356, -1, 1170, -1, -1, 1214, + -1, -1, -1, 1034, -1, 1134, -1, 1136, -1, 1138, + -1, 1042, 1043, -1, -1, 1144, -1, -1, -1, -1, + -1, 1195, 1196, -1, -1, -1, -1, -1, -1, 1203, + -1, -1, -1, -1, -1, -1, 1165, -1, -1, -1, + 1214, 1170, -1, -1, -1, -1, -1, -1, 1117, -1, + -1, -1, -1, -1, -1, -1, -1, 1186, -1, -1, + -1, -1, 643, -1, -1, -1, 1195, 1196, -1, -1, + -1, -1, 1103, -1, 1203, -1, -1, -1, 1109, -1, + -1, 1112, 453, -1, -1, 1214, 1117, 1118, -1, -1, + -1, 453, 463, -1, 1131, -1, -1, -1, -1, 327, + -1, -1, 1148, 331, 332, -1, 334, 335, 336, 337, + 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, + -1, -1, 350, 1154, 1155, -1, -1, 1164, -1, 25, + 26, 27, -1, 1179, -1, 1181, 32, 33, 34, 35, + 36, 37, 38, 39, 40, -1, 42, -1, -1, -1, + -1, -1, -1, 1199, -1, -1, 527, -1, -1, 530, + -1, -1, -1, -1, -1, 527, -1, -1, 530, -1, + -1, -1, -1, -1, 545, -1, -1, -1, -1, -1, + -1, 762, 12, 545, -1, -1, -1, -1, -1, 770, + -1, -1, -1, 774, 775, -1, -1, 778, 779, 780, + 781, 782, 783, 784, 785, 786, 787, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, 628, -1, - -1, 556, -1, -1, -1, -1, -1, 562, -1, -1, - -1, -1, 524, -1, -1, 527, -1, 683, 684, -1, - -1, 270, -1, -1, -1, -1, -1, -1, -1, -1, - 542, -1, -1, -1, -1, -1, -1, 703, -1, -1, - -1, -1, -1, 3, 4, 5, 6, 7, 8, 9, - -1, -1, 682, -1, -1, -1, -1, -1, -1, 308, - 309, 21, 22, 23, 24, -1, -1, -1, -1, 29, - 30, 31, -1, -1, -1, -1, -1, 37, -1, 745, - 746, -1, -1, 1120, -1, -1, -1, -1, -1, 49, - -1, -1, -1, -1, 724, 607, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 354, -1, 356, -1, -1, - 812, -1, 1149, -1, 1151, -1, -1, -1, -1, -1, - -1, 823, -1, -1, -1, 85, -1, -1, -1, -1, - 1167, -1, -1, -1, -1, -1, 363, -1, -1, 694, - -1, -1, 102, 103, 104, 105, 106, 107, 108, 109, - 110, 111, 112, -1, -1, -1, -1, -1, -1, 671, - -1, -1, -1, -1, -1, 677, -1, -1, -1, -1, - -1, -1, -1, 803, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 815, 146, -1, -1, -1, - -1, -1, -1, -1, -1, 825, -1, -1, -1, -1, - -1, -1, -1, 452, -1, -1, 979, -1, -1, -1, + 591, -1, -1, 451, 54, 55, 997, -1, -1, -1, + -1, 61, 62, 63, 64, 65, 66, 67, 68, 69, + 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 482, 483, 484, -1, -1, 487, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 741, - 742, 743, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 470, -1, -1, -1, -1, -1, -1, - -1, -1, 1025, -1, -1, -1, 886, -1, -1, -1, + -1, -1, 1043, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 656, -1, 515, -1, -1, + -1, 662, -1, 521, 656, 1066, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, 534, -1, 138, 1080, + 140, 141, -1, 143, 144, 543, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 156, -1, -1, -1, + -1, -1, 1103, -1, -1, -1, -1, -1, -1, 920, + -1, 1112, 923, -1, 32, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, -1, -1, -1, -1, -1, + 731, 732, 733, 51, -1, -1, -1, -1, -1, 731, + 732, 733, -1, -1, -1, -1, -1, 958, -1, -1, + 1151, -1, -1, -1, 1155, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 1165, -1, -1, -1, -1, 87, + 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, + 98, 99, 100, 101, -1, 1186, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 1045, -1, -1, 524, -1, -1, 527, -1, - -1, -1, 1055, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 542, 924, -1, -1, 3, 4, 5, - 6, 7, 8, 9, -1, 1078, -1, -1, -1, -1, - 822, -1, 942, -1, 1087, 21, 22, 23, 24, -1, - -1, -1, -1, -1, 1026, -1, 1028, -1, 1030, 884, - -1, -1, -1, -1, -1, -1, 1002, -1, -1, -1, - -1, -1, -1, 49, -1, -1, -1, -1, -1, -1, - 1123, -1, -1, -1, 1127, -1, -1, -1, -1, -1, - -1, -1, -1, 1136, -1, 920, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 1079, -1, 85, - -1, -1, 1155, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 102, 103, 104, 105, - 106, 107, 108, 109, 110, 111, 112, -1, 920, -1, - 922, -1, -1, -1, 926, -1, 928, -1, -1, -1, - -1, -1, 671, -1, -1, -1, -1, -1, -1, 135, - -1, 658, -1, 139, -1, -1, -1, -1, -1, -1, - 146, -1, -1, 1073, -1, 1000, -1, -1, -1, -1, - -1, -1, -1, -1, 1120, -1, -1, -1, -1, -1, - 1090, 1016, -1, -1, -1, -1, -1, -1, -1, 1024, - 1025, -1, 1102, -1, -1, -1, 1106, -1, 1108, -1, - -1, -1, -1, 1149, -1, 1151, -1, -1, -1, -1, - 1002, 1121, 741, 742, 743, 1125, -1, -1, -1, 1129, - -1, 1167, -1, -1, -1, -1, -1, -1, -1, 1139, - -1, -1, -1, -1, -1, -1, -1, 1029, -1, -1, - 1150, -1, -1, 1078, -1, -1, -1, -1, -1, 1084, - -1, -1, 1087, -1, -1, -1, -1, 1092, 1093, -1, - -1, -1, -1, -1, -1, 772, -1, -1, -1, -1, - -1, -1, -1, 780, 12, -1, -1, 784, 785, -1, - -1, 788, 789, 790, 791, 792, 793, 794, 795, 796, - 797, 1126, 1127, 822, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 1018, -1, -1, + -1, 812, 670, -1, -1, -1, -1, -1, -1, -1, + 812, 679, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, 937, -1, 939, -1, + -1, -1, 943, -1, 945, 937, -1, 939, -1, 807, + -1, 943, -1, -1, 135, 136, -1, 138, 139, 140, + 141, -1, 143, 144, 145, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 54, 55, -1, -1, - -1, -1, 829, 61, 62, 63, 64, 65, 66, 67, - 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, - 78, 79, 80, 81, 82, 83, -1, -1, 3, 4, - 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 21, 22, 23, -1, - 25, 26, 27, 28, -1, -1, -1, 32, 33, 34, - 35, 36, 37, 38, 39, 40, -1, 42, 43, 44, - -1, 920, -1, 922, 49, 50, 903, 926, 53, 906, - 138, -1, 140, 141, -1, 143, 144, -1, 146, 147, - 148, 149, 150, 151, 152, 153, 154, 155, 156, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 85, -1, 87, 88, 89, 90, 91, 92, 93, 94, - 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, - 105, 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 1002, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 1020, + -1, -1, -1, -1, -1, -1, -1, -1, 1020, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 146, -1, 1000, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, 1047, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, 32, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, -1, -1, + -1, -1, -1, -1, -1, -1, 51, -1, -1, 135, + 136, 137, 138, 139, 140, 141, -1, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, -1, 78, -1, -1, -1, -1, -1, -1, + -1, -1, 87, 88, 89, 90, 91, 92, 93, 94, + 95, 96, 97, 98, 99, 100, 101, -1, -1, 3, + 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, + -1, -1, -1, -1, -1, 29, 30, 31, -1, -1, + 135, -1, -1, 37, -1, -1, -1, -1, -1, -1, + -1, -1, 147, 148, -1, 49, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 135, 136, -1, 138, - 139, 140, 141, -1, 143, 144, 145, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, + 1148, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 85, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 1179, -1, 1181, -1, -1, -1, -1, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + -1, 1199, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, 146, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 135, 136, -1, 138, 139, 140, + 141, -1, 143, 144, 145, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 135, 136, 137, 138, 139, 140, 141, -1, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, + 136, -1, 138, 139, 140, 141, 142, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 135, 136, -1, 138, - 139, 140, 141, -1, 143, 144, 145, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + -1, -1, -1, -1, 135, 136, 137, 138, 139, 140, + 141, -1, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, + 136, 137, 138, 139, 140, 141, -1, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 135, 136, -1, 138, 139, 140, 141, 142, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 135, 136, 137, 138, 139, 140, + 141, -1, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 135, 136, 137, 138, - 139, 140, 141, -1, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, + 136, 137, 138, 139, 140, 141, -1, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 135, 136, 137, 138, 139, 140, + 141, -1, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 135, 136, 137, 138, 139, 140, 141, -1, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, + 136, -1, 138, 139, 140, 141, -1, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 135, 136, 137, 138, - 139, 140, 141, -1, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + -1, -1, -1, -1, 135, 136, -1, 138, 139, 140, + 141, -1, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 135, 136, 137, 138, 139, 140, 141, -1, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, + 136, -1, 138, 139, 140, 141, 142, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 135, 136, 137, 138, - 139, 140, 141, -1, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + -1, -1, -1, -1, 135, 136, -1, 138, 139, 140, + 141, -1, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, + 136, -1, 138, 139, 140, 141, -1, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 135, 136, -1, 138, 139, 140, 141, -1, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 136, -1, 138, 139, 140, + 141, -1, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, -1, 85, + -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 135, 136, -1, 138, - 139, 140, 141, -1, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, + 136, 137, 138, 139, 140, 141, -1, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 136, -1, 138, 139, 140, + 141, -1, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, + 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 136, -1, 138, 139, 140, 141, 142, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 135, 136, -1, 138, - 139, 140, 141, -1, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + 136, -1, 138, 139, 140, 141, -1, -1, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, -1, 85, -1, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 136, -1, 138, 139, 140, + 141, 142, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, -1, 85, + -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 135, 136, -1, 138, 139, 140, 141, -1, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 136, -1, 138, - 139, 140, 141, -1, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + 136, -1, 138, 139, 140, 141, 142, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, -1, 85, -1, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 136, -1, 138, 139, 140, + 141, 142, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, -1, 85, + -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 135, 136, 137, 138, 139, 140, 141, -1, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 136, -1, 138, - 139, 140, 141, -1, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + 136, -1, 138, 139, 140, 141, -1, 143, 144, 145, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, -1, 85, -1, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 136, -1, 138, 139, 140, + 141, -1, 143, 144, 145, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, -1, 85, + -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 136, -1, 138, 139, 140, 141, -1, -1, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, -1, 85, -1, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 136, -1, 138, - 139, 140, 141, 142, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 136, -1, 138, 139, 140, 141, 142, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, -1, 85, -1, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 136, -1, 138, - 139, 140, 141, 142, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 136, -1, 138, 139, 140, 141, -1, 143, - 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, -1, 85, -1, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 136, -1, 138, - 139, 140, 141, -1, 143, 144, 145, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 136, -1, 138, 139, 140, 141, -1, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, -1, 85, -1, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 136, -1, 138, - 139, 140, 141, -1, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 136, -1, 138, 139, 140, 141, -1, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, -1, 85, -1, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 136, -1, 138, 139, 140, 141, -1, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, -1, 85, -1, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 136, -1, 138, 139, 140, + 141, -1, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, -1, 85, + -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, - 139, -1, 141, -1, 143, 144, -1, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, - -1, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, 45, -1, -1, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - -1, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 136, -1, -1, 139, -1, 141, -1, 143, 144, -1, + 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, 10, + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, -1, -1, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, 45, -1, -1, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, + 61, 62, 63, -1, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, -1, 85, -1, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 136, -1, -1, 139, -1, 141, -1, 143, - 144, -1, 146, 147, 148, -1, 150, 151, 152, 153, - 154, 155, 156, 157, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, - 29, 30, 31, 32, -1, -1, 35, 36, 37, 38, - 39, 40, -1, 42, 43, 44, 45, -1, -1, 48, - 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, - 59, 60, 61, 62, 63, -1, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, - 79, 80, 81, 82, 83, -1, -1, -1, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 136, -1, -1, 139, -1, + 141, -1, 143, 144, -1, 146, 147, 148, -1, 150, + 151, 152, 153, 154, 155, 156, 157, 3, 4, 5, + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, 45, + -1, -1, 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, -1, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, 78, 79, 80, 81, 82, 83, -1, -1, + -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, - 139, -1, 141, -1, -1, 144, -1, 146, 147, 148, - -1, 150, 151, 152, 153, 154, 155, 156, 157, 3, - 4, 5, 6, 7, 8, 9, -1, -1, 12, -1, - -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, - -1, 25, 26, 27, 28, -1, -1, -1, 32, 33, - 34, 35, 36, 37, 38, 39, 40, -1, 42, -1, - -1, -1, -1, -1, -1, 49, 50, -1, -1, -1, - 54, 55, -1, -1, -1, -1, -1, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, - 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, 3, - 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, - -1, -1, -1, -1, 138, -1, 140, 141, -1, 143, - 144, -1, 146, 147, 148, 149, 150, 151, 152, 153, - 154, 155, 156, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 21, 22, 23, 24, 25, 26, 27, 28, -1, - -1, -1, 32, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 42, 43, 44, -1, -1, -1, -1, 49, - 50, 51, -1, 53, -1, -1, -1, -1, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + 136, -1, -1, 139, -1, 141, -1, -1, 144, -1, + 146, 147, 148, -1, 150, 151, 152, 153, 154, 155, + 156, 157, 3, 4, 5, 6, 7, 8, 9, -1, + -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, + 21, 22, 23, -1, 25, 26, 27, 28, -1, -1, + -1, 32, 33, 34, 35, 36, 37, 38, 39, 40, + -1, 42, -1, -1, -1, -1, -1, -1, 49, 50, + -1, -1, -1, 54, 55, -1, -1, -1, -1, -1, + 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, + 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, + 81, 82, 83, -1, 85, -1, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 85, -1, 87, 88, 89, - 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, - 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, - 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, - 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, - 130, 131, 132, 133, 134, 135, 3, 4, 5, 6, - 7, 8, 9, -1, -1, -1, 146, -1, -1, -1, - -1, -1, -1, -1, 21, 22, 23, 24, 25, 26, + 21, 22, 23, -1, -1, -1, -1, 138, -1, 140, + 141, -1, 143, 144, -1, 146, 147, 148, 149, 150, + 151, 152, 153, 154, 155, 156, 3, 4, 5, 6, + 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 21, 22, 23, -1, 25, 26, 27, 28, -1, -1, -1, 32, 33, 34, 35, 36, - 37, 38, 39, 40, -1, 42, 43, 44, -1, -1, - -1, -1, 49, 50, 51, 52, 53, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 37, 38, 39, 40, 41, 42, 43, 44, -1, -1, + -1, -1, 49, 50, 51, -1, 53, -1, -1, -1, + -1, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, - 127, 128, 129, 130, 131, 132, 133, -1, 135, 3, + 127, 128, 129, 130, 131, 132, 133, 134, 135, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, 146, -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, -1, 25, 26, 27, 28, -1, -1, -1, 32, 33, 34, 35, 36, 37, 38, 39, 40, -1, 42, 43, - 44, -1, -1, -1, -1, 49, 50, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, - -1, -1, -1, -1, 3, 4, 5, 6, 7, 8, - 9, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 21, 22, 23, -1, 25, 26, 27, 28, - 51, -1, 146, 32, 33, 34, 35, 36, 37, 38, - 39, 40, -1, 42, 43, -1, -1, -1, -1, -1, - 49, 50, 51, -1, -1, -1, -1, 78, -1, -1, - -1, -1, -1, -1, -1, -1, 87, 88, 89, 90, - 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, - 101, -1, -1, -1, -1, -1, 85, -1, 87, 88, - 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, - 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, 135, -1, -1, -1, -1, 3, - 4, 5, 6, 7, 8, 9, 147, 148, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, - -1, 25, 26, 27, 28, -1, -1, 146, 32, 33, - 34, 35, 36, 37, 38, 39, 40, -1, 42, 43, - -1, -1, -1, -1, -1, 49, 50, -1, -1, -1, + 44, -1, -1, -1, -1, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, 3, - 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, - 3, 4, 5, 6, 7, 8, 9, 21, 22, 23, - -1, -1, -1, -1, -1, 29, 30, 31, 21, 22, - 23, -1, 146, 37, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 49, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 49, 50, -1, 52, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 85, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 85, -1, -1, -1, -1, -1, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, 102, - 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, - 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, - -1, 3, 4, 5, 6, 7, 8, 9, 21, 22, - 23, 24, 146, -1, -1, -1, -1, -1, -1, 21, - 22, 23, -1, 146, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 49, -1, -1, -1, - -1, 43, 44, -1, -1, -1, -1, 49, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 3, 4, 5, 6, 7, - 8, 9, 85, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 21, 22, 23, 24, -1, -1, 102, - 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, - 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, - 112, 49, 3, 4, 5, 6, 7, 8, 9, -1, - -1, -1, -1, -1, -1, -1, 139, -1, -1, -1, - 21, 22, 23, 146, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, 146, -1, -1, 85, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, 49, 50, - -1, -1, -1, -1, 102, 103, 104, 105, 106, 107, - 108, 109, 110, 111, 112, -1, -1, 3, 4, 5, - 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, 85, 21, 22, 23, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, 146, -1, - -1, 102, 103, 104, 105, 106, 107, 108, 109, 110, - 111, 112, -1, 49, 3, 4, 5, 6, 7, 8, - 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 21, 22, 23, -1, -1, -1, 3, 4, - 5, 6, 7, 8, 9, 146, -1, -1, -1, 85, - -1, -1, -1, -1, -1, 44, 21, 22, 23, -1, - 49, -1, -1, -1, -1, -1, 102, 103, 104, 105, - 106, 107, 108, 109, 110, 111, 112, -1, 43, -1, - -1, -1, -1, -1, 49, 3, 4, 5, 6, 7, - 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 21, 22, 23, -1, -1, -1, -1, - 146, -1, -1, 102, 103, 104, 105, 106, 107, 108, - 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, - -1, 49, -1, -1, -1, -1, -1, 102, 103, 104, - 105, 106, 107, 108, 109, 110, 111, 112, -1, 3, - 4, 5, 6, 7, 8, 9, -1, 146, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, - 24, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 146, -1, -1, 102, 103, 104, 105, 106, 107, - 108, 109, 110, 111, 112, 49, 3, 4, 5, 6, - 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, 21, 22, 23, 24, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, 146, -1, - -1, 85, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 49, -1, -1, -1, -1, -1, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, - -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, - 5, 6, 7, 8, 9, -1, -1, -1, 85, -1, - -1, 135, 136, -1, -1, 139, 21, 22, 23, 24, - -1, -1, -1, -1, -1, 102, 103, 104, 105, 106, - 107, 108, 109, 110, 111, 112, 3, 4, 5, 6, - 7, 8, 9, -1, 49, -1, -1, -1, -1, -1, - -1, -1, -1, -1, 21, 22, 23, 24, 135, -1, - -1, -1, 139, -1, -1, -1, -1, -1, -1, -1, + 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, + 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, + 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, + -1, 135, 3, 4, 5, 6, 7, 8, 9, -1, + -1, -1, 146, -1, -1, -1, -1, -1, -1, -1, + 21, 22, 23, -1, 25, 26, 27, 28, -1, -1, + -1, 32, 33, 34, 35, 36, 37, 38, 39, 40, + -1, 42, 43, 44, -1, -1, -1, -1, 49, 50, + -1, -1, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 85, -1, 49, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 102, 103, 104, - 105, 106, 107, 108, 109, 110, 111, 112, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, 85, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, 136, -1, -1, 139, 102, 103, 104, 105, 106, - 107, 108, 109, 110, 111, 112, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, -1, -1, -1, - -1, -1, -1, -1, -1, 51, -1, -1, -1, -1, - -1, -1, 139, -1, -1, -1, -1, -1, 3, 4, - 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, - -1, -1, 78, -1, -1, -1, 21, 22, 23, 24, - -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, -1, 3, 4, 5, - 6, 7, 8, 9, 49, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 21, 22, 23, -1, 25, - 26, 27, 28, -1, -1, -1, 32, 33, 34, 35, - 36, 37, 38, 39, 40, -1, 42, 43, 44, -1, - 85, 147, 148, 49, 50, -1, -1, 53, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 102, 103, 104, - 105, 106, 107, 108, 109, 110, 111, 112, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 85, - -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, - 106, 107, 108, 109, 110, 111, 112, 3, 4, 5, + -1, -1, -1, -1, 85, -1, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, 3, 4, 5, 6, 7, 8, 9, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 21, 22, 23, -1, 25, - 26, 27, 28, 51, -1, -1, 32, 33, 34, 35, - 36, 37, 38, 39, 40, -1, 42, 43, -1, -1, - -1, -1, -1, 49, 50, 51, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 87, + 26, 27, 28, 51, -1, 146, 32, 33, 34, 35, + 36, 37, 38, 39, 40, -1, 42, 43, 44, -1, + -1, -1, -1, 49, 50, -1, -1, -1, -1, -1, + 78, -1, -1, -1, -1, -1, -1, -1, -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, -1, -1, -1, -1, -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, - 106, 107, 108, 109, 110, 111, 112, 3, 4, 5, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, + -1, -1, 3, 4, 5, 6, 7, 8, 9, 147, + 148, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 21, 22, 23, -1, 25, 26, 27, 28, -1, -1, + 146, 32, 33, 34, 35, 36, 37, 38, 39, 40, + -1, 42, 43, -1, -1, -1, -1, -1, 49, 50, + 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 85, -1, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, + 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, -1, -1, -1, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, -1, 25, - 26, 27, 28, -1, -1, -1, 32, 33, 34, 35, + 26, 27, 28, -1, -1, 146, 32, 33, 34, 35, 36, 37, 38, 39, 40, -1, 42, 43, -1, -1, -1, -1, -1, 49, 50, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, @@ -4434,58 +4321,160 @@ static const short int yycheck[] = 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 21, 22, 23, -1, 25, - 26, 27, 28, -1, -1, -1, 32, 33, 34, 35, - 36, 37, 38, 39, 40, -1, 42, -1, -1, -1, - -1, -1, -1, 49, 50, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 21, 22, 23, 3, 4, + 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, + 146, -1, -1, -1, -1, -1, 21, 22, 23, -1, + -1, -1, -1, 49, 50, -1, 52, 3, 4, 5, + 6, 7, 8, 9, -1, -1, -1, -1, 43, 44, + -1, -1, -1, -1, 49, 21, 22, 23, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 85, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 49, -1, -1, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 102, 103, 104, + 105, 106, 107, 108, 109, 110, 111, 112, -1, 85, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 146, -1, -1, -1, -1, -1, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, + -1, 146, 3, 4, 5, 6, 7, 8, 9, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, + 21, 22, 23, 139, -1, -1, -1, -1, -1, -1, + 146, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, 49, 3, + 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 85, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 49, 50, -1, -1, -1, + -1, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, -1, -1, 3, 4, 5, 6, 7, 8, + 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 85, 21, 22, 23, -1, -1, -1, 139, -1, + -1, -1, -1, -1, -1, 146, -1, -1, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + 49, 3, 4, 5, 6, 7, 8, 9, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 21, + 22, 23, -1, -1, -1, 3, 4, 5, 6, 7, + 8, 9, 146, -1, -1, -1, 85, -1, -1, -1, + -1, -1, 44, 21, 22, 23, -1, 49, -1, -1, + -1, -1, -1, 102, 103, 104, 105, 106, 107, 108, + 109, 110, 111, 112, -1, 43, -1, -1, -1, -1, + -1, 49, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 21, 22, 23, -1, -1, -1, -1, 146, -1, -1, + 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, + 112, -1, -1, -1, -1, -1, -1, -1, 49, -1, + -1, -1, -1, -1, 102, 103, 104, 105, 106, 107, + 108, 109, 110, 111, 112, -1, 3, 4, 5, 6, + 7, 8, 9, -1, 146, -1, -1, 3, 4, 5, + 6, 7, 8, 9, 21, 22, 23, -1, -1, -1, + -1, -1, -1, -1, -1, 21, 22, 23, 146, -1, + -1, 102, 103, 104, 105, 106, 107, 108, 109, 110, + 111, 112, 49, -1, -1, 3, 4, 5, 6, 7, + 8, 9, -1, 49, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 21, 22, 23, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 146, -1, -1, 85, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 85, - -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, + -1, 49, -1, -1, -1, 102, 103, 104, 105, 106, + 107, 108, 109, 110, 111, 112, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 3, 4, 5, - 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 21, 22, 23, -1, 25, - -1, 27, 28, -1, -1, -1, 32, 33, 34, 35, - 36, 37, 38, 39, 40, -1, 42, -1, -1, -1, + 6, 7, 8, 9, -1, -1, -1, 85, 135, 136, + -1, -1, 139, -1, -1, 21, 22, 23, -1, 135, + -1, -1, -1, 139, 102, 103, 104, 105, 106, 107, + 108, 109, 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, -1, 49, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, + -1, 139, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 85, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, + 4, 5, 6, 7, 8, 9, 102, 103, 104, 105, + 106, 107, 108, 109, 110, 111, 112, 21, 22, 23, + -1, 25, 26, 27, 28, -1, -1, -1, 32, 33, + 34, 35, 36, 37, 38, 39, 40, -1, 42, 43, + 44, -1, -1, 139, -1, 49, 50, -1, -1, 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 85, - -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, - 106, 107, 108, 109, 110, 111, 112, 3, 4, 5, - 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 21, 22, 23, -1, 3, - 4, 5, 6, 7, 8, 9, 32, 33, 34, 35, - 36, 37, 38, 39, 40, -1, 42, 21, 22, 23, - -1, -1, -1, 49, 50, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - 44, -1, -1, -1, -1, 49, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 85, - -1, 87, 88, 89, 90, 91, 92, 93, 94, 95, - 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, - 106, 107, 108, 109, 110, 111, 112, -1, -1, -1, - -1, 3, 4, 5, 6, 7, 8, 9, 102, 103, - 104, 105, 106, 107, 108, 109, 110, 111, 112, 21, - 22, 23, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, 112, 3, + 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, + -1, 25, 26, 27, 28, -1, -1, -1, 32, 33, + 34, 35, 36, 37, 38, 39, 40, -1, 42, 43, + -1, -1, -1, -1, -1, 49, 50, 51, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, 112, 3, + 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, + -1, 25, 26, 27, 28, -1, -1, -1, 32, 33, + 34, 35, 36, 37, 38, 39, 40, -1, 42, 43, + -1, -1, -1, -1, -1, 49, 50, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, 112, 3, + 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, + -1, 25, 26, 27, 28, -1, -1, -1, 32, 33, + 34, 35, 36, 37, 38, 39, 40, -1, 42, -1, + -1, -1, -1, -1, -1, 49, 50, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 49, -1, -1, + -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, 112, 3, + 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, + -1, 25, -1, 27, 28, -1, -1, -1, 32, 33, + 34, 35, 36, 37, 38, 39, 40, -1, 42, -1, + -1, -1, -1, -1, -1, 49, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, 112, 3, + 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 21, 22, 23, + -1, 3, 4, 5, 6, 7, 8, 9, 32, 33, + 34, 35, 36, 37, 38, 39, 40, -1, 42, 21, + 22, 23, -1, -1, -1, 49, 50, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 44, -1, -1, -1, -1, 49, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 85, -1, 87, 88, 89, 90, 91, 92, 93, + 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, 112, -1, + -1, -1, -1, 3, 4, 5, 6, 7, 8, 9, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, - 112 + 112, 21, 22, 23, 3, 4, 5, 6, 7, 8, + 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 21, 22, 23, -1, -1, -1, -1, 49, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 49, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 85, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 102, 103, 104, 105, 106, 107, 108, 109, + 110, 111, 112, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 102, 103, 104, 105, 106, 107, 108, + 109, 110, 111, 112 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const unsigned short int yystos[] = { - 0, 159, 160, 0, 161, 367, 3, 4, 5, 6, - 7, 8, 9, 21, 22, 23, 24, 25, 26, 27, + 0, 159, 160, 0, 161, 370, 371, 3, 4, 5, + 6, 7, 8, 9, 21, 22, 23, 25, 26, 27, 28, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 49, 50, 51, 52, 53, 85, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, @@ -4495,114 +4484,117 @@ static const unsigned short int yystos[] = 128, 129, 130, 131, 132, 133, 135, 146, 162, 163, 164, 165, 166, 168, 169, 170, 171, 172, 174, 177, 192, 193, 194, 196, 197, 207, 208, 217, 219, 220, - 222, 239, 240, 241, 242, 245, 246, 249, 255, 289, - 319, 320, 321, 322, 324, 325, 326, 327, 329, 331, - 332, 335, 336, 337, 338, 339, 341, 342, 345, 346, - 357, 358, 359, 368, 371, 369, 25, 26, 12, 44, - 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, - 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, - 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, - 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, - 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, - 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, - 78, 79, 80, 81, 82, 83, 84, 85, 86, 102, + 222, 239, 240, 241, 242, 245, 246, 249, 255, 292, + 322, 323, 324, 325, 327, 328, 329, 330, 332, 334, + 335, 338, 339, 340, 341, 342, 344, 345, 348, 349, + 360, 361, 362, 390, 382, 25, 26, 12, 44, 3, + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, 32, 35, + 36, 37, 38, 39, 40, 42, 43, 44, 45, 48, + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, + 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, + 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, + 79, 80, 81, 82, 83, 84, 85, 86, 102, 103, + 104, 105, 106, 107, 108, 109, 110, 111, 112, 136, + 138, 139, 140, 141, 143, 144, 146, 147, 148, 149, + 150, 151, 152, 153, 154, 155, 156, 157, 361, 362, + 415, 416, 417, 447, 448, 449, 450, 451, 333, 350, + 3, 4, 5, 6, 7, 8, 9, 42, 172, 177, + 194, 197, 324, 325, 330, 332, 338, 344, 3, 4, + 5, 6, 7, 8, 9, 136, 335, 3, 4, 5, + 6, 7, 8, 9, 21, 22, 23, 50, 52, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, - 136, 138, 139, 140, 141, 143, 144, 146, 147, 148, - 149, 150, 151, 152, 153, 154, 155, 156, 157, 358, - 359, 396, 397, 398, 428, 429, 430, 431, 432, 330, - 347, 3, 4, 5, 6, 7, 8, 9, 42, 172, - 177, 194, 197, 321, 322, 327, 329, 335, 341, 3, - 4, 5, 6, 7, 8, 9, 136, 332, 3, 4, - 5, 6, 7, 8, 9, 21, 22, 23, 50, 52, - 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, - 112, 218, 319, 321, 322, 326, 327, 329, 141, 141, + 218, 322, 324, 325, 329, 330, 332, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, - 141, 141, 141, 141, 141, 141, 141, 141, 141, 333, - 173, 367, 333, 136, 367, 44, 53, 163, 170, 171, - 197, 203, 220, 222, 239, 289, 335, 341, 46, 135, - 136, 265, 266, 265, 265, 265, 141, 177, 335, 341, - 135, 367, 44, 246, 270, 273, 320, 325, 327, 329, - 179, 327, 329, 331, 332, 326, 320, 321, 326, 367, - 326, 143, 172, 177, 194, 197, 208, 246, 322, 336, - 345, 367, 10, 11, 84, 233, 290, 298, 300, 78, - 147, 148, 295, 360, 361, 362, 363, 366, 343, 367, - 367, 404, 136, 428, 424, 424, 64, 149, 223, 414, - 424, 425, 424, 10, 11, 141, 418, 319, 12, 333, - 367, 333, 367, 320, 172, 194, 212, 213, 216, 233, - 298, 424, 138, 167, 319, 319, 135, 367, 249, 254, - 255, 322, 3, 4, 5, 6, 7, 8, 9, 331, - 373, 376, 377, 331, 331, 381, 331, 331, 331, 331, - 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, - 41, 51, 291, 294, 295, 334, 336, 359, 136, 135, - 139, 178, 179, 322, 326, 327, 329, 291, 195, 135, - 139, 198, 319, 319, 367, 335, 233, 139, 275, 424, - 247, 367, 323, 271, 141, 326, 326, 326, 328, 333, - 367, 333, 367, 246, 270, 367, 344, 301, 250, 252, - 254, 255, 256, 268, 309, 320, 322, 292, 138, 285, - 286, 288, 233, 298, 307, 360, 367, 367, 367, 361, - 363, 333, 24, 64, 85, 136, 138, 139, 140, 143, - 144, 149, 157, 358, 359, 370, 396, 397, 398, 402, - 403, 405, 406, 415, 418, 422, 160, 425, 135, 143, - 145, 426, 427, 428, 137, 224, 226, 227, 229, 231, - 145, 135, 427, 142, 420, 421, 419, 367, 209, 211, - 295, 178, 209, 319, 333, 333, 210, 309, 320, 327, - 329, 137, 321, 327, 136, 135, 138, 12, 54, 55, - 64, 138, 140, 141, 143, 144, 149, 395, 396, 249, - 254, 140, 331, 331, 331, 140, 140, 331, 140, 140, - 140, 140, 140, 140, 140, 140, 140, 140, 140, 142, - 142, 140, 135, 292, 290, 367, 181, 176, 3, 135, - 180, 367, 179, 327, 329, 322, 135, 200, 201, 331, - 199, 198, 367, 319, 322, 276, 277, 319, 136, 137, - 278, 279, 178, 327, 275, 274, 408, 291, 178, 291, - 319, 333, 339, 340, 365, 251, 367, 257, 311, 312, - 313, 367, 250, 256, 320, 135, 140, 287, 422, 142, - 298, 364, 417, 423, 416, 145, 137, 135, 145, 140, - 414, 25, 27, 197, 321, 327, 329, 335, 352, 353, - 356, 357, 26, 50, 234, 222, 404, 404, 404, 135, - 210, 216, 135, 198, 209, 209, 135, 140, 141, 367, + 141, 141, 141, 141, 141, 141, 141, 141, 336, 173, + 380, 381, 336, 136, 380, 44, 53, 163, 170, 171, + 197, 203, 220, 222, 239, 292, 338, 344, 46, 135, + 136, 265, 266, 265, 265, 265, 141, 177, 338, 344, + 135, 370, 44, 246, 270, 273, 323, 328, 330, 332, + 179, 330, 332, 334, 335, 329, 323, 324, 329, 370, + 329, 143, 172, 177, 194, 197, 208, 246, 325, 339, + 348, 370, 10, 11, 84, 233, 293, 301, 303, 78, + 147, 148, 298, 363, 364, 365, 366, 369, 346, 370, + 370, 24, 383, 136, 447, 443, 443, 64, 149, 223, + 433, 443, 444, 443, 10, 11, 141, 437, 322, 12, + 336, 380, 336, 380, 323, 172, 194, 212, 213, 216, + 233, 301, 443, 138, 167, 322, 322, 135, 372, 373, + 249, 254, 255, 325, 3, 4, 5, 6, 7, 8, + 9, 334, 392, 395, 396, 334, 334, 400, 334, 334, + 334, 334, 334, 334, 334, 334, 334, 334, 334, 334, + 334, 334, 41, 51, 294, 297, 298, 337, 339, 362, + 136, 135, 139, 178, 179, 325, 329, 330, 332, 382, + 294, 195, 135, 139, 198, 322, 322, 380, 338, 233, + 139, 275, 443, 247, 380, 326, 271, 141, 329, 329, + 329, 331, 336, 380, 336, 380, 246, 270, 370, 347, + 304, 250, 252, 254, 255, 256, 268, 312, 323, 325, + 295, 138, 285, 286, 288, 289, 233, 301, 310, 363, + 374, 375, 374, 374, 364, 366, 336, 384, 385, 386, + 160, 444, 135, 143, 145, 445, 446, 447, 137, 224, + 226, 227, 229, 231, 145, 135, 446, 142, 439, 440, + 438, 370, 209, 211, 298, 178, 209, 322, 336, 336, + 210, 312, 323, 330, 332, 137, 324, 330, 136, 135, + 138, 382, 12, 54, 55, 64, 138, 140, 141, 143, + 144, 149, 414, 415, 249, 254, 140, 334, 334, 334, + 140, 140, 334, 140, 140, 140, 140, 140, 140, 140, + 140, 140, 140, 140, 142, 142, 140, 135, 295, 293, + 370, 181, 176, 3, 135, 180, 370, 179, 330, 332, + 325, 135, 200, 201, 334, 199, 198, 370, 322, 325, + 276, 277, 322, 136, 137, 278, 279, 178, 330, 275, + 274, 427, 294, 178, 294, 322, 336, 342, 343, 368, + 251, 372, 257, 314, 315, 316, 372, 250, 256, 323, + 135, 140, 287, 136, 441, 141, 142, 301, 382, 367, + 140, 145, 328, 335, 388, 389, 137, 135, 145, 140, + 433, 25, 27, 197, 324, 330, 332, 338, 355, 356, + 359, 360, 26, 50, 234, 222, 423, 423, 423, 135, + 210, 216, 135, 198, 209, 209, 135, 140, 141, 372, 135, 160, 221, 3, 144, 144, 64, 149, 142, 145, - 372, 140, 142, 142, 378, 380, 140, 341, 384, 386, - 388, 390, 385, 387, 389, 391, 392, 393, 319, 29, + 391, 140, 142, 142, 397, 399, 140, 344, 403, 405, + 407, 409, 404, 406, 408, 410, 411, 412, 322, 29, 30, 31, 137, 182, 183, 29, 30, 31, 37, 187, - 188, 191, 319, 139, 367, 179, 137, 140, 138, 342, - 135, 331, 140, 431, 424, 142, 84, 280, 282, 283, - 326, 272, 278, 138, 140, 143, 402, 410, 411, 412, - 414, 135, 135, 135, 198, 339, 257, 141, 3, 32, - 45, 48, 67, 138, 258, 260, 261, 262, 263, 144, - 314, 315, 139, 141, 367, 293, 64, 143, 149, 399, - 400, 402, 412, 299, 365, 404, 409, 404, 145, 225, - 319, 319, 319, 345, 233, 296, 300, 295, 354, 296, - 234, 142, 142, 142, 135, 135, 211, 214, 137, 341, - 145, 145, 341, 374, 341, 341, 382, 142, 341, 341, - 341, 341, 341, 341, 341, 341, 341, 341, 140, 394, - 367, 139, 190, 191, 140, 37, 189, 233, 175, 367, - 201, 202, 138, 204, 429, 277, 233, 137, 367, 140, - 341, 257, 142, 413, 135, 262, 253, 259, 264, 19, - 55, 56, 418, 316, 315, 13, 14, 15, 16, 310, - 269, 294, 401, 400, 141, 302, 312, 145, 135, 137, - 406, 407, 145, 226, 355, 308, 309, 228, 367, 333, - 230, 296, 278, 296, 142, 341, 379, 142, 341, 142, - 142, 142, 142, 142, 142, 142, 142, 140, 140, 142, - 41, 42, 53, 134, 135, 164, 169, 171, 184, 185, - 186, 192, 193, 207, 217, 220, 222, 243, 244, 245, - 270, 289, 319, 320, 322, 335, 341, 371, 319, 367, - 319, 187, 399, 425, 135, 267, 248, 84, 281, 296, - 262, 367, 408, 278, 418, 335, 346, 348, 349, 317, - 318, 278, 403, 303, 145, 333, 302, 138, 235, 236, - 296, 306, 360, 235, 232, 142, 135, 375, 140, 383, - 13, 13, 169, 177, 205, 222, 244, 320, 335, 341, - 431, 171, 185, 220, 222, 243, 289, 335, 265, 135, - 254, 270, 322, 233, 233, 188, 233, 47, 257, 282, - 284, 414, 142, 346, 350, 295, 145, 399, 142, 278, - 237, 142, 296, 235, 215, 142, 425, 142, 142, 142, - 367, 177, 205, 335, 265, 177, 233, 335, 367, 254, - 256, 431, 262, 285, 367, 351, 333, 367, 367, 142, - 238, 410, 297, 305, 142, 136, 139, 178, 206, 367, - 177, 367, 135, 367, 136, 333, 367, 410, 302, 32, - 34, 45, 48, 424, 425, 180, 178, 367, 178, 206, - 135, 424, 304, 431, 431, 137, 135, 206, 178, 180, - 137, 305, 425, 206, 135 + 188, 191, 322, 139, 370, 179, 137, 140, 138, 345, + 135, 334, 140, 450, 443, 142, 84, 280, 282, 370, + 329, 272, 278, 24, 85, 138, 139, 140, 143, 144, + 157, 361, 362, 415, 416, 417, 421, 422, 429, 430, + 431, 433, 434, 437, 441, 135, 135, 135, 198, 342, + 257, 141, 3, 32, 45, 48, 67, 138, 258, 260, + 261, 262, 263, 144, 317, 318, 139, 141, 372, 296, + 64, 143, 149, 418, 419, 421, 431, 442, 290, 417, + 302, 368, 385, 145, 329, 84, 387, 437, 225, 322, + 322, 322, 348, 233, 299, 303, 298, 357, 299, 234, + 64, 138, 140, 142, 143, 149, 421, 424, 425, 142, + 142, 135, 135, 211, 214, 137, 344, 145, 145, 344, + 393, 344, 344, 401, 142, 344, 344, 344, 344, 344, + 344, 344, 344, 344, 344, 140, 413, 370, 139, 190, + 191, 140, 37, 189, 233, 175, 370, 201, 202, 138, + 204, 448, 277, 233, 137, 376, 377, 140, 283, 257, + 142, 436, 432, 435, 135, 262, 253, 259, 264, 19, + 55, 56, 437, 319, 318, 13, 14, 15, 16, 313, + 269, 297, 420, 419, 428, 140, 142, 141, 305, 315, + 328, 226, 358, 311, 312, 228, 374, 336, 230, 299, + 278, 299, 142, 344, 398, 142, 344, 142, 142, 142, + 142, 142, 142, 142, 142, 140, 140, 142, 41, 42, + 53, 134, 135, 164, 169, 171, 184, 185, 186, 192, + 193, 207, 217, 220, 222, 243, 244, 245, 270, 292, + 322, 323, 325, 338, 344, 390, 322, 370, 322, 187, + 418, 444, 135, 267, 248, 382, 84, 281, 344, 262, + 376, 423, 427, 423, 278, 437, 338, 349, 351, 352, + 320, 321, 278, 422, 135, 137, 425, 426, 291, 306, + 336, 305, 138, 235, 236, 299, 309, 363, 235, 232, + 142, 135, 394, 140, 402, 13, 13, 169, 177, 205, + 222, 244, 323, 338, 344, 450, 171, 185, 220, 222, + 243, 292, 338, 265, 135, 254, 270, 325, 233, 233, + 188, 233, 47, 257, 282, 299, 145, 433, 145, 142, + 349, 353, 298, 145, 418, 142, 418, 278, 237, 142, + 299, 235, 215, 142, 444, 142, 142, 142, 380, 177, + 205, 338, 265, 177, 233, 338, 372, 254, 256, 450, + 262, 284, 145, 376, 354, 336, 378, 379, 376, 142, + 238, 429, 300, 308, 142, 136, 139, 178, 206, 380, + 177, 380, 135, 372, 136, 285, 336, 382, 376, 429, + 305, 32, 34, 45, 48, 443, 444, 180, 178, 380, + 178, 206, 135, 443, 307, 450, 450, 137, 135, 206, + 178, 180, 137, 308, 444, 206, 135 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ @@ -4635,50 +4627,53 @@ static const unsigned short int yyr1[] = 266, 267, 267, 269, 268, 271, 272, 270, 274, 273, 275, 275, 276, 276, 277, 278, 279, 278, 280, 281, 280, 280, 280, 283, 284, 282, 285, 285, 287, 286, - 288, 286, 289, 290, 291, 291, 292, 293, 292, 294, - 295, 295, 296, 297, 296, 298, 299, 298, 301, 300, - 300, 302, 303, 304, 302, 302, 305, 305, 305, 305, - 305, 305, 306, 306, 307, 307, 308, 308, 309, 309, - 310, 310, 310, 310, 311, 311, 313, 312, 314, 314, - 316, 315, 317, 318, 317, 319, 319, 320, 320, 320, - 320, 320, 321, 321, 321, 322, 322, 322, 322, 322, - 322, 323, 322, 324, 325, 326, 328, 327, 330, 329, - 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, - 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, - 331, 332, 332, 332, 332, 332, 332, 332, 333, 333, - 334, 334, 334, 334, 335, 335, 336, 336, 336, 336, - 337, 337, 337, 337, 337, 338, 338, 338, 339, 339, - 340, 340, 341, 343, 342, 344, 342, 345, 345, 345, - 346, 346, 347, 346, 346, 346, 348, 350, 349, 351, - 349, 352, 354, 353, 355, 353, 356, 356, 356, 356, - 356, 356, 356, 357, 357, 358, 358, 358, 358, 358, - 358, 358, 358, 358, 358, 358, 358, 358, 358, 358, - 358, 358, 358, 358, 358, 358, 359, 359, 359, 359, - 359, 359, 359, 359, 359, 359, 359, 359, 359, 359, - 359, 360, 360, 360, 360, 361, 362, 364, 363, 365, - 365, 366, 366, 367, 367, 369, 370, 368, 372, 371, - 373, 374, 375, 371, 376, 371, 377, 371, 378, 379, - 371, 380, 371, 381, 382, 383, 371, 371, 384, 371, - 385, 371, 386, 371, 387, 371, 388, 371, 389, 371, - 390, 371, 391, 371, 392, 371, 393, 371, 371, 371, - 371, 394, 394, 395, 395, 395, 395, 395, 395, 395, - 395, 395, 395, 395, 395, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 396, - 396, 396, 396, 396, 396, 396, 396, 396, 396, 397, - 397, 397, 397, 397, 397, 397, 397, 397, 397, 397, - 397, 397, 397, 397, 397, 397, 397, 397, 397, 397, - 397, 397, 397, 397, 397, 397, 397, 397, 398, 398, - 398, 398, 398, 398, 398, 398, 398, 399, 399, 400, - 400, 400, 401, 400, 400, 402, 402, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 404, 404, 405, - 405, 405, 405, 406, 406, 406, 407, 407, 408, 408, - 409, 409, 410, 410, 411, 411, 411, 413, 412, 414, - 414, 416, 415, 417, 415, 419, 418, 420, 418, 421, - 418, 423, 422, 424, 424, 425, 425, 426, 426, 427, - 427, 428, 428, 428, 428, 428, 428, 428, 428, 428, - 428, 428, 428, 428, 428, 428, 428, 428, 429, 430, - 430, 431, 432, 432, 432 + 288, 286, 289, 286, 290, 291, 290, 292, 293, 294, + 294, 295, 296, 295, 297, 298, 298, 299, 300, 299, + 301, 302, 301, 304, 303, 303, 305, 306, 307, 305, + 305, 308, 308, 308, 308, 308, 308, 309, 309, 310, + 310, 311, 311, 312, 312, 313, 313, 313, 313, 314, + 314, 316, 315, 317, 317, 319, 318, 320, 321, 320, + 322, 322, 323, 323, 323, 323, 323, 324, 324, 324, + 325, 325, 325, 325, 325, 325, 326, 325, 327, 328, + 329, 331, 330, 333, 332, 334, 334, 334, 334, 334, + 334, 334, 334, 334, 334, 334, 334, 334, 334, 334, + 334, 334, 334, 334, 334, 334, 335, 335, 335, 335, + 335, 335, 335, 336, 336, 337, 337, 337, 337, 338, + 338, 339, 339, 339, 339, 340, 340, 340, 340, 340, + 341, 341, 341, 342, 342, 343, 343, 344, 346, 345, + 347, 345, 348, 348, 348, 349, 349, 350, 349, 349, + 349, 351, 353, 352, 354, 352, 355, 357, 356, 358, + 356, 359, 359, 359, 359, 359, 359, 359, 360, 360, + 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, + 361, 361, 361, 361, 361, 361, 361, 361, 361, 361, + 361, 362, 362, 362, 362, 362, 362, 362, 362, 362, + 362, 362, 362, 362, 362, 362, 363, 363, 363, 363, + 364, 365, 367, 366, 368, 368, 369, 369, 371, 370, + 373, 372, 375, 374, 377, 376, 379, 378, 381, 380, + 382, 382, 383, 384, 384, 384, 384, 386, 385, 387, + 387, 388, 388, 389, 389, 391, 390, 392, 393, 394, + 390, 395, 390, 396, 390, 397, 398, 390, 399, 390, + 400, 401, 402, 390, 390, 403, 390, 404, 390, 405, + 390, 406, 390, 407, 390, 408, 390, 409, 390, 410, + 390, 411, 390, 412, 390, 390, 390, 390, 413, 413, + 414, 414, 414, 414, 414, 414, 414, 414, 414, 414, + 414, 414, 415, 415, 415, 415, 415, 415, 415, 415, + 415, 415, 415, 415, 415, 415, 415, 415, 415, 415, + 415, 415, 415, 415, 415, 415, 415, 415, 415, 415, + 415, 415, 415, 415, 415, 415, 416, 416, 416, 416, + 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, + 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, + 416, 416, 416, 416, 416, 417, 417, 417, 417, 417, + 417, 417, 417, 417, 418, 418, 419, 419, 419, 420, + 419, 419, 421, 421, 422, 422, 422, 422, 422, 422, + 422, 422, 422, 422, 423, 423, 424, 424, 424, 424, + 425, 425, 425, 426, 426, 427, 427, 428, 428, 429, + 429, 430, 430, 430, 432, 431, 433, 433, 435, 434, + 436, 434, 438, 437, 439, 437, 440, 437, 442, 441, + 443, 443, 444, 444, 445, 445, 446, 446, 447, 447, + 447, 447, 447, 447, 447, 447, 447, 447, 447, 447, + 447, 447, 447, 447, 447, 448, 449, 449, 450, 451, + 451, 451 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ @@ -4710,51 +4705,54 @@ static const unsigned char yyr2[] = 1, 2, 2, 0, 1, 0, 3, 3, 1, 1, 6, 0, 6, 0, 7, 0, 0, 6, 0, 6, 0, 2, 1, 3, 3, 0, 0, 2, 1, 0, - 4, 3, 1, 0, 0, 5, 0, 1, 0, 3, - 0, 2, 4, 2, 0, 2, 0, 0, 4, 2, - 0, 1, 3, 0, 6, 3, 0, 5, 0, 3, - 1, 0, 0, 0, 7, 1, 0, 2, 2, 3, - 3, 2, 1, 2, 1, 2, 0, 1, 2, 4, - 1, 1, 1, 1, 0, 1, 0, 2, 1, 2, - 0, 5, 0, 0, 2, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, - 3, 0, 5, 1, 1, 1, 0, 5, 0, 3, + 4, 3, 1, 0, 0, 6, 0, 1, 0, 3, + 0, 2, 0, 4, 1, 0, 4, 4, 2, 0, + 2, 0, 0, 4, 2, 0, 1, 3, 0, 6, + 3, 0, 5, 0, 3, 1, 0, 0, 0, 7, + 1, 0, 2, 2, 3, 3, 2, 1, 2, 1, + 2, 0, 1, 2, 4, 1, 1, 1, 1, 0, + 1, 0, 2, 1, 2, 0, 5, 0, 0, 2, + 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, + 2, 2, 2, 3, 3, 3, 0, 5, 1, 1, + 1, 0, 5, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 0, 3, - 1, 1, 1, 1, 2, 3, 1, 1, 1, 1, - 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, - 1, 2, 2, 0, 3, 0, 4, 1, 3, 4, - 1, 1, 0, 4, 2, 2, 2, 0, 3, 0, - 4, 2, 0, 3, 0, 4, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, + 1, 1, 1, 0, 3, 1, 1, 1, 1, 2, + 3, 1, 1, 1, 1, 1, 1, 2, 1, 1, + 1, 1, 1, 1, 1, 1, 2, 2, 0, 3, + 0, 4, 1, 3, 4, 1, 1, 0, 4, 2, + 2, 2, 0, 3, 0, 4, 2, 0, 3, 0, + 4, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 2, 2, 2, 0, 4, 0, - 1, 1, 2, 0, 2, 0, 0, 6, 0, 7, - 0, 0, 0, 9, 0, 5, 0, 5, 0, 0, - 10, 0, 7, 0, 0, 0, 9, 6, 0, 7, - 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, - 0, 7, 0, 7, 0, 9, 0, 9, 4, 4, - 7, 0, 1, 2, 2, 3, 3, 1, 1, 1, - 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, + 2, 2, 0, 4, 0, 1, 1, 2, 0, 2, + 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, + 0, 2, 4, 0, 1, 2, 3, 0, 3, 0, + 1, 1, 2, 1, 3, 0, 7, 0, 0, 0, + 9, 0, 5, 0, 5, 0, 0, 10, 0, 7, + 0, 0, 0, 9, 6, 0, 7, 0, 7, 0, + 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, + 7, 0, 9, 0, 9, 4, 4, 7, 0, 1, + 2, 2, 3, 3, 1, 1, 1, 1, 2, 2, + 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, - 1, 1, 0, 3, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 0, 2, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 0, 2, - 0, 2, 1, 1, 1, 1, 1, 0, 4, 1, - 1, 0, 4, 0, 5, 0, 4, 0, 4, 0, - 4, 0, 4, 0, 2, 0, 2, 1, 1, 1, + 1, 1, 1, 1, 1, 2, 1, 1, 1, 0, + 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 0, 2, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 0, 2, 0, 2, 1, + 1, 1, 1, 1, 0, 4, 1, 1, 0, 4, + 0, 5, 0, 4, 0, 4, 0, 4, 0, 4, + 0, 2, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, - 4, 3, 1, 1, 1 + 1, 1, 1, 1, 1, 3, 3, 4, 3, 1, + 1, 1 }; @@ -4831,7 +4829,10 @@ static const unsigned char yydprec[] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0 }; /* YYMERGER[RULE-NUM] -- Index of merging function for rule #RULE-NUM. */ @@ -4907,7 +4908,10 @@ static const unsigned char yymerger[] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0 }; /* YYIMMEDIATE[RULE-NUM] -- True iff rule #RULE-NUM is not to be deferred, as @@ -4984,54 +4988,30 @@ static const yybool yyimmediate[] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0 }; /* YYCONFLP[YYPACT[STATE-NUM]] -- Pointer into YYCONFL of start of list of conflicting reductions corresponding to action entry for state STATE-NUM in yytable. 0 means no conflicts. The list in yyconfl is terminated by a rule number of 0. */ -static const unsigned char yyconflp[] = +static const unsigned short int yyconflp[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, - 3, 0, 0, 0, 0, 0, 5, 0, 0, 0, - 0, 0, 249, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 251, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, + 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, + 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 257, 0, 261, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -5046,8 +5026,10 @@ static const unsigned char yyconflp[] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 259, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -5060,9 +5042,11 @@ static const unsigned char yyconflp[] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 251, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 253, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -5071,6 +5055,7 @@ static const unsigned char yyconflp[] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -5591,7 +5576,22 @@ static const unsigned char yyconflp[] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 9, 11, 13, 15, 17, 19, 21, 23, + 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, + 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, + 65, 67, 0, 0, 69, 71, 73, 75, 77, 79, + 0, 81, 83, 85, 87, 0, 0, 89, 91, 93, + 95, 97, 99, 101, 103, 105, 107, 109, 111, 113, + 115, 117, 119, 121, 123, 125, 127, 129, 131, 133, + 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, + 155, 157, 159, 0, 161, 0, 163, 165, 167, 169, + 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, + 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, + 211, 213, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 215, 0, 0, 217, 219, + 221, 0, 223, 225, 0, 227, 229, 231, 233, 235, + 237, 239, 241, 243, 245, 247, 249, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -5611,23 +5611,8 @@ static const unsigned char yyconflp[] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, - 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, - 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, - 49, 51, 53, 55, 57, 59, 61, 63, 65, 0, - 0, 67, 69, 71, 73, 75, 77, 0, 79, 81, - 83, 85, 0, 0, 87, 89, 91, 93, 95, 97, - 99, 101, 103, 105, 107, 109, 111, 113, 115, 117, - 119, 121, 123, 125, 127, 129, 131, 133, 135, 137, - 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, - 0, 159, 0, 161, 163, 165, 167, 169, 171, 173, - 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, - 195, 197, 199, 201, 203, 205, 207, 209, 211, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 213, 0, 0, 215, 217, 219, 0, 221, - 223, 0, 225, 227, 229, 231, 233, 235, 237, 239, - 241, 243, 245, 247, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -5887,62 +5872,40 @@ static const unsigned char yyconflp[] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0 + 0, 0, 0, 0 }; /* YYCONFL[I] -- lists of conflicting rule numbers, each terminated by 0, pointed into by YYCONFLP. */ static const short int yyconfl[] = { - 0, 408, 0, 408, 0, 408, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 657, - 0, 657, 0, 657, 0, 657, 0, 657, 0, 408, - 0, 408, 0 + 0, 413, 0, 413, 0, 413, 0, 313, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 684, 0, 684, 0, 684, 0, 684, 0, 684, + 0, 296, 0, 296, 0, 296, 0, 413, 0, 306, + 0, 413, 0 }; /* Error token number */ @@ -6300,6 +6263,7 @@ yyfillin (yyGLRStackItem *yyvsp, int yylow0, int yylow1) * YYVSP[YYLOW1 .. *YYLOW-1] as in yyfillin and set *YYLOW = YYLOW1. * For convenience, always return YYLOW1. */ static int yyfill (yyGLRStackItem *, int *, int, yybool); + static int yyfill (yyGLRStackItem *yyvsp, int *yylow, int yylow1, yybool yynormal) { @@ -7256,8 +7220,32 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; + case 272: + + { clearVarValue(); markSig(); postSig("("); } + + break; + case 273: + { chopSig(); postSig(")"); setVarValue(copySig()); } + + break; + + case 274: + + { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } + + break; + + case 275: + + { postSig(", "); } + + break; + + case 278: + { unsigned int type = getType(); ValueInfo *var = (ValueInfo *)malloc(sizeof(ValueInfo)); @@ -7329,25 +7317,25 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 277: + case 282: { postSig(", "); } break; - case 280: + case 285: { setTypePtr(0); } break; - case 281: + case 286: { setTypePtr((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 282: + case 287: { if ((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer) == VTK_PARSE_FUNCTION) @@ -7362,13 +7350,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 283: + case 288: { postSig(")"); } break; - case 284: + case 289: { const char *scope = getScope(); @@ -7387,19 +7375,19 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 285: + case 290: { ((*yyvalp).integer) = (((yyGLRStackItem const *)yyvsp)[YYFILL (-2)].yystate.yysemantics.yysval.integer); } break; - case 286: + case 291: { postSig(")"); } break; - case 287: + case 292: { const char *scope = getScope(); @@ -7418,44 +7406,44 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 288: + case 293: { postSig("("); scopeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); postSig("*"); } break; - case 289: + case 294: { ((*yyvalp).integer) = (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer); } break; - case 290: + case 295: { postSig("("); scopeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); postSig("&"); ((*yyvalp).integer) = VTK_PARSE_REF; } break; - case 291: + case 296: { ((*yyvalp).integer) = 0; } break; - case 292: + case 297: { pushFunction(); postSig("("); } break; - case 293: + case 298: { postSig(")"); } break; - case 294: + case 299: { ((*yyvalp).integer) = VTK_PARSE_FUNCTION; @@ -7464,193 +7452,193 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 295: + case 300: { ((*yyvalp).integer) = VTK_PARSE_ARRAY; } break; - case 298: + case 303: { currentFunction->IsConst = 1; } break; - case 303: + case 308: { ((*yyvalp).integer) = add_indirection((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.integer), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 305: + case 310: { ((*yyvalp).integer) = add_indirection((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.integer), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 306: + case 311: { clearVarName(); chopSig(); } break; - case 308: + case 313: { setVarName((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str)); } break; - case 309: + case 314: { setVarName((((yyGLRStackItem const *)yyvsp)[YYFILL (-3)].yystate.yysemantics.yysval.str)); } break; - case 314: + case 319: { clearArray(); } break; - case 316: + case 321: { clearArray(); } break; - case 320: + case 325: { postSig("["); } break; - case 321: + case 326: { postSig("]"); } break; - case 322: + case 327: { pushArraySize(""); } break; - case 323: + case 328: { markSig(); } break; - case 324: + case 329: { chopSig(); pushArraySize(copySig()); } break; - case 330: + case 335: { ((*yyvalp).str) = vtkstrcat("~", (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 331: + case 336: { ((*yyvalp).str) = vtkstrcat("~", (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 332: + case 337: { ((*yyvalp).str) = vtkstrcat((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 333: + case 338: { ((*yyvalp).str) = vtkstrcat((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 334: + case 339: { ((*yyvalp).str) = vtkstrcat((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 335: + case 340: { ((*yyvalp).str) = vtkstrcat((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 336: + case 341: { ((*yyvalp).str) = vtkstrcat((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 337: + case 342: { ((*yyvalp).str) = vtkstrcat((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 338: + case 343: { ((*yyvalp).str) = vtkstrcat3((((yyGLRStackItem const *)yyvsp)[YYFILL (-2)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 339: + case 344: { ((*yyvalp).str) = vtkstrcat3((((yyGLRStackItem const *)yyvsp)[YYFILL (-2)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 340: + case 345: { ((*yyvalp).str) = vtkstrcat3((((yyGLRStackItem const *)yyvsp)[YYFILL (-2)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 341: + case 346: { postSig("template "); } break; - case 342: + case 347: { ((*yyvalp).str) = vtkstrcat4((((yyGLRStackItem const *)yyvsp)[YYFILL (-4)].yystate.yysemantics.yysval.str), "template ", (((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 343: + case 348: { postSig("~"); } break; - case 344: + case 349: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 345: + case 350: { ((*yyvalp).str) = "::"; postSig(((*yyvalp).str)); } break; - case 346: + case 351: { markSig(); postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str)); postSig("<"); } break; - case 347: + case 352: { chopSig(); if (getSig()[getSigLength()-1] == '>') { postSig(" "); } @@ -7659,625 +7647,625 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 348: + case 353: { markSig(); postSig("decltype"); } break; - case 349: + case 354: { chopSig(); ((*yyvalp).str) = copySig(); clearTypeId(); } break; - case 350: + case 355: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 351: + case 356: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 352: + case 357: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 353: + case 358: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 354: + case 359: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 355: + case 360: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 356: + case 361: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 357: + case 362: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 358: + case 363: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 359: + case 364: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 360: + case 365: { ((*yyvalp).str) = "vtkTypeInt8"; postSig(((*yyvalp).str)); } break; - case 361: + case 366: { ((*yyvalp).str) = "vtkTypeUInt8"; postSig(((*yyvalp).str)); } break; - case 362: + case 367: { ((*yyvalp).str) = "vtkTypeInt16"; postSig(((*yyvalp).str)); } break; - case 363: + case 368: { ((*yyvalp).str) = "vtkTypeUInt16"; postSig(((*yyvalp).str)); } break; - case 364: + case 369: { ((*yyvalp).str) = "vtkTypeInt32"; postSig(((*yyvalp).str)); } break; - case 365: + case 370: { ((*yyvalp).str) = "vtkTypeUInt32"; postSig(((*yyvalp).str)); } break; - case 366: + case 371: { ((*yyvalp).str) = "vtkTypeInt64"; postSig(((*yyvalp).str)); } break; - case 367: + case 372: { ((*yyvalp).str) = "vtkTypeUInt64"; postSig(((*yyvalp).str)); } break; - case 368: + case 373: { ((*yyvalp).str) = "vtkTypeFloat32"; postSig(((*yyvalp).str)); } break; - case 369: + case 374: { ((*yyvalp).str) = "vtkTypeFloat64"; postSig(((*yyvalp).str)); } break; - case 370: + case 375: { ((*yyvalp).str) = "vtkIdType"; postSig(((*yyvalp).str)); } break; - case 381: + case 386: { setTypeBase(buildTypeBase(getType(), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer))); } break; - case 382: + case 387: { setTypeMod(VTK_PARSE_TYPEDEF); } break; - case 383: + case 388: { setTypeMod(VTK_PARSE_FRIEND); } break; - case 386: + case 391: { setTypeMod((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 387: + case 392: { setTypeMod((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 388: + case 393: { setTypeMod((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 389: + case 394: { postSig("constexpr "); ((*yyvalp).integer) = 0; } break; - case 390: + case 395: { postSig("mutable "); ((*yyvalp).integer) = VTK_PARSE_MUTABLE; } break; - case 391: + case 396: { ((*yyvalp).integer) = 0; } break; - case 392: + case 397: { ((*yyvalp).integer) = 0; } break; - case 393: + case 398: { postSig("static "); ((*yyvalp).integer) = VTK_PARSE_STATIC; } break; - case 394: + case 399: { postSig("thread_local "); ((*yyvalp).integer) = VTK_PARSE_THREAD_LOCAL; } break; - case 395: + case 400: { ((*yyvalp).integer) = 0; } break; - case 396: + case 401: { postSig("virtual "); ((*yyvalp).integer) = VTK_PARSE_VIRTUAL; } break; - case 397: + case 402: { postSig("explicit "); ((*yyvalp).integer) = VTK_PARSE_EXPLICIT; } break; - case 398: + case 403: { postSig("const "); ((*yyvalp).integer) = VTK_PARSE_CONST; } break; - case 399: + case 404: { postSig("volatile "); ((*yyvalp).integer) = VTK_PARSE_VOLATILE; } break; - case 401: + case 406: { ((*yyvalp).integer) = ((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.integer) | (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 403: + case 408: { setTypeBase((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 405: + case 410: { setTypeBase((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 408: + case 413: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = guess_id_type((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 409: + case 414: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = guess_id_type((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str)); } break; - case 411: + case 416: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = 0; } break; - case 412: + case 417: { postSig("typename "); } break; - case 413: + case 418: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = guess_id_type((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str)); } break; - case 414: + case 419: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = guess_id_type((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str)); } break; - case 415: + case 420: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = guess_id_type((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.str)); } break; - case 417: + case 422: { setTypeBase((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 419: + case 424: { setTypeBase((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 422: + case 427: { setTypeBase((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 424: + case 429: { setTypeBase((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 427: + case 432: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = 0; } break; - case 428: + case 433: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = guess_id_type((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 429: + case 434: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = guess_id_type((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 430: + case 435: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = guess_id_type((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 431: + case 436: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = guess_id_type((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 432: + case 437: { postSig(" "); setTypeId((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = guess_id_type((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 433: + case 438: { setTypeId(""); } break; - case 435: + case 440: { typeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = VTK_PARSE_STRING; } break; - case 436: + case 441: { typeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = VTK_PARSE_UNICODE_STRING;} break; - case 437: + case 442: { typeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = VTK_PARSE_OSTREAM; } break; - case 438: + case 443: { typeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = VTK_PARSE_ISTREAM; } break; - case 439: + case 444: { typeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = VTK_PARSE_UNKNOWN; } break; - case 440: + case 445: { typeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = VTK_PARSE_OBJECT; } break; - case 441: + case 446: { typeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = VTK_PARSE_QOBJECT; } break; - case 442: + case 447: { typeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = VTK_PARSE_NULLPTR_T; } break; - case 443: + case 448: { typeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = VTK_PARSE_SSIZE_T; } break; - case 444: + case 449: { typeSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); ((*yyvalp).integer) = VTK_PARSE_SIZE_T; } break; - case 445: + case 450: { typeSig("vtkTypeInt8"); ((*yyvalp).integer) = VTK_PARSE_INT8; } break; - case 446: + case 451: { typeSig("vtkTypeUInt8"); ((*yyvalp).integer) = VTK_PARSE_UINT8; } break; - case 447: + case 452: { typeSig("vtkTypeInt16"); ((*yyvalp).integer) = VTK_PARSE_INT16; } break; - case 448: + case 453: { typeSig("vtkTypeUInt16"); ((*yyvalp).integer) = VTK_PARSE_UINT16; } break; - case 449: + case 454: { typeSig("vtkTypeInt32"); ((*yyvalp).integer) = VTK_PARSE_INT32; } break; - case 450: + case 455: { typeSig("vtkTypeUInt32"); ((*yyvalp).integer) = VTK_PARSE_UINT32; } break; - case 451: + case 456: { typeSig("vtkTypeInt64"); ((*yyvalp).integer) = VTK_PARSE_INT64; } break; - case 452: + case 457: { typeSig("vtkTypeUInt64"); ((*yyvalp).integer) = VTK_PARSE_UINT64; } break; - case 453: + case 458: { typeSig("vtkTypeFloat32"); ((*yyvalp).integer) = VTK_PARSE_FLOAT32; } break; - case 454: + case 459: { typeSig("vtkTypeFloat64"); ((*yyvalp).integer) = VTK_PARSE_FLOAT64; } break; - case 455: + case 460: { typeSig("vtkIdType"); ((*yyvalp).integer) = VTK_PARSE_ID_TYPE; } break; - case 456: + case 461: { postSig("auto "); ((*yyvalp).integer) = 0; } break; - case 457: + case 462: { postSig("void "); ((*yyvalp).integer) = VTK_PARSE_VOID; } break; - case 458: + case 463: { postSig("bool "); ((*yyvalp).integer) = VTK_PARSE_BOOL; } break; - case 459: + case 464: { postSig("float "); ((*yyvalp).integer) = VTK_PARSE_FLOAT; } break; - case 460: + case 465: { postSig("double "); ((*yyvalp).integer) = VTK_PARSE_DOUBLE; } break; - case 461: + case 466: { postSig("char "); ((*yyvalp).integer) = VTK_PARSE_CHAR; } break; - case 462: + case 467: { postSig("char16_t "); ((*yyvalp).integer) = VTK_PARSE_CHAR16_T; } break; - case 463: + case 468: { postSig("char32_t "); ((*yyvalp).integer) = VTK_PARSE_CHAR32_T; } break; - case 464: + case 469: { postSig("wchar_t "); ((*yyvalp).integer) = VTK_PARSE_WCHAR_T; } break; - case 465: + case 470: { postSig("int "); ((*yyvalp).integer) = VTK_PARSE_INT; } break; - case 466: + case 471: { postSig("short "); ((*yyvalp).integer) = VTK_PARSE_SHORT; } break; - case 467: + case 472: { postSig("long "); ((*yyvalp).integer) = VTK_PARSE_LONG; } break; - case 468: + case 473: { postSig("__int64 "); ((*yyvalp).integer) = VTK_PARSE___INT64; } break; - case 469: + case 474: { postSig("signed "); ((*yyvalp).integer) = VTK_PARSE_INT; } break; - case 470: + case 475: { postSig("unsigned "); ((*yyvalp).integer) = VTK_PARSE_UNSIGNED_INT; } break; - case 474: + case 479: { ((*yyvalp).integer) = ((((yyGLRStackItem const *)yyvsp)[YYFILL (-1)].yystate.yysemantics.yysval.integer) | (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } break; - case 475: + case 480: { postSig("&"); ((*yyvalp).integer) = VTK_PARSE_REF; } break; - case 476: + case 481: { postSig("&&"); ((*yyvalp).integer) = (VTK_PARSE_RVALUE | VTK_PARSE_REF); } break; - case 477: + case 482: { postSig("*"); } break; - case 478: + case 483: { ((*yyvalp).integer) = (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer); } break; - case 479: + case 484: { ((*yyvalp).integer) = VTK_PARSE_POINTER; } break; - case 480: + case 485: { if (((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer) & VTK_PARSE_CONST) != 0) @@ -8292,7 +8280,7 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 482: + case 487: { unsigned int n; @@ -8306,25 +8294,109 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 485: + case 488: - { closeSig(); } + { setAttributeRole(VTK_PARSE_ATTRIB_DECL); } break; - case 486: + case 489: - { openSig(); } + { clearAttributeRole(); } break; - case 488: + case 490: + + { setAttributeRole(VTK_PARSE_ATTRIB_ID); } + + break; + + case 491: + + { clearAttributeRole(); } + + break; + + case 492: + + { setAttributeRole(VTK_PARSE_ATTRIB_REF); } + + break; + + case 493: + + { clearAttributeRole(); } + + break; + + case 494: + + { setAttributeRole(VTK_PARSE_ATTRIB_FUNC); } + + break; + + case 495: + + { clearAttributeRole(); } + + break; + + case 496: + + { setAttributeRole(VTK_PARSE_ATTRIB_ARRAY); } + + break; + + case 497: + + { clearAttributeRole(); } + + break; + + case 498: + + { setAttributeRole(VTK_PARSE_ATTRIB_CLASS); } + + break; + + case 499: + + { clearAttributeRole(); } + + break; + + case 507: + + { markSig(); } + + break; + + case 508: + + { handle_attribute(cutSig(), (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.integer)); } + + break; + + case 509: + + { ((*yyvalp).integer) = 0; } + + break; + + case 510: + + { ((*yyvalp).integer) = VTK_PARSE_PACK; } + + break; + + case 515: {preSig("void Set"); postSig("(");} break; - case 489: + case 516: { postSig("a);"); @@ -8338,25 +8410,25 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 490: + case 517: {postSig("Get");} break; - case 491: + case 518: {markSig();} break; - case 492: + case 519: {swapSig();} break; - case 493: + case 520: { postSig("();"); @@ -8369,13 +8441,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 494: + case 521: {preSig("void Set");} break; - case 495: + case 522: { postSig("(char *);"); @@ -8389,13 +8461,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 496: + case 523: {preSig("char *Get");} break; - case 497: + case 524: { postSig("();"); @@ -8408,19 +8480,19 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 498: + case 525: {startSig(); markSig();} break; - case 499: + case 526: {closeSig();} break; - case 500: + case 527: { const char *typeText; @@ -8455,13 +8527,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 501: + case 528: {preSig("void Set"); postSig("("); } break; - case 502: + case 529: { postSig("*);"); @@ -8475,25 +8547,25 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 503: + case 530: {postSig("*Get");} break; - case 504: + case 531: {markSig();} break; - case 505: + case 532: {swapSig();} break; - case 506: + case 533: { postSig("();"); @@ -8506,7 +8578,7 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 507: + case 534: { currentFunction->Macro = "vtkBooleanMacro"; @@ -8528,13 +8600,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 508: + case 535: {startSig(); markSig();} break; - case 509: + case 536: { chopSig(); @@ -8543,13 +8615,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 510: + case 537: {startSig(); markSig();} break; - case 511: + case 538: { chopSig(); @@ -8558,13 +8630,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 512: + case 539: {startSig(); markSig();} break; - case 513: + case 540: { chopSig(); @@ -8573,13 +8645,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 514: + case 541: {startSig(); markSig();} break; - case 515: + case 542: { chopSig(); @@ -8588,13 +8660,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 516: + case 543: {startSig(); markSig();} break; - case 517: + case 544: { chopSig(); @@ -8603,13 +8675,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 518: + case 545: {startSig(); markSig();} break; - case 519: + case 546: { chopSig(); @@ -8618,13 +8690,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 520: + case 547: {startSig(); markSig();} break; - case 521: + case 548: { chopSig(); @@ -8633,13 +8705,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 522: + case 549: {startSig(); markSig();} break; - case 523: + case 550: { chopSig(); @@ -8648,13 +8720,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 524: + case 551: {startSig(); markSig();} break; - case 525: + case 552: { const char *typeText; @@ -8674,13 +8746,13 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 526: + case 553: {startSig();} break; - case 527: + case 554: { chopSig(); @@ -8697,7 +8769,7 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 528: + case 555: { currentFunction->Macro = "vtkViewportCoordinateMacro"; @@ -8738,7 +8810,7 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 529: + case 556: { currentFunction->Macro = "vtkWorldCoordinateMacro"; @@ -8780,7 +8852,7 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 530: + case 557: { currentFunction->Macro = "vtkTypeMacro"; @@ -8804,7 +8876,8 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, currentFunction->Name = "NewInstance"; currentFunction->Signature = vtkstrcat((((yyGLRStackItem const *)yyvsp)[YYFILL (-4)].yystate.yysemantics.yysval.str), " *NewInstance();"); currentFunction->Comment = vtkstrdup(getComment()); - set_return(currentFunction, VTK_PARSE_OBJECT_PTR, (((yyGLRStackItem const *)yyvsp)[YYFILL (-4)].yystate.yysemantics.yysval.str), 0); + set_return(currentFunction, VTK_PARSE_NEWINSTANCE | VTK_PARSE_OBJECT_PTR, + (((yyGLRStackItem const *)yyvsp)[YYFILL (-4)].yystate.yysemantics.yysval.str), 0); output_function(); currentFunction->Macro = "vtkTypeMacro"; @@ -8820,475 +8893,475 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 533: + case 560: { ((*yyvalp).str) = "()"; } break; - case 534: + case 561: { ((*yyvalp).str) = "[]"; } break; - case 535: + case 562: { ((*yyvalp).str) = " new[]"; } break; - case 536: + case 563: { ((*yyvalp).str) = " delete[]"; } break; - case 537: + case 564: { ((*yyvalp).str) = "<"; } break; - case 538: + case 565: { ((*yyvalp).str) = ">"; } break; - case 539: + case 566: { ((*yyvalp).str) = ","; } break; - case 540: + case 567: { ((*yyvalp).str) = "="; } break; - case 541: + case 568: { ((*yyvalp).str) = ">>"; } break; - case 542: + case 569: { ((*yyvalp).str) = ">>"; } break; - case 543: + case 570: { ((*yyvalp).str) = vtkstrcat("\"\" ", (((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); } break; - case 545: + case 572: { ((*yyvalp).str) = "%"; } break; - case 546: + case 573: { ((*yyvalp).str) = "*"; } break; - case 547: + case 574: { ((*yyvalp).str) = "/"; } break; - case 548: + case 575: { ((*yyvalp).str) = "-"; } break; - case 549: + case 576: { ((*yyvalp).str) = "+"; } break; - case 550: + case 577: { ((*yyvalp).str) = "!"; } break; - case 551: + case 578: { ((*yyvalp).str) = "~"; } break; - case 552: + case 579: { ((*yyvalp).str) = "&"; } break; - case 553: + case 580: { ((*yyvalp).str) = "|"; } break; - case 554: + case 581: { ((*yyvalp).str) = "^"; } break; - case 555: + case 582: { ((*yyvalp).str) = " new"; } break; - case 556: + case 583: { ((*yyvalp).str) = " delete"; } break; - case 557: + case 584: { ((*yyvalp).str) = "<<="; } break; - case 558: + case 585: { ((*yyvalp).str) = ">>="; } break; - case 559: + case 586: { ((*yyvalp).str) = "<<"; } break; - case 560: + case 587: { ((*yyvalp).str) = ".*"; } break; - case 561: + case 588: { ((*yyvalp).str) = "->*"; } break; - case 562: + case 589: { ((*yyvalp).str) = "->"; } break; - case 563: + case 590: { ((*yyvalp).str) = "+="; } break; - case 564: + case 591: { ((*yyvalp).str) = "-="; } break; - case 565: + case 592: { ((*yyvalp).str) = "*="; } break; - case 566: + case 593: { ((*yyvalp).str) = "/="; } break; - case 567: + case 594: { ((*yyvalp).str) = "%="; } break; - case 568: + case 595: { ((*yyvalp).str) = "++"; } break; - case 569: + case 596: { ((*yyvalp).str) = "--"; } break; - case 570: + case 597: { ((*yyvalp).str) = "&="; } break; - case 571: + case 598: { ((*yyvalp).str) = "|="; } break; - case 572: + case 599: { ((*yyvalp).str) = "^="; } break; - case 573: + case 600: { ((*yyvalp).str) = "&&"; } break; - case 574: + case 601: { ((*yyvalp).str) = "||"; } break; - case 575: + case 602: { ((*yyvalp).str) = "=="; } break; - case 576: + case 603: { ((*yyvalp).str) = "!="; } break; - case 577: + case 604: { ((*yyvalp).str) = "<="; } break; - case 578: + case 605: { ((*yyvalp).str) = ">="; } break; - case 579: + case 606: { ((*yyvalp).str) = "typedef"; } break; - case 580: + case 607: { ((*yyvalp).str) = "typename"; } break; - case 581: + case 608: { ((*yyvalp).str) = "class"; } break; - case 582: + case 609: { ((*yyvalp).str) = "struct"; } break; - case 583: + case 610: { ((*yyvalp).str) = "union"; } break; - case 584: + case 611: { ((*yyvalp).str) = "template"; } break; - case 585: + case 612: { ((*yyvalp).str) = "public"; } break; - case 586: + case 613: { ((*yyvalp).str) = "protected"; } break; - case 587: + case 614: { ((*yyvalp).str) = "private"; } break; - case 588: + case 615: { ((*yyvalp).str) = "const"; } break; - case 589: + case 616: { ((*yyvalp).str) = "static"; } break; - case 590: + case 617: { ((*yyvalp).str) = "thread_local"; } break; - case 591: + case 618: { ((*yyvalp).str) = "constexpr"; } break; - case 592: + case 619: { ((*yyvalp).str) = "inline"; } break; - case 593: + case 620: { ((*yyvalp).str) = "virtual"; } break; - case 594: + case 621: { ((*yyvalp).str) = "explicit"; } break; - case 595: + case 622: { ((*yyvalp).str) = "decltype"; } break; - case 596: + case 623: { ((*yyvalp).str) = "default"; } break; - case 597: + case 624: { ((*yyvalp).str) = "extern"; } break; - case 598: + case 625: { ((*yyvalp).str) = "using"; } break; - case 599: + case 626: { ((*yyvalp).str) = "namespace"; } break; - case 600: + case 627: { ((*yyvalp).str) = "operator"; } break; - case 601: + case 628: { ((*yyvalp).str) = "enum"; } break; - case 602: + case 629: { ((*yyvalp).str) = "throw"; } break; - case 603: + case 630: { ((*yyvalp).str) = "noexcept"; } break; - case 604: + case 631: { ((*yyvalp).str) = "const_cast"; } break; - case 605: + case 632: { ((*yyvalp).str) = "dynamic_cast"; } break; - case 606: + case 633: { ((*yyvalp).str) = "static_cast"; } break; - case 607: + case 634: { ((*yyvalp).str) = "reinterpret_cast"; } break; - case 621: + case 648: { postSig("< "); } break; - case 622: + case 649: { postSig("> "); } break; - case 624: + case 651: { postSig(">"); } break; - case 626: + case 653: { chopSig(); postSig("::"); } break; - case 630: + case 657: { if ((((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str))[0] == '+' || ((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str))[0] == '-' || @@ -9322,31 +9395,31 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 631: + case 658: { postSig(":"); postSig(" "); } break; - case 632: + case 659: { postSig("."); } break; - case 633: + case 660: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); postSig(" "); } break; - case 634: + case 661: { postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); postSig(" "); } break; - case 636: + case 663: { int c1 = 0; @@ -9372,55 +9445,55 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 640: + case 667: { postSig("< "); } break; - case 641: + case 668: { postSig("> "); } break; - case 642: + case 669: { postSig(">"); } break; - case 644: + case 671: { postSig("= "); } break; - case 645: + case 672: { chopSig(); postSig(", "); } break; - case 647: + case 674: { chopSig(); postSig(";"); } break; - case 655: + case 682: { postSig("= "); } break; - case 656: + case 683: { chopSig(); postSig(", "); } break; - case 657: + case 684: { chopSig(); @@ -9430,7 +9503,7 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 658: + case 685: { chopSig(); @@ -9440,73 +9513,73 @@ yyuserAction (yyRuleNum yyn, size_t yyrhslen, yyGLRStackItem* yyvsp, break; - case 661: + case 688: { postSig("["); } break; - case 662: + case 689: { chopSig(); postSig("] "); } break; - case 663: + case 690: { postSig("[["); } break; - case 664: + case 691: { chopSig(); postSig("]] "); } break; - case 665: + case 692: { postSig("("); } break; - case 666: + case 693: { chopSig(); postSig(") "); } break; - case 667: + case 694: { postSig("("); postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); postSig("*"); } break; - case 668: + case 695: { chopSig(); postSig(") "); } break; - case 669: + case 696: { postSig("("); postSig((((yyGLRStackItem const *)yyvsp)[YYFILL (0)].yystate.yysemantics.yysval.str)); postSig("&"); } break; - case 670: + case 697: { chopSig(); postSig(") "); } break; - case 671: + case 698: { postSig("{ "); } break; - case 672: + case 699: { postSig("} "); } @@ -9607,7 +9680,7 @@ yylhsNonterm (yyRuleNum yyrule) } #define yypact_value_is_default(Yystate) \ - (!!((Yystate) == (-1052))) + (!!((Yystate) == (-1011))) /** True iff LR state YYSTATE has only a default reduction (regardless * of token). */ @@ -12029,6 +12102,60 @@ void handle_complex_type( val->Count = count_from_dimensions(val); } +/* handle [[attributes]] */ +void handle_attribute(const char *att, int pack) +{ + /* the role means "this is what the attribute applies to" */ + int role = getAttributeRole(); + + size_t l = 0; + const char *args = NULL; + + if (!att) + { + return; + } + + /* search for arguments */ + l = vtkParse_SkipId(att); + while (att[l] == ':' && att[l+1] == ':') + { + l += 2; + l += vtkParse_SkipId(&att[l]); + } + if (att[l] == '(') + { + args = &att[l]; + } + + /* check for namespace */ + if (strncmp(att, "vtk::", 5) == 0) + { + if (args) + { + /* no current vtk attributes use arguments */ + print_parser_error("attribute takes no args", att, l); + exit(1); + } + else if (pack) + { + /* no current vtk attributes use '...' */ + print_parser_error("attribute takes no ...", att, l); + exit(1); + } + else if (strcmp(att, "vtk::newinstance") == 0 && + role == VTK_PARSE_ATTRIB_DECL) + { + setTypeMod(VTK_PARSE_NEWINSTANCE); + } + else + { + print_parser_error("attribute cannot be used here", att, l); + exit(1); + } + } +} + /* add a parameter to the legacy part of the FunctionInfo struct */ void add_legacy_parameter(FunctionInfo *func, ValueInfo *param) { @@ -12362,19 +12489,6 @@ void outputGetVectorMacro(const char *var, unsigned int paramType, output_function(); } -/* Set a flag to ignore BTX/ETX markers in the files */ -void vtkParse_SetIgnoreBTX(int option) -{ - if (option) - { - IgnoreBTX = 1; - } - else - { - IgnoreBTX = 0; - } -} - /* Set a flag to recurse into included files */ void vtkParse_SetRecursive(int option) { diff --git a/Wrapping/Tools/vtkParse.y b/Wrapping/Tools/vtkParse.y index e6476f7322f..7919cc45fd2 100644 --- a/Wrapping/Tools/vtkParse.y +++ b/Wrapping/Tools/vtkParse.y @@ -87,6 +87,12 @@ order to eliminate shift/reduce conflicts in the parser. However, this means that this parser will only recognize "scope::*" as valid if it is preceded by "(", e.g. as part of a member function pointer specification. +Variables that are initialized via constructor arguments, for example +"someclass variablename(arglist)", must take a literals as the first +argument. If an identifier is used as the first argument, then the +parser will interpret the variable declaration as a function declaration, +since the parser will assume the identifier names a type. + An odd bit of C++ ambiguity is that y(x); can be interpreted variously as declaration of variable "x" of type "y", as a function call if "y" is the name of a function, or as a constructor if "y" is the name of @@ -174,6 +180,18 @@ static unsigned int vtkParseTypeMap[] = #define VTK_PARSE_FLOAT32 vtkParseTypeMap[VTK_TYPE_FLOAT32] #define VTK_PARSE_FLOAT64 vtkParseTypeMap[VTK_TYPE_FLOAT64] +/* Define the kinds of [[attributes]] to collect */ +enum + { + VTK_PARSE_ATTRIB_NONE, + VTK_PARSE_ATTRIB_DECL, /* modify a declaration */ + VTK_PARSE_ATTRIB_ID, /* modify an id */ + VTK_PARSE_ATTRIB_REF, /* modify *, &, or && */ + VTK_PARSE_ATTRIB_FUNC, /* modify a function or method */ + VTK_PARSE_ATTRIB_ARRAY, /* modify an array size specifier */ + VTK_PARSE_ATTRIB_CLASS /* modify class, struct, union, or enum */ + }; + #define vtkParseDebug(s1, s2) \ if ( parseDebug ) { fprintf(stderr, " %s %s\n", s1, s2); } @@ -196,7 +214,6 @@ int NumberOfDefinitions = 0; const char **Definitions; /* options that can be set by the programs that use the parser */ -int IgnoreBTX = 0; int Recursive = 0; const char *CommandName = NULL; @@ -245,6 +262,7 @@ void handle_complex_type(ValueInfo *val, unsigned int datatype, unsigned int extra, const char *funcSig); void handle_function_type(ValueInfo *param, const char *name, const char *funcSig); +void handle_attribute(const char *att, int pack); void add_legacy_parameter(FunctionInfo *func, ValueInfo *param); void outputSetVectorMacro(const char *var, unsigned int paramType, @@ -1192,6 +1210,23 @@ const char *copySig() return vtkstrdup(cp); } +/* cut the sig from the mark to the current location, and clear the mark */ +const char *cutSig() +{ + const char *cp = NULL; + if (sigMarkDepth > 0) + { + sigMarkDepth--; + } + if (signature) + { + sigLength = sigMark[sigMarkDepth]; + cp = vtkstrdup(&signature[sigLength]); + signature[sigLength] = 0; + } + return cp; +} + /* swap the signature text using the mark as the radix */ void swapSig() { @@ -1594,6 +1629,30 @@ FunctionInfo *getFunction() return functionStack[functionDepth+1]; } +/*---------------------------------------------------------------- + * Attributes + */ + +int attributeRole = 0; + +/* Set kind of attributes to collect in attribute_specifier_seq */ +void setAttributeRole(int x) +{ + attributeRole = x; +} + +/* Get the current kind of attribute */ +int getAttributeRole() +{ + return attributeRole; +} + +/* Ignore attributes until further notice */ +void clearAttributeRole() +{ + attributeRole = 0; +} + /*---------------------------------------------------------------- * Utility methods */ @@ -1724,8 +1783,9 @@ unsigned int add_indirection_to_array(unsigned int type) /* Use the GLR parser algorithm for tricky cases */ %glr-parser -/* Expect five shift-reduce conflicts from opt_final (final classes) */ -%expect 5 +/* Expect five shift-reduce conflicts from opt_final (final classes) + and five from '(' constructor_args ')' in initializer */ +%expect 10 /* Expect 121 reduce/reduce conflicts, these can be cleared by removing either '<' or angle_brackets_sig from constant_expression_item. */ @@ -1920,7 +1980,7 @@ opt_declaration_seq: clearTemplate(); closeComment(); } - attribute_specifier_seq declaration + decl_attribute_specifier_seq declaration declaration: using_directive @@ -1982,9 +2042,9 @@ forward_declaration: | template_head simple_forward_declaration simple_forward_declaration: - class_key attribute_specifier_seq class_head_name ';' - | class_key attribute_specifier_seq ';' - | decl_specifier_seq class_key attribute_specifier_seq class_head_name ';' + class_key class_attribute_specifier_seq class_head_name ';' + | class_key class_attribute_specifier_seq ';' + | decl_specifier_seq class_key class_attribute_specifier_seq class_head_name ';' class_definition: class_specifier opt_decl_specifier_seq opt_declarator_list ';' @@ -2005,23 +2065,23 @@ class_specifier: } class_head: - class_key attribute_specifier_seq class_head_name opt_final ':' + class_key class_attribute_specifier_seq class_head_name opt_final ':' { start_class($3, $1); currentClass->IsFinal = $4; } base_specifier_list - | class_key attribute_specifier_seq class_head_name opt_final + | class_key class_attribute_specifier_seq class_head_name opt_final { start_class($3, $1); currentClass->IsFinal = $4; } - | class_key attribute_specifier_seq ':' + | class_key class_attribute_specifier_seq ':' { start_class(NULL, $1); } base_specifier_list - | class_key attribute_specifier_seq + | class_key class_attribute_specifier_seq { start_class(NULL, $1); } @@ -2032,11 +2092,11 @@ class_key: | UNION { $$ = 2; } class_head_name: - nested_name_specifier class_name attribute_specifier_seq + nested_name_specifier class_name decl_attribute_specifier_seq { $$ = vtkstrcat($1, $2); } - | scope_operator_sig nested_name_specifier class_name attribute_specifier_seq + | scope_operator_sig nested_name_specifier class_name decl_attribute_specifier_seq { $$ = vtkstrcat3("::", $2, $3); } - | class_name attribute_specifier_seq + | class_name decl_attribute_specifier_seq class_name: simple_id @@ -2055,7 +2115,7 @@ member_specification: clearTemplate(); closeComment(); } - attribute_specifier_seq member_declaration + decl_attribute_specifier_seq member_declaration | member_specification member_access_specifier ':' @@ -2097,7 +2157,7 @@ friend_declaration: base_specifier_list: base_specifier - | base_specifier_list ',' attribute_specifier_seq base_specifier + | base_specifier_list ',' decl_attribute_specifier_seq base_specifier base_specifier: id_expression opt_ellipsis @@ -2131,9 +2191,9 @@ access_specifier: */ opaque_enum_declaration: - enum_key attribute_specifier_seq id_expression opt_enum_base ';' - | enum_key attribute_specifier_seq ';' - | decl_specifier_seq enum_key attribute_specifier_seq + enum_key class_attribute_specifier_seq id_expression opt_enum_base ';' + | enum_key class_attribute_specifier_seq ';' + | decl_specifier_seq enum_key class_attribute_specifier_seq id_expression opt_enum_base ';' enum_definition: @@ -2155,13 +2215,13 @@ enum_specifier: } enum_head: - enum_key attribute_specifier_seq id_expression opt_enum_base + enum_key class_attribute_specifier_seq id_expression opt_enum_base { start_enum($3, $1, $4, getTypeId()); clearTypeId(); $$ = $3; } - | enum_key attribute_specifier_seq opt_enum_base + | enum_key class_attribute_specifier_seq opt_enum_base { start_enum(NULL, $1, $3, getTypeId()); clearTypeId(); @@ -2200,12 +2260,12 @@ ignored_initializer: | ignored_braces ignored_class: - class_key attribute_specifier_seq + class_key class_attribute_specifier_seq class_head_name opt_final ignored_class_body - | decl_specifier_seq class_key attribute_specifier_seq + | decl_specifier_seq class_key class_attribute_specifier_seq class_head_name opt_final ignored_class_body - | class_key attribute_specifier_seq ignored_class_body - | decl_specifier_seq class_key attribute_specifier_seq ignored_class_body + | class_key class_attribute_specifier_seq ignored_class_body + | decl_specifier_seq class_key class_attribute_specifier_seq ignored_class_body ignored_class_body: '{' ignored_items '}' ignored_expression ';' @@ -2309,7 +2369,7 @@ using_directive: USING NAMESPACE id_expression ';' { add_using($3, 1); } alias_declaration: - USING id_expression attribute_specifier_seq '=' { markSig(); } + USING id_expression id_attribute_specifier_seq '=' { markSig(); } store_type direct_abstract_declarator ';' { ValueInfo *item = (ValueInfo *)malloc(sizeof(ValueInfo)); @@ -2439,9 +2499,9 @@ nested_operator_declaration: method_definition: method_declaration function_body { output_function(); } - | nested_name_specifier operator_function_id attribute_specifier_seq ';' + | nested_name_specifier operator_function_id id_attribute_specifier_seq ';' | decl_specifier_seq nested_name_specifier operator_function_id - attribute_specifier_seq ';' + id_attribute_specifier_seq ';' method_declaration: store_type opt_ellipsis function_nr @@ -2461,8 +2521,8 @@ conversion_function: currentFunction->IsExplicit = ((getType() & VTK_PARSE_EXPLICIT) != 0); set_return(currentFunction, getType(), getTypeId(), 0); } - parameter_declaration_clause ')' attribute_specifier_seq { postSig(")"); } - function_trailer_clause opt_trailing_return_type + parameter_declaration_clause ')' func_attribute_specifier_seq + { postSig(")"); } function_trailer_clause opt_trailing_return_type { postSig(";"); closeSig(); @@ -2488,13 +2548,13 @@ operator_function_nr: } operator_function_sig: - operator_function_id attribute_specifier_seq '(' + operator_function_id id_attribute_specifier_seq '(' { postSig("("); currentFunction->IsOperator = 1; set_return(currentFunction, getType(), getTypeId(), 0); } - parameter_declaration_clause ')' attribute_specifier_seq + parameter_declaration_clause ')' func_attribute_specifier_seq operator_function_id: operator_sig operator_id @@ -2564,12 +2624,13 @@ handler_seq: | handler_seq CATCH ignored_parentheses '{' ignored_items '}' function_sig: - unqualified_id attribute_specifier_seq '(' + unqualified_id id_attribute_specifier_seq '(' { postSig("("); set_return(currentFunction, getType(), getTypeId(), 0); } - parameter_declaration_clause ')' attribute_specifier_seq { postSig(")"); } + parameter_declaration_clause ')' func_attribute_specifier_seq + { postSig(")"); } /* @@ -2598,7 +2659,7 @@ structor_declaration: structor_sig: unqualified_id '(' { pushType(); postSig("("); } - parameter_declaration_clause ')' attribute_specifier_seq + parameter_declaration_clause ')' func_attribute_specifier_seq { popType(); postSig(")"); } opt_ctor_initializer: @@ -2628,13 +2689,13 @@ parameter_list: { currentFunction->IsVariadic = 1; postSig("..."); } parameter_declaration: - { markSig(); } + decl_attribute_specifier_seq { markSig(); } store_type direct_abstract_declarator { ValueInfo *param = (ValueInfo *)malloc(sizeof(ValueInfo)); vtkParse_InitValue(param); - handle_complex_type(param, getType(), $3, copySig()); + handle_complex_type(param, getType(), $4, copySig()); add_legacy_parameter(currentFunction, param); if (getVarName()) @@ -2662,6 +2723,14 @@ initializer: constant_expression { chopSig(); setVarValue(copySig()); } | { clearVarValue(); markSig(); } braces_sig { chopSig(); setVarValue(copySig()); } + | { clearVarValue(); markSig(); postSig("("); } + '(' constructor_args ')' + { chopSig(); postSig(")"); setVarValue(copySig()); } + +constructor_args: + literal { postSig($1); } + | constructor_args ',' { postSig(", "); } constant_expression + /* * Variables @@ -2767,8 +2836,8 @@ direct_abstract_declarator: $$ = $1; } } - | lp_or_la attribute_specifier_seq abstract_declarator ')' { postSig(")"); } - opt_array_or_parameters + | lp_or_la ref_attribute_specifier_seq abstract_declarator ')' + { postSig(")"); } opt_array_or_parameters { const char *scope = getScope(); unsigned int parens = add_indirection($1, $3); @@ -2814,7 +2883,7 @@ lp_or_la: opt_array_or_parameters: { $$ = 0; } | '(' { pushFunction(); postSig("("); } parameter_declaration_clause ')' - attribute_specifier_seq { postSig(")"); } function_qualifiers + func_attribute_specifier_seq { postSig(")"); } function_qualifiers { $$ = VTK_PARSE_FUNCTION; popFunction(); @@ -2843,8 +2912,8 @@ opt_declarator_id: | declarator_id declarator_id: - unqualified_id attribute_specifier_seq { setVarName($1); } - | unqualified_id attribute_specifier_seq ':' bitfield_size + unqualified_id id_attribute_specifier_seq { setVarName($1); } + | unqualified_id id_attribute_specifier_seq ':' bitfield_size { setVarName($1); } bitfield_size: @@ -2865,8 +2934,8 @@ array_decorator_seq_impl: | array_decorator_seq_impl array_decorator array_decorator: - '[' { postSig("["); } array_size_specifier ']' attribute_specifier_seq - { postSig("]"); } + '[' { postSig("["); } array_size_specifier ']' + array_attribute_specifier_seq { postSig("]"); } array_size_specifier: { pushArraySize(""); } @@ -2979,7 +3048,7 @@ identifier: */ opt_decl_specifier_seq: - | opt_decl_specifier_seq decl_specifier2 attribute_specifier_seq + | opt_decl_specifier_seq decl_specifier2 decl_attribute_specifier_seq decl_specifier2: decl_specifier @@ -2989,8 +3058,8 @@ decl_specifier2: | FRIEND { setTypeMod(VTK_PARSE_FRIEND); } decl_specifier_seq: - decl_specifier attribute_specifier_seq - | decl_specifier_seq decl_specifier attribute_specifier_seq + decl_specifier decl_attribute_specifier_seq + | decl_specifier_seq decl_specifier decl_attribute_specifier_seq decl_specifier: storage_class_specifier { setTypeMod($1); } @@ -3035,20 +3104,21 @@ store_type_specifier: type_specifier: trailing_type_specifier - | class_key attribute_specifier_seq class_head_name + | class_key class_attribute_specifier_seq class_head_name { postSig(" "); setTypeId($3); $$ = guess_id_type($3); } - | enum_key attribute_specifier_seq id_expression attribute_specifier_seq + | enum_key class_attribute_specifier_seq id_expression decl_attribute_specifier_seq { postSig(" "); setTypeId($3); $$ = guess_id_type($3); } trailing_type_specifier: simple_type_specifier | decltype_specifier { postSig(" "); setTypeId($1); $$ = 0; } - | TYPENAME { postSig("typename "); } id_expression attribute_specifier_seq + | TYPENAME { postSig("typename "); } + id_expression decl_attribute_specifier_seq { postSig(" "); setTypeId($3); $$ = guess_id_type($3); } - | template_id attribute_specifier_seq + | template_id decl_attribute_specifier_seq { postSig(" "); setTypeId($1); $$ = guess_id_type($1); } - | qualified_id attribute_specifier_seq + | qualified_id decl_attribute_specifier_seq { postSig(" "); setTypeId($1); $$ = guess_id_type($1); } trailing_type_specifier_seq: @@ -3085,8 +3155,8 @@ tparam_type_specifier: { postSig(" "); setTypeId($2); $$ = guess_id_type($2); } simple_type_specifier: - primitive_type attribute_specifier_seq { setTypeId(""); } - | type_name attribute_specifier_seq + primitive_type decl_attribute_specifier_seq { setTypeId(""); } + | type_name decl_attribute_specifier_seq type_name: StdString { typeSig($1); $$ = VTK_PARSE_STRING; } @@ -3152,15 +3222,15 @@ ptr_operator_seq: | pointer_seq reference { $$ = ($1 | $2); } reference: - '&' attribute_specifier_seq + '&' ref_attribute_specifier_seq { postSig("&"); $$ = VTK_PARSE_REF; } rvalue_reference: - OP_LOGIC_AND attribute_specifier_seq + OP_LOGIC_AND ref_attribute_specifier_seq { postSig("&&"); $$ = (VTK_PARSE_RVALUE | VTK_PARSE_REF); } pointer: - '*' attribute_specifier_seq { postSig("*"); } + '*' ref_attribute_specifier_seq { postSig("*"); } ptr_cv_qualifier_seq { $$ = $4; } ptr_cv_qualifier_seq: @@ -3195,13 +3265,67 @@ pointer_seq: /* * Attributes + * + * An attribute can play are role: + * 1) within a declaration specifier list + * 2) after an id expression + * 3) after *, &, or && + * 4) after a function or template parameter list + * 5) after the closing bracket of an array size specifier + * 6) after a 'class', 'struct', 'union', or 'enum' key */ +decl_attribute_specifier_seq: + { setAttributeRole(VTK_PARSE_ATTRIB_DECL); } + attribute_specifier_seq { clearAttributeRole(); } + +id_attribute_specifier_seq: + { setAttributeRole(VTK_PARSE_ATTRIB_ID); } + attribute_specifier_seq { clearAttributeRole(); } + +ref_attribute_specifier_seq: + { setAttributeRole(VTK_PARSE_ATTRIB_REF); } + attribute_specifier_seq { clearAttributeRole(); } + +func_attribute_specifier_seq: + { setAttributeRole(VTK_PARSE_ATTRIB_FUNC); } + attribute_specifier_seq { clearAttributeRole(); } + +array_attribute_specifier_seq: + { setAttributeRole(VTK_PARSE_ATTRIB_ARRAY); } + attribute_specifier_seq { clearAttributeRole(); } + +class_attribute_specifier_seq: + { setAttributeRole(VTK_PARSE_ATTRIB_CLASS); } + attribute_specifier_seq { clearAttributeRole(); } + attribute_specifier_seq: | attribute_specifier_seq attribute_specifier attribute_specifier: - BEGIN_ATTRIB { closeSig(); } any_bracket_contents { openSig(); } ']' ']' + BEGIN_ATTRIB attribute_list ']' ']' + +attribute_list: + | attribute + | attribute_list ',' + | attribute_list ',' attribute + +attribute: + { markSig(); } attribute_sig attribute_pack + { handle_attribute(cutSig(), $3); } + +attribute_pack: + { $$ = 0; } + | ELLIPSIS { $$ = VTK_PARSE_PACK; } + +attribute_sig: + attribute_token + | attribute_token parentheses_sig + +attribute_token: + identifier_sig + | identifier_sig scope_operator_sig identifier_sig + /* * VTK Macros @@ -3487,7 +3611,8 @@ declaration_macro: currentFunction->Name = "NewInstance"; currentFunction->Signature = vtkstrcat($3, " *NewInstance();"); currentFunction->Comment = vtkstrdup(getComment()); - set_return(currentFunction, VTK_PARSE_OBJECT_PTR, $3, 0); + set_return(currentFunction, VTK_PARSE_NEWINSTANCE | VTK_PARSE_OBJECT_PTR, + $3, 0); output_function(); currentFunction->Macro = "vtkTypeMacro"; @@ -4626,6 +4751,60 @@ void handle_complex_type( val->Count = count_from_dimensions(val); } +/* handle [[attributes]] */ +void handle_attribute(const char *att, int pack) +{ + /* the role means "this is what the attribute applies to" */ + int role = getAttributeRole(); + + size_t l = 0; + const char *args = NULL; + + if (!att) + { + return; + } + + /* search for arguments */ + l = vtkParse_SkipId(att); + while (att[l] == ':' && att[l+1] == ':') + { + l += 2; + l += vtkParse_SkipId(&att[l]); + } + if (att[l] == '(') + { + args = &att[l]; + } + + /* check for namespace */ + if (strncmp(att, "vtk::", 5) == 0) + { + if (args) + { + /* no current vtk attributes use arguments */ + print_parser_error("attribute takes no args", att, l); + exit(1); + } + else if (pack) + { + /* no current vtk attributes use '...' */ + print_parser_error("attribute takes no ...", att, l); + exit(1); + } + else if (strcmp(att, "vtk::newinstance") == 0 && + role == VTK_PARSE_ATTRIB_DECL) + { + setTypeMod(VTK_PARSE_NEWINSTANCE); + } + else + { + print_parser_error("attribute cannot be used here", att, l); + exit(1); + } + } +} + /* add a parameter to the legacy part of the FunctionInfo struct */ void add_legacy_parameter(FunctionInfo *func, ValueInfo *param) { @@ -4959,19 +5138,6 @@ void outputGetVectorMacro(const char *var, unsigned int paramType, output_function(); } -/* Set a flag to ignore BTX/ETX markers in the files */ -void vtkParse_SetIgnoreBTX(int option) -{ - if (option) - { - IgnoreBTX = 1; - } - else - { - IgnoreBTX = 0; - } -} - /* Set a flag to recurse into included files */ void vtkParse_SetRecursive(int option) { diff --git a/Wrapping/Tools/vtkParseHierarchy.c b/Wrapping/Tools/vtkParseHierarchy.c index e4053455f05..0a22bd46219 100644 --- a/Wrapping/Tools/vtkParseHierarchy.c +++ b/Wrapping/Tools/vtkParseHierarchy.c @@ -102,6 +102,10 @@ static void sort_hierarchy_entries(HierarchyInfo *info) &compare_hierarchy_entries); } +/* forward declaration */ +static int vtkParseHierarchy_ReadFileIntoInfo( + HierarchyInfo* info, const char *filename); + /* Find an entry with a binary search */ HierarchyEntry *vtkParseHierarchy_FindEntry( const HierarchyInfo *info, const char *classname) @@ -153,13 +157,53 @@ HierarchyEntry *vtkParseHierarchy_FindEntry( return entry; } - -/* read a hierarchy file into a HeirarchyInfo struct, or return NULL */ +/* read a hierarchy file into a HeirarchyInfo struct, or return NULL + * XXX DEPRECATED; use vtkParseHierarchy_ReadFiles + */ HierarchyInfo *vtkParseHierarchy_ReadFile(const char *filename) +{ + char *fn = (char *)filename; + return vtkParseHierarchy_ReadFiles(1, &fn); +} + +/* read hierarchy files into a HierarchyInfo struct, or return NULL */ +HierarchyInfo *vtkParseHierarchy_ReadFiles(int n, char **filenames) { HierarchyInfo *info; + int currentFile = 0; + + info = (HierarchyInfo *)malloc(sizeof(HierarchyInfo)); + info->MaxNumberOfEntries = 500; + info->NumberOfEntries = 0; + info->Entries = + (HierarchyEntry *)malloc(info->MaxNumberOfEntries*sizeof(HierarchyEntry)); + info->Strings = (StringCache *)malloc(sizeof(StringCache)); + vtkParse_InitStringCache(info->Strings); + + for (currentFile = 0; currentFile < n; currentFile++) + { + if (!vtkParseHierarchy_ReadFileIntoInfo(info, filenames[currentFile])) + { + vtkParseHierarchy_Free(info); + info = NULL; + break; + } + } + + if (info) + { + sort_hierarchy_entries(info); + } + + return info; +} + +/* read hierarchy file into a HierarchyInfo struct, return 1 if success */ +static int vtkParseHierarchy_ReadFileIntoInfo( + HierarchyInfo* info, const char *filename) +{ HierarchyEntry *entry; - int maxClasses = 500; + FILE *fp; char *line; char *cp; @@ -168,22 +212,17 @@ HierarchyInfo *vtkParseHierarchy_ReadFile(const char *filename) size_t i, j, n, m; unsigned int bits, pointers; static const char *delims = ">,="; + int success = 1; fp = fopen(filename, "r"); if (fp == NULL) { - return NULL; + return 0; } line = (char *)malloc(maxlen); - info = (HierarchyInfo *)malloc(sizeof(HierarchyInfo)); - info->NumberOfEntries = 0; - info->Entries = (HierarchyEntry *)malloc(maxClasses*sizeof(HierarchyEntry)); - info->Strings = (StringCache *)malloc(sizeof(StringCache)); - vtkParse_InitStringCache(info->Strings); - while (fgets(line, (int)maxlen, fp)) { n = strlen(line); @@ -208,11 +247,11 @@ HierarchyInfo *vtkParseHierarchy_ReadFile(const char *filename) continue; } - if (info->NumberOfEntries == maxClasses) + if (info->NumberOfEntries == info->MaxNumberOfEntries) { - maxClasses *= 2; + info->MaxNumberOfEntries *= 2; info->Entries = (HierarchyEntry *)realloc( - info->Entries, sizeof(HierarchyEntry)*maxClasses*2); + info->Entries, sizeof(HierarchyEntry)*info->MaxNumberOfEntries); } entry = &info->Entries[info->NumberOfEntries++]; @@ -523,17 +562,12 @@ HierarchyInfo *vtkParseHierarchy_ReadFile(const char *filename) if (!feof(fp)) { - vtkParseHierarchy_Free(info); - info = NULL; - } - else - { - sort_hierarchy_entries(info); + success = 0; } fclose(fp); - return info; + return success; } /* free a HierarchyInfo struct */ diff --git a/Wrapping/Tools/vtkParseHierarchy.h b/Wrapping/Tools/vtkParseHierarchy.h index 6edef615f31..e194f7cb207 100644 --- a/Wrapping/Tools/vtkParseHierarchy.h +++ b/Wrapping/Tools/vtkParseHierarchy.h @@ -69,6 +69,7 @@ typedef struct _HierarchyEntry */ typedef struct _HierarchyInfo { + int MaxNumberOfEntries; int NumberOfEntries; HierarchyEntry *Entries; StringCache *Strings; @@ -79,10 +80,16 @@ extern "C" { #endif /** - * Read a hierarchy file into a HeirarchyInfo struct, or return NULL - */ +* Read a hierarchy file into a HeirarchyInfo struct, or return NULL +* XXX DEPRECATED; use vtkParseHierarchy_ReadFiles +*/ HierarchyInfo *vtkParseHierarchy_ReadFile(const char *filename); +/** + * Read hierarchy files into a HierarchyInfo struct, or return NULL + */ +HierarchyInfo *vtkParseHierarchy_ReadFiles(int n, char **filenames); + /** * Free a HierarchyInfo struct */ diff --git a/Wrapping/Tools/vtkParseJava.c b/Wrapping/Tools/vtkParseJava.c index 41a6b94e5c1..d8c9403da0c 100644 --- a/Wrapping/Tools/vtkParseJava.c +++ b/Wrapping/Tools/vtkParseJava.c @@ -833,6 +833,9 @@ int main(int argc, char *argv[]) FILE *fp; int i; + /* pre-define a macro to identify the language */ + vtkParse_DefineMacro("__VTK_WRAP_JAVA__", 0); + /* get command-line args and parse the header file */ file_info = vtkParse_Main(argc, argv); @@ -859,9 +862,10 @@ int main(int argc, char *argv[]) } /* get the hierarchy info for accurate typing */ - if (options->HierarchyFileName) + if (options->HierarchyFileNames) { - hierarchyInfo = vtkParseHierarchy_ReadFile(options->HierarchyFileName); + hierarchyInfo = vtkParseHierarchy_ReadFiles( + options->NumberOfHierarchyFileNames, options->HierarchyFileNames); if (hierarchyInfo) { /* resolve using declarations within the header files */ diff --git a/Wrapping/Tools/vtkParseJavaBeans.c b/Wrapping/Tools/vtkParseJavaBeans.c index 6fb49a72c06..e2e92479c46 100644 --- a/Wrapping/Tools/vtkParseJavaBeans.c +++ b/Wrapping/Tools/vtkParseJavaBeans.c @@ -682,9 +682,10 @@ void vtkParseOutput(FILE *fp, FileInfo *file_info) options = vtkParse_GetCommandLineOptions(); /* get the hierarchy info for accurate typing */ - if (options->HierarchyFileName) + if (options->HierarchyFileNames) { - hierarchyInfo = vtkParseHierarchy_ReadFile(options->HierarchyFileName); + hierarchyInfo = vtkParseHierarchy_ReadFiles( + options->NumberOfHierarchyFileNames, options->HierarchyFileNames); } fprintf(fp,"// java wrapper for %s object\n//\n",data->Name); diff --git a/Wrapping/Tools/vtkParseMain.c b/Wrapping/Tools/vtkParseMain.c index a41c7f070f2..05684b83b51 100644 --- a/Wrapping/Tools/vtkParseMain.c +++ b/Wrapping/Tools/vtkParseMain.c @@ -267,7 +267,10 @@ static int parse_check_options(int argc, char *argv[], int multi) options.InputFileName = NULL; options.OutputFileName = NULL; options.HierarchyFileName = 0; - options.HintFileName = 0; + options.NumberOfHierarchyFileNames = 0; + options.HierarchyFileNames = NULL; + options.NumberOfHintFileNames = 0; + options.HintFileNames = NULL; for (i = 1; i < argc; i++) { @@ -336,7 +339,16 @@ static int parse_check_options(int argc, char *argv[], int multi) { return -1; } - options.HintFileName = argv[i]; + if (options.NumberOfHintFileNames == 0) + { + options.HintFileNames = (char **)malloc(sizeof(char *)); + } + else if ((options.NumberOfHintFileNames & (options.NumberOfHintFileNames - 1)) == 0) + { + options.HintFileNames = (char **)realloc( + options.HintFileNames, 2 * options.NumberOfHintFileNames*sizeof(char *)); + } + options.HintFileNames[options.NumberOfHintFileNames++] = argv[i]; } else if (!multi && strcmp(argv[i], "--types") == 0) { @@ -345,7 +357,17 @@ static int parse_check_options(int argc, char *argv[], int multi) { return -1; } - options.HierarchyFileName = argv[i]; + if (options.NumberOfHierarchyFileNames == 0) + { + options.HierarchyFileNames = (char **)malloc(sizeof(char *)); + options.HierarchyFileName = argv[i]; // legacy + } + else if ((options.NumberOfHierarchyFileNames & (options.NumberOfHierarchyFileNames - 1)) == 0) + { + options.HierarchyFileNames = (char **)realloc( + options.HierarchyFileNames, 2*options.NumberOfHierarchyFileNames*sizeof(char *)); + } + options.HierarchyFileNames[options.NumberOfHierarchyFileNames++] = argv[i]; } else if (strcmp(argv[i], "--vtkobject") == 0 || strcmp(argv[i], "--special") == 0 || @@ -373,6 +395,9 @@ FileInfo *vtkParse_Main(int argc, char *argv[]) int expected_files; FILE *ifile; FILE *hfile = 0; + int nhfiles; + int ihfiles; + const char *hfilename; FileInfo *data; StringCache strings; int argn; @@ -381,6 +406,9 @@ FileInfo *vtkParse_Main(int argc, char *argv[]) /* set the command name for diagnostics */ vtkParse_SetCommandName(parse_exename(argv[0])); + /* pre-define the __VTK_WRAP__ macro */ + vtkParse_DefineMacro("__VTK_WRAP__", 0); + /* expand any "@file" args */ vtkParse_InitStringCache(&strings); parse_expand_args(&strings, argc, argv, &argn, &args); @@ -423,36 +451,14 @@ FileInfo *vtkParse_Main(int argc, char *argv[]) /* free the expanded args */ free(args); - /* open the hint file, if given on the command line */ - if (options.HintFileName && options.HintFileName[0] != '\0') - { - if (!(hfile = fopen(options.HintFileName, "r"))) - { - fprintf(stderr, "Error opening hint file %s\n", options.HintFileName); - fclose(ifile); - exit(1); - } - } - /* make sure than an output file was given on the command line */ if (options.OutputFileName == NULL) { fprintf(stderr, "No output file was specified\n"); fclose(ifile); - if (hfile) - { - fclose(hfile); - } exit(1); } - /* if a hierarchy is was given, then BTX/ETX can be ignored */ - vtkParse_SetIgnoreBTX(0); - if (options.HierarchyFileName) - { - vtkParse_SetIgnoreBTX(1); - } - /* parse the input file */ data = vtkParse_ParseFile(options.InputFileName, ifile, stderr); @@ -461,10 +467,24 @@ FileInfo *vtkParse_Main(int argc, char *argv[]) exit(1); } - /* fill in some blanks by using the hints file */ - if (hfile) + /* open and parse each hint file, if given on the command line */ + nhfiles = options.NumberOfHintFileNames; + for (ihfiles = 0; ihfiles < nhfiles; ihfiles++) { - vtkParse_ReadHints(data, hfile, stderr); + hfilename = options.HintFileNames[ihfiles]; + if (hfilename && hfilename[0] != '\0') + { + if (!(hfile = fopen(hfilename, "r"))) + { + fprintf(stderr, "Error opening hint file %s\n", hfilename); + fclose(ifile); + vtkParse_FreeFile(data); + exit(1); + } + + /* fill in some blanks by using the hints file */ + vtkParse_ReadHints(data, hfile, stderr); + } } if (data->MainClass) @@ -499,6 +519,9 @@ void vtkParse_MainMulti(int argc, char *argv[]) /* set the command name for diagnostics */ vtkParse_SetCommandName(parse_exename(argv[0])); + /* pre-define the __VTK_WRAP__ macro */ + vtkParse_DefineMacro("__VTK_WRAP__", 0); + /* expand any "@file" args */ vtkParse_InitStringCache(&strings); parse_expand_args(&strings, argc, argv, &argn, &args); diff --git a/Wrapping/Tools/vtkParseMain.h b/Wrapping/Tools/vtkParseMain.h index 4362fb8004b..847b155914e 100644 --- a/Wrapping/Tools/vtkParseMain.h +++ b/Wrapping/Tools/vtkParseMain.h @@ -51,12 +51,15 @@ */ typedef struct _OptionInfo { - int NumberOfFiles; /* the total number of file arguments */ - char **Files; /* all of the file arguments */ - char *InputFileName; /* the first file argument */ - char *OutputFileName; /* the second file, or the "-o" file */ - char *HintFileName; /* the file preceded by "--hints" */ - char *HierarchyFileName; /* the file preceded by "--types" */ + int NumberOfFiles; /* the total number of file arguments */ + char **Files; /* all of the file arguments */ + char *InputFileName; /* the first file argument */ + char *OutputFileName; /* the second file, or the "-o" file */ + int NumberOfHintFileNames; /* the total number of hints arguments */ + char **HintFileNames; /* all of the hints arguments */ + char *HierarchyFileName; /* the file preceded by "--types" XXX DEPRECATED */ + int NumberOfHierarchyFileNames; /* the total number of types argument */ + char **HierarchyFileNames; /* the file preceded by "--types" */ } OptionInfo; #ifdef __cplusplus diff --git a/Wrapping/Tools/vtkParseMerge.c b/Wrapping/Tools/vtkParseMerge.c index f8494a33929..8fe55bdf92a 100644 --- a/Wrapping/Tools/vtkParseMerge.c +++ b/Wrapping/Tools/vtkParseMerge.c @@ -518,7 +518,8 @@ int vtkParseMerge_Merge( * superclasses to "merge" */ void vtkParseMerge_MergeHelper( FileInfo *finfo, const NamespaceInfo *data, const HierarchyInfo *hinfo, - const char *classname, FILE *hintfile, MergeInfo *info, ClassInfo *merge) + const char *classname, int nhintfiles, char **hintfiles, MergeInfo *info, + ClassInfo *merge) { FILE *fp = NULL; ClassInfo *cinfo = NULL; @@ -532,6 +533,9 @@ void vtkParseMerge_MergeHelper( const char *filename; int i, j, n, m; int recurse; + FILE *hintfile = NULL; + int ihintfiles = 0; + const char *hintfilename = NULL; /* Note: this method does not deal with scoping yet. * "classname" might be a scoped name, in which case the @@ -597,7 +601,6 @@ void vtkParseMerge_MergeHelper( header = entry->HeaderFile; if (!header) { - if (hintfile) { fclose(hintfile); } fprintf(stderr, "Null header file for class %s!\n", classname); exit(1); } @@ -605,7 +608,6 @@ void vtkParseMerge_MergeHelper( filename = vtkParse_FindIncludeFile(header); if (!filename) { - if (hintfile) { fclose(hintfile); } fprintf(stderr, "Couldn't locate header file %s\n", header); exit(1); } @@ -613,7 +615,6 @@ void vtkParseMerge_MergeHelper( fp = fopen(filename, "r"); if (!fp) { - if (hintfile) { fclose(hintfile); } fprintf(stderr, "Couldn't open header file %s\n", header); exit(1); } @@ -623,14 +624,27 @@ void vtkParseMerge_MergeHelper( if (!finfo) { - if (hintfile) { fclose(hintfile); } exit(1); } - if (hintfile) + if (nhintfiles > 0 && hintfiles) { - rewind(hintfile); - vtkParse_ReadHints(finfo, hintfile, stderr); + for (ihintfiles = 0; ihintfiles < nhintfiles; ihintfiles++) + { + hintfilename = hintfiles[ihintfiles]; + if (hintfilename && hintfilename[0] != '\0') + { + if (!(hintfile = fopen(hintfilename, "r"))) + { + fprintf(stderr, "Error opening hint file %s\n", hintfilename); + vtkParse_FreeFile(finfo); + exit(1); + } + + vtkParse_ReadHints(finfo, hintfile, stderr); + fclose(hintfile); + } + } } data = finfo->Contents; @@ -709,7 +723,7 @@ void vtkParseMerge_MergeHelper( for (i = 0; i < n; i++) { vtkParseMerge_MergeHelper(finfo, data, hinfo, cinfo->SuperClasses[i], - hintfile, info, merge); + nhintfiles, hintfiles, info, merge); } } } @@ -725,7 +739,6 @@ void vtkParseMerge_MergeHelper( MergeInfo *vtkParseMerge_MergeSuperClasses( FileInfo *finfo, NamespaceInfo *data, ClassInfo *classInfo) { - FILE *hintfile = NULL; HierarchyInfo *hinfo = NULL; MergeInfo *info = NULL; OptionInfo *oinfo = NULL; @@ -733,14 +746,10 @@ MergeInfo *vtkParseMerge_MergeSuperClasses( oinfo = vtkParse_GetCommandLineOptions(); - if (oinfo->HierarchyFileName) + if (oinfo->HierarchyFileNames) { - hinfo = vtkParseHierarchy_ReadFile(oinfo->HierarchyFileName); - - if (oinfo->HintFileName) - { - hintfile = fopen(oinfo->HintFileName, "r"); - } + hinfo = vtkParseHierarchy_ReadFiles( + oinfo->NumberOfHierarchyFileNames, oinfo->HierarchyFileNames); info = vtkParseMerge_CreateMergeInfo(classInfo); @@ -749,12 +758,9 @@ MergeInfo *vtkParseMerge_MergeSuperClasses( { vtkParseMerge_MergeHelper(finfo, data, hinfo, classInfo->SuperClasses[i], - hintfile, info, classInfo); - } - - if (hintfile) - { - fclose(hintfile); + oinfo->NumberOfHintFileNames, + oinfo->HintFileNames, + info, classInfo); } } diff --git a/Wrapping/Tools/vtkParseMerge.h b/Wrapping/Tools/vtkParseMerge.h index 8e5d1bdb30b..0f84950917b 100644 --- a/Wrapping/Tools/vtkParseMerge.h +++ b/Wrapping/Tools/vtkParseMerge.h @@ -72,7 +72,8 @@ void vtkParseMerge_FreeMergeInfo(MergeInfo *info); */ void vtkParseMerge_MergeHelper( FileInfo *finfo, const NamespaceInfo *data, const HierarchyInfo *hinfo, - const char *classname, FILE *hintfile, MergeInfo *info, ClassInfo *merge); + const char *classname, int nhintfiles, char **hintfiles, MergeInfo *info, + ClassInfo *merge); #ifdef __cplusplus } /* extern "C" */ diff --git a/Wrapping/Tools/vtkWrap.c b/Wrapping/Tools/vtkWrap.c index bc49119ff16..6fd2f4424e1 100644 --- a/Wrapping/Tools/vtkWrap.c +++ b/Wrapping/Tools/vtkWrap.c @@ -16,6 +16,7 @@ #include "vtkWrap.h" #include "vtkParseData.h" #include "vtkParseExtras.h" +#include "vtkParseMain.h" #include "vtkParseMerge.h" #include "vtkParseString.h" #include @@ -657,7 +658,8 @@ void vtkWrap_FindCountHints( } /* add hints for array GetTuple methods */ - if (vtkWrap_IsTypeOf(hinfo, data->Name, "vtkDataArray")) + if (vtkWrap_IsTypeOf(hinfo, data->Name, "vtkDataArray") || + vtkWrap_IsTypeOf(hinfo, data->Name, "vtkArrayIterator")) { countMethod = "GetNumberOfComponents()"; @@ -666,7 +668,7 @@ void vtkWrap_FindCountHints( theFunc = data->Functions[i]; if ((strcmp(theFunc->Name, "GetTuple") == 0 || - strcmp(theFunc->Name, "GetTupleValue") == 0) && + strcmp(theFunc->Name, "GetTypedTuple") == 0) && theFunc->ReturnValue && theFunc->ReturnValue->Count == 0 && theFunc->NumberOfParameters == 1 && theFunc->Parameters[0]->Type == VTK_PARSE_ID_TYPE) @@ -674,11 +676,11 @@ void vtkWrap_FindCountHints( theFunc->ReturnValue->CountHint = countMethod; } else if ((strcmp(theFunc->Name, "SetTuple") == 0 || - strcmp(theFunc->Name, "SetTupleValue") == 0 || + strcmp(theFunc->Name, "SetTypedTuple") == 0 || strcmp(theFunc->Name, "GetTuple") == 0 || - strcmp(theFunc->Name, "GetTupleValue") == 0 || + strcmp(theFunc->Name, "GetTypedTuple") == 0 || strcmp(theFunc->Name, "InsertTuple") == 0 || - strcmp(theFunc->Name, "InsertTupleValue") == 0) && + strcmp(theFunc->Name, "InsertTypedTuple") == 0) && theFunc->NumberOfParameters == 2 && theFunc->Parameters[0]->Type == VTK_PARSE_ID_TYPE && theFunc->Parameters[1]->Count == 0) @@ -686,7 +688,7 @@ void vtkWrap_FindCountHints( theFunc->Parameters[1]->CountHint = countMethod; } else if ((strcmp(theFunc->Name, "InsertNextTuple") == 0 || - strcmp(theFunc->Name, "InsertNextTupleValue") == 0) && + strcmp(theFunc->Name, "InsertNextTypedTuple") == 0) && theFunc->NumberOfParameters == 1 && theFunc->Parameters[0]->Count == 0) { @@ -771,6 +773,7 @@ void vtkWrap_FindNewInstanceMethods( { int i; FunctionInfo *theFunc; + OptionInfo *options; for (i = 0; i < data->NumberOfFunctions; i++) { @@ -780,25 +783,17 @@ void vtkWrap_FindNewInstanceMethods( vtkWrap_IsVTKObjectBaseType(hinfo, theFunc->ReturnValue->Class)) { if (strcmp(theFunc->Name, "NewInstance") == 0 || - strcmp(theFunc->Name, "CreateInstance") == 0 || - (strcmp(theFunc->Name, "CreateLookupTable") == 0 && - strcmp(data->Name, "vtkColorSeries") == 0) || - (strcmp(theFunc->Name, "CreateImageReader2") == 0 && - strcmp(data->Name, "vtkImageReader2Factory") == 0) || - (strcmp(theFunc->Name, "CreateDataArray") == 0 && - strcmp(data->Name, "vtkDataArray") == 0) || - (strcmp(theFunc->Name, "CreateArray") == 0 && - strcmp(data->Name, "vtkAbstractArray") == 0) || - (strcmp(theFunc->Name, "CreateArray") == 0 && - strcmp(data->Name, "vtkArray") == 0) || - (strcmp(theFunc->Name, "GetQueryInstance") == 0 && - strcmp(data->Name, "vtkSQLDatabase") == 0) || - (strcmp(theFunc->Name, "CreateFromURL") == 0 && - strcmp(data->Name, "vtkSQLDatabase") == 0) || - (strcmp(theFunc->Name, "MakeTransform") == 0 && - vtkWrap_IsTypeOf(hinfo, data->Name, "vtkAbstractTransform"))) + strcmp(theFunc->Name, "NewIterator") == 0 || + strcmp(theFunc->Name, "CreateInstance") == 0) { - theFunc->ReturnValue->Type |= VTK_PARSE_NEWINSTANCE; + if ((theFunc->ReturnValue->Type & VTK_PARSE_NEWINSTANCE) == 0) + { + /* get the command-line options */ + options = vtkParse_GetCommandLineOptions(); + fprintf(stderr, "Warning: %s without VTK_NEWINSTANCE hint in %s\n", + theFunc->Name, options->InputFileName); + theFunc->ReturnValue->Type |= VTK_PARSE_NEWINSTANCE; + } } } } @@ -871,7 +866,7 @@ void vtkWrap_ApplyUsingDeclarations( { vtkParseMerge_MergeHelper( finfo, finfo->Contents, hinfo, data->SuperClasses[i], - NULL, NULL, data); + 0, NULL, NULL, data); } } } diff --git a/Wrapping/Tools/vtkWrapHierarchy.c b/Wrapping/Tools/vtkWrapHierarchy.c index fa9e00648a4..fbc4e83ca33 100644 --- a/Wrapping/Tools/vtkWrapHierarchy.c +++ b/Wrapping/Tools/vtkWrapHierarchy.c @@ -576,9 +576,6 @@ static char **vtkWrapHierarchy_ParseHeaderFile( lines[0] = NULL; } - /* always ignore BTX markers when building hierarchy files */ - vtkParse_SetIgnoreBTX(1); - /* the "concrete" flag doesn't matter, just set to zero */ data = vtkParse_ParseFile(filename, fp, stderr); diff --git a/Wrapping/Tools/vtkWrapJava.c b/Wrapping/Tools/vtkWrapJava.c index 286fe8d99c2..eb1f6b6efcf 100644 --- a/Wrapping/Tools/vtkWrapJava.c +++ b/Wrapping/Tools/vtkWrapJava.c @@ -1248,6 +1248,9 @@ int main(int argc, char *argv[]) FILE *fp; int i; + /* pre-define a macro to identify the language */ + vtkParse_DefineMacro("__VTK_WRAP_JAVA__", 0); + /* get command-line args and parse the header file */ file_info = vtkParse_Main(argc, argv); @@ -1274,9 +1277,10 @@ int main(int argc, char *argv[]) } /* get the hierarchy info for accurate typing */ - if (options->HierarchyFileName) + if (options->HierarchyFileNames) { - hierarchyInfo = vtkParseHierarchy_ReadFile(options->HierarchyFileName); + hierarchyInfo = vtkParseHierarchy_ReadFiles( + options->NumberOfHierarchyFileNames, options->HierarchyFileNames); if (hierarchyInfo) { /* resolve using declarations within the header files */ diff --git a/Wrapping/Tools/vtkWrapPython.c b/Wrapping/Tools/vtkWrapPython.c index af31c25a946..5ebd9548ddb 100644 --- a/Wrapping/Tools/vtkWrapPython.c +++ b/Wrapping/Tools/vtkWrapPython.c @@ -165,6 +165,12 @@ static void vtkWrapPython_GenerateSpecialHeaders( types = (const char **)malloc(1000*sizeof(const char *)); + /* always include vtkVariant, it is often used as a template arg + for templated array types, and the file_info doesn't tell us + what types each templated class is instantiated for (that info + might be in the .cxx files, which we cannot access here) */ + types[numTypes++] = "vtkVariant"; + nn = file_info->Contents->NumberOfClasses; for (ii = 0; ii < nn; ii++) { @@ -299,6 +305,9 @@ int main(int argc, char *argv[]) size_t k, m; int is_vtkobject; + /* pre-define a macro to identify the language */ + vtkParse_DefineMacro("__VTK_WRAP_PYTHON__", 0); + /* get command-line args and parse the header file */ file_info = vtkParse_Main(argc, argv); @@ -315,9 +324,10 @@ int main(int argc, char *argv[]) } /* get the hierarchy info for accurate typing */ - if (options->HierarchyFileName) + if (options->HierarchyFileNames) { - hinfo = vtkParseHierarchy_ReadFile(options->HierarchyFileName); + hinfo = vtkParseHierarchy_ReadFiles( + options->NumberOfHierarchyFileNames, options->HierarchyFileNames); } /* get the filename without the extension */ @@ -375,6 +385,7 @@ int main(int argc, char *argv[]) "#include \"vtkPythonArgs.h\"\n" "#include \"vtkPythonOverload.h\"\n" "#include \"vtkConfigure.h\"\n" + "#include \n" "#include \n"); /* vtkPythonCommand is needed to wrap vtkObject.h */ diff --git a/Wrapping/Tools/vtkWrapPythonClass.c b/Wrapping/Tools/vtkWrapPythonClass.c index 224d95f4c09..59f97086bb8 100644 --- a/Wrapping/Tools/vtkWrapPythonClass.c +++ b/Wrapping/Tools/vtkWrapPythonClass.c @@ -550,9 +550,29 @@ void vtkWrapPython_GenerateObjectType( " PyVTKObject_Traverse, // tp_traverse\n" " 0, // tp_clear\n" " 0, // tp_richcompare\n" - " offsetof(PyVTKObject, vtk_weakreflist), // tp_weaklistoffset\n" - " 0, // tp_iter\n" - " 0, // tp_iternext\n" + " offsetof(PyVTKObject, vtk_weakreflist), // tp_weaklistoffset\n"); + if (strcmp(classname, "vtkCollection") == 0) + { + fprintf(fp, + " PyvtkCollection_iter, // tp_iter\n" + " 0, // tp_iternext\n"); + } + else + { + if(strcmp(classname, "vtkCollectionIterator") == 0) + { + fprintf(fp, + " PyvtkCollectionIterator_iter, // tp_iter\n" + " PyvtkCollectionIterator_next, // tp_iternext\n"); + } + else + { + fprintf(fp, + " 0, // tp_iter\n" + " 0, // tp_iternext\n"); + } + } + fprintf(fp, " 0, // tp_methods\n" " 0, // tp_members\n" " PyVTKObject_GetSet, // tp_getset\n" diff --git a/Wrapping/Tools/vtkWrapPythonInit.c b/Wrapping/Tools/vtkWrapPythonInit.c index 0debb4e73d6..9750ae4e434 100644 --- a/Wrapping/Tools/vtkWrapPythonInit.c +++ b/Wrapping/Tools/vtkWrapPythonInit.c @@ -169,7 +169,8 @@ int main(int argc,char *argv[]) } /* extra functions, types, etc. for the CommonCore module */ - if (strcmp(libName, "vtkCommonCorePython") == 0) + if (strcmp(libName, "vtkCommonCorePython") == 0 || + strcmp(libName, "vtkCommonKitPython") == 0) { files[numFiles] = strdup("PyVTKExtras"); numFiles++; diff --git a/Wrapping/Tools/vtkWrapPythonMethodDef.c b/Wrapping/Tools/vtkWrapPythonMethodDef.c index b2a8552c625..3a5cfdc6ee8 100644 --- a/Wrapping/Tools/vtkWrapPythonMethodDef.c +++ b/Wrapping/Tools/vtkWrapPythonMethodDef.c @@ -410,6 +410,14 @@ static void vtkWrapPython_ClassMethodDef( classname); } + /* vtkObject needs a special entry for InvokeEvent */ + if (strcmp("vtkObject", data->Name) == 0) + { + fprintf(fp, + "{\"InvokeEvent\", PyvtkObject_InvokeEvent, METH_VARARGS,\n" + " \"V.InvokeEvent(int, void) -> int\\nC++: int InvokeEvent(unsigned long event, void *callData)\\nV.InvokeEvent(string, void) -> int\\nC++: int InvokeEvent(const char *event, void *callData)\\nV.InvokeEvent(int) -> int\\nC++: int InvokeEvent(unsigned long event)\\nV.InvokeEvent(string) -> int\\nC++: int InvokeEvent(const char *event)\\n\\nThis method invokes an event and return whether the event was\\naborted or not. If the event was aborted, the return value is 1,\\notherwise it is 0.\"\n},\n"); + } + /* vtkObjectBase needs GetAddressAsString, UnRegister */ else if (strcmp("vtkObjectBase", data->Name) == 0) { @@ -604,6 +612,7 @@ int vtkWrapPython_MethodCheck( return 1; } + /* -------------------------------------------------------------------- */ /* generate code for custom methods for some classes */ static void vtkWrapPython_CustomMethods( @@ -720,6 +729,140 @@ static void vtkWrapPython_CustomMethods( "\n"); } + + /* the python vtkObject needs a special InvokeEvent to turn any + calldata into an appropriately unwrapped void pointer */ + if (strcmp("vtkObject", data->Name) == 0 && + do_constructors == 0) + { + + /* different types of callback data */ + + int numCallBackTypes = 5; + + static const char *callBackTypeString[] = + {"z", "", "i", "d", "V"}; + static const char *fullCallBackTypeString[] = + {"z", "", "i", "d", "V *vtkObjectBase"}; + static const char *callBackTypeDecl[] = + {"char *calldata = NULL;", + "", + "long calldata;", + "double calldata;", + "vtkObjectBase *calldata = NULL;"}; + static const char *callBackReadArg[] = + {"pyArgs.GetValue(calldata)", + "1", + "pyArgs.GetValue(calldata)", + "pyArgs.GetValue(calldata)", + "pyArgs.GetVTKObject(calldata, \"vtkObject\")"}; + + static const char *methodCallSecondHalf[] = + {", calldata", + "", + ", &calldata", + ", &calldata", + ", calldata"}; + + /* two ways to refer to an event */ + static const char *eventTypeString[] = {"L", "z"}; + static const char *eventTypeDecl[] = {"unsigned long event;", + "char *event = NULL;"}; + + int callBackIdx, eventIdx; + + /* Remove the original InvokeEvent method */ + for (i = 0; i < data->NumberOfFunctions; i++) + { + theFunc = data->Functions[i]; + + if (theFunc->Name && strcmp(theFunc->Name, "InvokeEvent") == 0) + { + data->Functions[i]->Name = NULL; + } + } + + /* Add the InvokeEvent method to vtkObject. */ + fprintf(fp, + "// This collection of methods that handle InvokeEvent are\n" + "//generated by a special case in vtkWrapPythonMethodDef.c\n" + "//The last characters of the method name indicate the type signature\n" + "//of the overload they handle: for example, \"_zd\" indicates that\n" + "//the event type is specified by string and the calldata is a double\n"); + + for(callBackIdx = 0; callBackIdx < numCallBackTypes; callBackIdx++) + { + for(eventIdx = 0; eventIdx < 2; eventIdx++) + { + fprintf(fp, + "static PyObject *\n" + "PyvtkObject_InvokeEvent_%s%s(PyObject *self, PyObject *args)\n" + "{\n" + " vtkPythonArgs pyArgs(self, args, \"InvokeEvent\");\n" + " vtkObjectBase *vp = pyArgs.GetSelfPointer(self, args);\n" + " vtkObject *unwrappedSelf = static_cast(vp);\n" + "\n" + " %s\n" + " %s\n" + " PyObject *result = NULL;\n" + "\n" + " if (unwrappedSelf &&\n" + " pyArgs.GetValue(event) &&\n" + " %s)\n" + " {\n" + " int unwrappedResult = unwrappedSelf->InvokeEvent(event%s);\n" + "\n" + " if (!pyArgs.ErrorOccurred())\n" + " {\n" + " result = pyArgs.BuildValue(unwrappedResult);\n" + " }\n" + " }\n" + " return result;\n" + "}\n" + "\n", + eventTypeString[eventIdx], + callBackTypeString[callBackIdx], + eventTypeDecl[eventIdx], + callBackTypeDecl[callBackIdx], + callBackReadArg[callBackIdx], + methodCallSecondHalf[callBackIdx]); + } + } + fprintf(fp, + "static PyMethodDef PyvtkObject_InvokeEvent_Methods[] = {\n"); + for(callBackIdx = 0; callBackIdx < numCallBackTypes; callBackIdx++) + { + for(eventIdx = 0; eventIdx < 2; eventIdx++) + { + fprintf(fp, + " {NULL, PyvtkObject_InvokeEvent_%s%s, METH_VARARGS,\n" + " \"@%s%s\"},\n", + eventTypeString[eventIdx], + callBackTypeString[callBackIdx], + eventTypeString[eventIdx], + fullCallBackTypeString[callBackIdx]); + } + } + + fprintf(fp, + " {NULL, NULL, 0, NULL}\n" + "};\n" + "\n" + "static PyObject *\n" + "PyvtkObject_InvokeEvent(PyObject *self, PyObject *args)\n" + "{\n" + " PyMethodDef *methods = PyvtkObject_InvokeEvent_Methods;\n" + " int nargs = vtkPythonArgs::GetArgCount(self, args);\n" + " \n" + " if (nargs == 1 || nargs == 2)\n" + " {\n" + " return vtkPythonOverload::CallMethod(methods, self, args);\n" + " }\n" + "\n" + " vtkPythonArgs::ArgCountError(nargs, \"InvokeEvent\");\n" + " return NULL;\n" + "}\n"); + } /* the python vtkObjectBase needs a couple extra functions */ if (strcmp("vtkObjectBase", data->Name) == 0 && do_constructors == 0) @@ -873,4 +1016,59 @@ static void vtkWrapPython_CustomMethods( "\n", classname, data->Name, data->Name, data->Name); } + if (strcmp("vtkCollection", data->Name) == 0 && + do_constructors == 0) + { + fprintf(fp, + "static PyObject *\n" + "PyvtkCollection_iter(PyObject *self)\n" + "{\n" + " PyVTKObject* vp = (PyVTKObject *) self;\n" + " vtkCollection *op = (vtkCollection* ) vp->vtk_ptr; \n" + " \n" + " PyObject *result = NULL;\n" + " \n" + " if (op)\n" + " {\n" + " vtkObject *tempr = (vtkObject *) op->NewIterator();\n" + " if (tempr != NULL)\n" + " {\n" + " result = vtkPythonArgs::BuildVTKObject(tempr);\n" + " tempr->UnRegister(0);\n" + " }\n" + " }\n" + "\n" + " return result;\n" + "}\n"); + } + if (strcmp("vtkCollectionIterator", data->Name) == 0 && + do_constructors == 0) + { + fprintf(fp, + "static PyObject * PyvtkCollectionIterator_next(PyObject *self)\n" + "{\n" + " PyVTKObject* vp = (PyVTKObject *) self;\n" + " vtkCollectionIterator *op = (vtkCollectionIterator* ) vp->vtk_ptr; \n" + " \n" + " PyObject *result = NULL;\n" + " \n" + " if (op)\n" + " {\n" + " vtkObject *tempr = op->GetCurrentObject();\n" + " op->GoToNextItem();\n" + " if (tempr != NULL)\n" + " {\n" + " result = vtkPythonArgs::BuildVTKObject(tempr);\n" + " }\n" + " }\n" + "\n" + " return result;\n" + "}\n" + "\n" + "static PyObject *PyvtkCollectionIterator_iter(PyObject *self)\n" + "{\n" + " Py_INCREF(self);\n" + " return self;\n" + "}\n"); + } } diff --git a/Wrapping/Tools/vtkWrapPythonTemplate.c b/Wrapping/Tools/vtkWrapPythonTemplate.c index 31495ed30c0..eb04bdd4a9d 100644 --- a/Wrapping/Tools/vtkWrapPythonTemplate.c +++ b/Wrapping/Tools/vtkWrapPythonTemplate.c @@ -264,7 +264,8 @@ int vtkWrapPython_WrapTemplatedClass( types = NULL; /* only do these classes directly */ - if (strcmp(entry->Name, "vtkDenseArray") == 0 || + if (strcmp(entry->Name, "vtkArrayIteratorTemplate") == 0 || + strcmp(entry->Name, "vtkDenseArray") == 0 || strcmp(entry->Name, "vtkSparseArray") == 0) { types = vtkParse_GetArrayTypes(); diff --git a/Wrapping/Tools/vtkWrapTcl.c b/Wrapping/Tools/vtkWrapTcl.c index 53d077bf550..cc978c0314c 100644 --- a/Wrapping/Tools/vtkWrapTcl.c +++ b/Wrapping/Tools/vtkWrapTcl.c @@ -1093,6 +1093,9 @@ int main(int argc, char *argv[]) FILE *fp; int i,j,k; + /* pre-define a macro to identify the language */ + vtkParse_DefineMacro("__VTK_WRAP_TCL__", 0); + /* get command-line args and parse the header file */ file_info = vtkParse_Main(argc, argv); @@ -1119,9 +1122,10 @@ int main(int argc, char *argv[]) } /* get the hierarchy info for accurate typing */ - if (options->HierarchyFileName) + if (options->HierarchyFileNames) { - hierarchyInfo = vtkParseHierarchy_ReadFile(options->HierarchyFileName); + hierarchyInfo = vtkParseHierarchy_ReadFiles( + options->NumberOfHierarchyFileNames, options->HierarchyFileNames); if (hierarchyInfo) { /* resolve using declarations within the header files */