From 57350b43a1832dfbd60497a146ee8dbaca9e96d1 Mon Sep 17 00:00:00 2001 From: hda Date: Fri, 7 Aug 2015 17:13:39 +0200 Subject: [PATCH 1/9] cmake : ensure that zlib is link with for the arnold procedural (seem to be need when using .prt) --- contrib/partio4Arnold/procedurals/CMakeLists.txt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/contrib/partio4Arnold/procedurals/CMakeLists.txt b/contrib/partio4Arnold/procedurals/CMakeLists.txt index 493992d3..5447d2c6 100644 --- a/contrib/partio4Arnold/procedurals/CMakeLists.txt +++ b/contrib/partio4Arnold/procedurals/CMakeLists.txt @@ -122,6 +122,11 @@ elseif(UNIX) SET(PARTIO_LIB libpartio.a) ENDIF() +SET(ZLIB "z") + +MESSAGE("CMakeLists.txt : partio4Arnold procedurals ZLIB = ${ZLIB}") +MESSAGE("CMakeLists.txt : partio4Arnold procedurals PARTIO_LIB = ${ZLIB}") + ADD_LIBRARY(${PLUGIN_NAME} SHARED ${TARGET_H} ${TARGET_SRC}) set_target_properties(${PLUGIN_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ./ ) From 6fb3c253f1901eba5326284a74c46734d127e762 Mon Sep 17 00:00:00 2001 From: hda Date: Fri, 7 Aug 2015 17:20:07 +0200 Subject: [PATCH 2/9] cmake : ensure that zlib is link with the arnold procedural (seem to be need when using .prt) --- contrib/partio4Arnold/procedurals/CMakeLists.txt | 4 ---- contrib/partio4Maya/plugin.cpp | 1 + 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/contrib/partio4Arnold/procedurals/CMakeLists.txt b/contrib/partio4Arnold/procedurals/CMakeLists.txt index 5447d2c6..8ff6f172 100644 --- a/contrib/partio4Arnold/procedurals/CMakeLists.txt +++ b/contrib/partio4Arnold/procedurals/CMakeLists.txt @@ -124,10 +124,6 @@ ENDIF() SET(ZLIB "z") -MESSAGE("CMakeLists.txt : partio4Arnold procedurals ZLIB = ${ZLIB}") -MESSAGE("CMakeLists.txt : partio4Arnold procedurals PARTIO_LIB = ${ZLIB}") - - ADD_LIBRARY(${PLUGIN_NAME} SHARED ${TARGET_H} ${TARGET_SRC}) set_target_properties(${PLUGIN_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ./ ) set_target_properties(${PLUGIN_NAME} PROPERTIES PREFIX "") diff --git a/contrib/partio4Maya/plugin.cpp b/contrib/partio4Maya/plugin.cpp index aecc8d9f..731e1be0 100644 --- a/contrib/partio4Maya/plugin.cpp +++ b/contrib/partio4Maya/plugin.cpp @@ -46,6 +46,7 @@ MStatus initializePlugin ( MObject obj ) MGlobal::executeCommand("source AEpartioInstancerTemplate.mel"); MGlobal::executeCommand("source partioExportGui.mel"); MGlobal::executeCommand("source partioUtils.mel"); + MGlobal::executeCommand("source shelf_Partio4Maya.mel"); MStatus status; MFnPlugin plugin ( obj, "RedpawFX,Luma Pictures,WDAS", "0.9.8", "Any" ); From 9e4b08239b9da065603f033c424b362ea44a7c1e Mon Sep 17 00:00:00 2001 From: hda Date: Fri, 7 Aug 2015 17:42:11 +0200 Subject: [PATCH 3/9] remove last 2 last bad commits --- contrib/partio4Arnold/procedurals/CMakeLists.txt | 1 - contrib/partio4Maya/plugin.cpp | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/contrib/partio4Arnold/procedurals/CMakeLists.txt b/contrib/partio4Arnold/procedurals/CMakeLists.txt index 8ff6f172..493992d3 100644 --- a/contrib/partio4Arnold/procedurals/CMakeLists.txt +++ b/contrib/partio4Arnold/procedurals/CMakeLists.txt @@ -122,7 +122,6 @@ elseif(UNIX) SET(PARTIO_LIB libpartio.a) ENDIF() -SET(ZLIB "z") ADD_LIBRARY(${PLUGIN_NAME} SHARED ${TARGET_H} ${TARGET_SRC}) set_target_properties(${PLUGIN_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ./ ) diff --git a/contrib/partio4Maya/plugin.cpp b/contrib/partio4Maya/plugin.cpp index 731e1be0..35bd2de6 100644 --- a/contrib/partio4Maya/plugin.cpp +++ b/contrib/partio4Maya/plugin.cpp @@ -45,8 +45,7 @@ MStatus initializePlugin ( MObject obj ) MGlobal::executeCommand("source AEpartioVisualizerTemplate.mel"); MGlobal::executeCommand("source AEpartioInstancerTemplate.mel"); MGlobal::executeCommand("source partioExportGui.mel"); - MGlobal::executeCommand("source partioUtils.mel"); - MGlobal::executeCommand("source shelf_Partio4Maya.mel"); + MGlobal::executeCommand("source partioUtils.mel"); MStatus status; MFnPlugin plugin ( obj, "RedpawFX,Luma Pictures,WDAS", "0.9.8", "Any" ); From 332af33fe355838d11887cd0d4f93f24f8a20058 Mon Sep 17 00:00:00 2001 From: hda Date: Fri, 7 Aug 2015 18:01:50 +0200 Subject: [PATCH 4/9] partio4Maya : create the partio shelves when loading the plug if not present --- contrib/partio4Maya/plugin.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contrib/partio4Maya/plugin.cpp b/contrib/partio4Maya/plugin.cpp index 35bd2de6..95381a17 100644 --- a/contrib/partio4Maya/plugin.cpp +++ b/contrib/partio4Maya/plugin.cpp @@ -45,7 +45,8 @@ MStatus initializePlugin ( MObject obj ) MGlobal::executeCommand("source AEpartioVisualizerTemplate.mel"); MGlobal::executeCommand("source AEpartioInstancerTemplate.mel"); MGlobal::executeCommand("source partioExportGui.mel"); - MGlobal::executeCommand("source partioUtils.mel"); + MGlobal::executeCommand("source partioUtils.mel"); + MGlobal::executeCommand("source shelf_Partio4Maya.mel"); MStatus status; MFnPlugin plugin ( obj, "RedpawFX,Luma Pictures,WDAS", "0.9.8", "Any" ); From 497061eb0ade94cc12726c5a1db544e66ae94afd Mon Sep 17 00:00:00 2001 From: hda Date: Fri, 7 Aug 2015 18:34:57 +0200 Subject: [PATCH 5/9] partio4Arnold : modify build file to ensure zlib is linked : (needed for .prt input) --- contrib/partio4Arnold/procedurals/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/contrib/partio4Arnold/procedurals/CMakeLists.txt b/contrib/partio4Arnold/procedurals/CMakeLists.txt index 493992d3..8ff6f172 100644 --- a/contrib/partio4Arnold/procedurals/CMakeLists.txt +++ b/contrib/partio4Arnold/procedurals/CMakeLists.txt @@ -122,6 +122,7 @@ elseif(UNIX) SET(PARTIO_LIB libpartio.a) ENDIF() +SET(ZLIB "z") ADD_LIBRARY(${PLUGIN_NAME} SHARED ${TARGET_H} ${TARGET_SRC}) set_target_properties(${PLUGIN_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ./ ) From e48f244a0b979dde6e148bbb43729908b8bed90c Mon Sep 17 00:00:00 2001 From: hda Date: Thu, 13 Aug 2015 11:03:52 +0200 Subject: [PATCH 6/9] Disable the build of partioHoudini (did not take the time to make it pass) --- contrib/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contrib/CMakeLists.txt b/contrib/CMakeLists.txt index 636fcac4..73eb983c 100644 --- a/contrib/CMakeLists.txt +++ b/contrib/CMakeLists.txt @@ -1,5 +1,5 @@ add_subdirectory(partio4Maya) if(NOT WIN32 AND NOT APPLE) add_subdirectory(partio4Arnold) - add_subdirectory(partio4Houdini) + #add_subdirectory(partio4Houdini) endif(NOT WIN32 AND NOT APPLE) From cb9a06eeecdd248cd832217cdb96adeaac726754 Mon Sep 17 00:00:00 2001 From: hda Date: Tue, 21 Mar 2017 14:39:55 +0100 Subject: [PATCH 7/9] portage for mtoa 1.4 --- .idea/misc.xml | 14 + .idea/modules.xml | 8 + .idea/partio.iml | 11 + .idea/vcs.xml | 6 + .idea/workspace.xml | 238 ++ CMakeLists.txt | 81 +- build.sh | 107 + contrib/CMakeLists.txt | 44 +- contrib/cmake/FindArnold.cmake | 3 + contrib/cmake/FindMaya.cmake | 93 +- contrib/cmake/FindMtoA.cmake | 39 +- contrib/partio4Arnold/CMakeLists.txt | 32 +- contrib/partio4Arnold/plugin/CMakeLists.txt | 300 ++- .../plugin/PartioVizTranslator.cpp | 446 ++-- .../plugin/PartioVizTranslator.h | 134 +- .../partio4Arnold/plugin/partioTranslator.py | 7 +- contrib/partio4Arnold/plugin/plugin.cpp | 47 +- .../partio4Arnold/procedurals/CMakeLists.txt | 168 +- .../procedurals/partioGenerator.cpp | 1056 ++++----- contrib/partio4Houdini/CMakeLists.txt | 92 +- contrib/partio4Maya/CMakeLists.txt | 195 +- contrib/partio4Maya/partio4MayaShared.cpp | 60 +- contrib/partio4Maya/partio4MayaShared.h | 3 +- contrib/partio4Maya/partioEmitter.cpp | 580 ++--- contrib/partio4Maya/partioExport.cpp | 565 +++-- contrib/partio4Maya/partioImport.cpp | 144 +- contrib/partio4Maya/partioInstancer.cpp | 1926 +++++++++-------- contrib/partio4Maya/partioInstancer.h | 259 +-- contrib/partio4Maya/partioVisualizer.cpp | 1350 +++++------- contrib/partio4Maya/partioVisualizer.h | 128 +- .../partioVisualizerDrawOverride.cpp | 495 +++++ .../partioVisualizerDrawOverride.h | 42 + contrib/partio4Maya/plugin.cpp | 90 +- .../scripts/AEpartioInstancerTemplate.mel | 510 ++--- .../scripts/AEpartioVisualizerTemplate.mel | 271 +-- .../partio4Maya/scripts/partioExportGui.mel | 2 +- contrib/partio4Maya/scripts/partioUtils.mel | 2 +- src/houdini/CMakeLists.txt | 29 +- src/lib/CMakeLists.txt | 16 +- src/lib/Partio.h | 6 +- src/lib/PartioAttribute.h | 9 +- src/lib/PartioConfig.h | 49 + src/lib/PartioIterator.h | 6 +- src/lib/core/KdTree.h | 6 +- src/lib/core/Mutex.h | 6 +- src/lib/core/Particle.cpp | 5 +- src/lib/core/ParticleCaching.cpp | 4 +- src/lib/core/ParticleCaching.h | 6 +- src/lib/core/ParticleHeaders.cpp | 3 +- src/lib/core/ParticleHeaders.h | 8 +- src/lib/core/ParticleSimple.cpp | 4 +- src/lib/core/ParticleSimple.h | 4 +- src/lib/core/ParticleSimpleInterleave.cpp | 3 +- src/lib/core/ParticleSimpleInterleave.h | 5 +- src/lib/io/3rdParty/nextLimit/FileReader.cpp | 4 + src/lib/io/3rdParty/nextLimit/FileReader.h | 6 + src/lib/io/3rdParty/nextLimit/RPCReader.cpp | 4 + src/lib/io/3rdParty/nextLimit/RPCReader.h | 6 + src/lib/io/BGEO.cpp | 5 +- src/lib/io/BIN.cpp | 4 +- src/lib/io/GEO.cpp | 5 +- src/lib/io/MC.cpp | 5 +- src/lib/io/NEW_BGEO.cpp | 6 +- src/lib/io/PCD.cpp | 5 +- src/lib/io/PDA.cpp | 5 +- src/lib/io/PDB.cpp | 13 +- src/lib/io/PDC.cpp | 4 +- src/lib/io/PRT.cpp | 4 +- src/lib/io/PTC.cpp | 5 +- src/lib/io/PTS.cpp | 5 +- src/lib/io/ParticleIO.cpp | 4 +- src/lib/io/PartioBinaryJson.h | 4 +- src/lib/io/PartioEndian.h | 7 +- src/lib/io/RIB.cpp | 6 +- src/lib/io/RPC.cpp | 5 +- src/lib/io/XYZ.cpp | 5 +- src/lib/io/ZIP.cpp | 5 +- src/lib/io/ZIP.h | 8 +- src/lib/io/pdb.h | 2 - src/lib/io/readers.h | 6 +- src/py/CMakeLists.txt | 58 +- src/py/cmake/FindNumPy.cmake | 45 +- src/py/partio.i | 15 +- src/tests/CMakeLists.txt | 6 +- src/tests/jsontest.cpp | 4 +- src/tests/makecircle.cpp | 8 +- src/tests/makeline.cpp | 20 +- src/tools/CMakeLists.txt | 37 +- src/tools/partattr.cpp | 4 +- src/tools/partconv.cpp | 6 +- src/tools/partinfo.cpp | 16 +- src/tools/partview.cpp | 8 +- src/tools/partview.h | 9 +- 93 files changed, 5531 insertions(+), 4560 deletions(-) create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/partio.iml create mode 100644 .idea/vcs.xml create mode 100644 .idea/workspace.xml create mode 100755 build.sh create mode 100644 contrib/partio4Maya/partioVisualizerDrawOverride.cpp create mode 100644 contrib/partio4Maya/partioVisualizerDrawOverride.h mode change 100755 => 100644 contrib/partio4Maya/scripts/AEpartioInstancerTemplate.mel mode change 100755 => 100644 contrib/partio4Maya/scripts/AEpartioVisualizerTemplate.mel create mode 100644 src/lib/PartioConfig.h diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 00000000..7c4b884a --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 00000000..3288d7d1 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/partio.iml b/.idea/partio.iml new file mode 100644 index 00000000..67116063 --- /dev/null +++ b/.idea/partio.iml @@ -0,0 +1,11 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 00000000..94a25f7f --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 00000000..423fbbe9 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,238 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1488995601417 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 50a35410..2f409f40 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -87,35 +87,35 @@ IF(WIN32) SET( SWIG_EXECUTABLE "${PARTIO_HOME}/winReqLibs/swigwin-2.0.4/swig.exe") SET( PARTIO_BUILD_PLATFORM "windows_x86_64") set(CMAKE_MODULE_PATH ${PARTIO_HOME}/cmake) - ELSE(WIN32) ADD_DEFINITIONS (-Wextra -Wno-unused-parameter) SET( CMAKE_CXX_FLAGS "-fPIC") ENDIF(WIN32) -## Set install location -IF (UNIX) - #EXECUTE_PROCESS(COMMAND sh -c "echo `uname`-`uname -r | cut -d'-' -f1`-`uname -m`" OUTPUT_VARIABLE VARIANT_DIRECTORY OUTPUT_STRIP_TRAILING_WHITESPACE) - EXECUTE_PROCESS(COMMAND sh -c "echo `uname`-`uname -m`" OUTPUT_VARIABLE VARIANT_DIRECTORY OUTPUT_STRIP_TRAILING_WHITESPACE) - SET(PARTIO_BUILD_PLATFORM "${VARIANT_DIRECTORY}") - MESSAGE(STATUS "Build Platform: ${PARTIO_BUILD_PLATFORM}") +# to switch between rez and local install paths +SET (LOCAL_INSTALL 0) +## Set install location +IF ( ${CMAKE_INSTALL_PREFIX} STREQUAL "/usr/local") + message(STATUS "CMAKE INSTALL PREFIX being changed to local build") + SET (LOCAL_INSTALL 1) + IF (UNIX) + EXECUTE_PROCESS(COMMAND sh -c "echo `uname`-`uname -m`" OUTPUT_VARIABLE VARIANT_DIRECTORY OUTPUT_STRIP_TRAILING_WHITESPACE) + SET(PARTIO_BUILD_PLATFORM "${VARIANT_DIRECTORY}") + MESSAGE(STATUS "Build Platform: ${PARTIO_BUILD_PLATFORM}") + ENDIF(UNIX) + +SET(CMAKE_INSTALL_PREFIX ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/) ENDIF() -# output executable and library path -SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/outputs/lib/${PARTIO_BUILD_PLATFORM}) -SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/outputs/bin/${PARTIO_BUILD_PLATFORM}) - -# output executable and library path -SET(EXECUTABLE_INSTALL_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/bin/${PARTIO_BUILD_PLATFORM}) -SET(LIBRARY_INSTALL_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/lib/${PARTIO_BUILD_PLATFORM}) -SET(INCLUDE_INSTALL_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/include) +message(STATUS "CMAKE INSTALL PREFIX = ${CMAKE_INSTALL_PREFIX}") ## Search for needed libraries find_package(SWIG REQUIRED) ## Search for useful libraries find_package(GLUT REQUIRED) + IF(GLUT_FOUND) INCLUDE_DIRECTORIES( ${GLUT_INCLUDE_PATH} ) LINK_DIRECTORIES (${GLUT_ROOT_PATH}/lib/x64) @@ -124,6 +124,12 @@ ELSE(GLUT_FOUND) LINK_DIRECTORIES ( ${GLUT_LIBRARY_PATH} ) ENDIF(GLUT_FOUND) +################################################################################ HDA TMP +message(STATUS " partio/CMakeLists.txt : GLEW_INCLUDE_DIR = ${GLEW_INCLUDE_DIR}") + +INCLUDE_DIRECTORIES( ${GLEW_INCLUDE_DIR} ) +################################################################################ HDA TMP + find_package(OpenGL REQUIRED) find_package(ZLIB REQUIRED) @@ -150,13 +156,42 @@ ENDIF() # make it so partio can be found INCLUDE_DIRECTORIES( ${CMAKE_SOURCE_DIR}/src/lib ) -## Traverse subdirectories -ADD_SUBDIRECTORY (src/lib) -ADD_SUBDIRECTORY (src/tools) -ADD_SUBDIRECTORY (src/py) -ADD_SUBDIRECTORY (src/tests) -#ADD_SUBDIRECTORY (src/houdini) -#ADD_SUBDIRECTORY (src/doc) -ADD_SUBDIRECTORY (contrib) +########################################################################## HDA +#SET (BUILD_PARTIO_LIBRARY 1) +#SET (BUILD_PARTIO_MAYA 1) +#SET (BUILD_PARTIO_MTOA 1) +########################################################################## HDA +SET (LEGACY_BUILD_MODE 1) +IF (BUILD_PARTIO_LIBRARY OR BUILD_PARTIO_MAYA OR BUILD_PARTIO_MTOA OR BUILD_PARTIO_ARNOLD OR BUILD_PARTIO_HOUDINI) + SET (LEGACY_BUILD_MODE 0) +ENDIF() +########################################################################## HDA +message(STATUS "partio/CMakeLists.txt : LEGACY_BUILD_MODE = ${LEGACY_BUILD_MODE}") +########################################################################## HDA +IF (LEGACY_BUILD_MODE) + ADD_SUBDIRECTORY (src/lib) + ADD_SUBDIRECTORY (src/tools) + ADD_SUBDIRECTORY (src/py) + ADD_SUBDIRECTORY (src/tests) + #ADD_SUBDIRECTORY (src/houdini) + #ADD_SUBDIRECTORY (src/doc) + ADD_SUBDIRECTORY (contrib) +ELSE (LEGACY_BUILD_MODE) + ########################################################################## HDA + message(STATUS "partio/CMakeLists.txt : BUILD_PARTIO_LIBRARY = ${BUILD_PARTIO_LIBRARY}") + ########################################################################## HDA + + IF (BUILD_PARTIO_LIBRARY) + ADD_SUBDIRECTORY (src/lib) + ADD_SUBDIRECTORY (src/tools) + ADD_SUBDIRECTORY (src/py) + ADD_SUBDIRECTORY (src/tests) + ENDIF (BUILD_PARTIO_LIBRARY) + #ADD_SUBDIRECTORY (src/houdini) + #ADD_DEFINITIONS_SUBDIRECTORY (src/doc) + IF (BUILD_PARTIO_MAYA OR BUILD_PARTIO_MTOA OR BUILD_PARTIO_ARNOLD OR BUILD_PARTIO_HOUDINI) + ADD_SUBDIRECTORY (contrib) + ENDIF() +ENDIF () diff --git a/build.sh b/build.sh new file mode 100755 index 00000000..fa2272aa --- /dev/null +++ b/build.sh @@ -0,0 +1,107 @@ +#!/bin/bash + +build_partio_lib=1 +build_partio_maya=1 +build_partio_arnold=1 + +build_type=Release + +#mayaVersions=(2015.sp6) #2014.sp4 do not build +#mayaVersions=(2016.sp6) #2014.sp4 do not build +mayaVersions=(ext2.2016.sp1) +#mayaVersions=(2017.0.0) + + +##################################################################### +# for MAYA 2016: # +# rez env gxx-4.6 cmake swig-3.0.5 glew-2.0 python-2.7 mayaAPI-2016 # +# # +##################################################################### + + +arnold_version='4.2.16.2' +mtoa_version='1.4.2.1.16' +compiler_path='/usr/bin/g++-4.6' + +swig_executable='/s/apps/packages/dev/swig/3.0.5/platform-linux/bin/swig' + + +glew_include_dir=$REZ_GLEW_ROOT'/include' +glew_static_library=$REZ_GLEW_ROOT'/lib64/libGLEW.a' + +#glew_include_dir='/s/apps/lin/vfx_test_apps/glew/1.11.0/include' +#glew_static_library='/s/apps/lin/vfx_test_apps/glew/1.11.0/lib/libGLEW.a' + + + + +export ARNOLD_HOME=/s/apps/packages/cg/arnold/$arnold_version/platform-linux +export MTOA_ROOT=/s/apps/packages/mikros/mayaModules/mimtoa/$mtoa_version/platform-linux/arnold-4.2/maya-2016 +export PARTIO_HOME=/datas/hda/build/partio/build-Linux-x86_64 + +rm -fr /datas/hda/build/partio/partio.build +rm -fr /datas/hda/build/partio/build-Linux-x86_64 + +mkdir partio.build +mkdir build-Linux-x86_64 + +cd partio.build + +if [ "$build_partio_lib" == 1 ]; then + + echo "BUILD PARTIO LIB" + + cmake .. \ + -DBUILD_PARTIO_LIBRARY=1 \ + -DBUILD_PARTIO_MAYA=0 \ + -DBUILD_PARTIO_MTOA=0 + + make -j12 + make install +fi + +### Build Partio Maya plugin +echo $build_partio_maya + +if [ "$build_partio_maya" == 1 ]; then + + echo "BUILD PARTIO MAYA" + + for mv in "${mayaVersions[@]}" + do + maya_executable='/s/apps/packages/cg/maya/'$mv'/platform-linux/bin/maya' + + cmake .. \ + -DCMAKE_BUILD_TYPE=$build_type \ + -DGLEW_INCLUDE_DIR=$glew_include_dir \ + -DGLEW_STATIC_LIBRARY=$glew_static_library \ + -DMAYA_EXECUTABLE=$maya_executable \ + -DBUILD_PARTIO_LIBRARY=1 \ + -DBUILD_PARTIO_MAYA=1 \ + -DBUILD_PARTIO_MTOA=0 + + make -j12 + make install + done +fi + +### Build Partio Arnold procedural +if [ "$build_partio_arnold" == 1 ]; then +cmake .. \ +-DCMAKE_BUILD_TYPE=$build_type \ +-DSWIG_EXECUTABLE=$swig_executable \ +-DGLEW_INCLUDE_DIR=$glew_include_dir \ +-DGLEW_STATIC_LIBRARY=$glew_static_library \ +-DBUILD_PARTIO_LIBRARY=1 \ +-DBUILD_PARTIO_MAYA=0 \ +-DBUILD_PARTIO_MTOA=1 + +#-DCMAKE_CXX_COMPILER=$compiler_path \ + +make -j12 +make install +fi + +# cp /s/apps/users/hda/build/partio/build-Linux-x86_64/maya/2016/plug-ins/Linux-x86_64/partio4Maya.so /s/apps/users/hda/packages/cgDev/partioMaya/dev/platform-linux/maya-2016/plug-ins + + diff --git a/contrib/CMakeLists.txt b/contrib/CMakeLists.txt index 73eb983c..42df8894 100644 --- a/contrib/CMakeLists.txt +++ b/contrib/CMakeLists.txt @@ -1,5 +1,39 @@ -add_subdirectory(partio4Maya) -if(NOT WIN32 AND NOT APPLE) - add_subdirectory(partio4Arnold) - #add_subdirectory(partio4Houdini) -endif(NOT WIN32 AND NOT APPLE) +set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake) +########################################################################## HDA +message(STATUS "HDA partio/contrib/CMakeLists.txt : LEGACY_BUILD_MODE = ${LEGACY_BUILD_MODE}") +########################################################################## HDA + + +if (LEGACY_BUILD_MODE) + find_package(Arnold) + find_package(Maya) + if (BUILD_PARTIO_HOUDINI) + find_package(Houdini) + endif () +else () + find_package(Partio) + include_directories(${PARTIO_INCLUDE_DIR}) + link_directories(${PARTIO_LIBRARY_DIR}) + if (BUILD_PARTIO_MTOA OR BUILD_PARTIO_ARNOLD) + find_package(Arnold) + endif () + if (BUILD_PARTIO_MAYA OR BUILD_PARTIO_MTOA) + find_package(Maya) + endif () + if (BUILD_PARTIO_HOUDINI) + find_package(Houdini) + endif () +endif () + +if (MAYA_FOUND AND BUILD_PARTIO_MAYA) + add_subdirectory(partio4Maya) +endif () + +if (NOT WIN32 AND NOT APPLE) + if (ARNOLD_FOUND) + add_subdirectory(partio4Arnold) + endif () + if (HOUDINI_FOUND) + add_subdirectory(partio4Houdini) + endif () +endif () diff --git a/contrib/cmake/FindArnold.cmake b/contrib/cmake/FindArnold.cmake index 628b9f23..60a16d76 100644 --- a/contrib/cmake/FindArnold.cmake +++ b/contrib/cmake/FindArnold.cmake @@ -11,6 +11,9 @@ # Input variables from CMake of the form Arnold_FOO # Output variables of the form ARNOLD_FOO # +########################################################################## HDA +message(STATUS "################## FindArnold.cmake ##################") +########################################################################## HDA find_library(ARNOLD_LIBRARY NAMES ai diff --git a/contrib/cmake/FindMaya.cmake b/contrib/cmake/FindMaya.cmake index fe7b7991..fd12ce77 100644 --- a/contrib/cmake/FindMaya.cmake +++ b/contrib/cmake/FindMaya.cmake @@ -34,6 +34,10 @@ # Output variables of the form MAYA_FOO # +########################################################################## HDA +message(STATUS "################## FindMaya.cmake ##################") +########################################################################## HDA + #============================================================================= # Macros #============================================================================= @@ -88,10 +92,9 @@ macro(MAYA_SET_PLUGIN_PROPERTIES target) endif() endmacro(MAYA_SET_PLUGIN_PROPERTIES) - #SET(MAYA_FOUND FALSE) set(_maya_TEST_VERSIONS) -set(_maya_KNOWN_VERSIONS "2008" "2009" "2010" "2011" "2012" "2013" "2014" "2015") +set(_maya_KNOWN_VERSIONS "2008" "2009" "2010" "2011" "2012" "2013" "2014" "2015" "2016") if(APPLE) set(MAYA_PLUGIN_SUFFIX ".bundle") @@ -176,21 +179,24 @@ endif() # Qt Versions -if(${MAYA_VERSION} STREQUAL "2011") +if("${MAYA_VERSION}" STREQUAL "2011") set(MAYA_QT_VERSION_SHORT CACHE STRING "4.5") set(MAYA_QT_VERSION_LONG CACHE STRING "4.5.3") -elseif(${MAYA_VERSION} STREQUAL "2012") +elseif("${MAYA_VERSION}" STREQUAL "2012") set(MAYA_QT_VERSION_SHORT CACHE STRING "4.7") set(MAYA_QT_VERSION_LONG CACHE STRING "4.7.1") -elseif(${MAYA_VERSION} STREQUAL "2013") +elseif("${MAYA_VERSION}" STREQUAL "2013") set(MAYA_QT_VERSION_SHORT CACHE STRING "4.7") set(MAYA_QT_VERSION_LONG CACHE STRING "4.7.1") -elseif(${MAYA_VERSION} STREQUAL "2014") +elseif("${MAYA_VERSION}" STREQUAL "2014") set(MAYA_QT_VERSION_SHORT CACHE STRING "4.8") set(MAYA_QT_VERSION_LONG CACHE STRING "4.8.2") elseif("${MAYA_VERSION}" STREQUAL "2015") set(MAYA_QT_VERSION_SHORT CACHE STRING "4.8") set(MAYA_QT_VERSION_LONG CACHE STRING "4.8.2") +elseif("${MAYA_VERSION}" STREQUAL "2016") + set(MAYA_QT_VERSION_SHORT CACHE STRING "4.8") + set(MAYA_QT_VERSION_LONG CACHE STRING "4.8.6") endif() # NOTE: the MAYA_LOCATION environment variable is often misunderstood. On every OS it is expected to point @@ -206,33 +212,79 @@ message(STATUS "Maya Location: ${MAYA_LOCATION}") message(STATUS "Maya VERSION: ${MAYA_VERSION}") SET(MAYA_FOUND TRUE) -find_path(MAYA_INCLUDE_DIR maya/MFn.h - HINTS ${MAYA_LOCATION} - PATH_SUFFIXES - include # linux and windows - ../../devkit/include # osx - DOC "Maya's include path") +#find_path(MAYA_INCLUDE_DIR maya/MFn.h +# HINTS ${MAYA_LOCATION} +# PATH_SUFFIXES +# include # linux and windows +# ../../devkit/include # osx +# DOC "Maya's include path") +# +#LIST(APPEND MAYA_INCLUDE_DIRS ${MAYA_INCLUDE_DIR}) + + +##################### HDA MODIF ##################### +#FIND_PATH(MAYA_DEVKIT_INC_DIR GL/glext.h +# HINTS +# ${MAYA_LOCATION} +# PATH_SUFFIXES +# devkit/plug-ins/ # linux +# ../../devkit/plug-ins # osx +# DOC "Maya's devkit headers path" +#) +#LIST(APPEND MAYA_INCLUDE_DIRS ${MAYA_DEVKIT_INC_DIR}) +# +# +#find_path(MAYA_LIBRARY_DIRS libOpenMaya.dylib libOpenMaya.so OpenMaya.lib +# HINTS ${MAYA_LOCATION} +# PATH_SUFFIXES +# lib # linux and windows +# MacOS # osx +# DOC "Maya's library path") + + +MESSAGE( STATUS " FindMaya HDA #### MAYA_API_LOCATION : " $ENV{MAYA_API_LOCATION} ) -LIST(APPEND MAYA_INCLUDE_DIRS ${MAYA_INCLUDE_DIR}) FIND_PATH(MAYA_DEVKIT_INC_DIR GL/glext.h HINTS - ${MAYA_LOCATION} + $ENV{MAYA_API_LOCATION} PATH_SUFFIXES - devkit/plug-ins/ # linux - ../../devkit/plug-ins # osx + devkit/plug-ins/ # linux + ../../devkit/plug-ins # osx DOC "Maya's devkit headers path" ) -LIST(APPEND MAYA_INCLUDE_DIRS ${MAYA_DEVKIT_INC_DIR}) + +FIND_PATH(MAYA_INC_DIR devkit + HINTS + $ENV{MAYA_API_LOCATION} + DOC "Maya's devkit headers path" +) + +MESSAGE( STATUS "FindMaya HDA #### MAYA_INC_DIR : " ${MAYA_INC_DIR} ) + + +LIST(APPEND MAYA_INCLUDE_DIRS ${MAYA_DEVKIT_INC_DIR}) +LIST(APPEND MAYA_INCLUDE_DIRS ${MAYA_INC_DIR}/include) + + +MESSAGE( STATUS "FindMaya HDA #### MAYA_DEVKIT_INC_DIR : " ${MAYA_DEVKIT_INC_DIR} ) +MESSAGE( STATUS "FindMaya HDA #### MAYA_INCLUDE_DIRS : " ${MAYA_INCLUDE_DIRS} ) +MESSAGE( STATUS "FindMaya HDA #### MAYA_INCLUDE_DIRS : " ${MAYA_INCLUDE_DIRS} ) + + +#message( FATAL_ERROR " HDA DEBUG ..." ) find_path(MAYA_LIBRARY_DIRS libOpenMaya.dylib libOpenMaya.so OpenMaya.lib - HINTS ${MAYA_LOCATION} + HINTS $ENV{MAYA_API_LOCATION} PATH_SUFFIXES lib # linux and windows MacOS # osx DOC "Maya's library path") + + + # Set deprecated variables to avoid compatibility breaks set(MAYA_INCLUDE_DIR ${MAYA_INCLUDE_DIRS}) set(MAYA_LIBRARY_DIR ${MAYA_LIBRARY_DIRS}) @@ -266,6 +318,11 @@ foreach(_maya_lib PATHS ${_maya_TEST_PATHS} PATH_SUFFIXES lib # linux and windows DOC "Maya's ${MAYA_LIB} library path") + + + MESSAGE( STATUS "!!! : MAYA_${_maya_lib}_LIBRARY " ${MAYA_${_maya_lib}_LIBRARY} ) + + endif() list(APPEND MAYA_LIBRARIES ${MAYA_${_maya_lib}_LIBRARY}) endforeach() diff --git a/contrib/cmake/FindMtoA.cmake b/contrib/cmake/FindMtoA.cmake index 229711e6..305e35c9 100644 --- a/contrib/cmake/FindMtoA.cmake +++ b/contrib/cmake/FindMtoA.cmake @@ -8,16 +8,49 @@ # MTOA_INCLUDE_DIR MtoA's include directory # MTOA_mtoa_api_LIBRARY Full path location of libmtoa_api +########################################################################## HDA +message(STATUS "################## FindMtoA.cmake ##################") +########################################################################## HDA + +message(STATUS "MTOA location DEBUG : ${MTOA_LOCATION}") +message(STATUS "MTOA location DEBUG MTOA_ROOT : $ENV{MTOA_ROOT}") + + + find_package(PackageHandleStandardArgs) ## ## Obtain MtoA install location ## -find_path(MTOA_LOCATION include/render/AOV.h - "$ENV{MTOA_ROOT}" + +find_path(MTOA_LOCATION bin/kick + HINTS ENV MTOA_ROOT NO_DEFAULT_PATH NO_SYSTEM_ENVIRONMENT_PATH) + +if(NOT MTOA_LOCATION) + # mtd file lives with the plugin and has consistent cross-platform extension + find_path(_plugin_path mtoa.mtd + HINTS ENV MAYA_PLUG_IN_PATH + NO_DEFAULT_PATH + NO_SYSTEM_ENVIRONMENT_PATH) + if(_plugin_path) + get_filename_component(MTOA_LOCATION ${_plugin_path} PATH) + endif() +endif() + +if(NOT MTOA_LOCATION) + # mtd file lives with the plugin and has consistent cross-platform extension + find_path(_plugin_path mtoa_shaders.mtd + HINTS ENV ARNOLD_PLUGIN_PATH + NO_DEFAULT_PATH + NO_SYSTEM_ENVIRONMENT_PATH) + if(_plugin_path) + get_filename_component(MTOA_LOCATION ${_plugin_path} PATH) + endif() +endif() + find_package_handle_standard_args(MtoA REQUIRED_VARS MTOA_LOCATION) @@ -37,6 +70,6 @@ if(MTOA_FOUND) set(MTOA_INCLUDE_DIR "${MTOA_LOCATION}/include" CACHE STRING "MtoA include path") message(STATUS "MTOA location: ${MTOA_LOCATION}") - message(STATUS "MTOA LIB dir: ${MTOA_mtoa_api_LIBRARY}") + message(STATUS "MTOA LIB: ${MTOA_mtoa_api_LIBRARY}") message(STATUS "MTOA INCLUDE: ${MTOA_INCLUDE_DIR}") endif() diff --git a/contrib/partio4Arnold/CMakeLists.txt b/contrib/partio4Arnold/CMakeLists.txt index 857caa3c..4b03ba53 100644 --- a/contrib/partio4Arnold/CMakeLists.txt +++ b/contrib/partio4Arnold/CMakeLists.txt @@ -1,5 +1,29 @@ -CMAKE_MINIMUM_REQUIRED( VERSION 2.4.6 ) -add_subdirectory(plugin) -add_subdirectory(procedurals) -add_subdirectory(shaders) +cmake_minimum_required(VERSION 2.4.6) +#if (BUILD_PARTIO_MTOA) + find_package(MtoA) +#endif () + +########################################################################## HDA +message(STATUS "partio/contrib/partio4Arnold/CMakeLists.txt : BUILD_PARTIO_MTOA = ${BUILD_PARTIO_MTOA}") +message(STATUS "partio/contrib/partio4Arnold/CMakeLists.txt : MTOA_FOUND = ${MTOA_FOUND}") +message(STATUS "partio/contrib/partio4Arnold/CMakeLists.txt : ARNOLD_FOUND = ${ARNOLD_FOUND}") +########################################################################## HDA + + +#if(MTOA_FOUND) +# add_subdirectory(plugin) +#else() +# add_subdirectory(procedurals) +#endif() + +########################################################################## HDA + +if(MTOA_FOUND) + add_subdirectory(plugin) +endif() + +if(ARNOLD_FOUND) + add_subdirectory(procedurals) +endif() +########################################################################## HDA diff --git a/contrib/partio4Arnold/plugin/CMakeLists.txt b/contrib/partio4Arnold/plugin/CMakeLists.txt index c6ecc675..39ee994f 100644 --- a/contrib/partio4Arnold/plugin/CMakeLists.txt +++ b/contrib/partio4Arnold/plugin/CMakeLists.txt @@ -1,173 +1,165 @@ ##### THIS WILL NEED SOME HELP WITH NON-Linux compiles +MESSAGE( STATUS "@@@@@@@@@@@@@@@@@@@ CMakeLists.txt partio4Arnold/plugin") + + ## CMake compatibility issues: don't modify this, please! -CMAKE_MINIMUM_REQUIRED( VERSION 2.4.6 ) +cmake_minimum_required(VERSION 2.4.6) # Check if the GCC version matches the required version on Linux -IF ( DEFINED USE_MAYA_CERTIFIED_COMPILER AND USE_MAYA_CERTIFIED_COMPILER ) - IF ( ${CMAKE_SYSTEM_NAME} MATCHES "Linux") - IF ( CMAKE_COMPILER_IS_GNUCC ) - EXECUTE_PROCESS ( COMMAND ${CMAKE_C_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION ) - MESSAGE ( "GCC_VERSION is ${GCC_VERSION}" ) - STRING ( REGEX MATCHALL "[0-9]+" GCC_VERSION_COMPONENTS ${GCC_VERSION}) - LIST ( GET GCC_VERSION_COMPONENTS 0 GCC_VERSION_MAJOR ) - LIST ( GET GCC_VERSION_COMPONENTS 1 GCC_VERSION_MINOR ) - LIST ( GET GCC_VERSION_COMPONENTS 2 GCC_VERSION_PATCH ) - IF (${GCC_VERSION_MAJOR} MATCHES "4" - AND - ${GCC_VERSION_MINOR} MATCHES "1" - AND - ${GCC_VERSION_PATCH} MATCHES "2" - ) - MESSAGE ("CORRECT VERSION OF COMPILER FOR MAYA PLUGINS") - ELSE () - MESSAGE (FATAL_ERROR "INCORRECT VERSION OF COMPILER FOR MAYA PLUGINS, EXPECTING GCC 4.1.2") - ENDIF() - ENDIF () - ENDIF () -ENDIF () - - -if(COMMAND cmake_policy) - cmake_policy(SET CMP0003 NEW) - cmake_policy(SET CMP0015 NEW) # to supress relative library directory warnings -endif(COMMAND cmake_policy) - -SET(CMAKE_CXX_WARNING_LEVEL 4) - -SET(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../cmake) - - -MARK_AS_ADVANCED(CMAKE_BACKWARDS_COMPATIBILITY) +if (DEFINED USE_MAYA_CERTifIED_COMPILER AND USE_MAYA_CERTifIED_COMPILER) + if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") + if (CMAKE_COMPILER_IS_GNUCC) + execute_process(COMMAND ${CMAKE_C_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION) + message("GCC_VERSION is ${GCC_VERSION}") + string(REGEX MATCHALL "[0-9]+" GCC_VERSION_COMPONENTS ${GCC_VERSION}) + list(GET GCC_VERSION_COMPONENTS 0 GCC_VERSION_MAJOR) + list(GET GCC_VERSION_COMPONENTS 1 GCC_VERSION_MINOR) + list(GET GCC_VERSION_COMPONENTS 2 GCC_VERSION_PATCH) + if (${GCC_VERSION_MAJOR} MATCHES "4" + AND + ${GCC_VERSION_MINOR} MATCHES "1" + AND + ${GCC_VERSION_PATCH} MATCHES "2" + ) + message("CORRECT VERSION OF COMPILER FOR MAYA PLUGINS") + else () + message(FATAL_ERROR "INCORRECT VERSION OF COMPILER FOR MAYA PLUGINS, EXPECTING GCC 4.1.2") + endif () + endif () + endif () +endif () + + +if (COMMAND cmake_policy) + cmake_policy(SET CMP0003 NEW) + cmake_policy(SET CMP0015 NEW) # to supress relative library directory warnings +endif () + +set(CMAKE_CXX_WARNING_LEVEL 4) + +mark_as_advanced(CMAKE_BACKWARDS_COMPATIBILITY) ## allow more human readable "if then else" constructs -SET( CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS TRUE ) +set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS TRUE) ## Use verbose make file -SET ( CMAKE_VERBOSE_MAKEFILE TRUE ) - -find_package(Arnold) -find_package(MtoA) -find_package(Maya) - -################################################## -### CUSTOMIZE PATH TO MTOA SOURCE -# Set this to the main source directory for MTOA -if(MTOA_FOUND) - SET( MTOA_DEVEL_INCLUDE ${MTOA_INCLUDE_DIR} ) - MESSAGE(STATUS "MTOA Found DEVEL_INCLUDE: ${MTOA_DEVEL_INCLUDE}") -else (MTOA_FOUND) - #SET (MTOA_DEVEL_HOME "/Volumes/sv-dev01/devRepo/johnc/arnold/mtoa") - #SET (MTOA_DEVEL_INCLUDE ${MTOA_DEVEL_HOME}/plugins/mtoa) - SET (MTOA_DEVEL_INCLUDE /Volumes/sv-dev01/soft/rez-release/mtoa/$ENV{MTOA_VERSION}/platform-linux/maya-$ENV{MAYA_VERSION_NUM}/arnold-4.1.3/include) - MESSAGE(STATUS "MTOA using DEVEL_INCLUDE: ${MTOA_DEVEL_INCLUDE}") - endif(MTOA_FOUND) - -### END -################################################## - -set (PLUGIN_NAME "partioTranslator") -set (CMAKE_PROJECT_NAME "partioVizTranslator") - -if(APPLE) - set (PLUGIN_SUFFIX ".bundle") - set (CMAKE_SHARED_LIBRARY_SUFFIX ".bundle") - set (SUFFIX ".bundle") -ENDIF() - -if(WIN32) - set (PLUGIN_SUFFIX ".dll") - set (CMAKE_SHARED_LIBRARY_SUFFIX ".dll") - set (SUFFIX ".dll") -ENDIF() - -if (UNIX) - set (PLUGIN_SUFFIX ".so") - set (CMAKE_SHARED_LIBRARY_SUFFIX ".so") - set (SUFFIX ".so") -ENDIF() +set(CMAKE_VERBOSE_MAKEFILE TRUE) +set(PLUGIN_NAME "partioTranslator") +set(CMAKE_PROJECT_NAME "partioVizTranslator") +if (APPLE) + set(PLUGIN_SUFFIX ".bundle") + set(CMAKE_SHARED_LIBRARY_SUFFIX ".bundle") + set(SUFFIX ".bundle") +endif () -SET (PARTIO_INCLUDE ${INCLUDE_OUTPUT_PATH} ) -SET (PARTIO_LIBDIR ${LIBRARY_OUTPUT_PATH} ) +if (WIN32) + set(PLUGIN_SUFFIX ".dll") + set(CMAKE_SHARED_LIBRARY_SUFFIX ".dll") + set(SUFFIX ".dll") +endif () -set (STD_INCLUDES "." ".." "/usr/X11R6/include" "/usr/include" "/usr/include/CC") -set (STD_LIB "/usr/lib/") +if (UNIX) + set(PLUGIN_SUFFIX ".so") + set(CMAKE_SHARED_LIBRARY_SUFFIX ".so") + set(SUFFIX ".so") +endif () +set(STD_INCLUDES "/usr/include" "/usr/include/CC") +set(STD_LIB "/usr/lib/") -include_directories (${STD_INCLUDES} ${partio4ArnoldINCLUDES} ${MAYA_INCLUDE_DIR} ${ARNOLD_INCLUDE_DIR} ${MTOA_DEVEL_INCLUDE} ${MTOA_INCLUDE_DIR} ${PARTIO_INCLUDE}) -link_directories ( ${STD_LIB} ${MAYA_LIBRARY_DIR} ${MTOA_mtoa_api_LIBRARY} ${ARNOLD_LIBRARY} ${PARTIO_LIBDIR} ${ZLIB_LIBRARY_DIR}) +include_directories(${STD_INCLUDES} + ${MAYA_INCLUDE_DIR} + ${ARNOLD_INCLUDE_DIR} + ${MTOA_INCLUDE_DIR}) +link_directories(${STD_LIB} + ${MAYA_LIBRARY_DIR} + ${MTOA_mtoa_api_LIBRARY} + ${ARNOLD_LIBRARY} + ${ZLIB_LIBRARY_DIR}) # Maya CFLAGS -IF (APPLE) - SET ( DEVKIT_LOCATION ${MAYA_LOCATION}/../../devkit ) - ADD_DEFINITIONS ( - -DMAC_PLUGIN - -D_BOOL - -DCC_GNU_ - -DOSMac_ - -DOSMacOSX_ - -DREQUIRE_IOSTREAM - -DOSMac_MachO_ - -D_LANGUAGE_C_PLUS_PLUS - -include "${DEVKIT_LOCATION}/include/maya/OpenMayaMac.h" - -fno-gnu-keywords - -fpascal-strings - -D_DARWIN # required by MtoA - ) -ELSE (APPLE) - ADD_DEFINITIONS ( - -DBits64_ - -m64 - -DUNIX - -D_BOOL - -DLINUX - -DFUNCPROTO - -D_GNU_SOURCE - -DLINUX_64 - -fPIC - -fno-strict-aliasing - -DREQUIRE_IOSTREAM - -Wno-deprecated - -Wall - -Wno-multichar - -Wno-comment - -Wno-sign-compare - -funsigned-char - -Wno-reorder - -fno-gnu-keywords - -ftemplate-depth-25 - -pthread - -DNDEBUG - -O3 - -D_LINUX # required by MtoA - ) -ENDIF (APPLE) - -FILE(GLOB partio4ArnoldCPP "*.cpp") -FILE(GLOB partio4ArnoldINCLUDES "*.h") - - -SET(MAYA_LIBS OpenMaya Foundation OpenMayaAnim OpenMayaFX OpenMayaUI OpenMayaRender) - -IF (WIN32) - SET(PARTIO_LIB partio) -elseif(APPLE) - SET(PARTIO_LIB libpartio.a) -elseif(UNIX) - SET(PARTIO_LIB libpartio.a) -ENDIF() - - -ADD_LIBRARY(${PLUGIN_NAME} SHARED ${partio4ArnoldINCLUDES} ${partio4ArnoldCPP}) +if (APPLE) + set(DEVKIT_LOCATION ${MAYA_LOCATION}/../../devkit) + add_definitions( + -DMAC_PLUGIN + -D_BOOL + -DCC_GNU_ + -DOSMac_ + -DOSMacOSX_ + -DREQUIRE_IOSTREAM + -DOSMac_MachO_ + -D_LANGUAGE_C_PLUS_PLUS + -include "${DEVKIT_LOCATION}/include/maya/OpenMayaMac.h" + -fno-gnu-keywords + -fpascal-strings + -D_DARWIN # required by MtoA + ) +else () + add_definitions( + -DBits64_ + -m64 + -DUNIX + -D_BOOL + -DLINUX + -DFUNCPROTO + -D_GNU_SOURCE + -DLINUX_64 + -fPIC + -fno-strict-aliasing + -DREQUIRE_IOSTREAM + -Wno-deprecated + -Wall + -Wno-multichar + -Wno-comment + -Wno-sign-compare + -funsigned-char + -Wno-reorder + -fno-gnu-keywords + -ftemplate-depth-25 + -pthread + -D_LINUX # required by MtoA + ) +endif () + +# no need to explicitly include header files, as they are +# included using "" +file(GLOB partio4ArnoldCPP "*.cpp") + +set(MAYA_LIBS + ${MAYA_OpenMaya_LIBRARY} + ${MAYA_Foundation_LIBRARY} + ${MAYA_OpenMayaAnim_LIBRARY} + ${MAYA_OpenMayaFX_LIBRARY} + ${MAYA_OpenMayaUI_LIBRARY} + ${MAYA_OpenMayaRender_LIBRARY}) + +# HDA +#MESSAGE(STATUS '######################### @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ CMakeLists.txt partioArnold/plugin') +#MESSAGE(${PLUGIN_NAME}) +#MESSAGE(${partioArnoldCPP}) + +add_library(${PLUGIN_NAME} SHARED ${partio4ArnoldCPP}) set_target_properties(${PLUGIN_NAME} PROPERTIES PREFIX "") -TARGET_LINK_LIBRARIES(${PLUGIN_NAME} ${ZLIB} ${MAYA_LIBS} ${PARTIO_LIB} ${ARNOLD_LIBRARY} ${MTOA_mtoa_api_LIBRARY} ) - -SET (PARTIO4ARNOLD_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/arnold/mtoa-$ENV{MTOA_VERSION}/${PARTIO_BUILD_PLATFORM}/extensions) - -INSTALL( TARGETS ${PLUGIN_NAME} DESTINATION ${PARTIO4ARNOLD_OUTPUT_PATH} ) - -FILE(GLOB PARTIO4ARNOLD_SCRIPTS "*.py") -INSTALL( FILES ${PARTIO4ARNOLD_SCRIPTS} DESTINATION ${PARTIO4ARNOLD_OUTPUT_PATH}) +target_link_libraries(${PLUGIN_NAME} + ${MAYA_LIBS} + ${PARTIO_LIBRARIES} + ${ARNOLD_LIBRARY} + ${MTOA_mtoa_api_LIBRARY}) + +set(PARTIO4ARNOLD_OUTPUT_PATH "arnold/mtoa/extensions") +if (BUILD_PARTIO_MTOA) + set (PARTIO4ARNOLD_OUTPUT_PATH "extensions") +elseif (${LOCAL_install}) # TODO : ask Johnc if this is still needed + set (PARTIO4ARNOLD_OUTPUT_PATH "arnold/mtoa-$ENV{MTOA_VERSION}/${PARTIO_BUILD_PLATFORM}/extensions") +endif () + +install(TARGETS ${PLUGIN_NAME} + DESTINATION ${PARTIO4ARNOLD_OUTPUT_PATH}) + +file(GLOB PARTIO4ARNOLD_SCRIPTS "*.py") +install(FILES ${PARTIO4ARNOLD_SCRIPTS} + DESTINATION ${PARTIO4ARNOLD_OUTPUT_PATH}) diff --git a/contrib/partio4Arnold/plugin/PartioVizTranslator.cpp b/contrib/partio4Arnold/plugin/PartioVizTranslator.cpp index f26a06c1..1ce3f8fe 100644 --- a/contrib/partio4Arnold/plugin/PartioVizTranslator.cpp +++ b/contrib/partio4Arnold/plugin/PartioVizTranslator.cpp @@ -14,53 +14,70 @@ #include #include #include - +// void* CPartioVizTranslator::creator() { return new CPartioVizTranslator(); } -void CPartioVizTranslator::NodeInitializer ( CAbTranslator context ) +void CPartioVizTranslator::NodeInitializer(CAbTranslator context) { - CExtensionAttrHelper helper ( context.maya, "procedural" ); - CShapeTranslator::MakeCommonAttributes ( helper ); + MGlobal::displayInfo("@@@@@@@@@@  CPartioVizTranslator::NodeInitializer"); + + + + CExtensionAttrHelper helper(context.maya, "procedural"); + CShapeTranslator::MakeCommonAttributes(helper); CAttrData data; - MStringArray enumNames; - enumNames.append ( "points" ); - enumNames.append ( "spheres" ); - enumNames.append ( "quads" ); + MStringArray enumNames; + enumNames.append("points"); + enumNames.append("spheres"); + enumNames.append("quads"); data.defaultValue.INT = 0; data.name = "aiRenderPointsAs"; data.shortName = "ai_render_points_as"; - data.enums= enumNames; - helper.MakeInputEnum ( data ); + data.enums = enumNames; + helper.MakeInputEnum(data); data.defaultValue.BOOL = false; data.name = "aiOverrideRadiusPP"; data.shortName = "ai_override_radiusPP"; - helper.MakeInputBoolean ( data ); + helper.MakeInputBoolean(data); - data.defaultValue.FLT = 1000000; + data.defaultValue.FLT = 1000000.0f; data.name = "aiMaxParticleRadius"; data.shortName = "ai_max_particle_radius"; - helper.MakeInputFloat ( data ); + data.hasMin = true; + data.min.FLT = 0.0f; + data.hasSoftMax = true; + data.softMax.FLT = 1000000.0f; + helper.MakeInputFloat(data); - data.defaultValue.FLT = 0.2; + data.defaultValue.FLT = 0.0f; + data.name = "aiMinParticleRadius"; + data.shortName = "ai_min_particle_radius"; + data.softMax.FLT = 1.0f; + helper.MakeInputFloat(data); + + data.defaultValue.FLT = 0.2f; data.name = "aiRadius"; data.shortName = "ai_radius"; - helper.MakeInputFloat ( data ); + helper.MakeInputFloat(data); - data.defaultValue.FLT = 1.0; + data.defaultValue.FLT = 1.0f; data.name = "aiRadiusMultiplier"; data.shortName = "ai_radius_multiplier"; - helper.MakeInputFloat ( data ); + helper.MakeInputFloat(data); - data.defaultValue.FLT = 1.0; + data.defaultValue.FLT = 1.0f; data.name = "aiMotionBlurMultiplier"; data.shortName = "ai_motion_blur_multiplier"; - helper.MakeInputFloat ( data ); + data.hasMin = false; + data.hasSoftMin = true; + data.softMin.FLT = 0.0f; + helper.MakeInputFloat(data); data.defaultValue.FLT = 0.f; data.name = "aiStepSize"; @@ -69,152 +86,123 @@ void CPartioVizTranslator::NodeInitializer ( CAbTranslator context ) data.min.FLT = 0.f; data.hasSoftMax = true; data.softMax.FLT = 2.f; - helper.MakeInputFloat ( data ); - - data.defaultValue.STR = ""; - data.name = "aiExportAttributes"; - data.shortName = "ai_export_attributes"; - helper.MakeInputString( data ); - - data.defaultValue.STR = ""; - data.name = "aiOverrideProcedural"; - data.shortName = "ai_override_procedural"; - helper.MakeInputString( data ); + data.hasSoftMin = false; + helper.MakeInputFloat(data); + data.defaultValue.FLT = 8.0f; + data.name = "aiFilterSmallParticles"; + data.shortName = "ai_filter_small_particles"; + data.hasMin = true; + data.min.FLT = 0.0f; + data.hasSoftMax = true; + data.softMax.FLT = 10.0f; + data.hasSoftMin = true; + data.softMin.FLT = 7.0f; + helper.MakeInputFloat(data); + + data.defaultValue.STR = ""; + data.name = "aiExportAttributes"; + data.shortName = "ai_export_attributes"; + helper.MakeInputString(data); + + data.defaultValue.STR = ""; + data.name = "aiOverrideProcedural"; + data.shortName = "ai_override_procedural"; + helper.MakeInputString(data); } AtNode* CPartioVizTranslator::CreateArnoldNodes() { - if ( IsMasterInstance() ) - { - AtNode * tmpRes = AddArnoldNode ( "procedural" ); - return tmpRes; - } - else - { - AtNode * tmpRes = AddArnoldNode ( "ginstance" ); - return tmpRes; - } + cout << "CreateArnoldNodes" << endl; + return IsMasterInstance() ? AddArnoldNode("procedural") : AddArnoldNode("ginstance"); } -/* -/// overrides CShapeTranslator::ProcessRenderFlags -void CPartioVizTranslator::ProcessRenderFlags(AtNode* node) +void CPartioVizTranslator::Export(AtNode* anode) { - AiNodeSetInt(node, "visibility", ComputeVisibility()); - - MPlug plug; - plug = FindMayaObjectPlug("aiSelfShadows"); - if (!plug.isNull()) AiNodeSetBool(node, "self_shadows", plug.asBool()); - - plug = FindMayaObjectPlug("receiveShadows"); - if (!plug.isNull()) AiNodeSetBool(node, "receive_shadows", plug.asBool()); - - // Sub-Surface Scattering - plug = FindMayaObjectPlug("aiSssSampleDistribution"); - if (!plug.isNull()) AiNodeSetInt(node, "sss_sample_distribution", plug.asInt()); - - plug = FindMayaObjectPlug("aiSssSampleSpacing"); - if (!plug.isNull()) AiNodeSetFlt(node, "sss_sample_spacing", plug.asFloat()); - -} -*/ - -void CPartioVizTranslator::Export ( AtNode* anode ) -{ - const char* nodeType = AiNodeEntryGetName ( AiNodeGetNodeEntry ( anode ) ); - if ( strcmp ( nodeType, "ginstance" ) == 0 ) - { - ExportInstance ( anode, GetMasterInstance() ); - } + cout << "Export" << endl; + if (AiNodeIs(anode, "ginstance")) + ExportInstance(anode, GetMasterInstance()); else - { - ExportProcedural ( anode, false ); - } + ExportProcedural(anode, false); } -void CPartioVizTranslator::ExportMotion ( AtNode* anode, unsigned int step ) +void CPartioVizTranslator::ExportMotion(AtNode* anode) { - ExportMatrix ( anode, step ); + cout << "ExportMotion" << endl; + ExportMatrix(anode); } -void CPartioVizTranslator::Update ( AtNode* anode ) +void CPartioVizTranslator::Update(AtNode* anode) { - const char* nodeType = AiNodeEntryGetName ( AiNodeGetNodeEntry ( anode ) ); - if ( strcmp ( nodeType, "ginstance" ) == 0 ) - { - ExportInstance ( anode, GetMasterInstance() ); - } - else - { - ExportProcedural ( anode, true ); - } -} -void CPartioVizTranslator::UpdateMotion ( AtNode* anode, unsigned int step ) -{ - ExportMatrix ( anode, step ); } // Deprecated : Arnold support procedural instance, but it's not safe. // -AtNode* CPartioVizTranslator::ExportInstance ( AtNode *instance, const MDagPath& masterInstance ) +AtNode* CPartioVizTranslator::ExportInstance(AtNode* instance, const MDagPath& masterInstance) { - AtNode* masterNode = AiNodeLookUpByName ( masterInstance.partialPathName().asChar() ); + cout << "ExportInstance" << endl; + AtNode* masterNode = AiNodeLookUpByName(masterInstance.partialPathName().asChar()); - AiNodeSetStr ( instance, "name", m_dagPath.partialPathName().asChar() ); + AiNodeSetStr(instance, "name", m_dagPath.partialPathName().asChar()); - ExportMatrix ( instance, 0 ); + //ExportMatrix(instance, 0); + ExportMatrix(instance); - AiNodeSetPtr ( instance, "node", masterNode ); - AiNodeSetBool ( instance, "inherit_xform", false ); + AiNodeSetPtr(instance, "node", masterNode); + AiNodeSetBool(instance, "inherit_xform", false); - int visibility = AiNodeGetInt ( masterNode, "visibility" ); - AiNodeSetInt ( instance, "visibility", visibility ); + int visibility = AiNodeGetInt(masterNode, "visibility"); + AiNodeSetInt(instance, "visibility", visibility); - m_DagNode.setObject ( masterInstance ); + m_DagNode.setObject(masterInstance); - ExportPartioVizShaders ( instance ); + ExportPartioVizShaders(instance); return instance; } void CPartioVizTranslator::ExportShaders() { - AiMsgWarning ( "[mtoa] Shaders untested with new multitranslator and standin code." ); + cout << "ExportShaders" << endl; + AiMsgWarning("[mtoa] Shaders untested with new multitranslator and standin code."); /// TODO: Test shaders with standins. - ExportPartioVizShaders ( GetArnoldRootNode() ); + //ExportPartioVizShaders(GetArnoldRootNode()); + ExportPartioVizShaders(GetArnoldNode()); } -void CPartioVizTranslator::ExportPartioVizShaders ( AtNode* procedural ) +void CPartioVizTranslator::ExportPartioVizShaders(AtNode* procedural) { + cout << "ExportPartioVizShaders" << endl; int instanceNum = m_dagPath.isInstanced() ? m_dagPath.instanceNumber() : 0; std::vector meshShaders; - MPlug shadingGroupPlug = GetNodeShadingGroup ( m_dagPath.node(), instanceNum ); - if ( !shadingGroupPlug.isNull() ) + MPlug shadingGroupPlug = GetNodeShadingGroup(m_dagPath.node(), instanceNum); + if (!shadingGroupPlug.isNull()) { - AtNode *shader = ExportNode ( shadingGroupPlug ); - if ( shader != NULL ) + //AtNode* shader = ExportNode(shadingGroupPlug); + AtNode* shader = ExportConnectedNode(shadingGroupPlug); + if (shader != 0) { - AiNodeSetPtr ( procedural, "shader", shader ); - meshShaders.push_back ( shader ); + AiNodeSetPtr(procedural, "shader", shader); + meshShaders.push_back(shader); } else { - AiMsgWarning ( "[mtoa] [translator %s] ShadingGroup %s has no surfaceShader input", - GetTranslatorName().asChar(), MFnDependencyNode ( shadingGroupPlug.node() ).name().asChar() ); + AiMsgWarning("[mtoa] [translator %s] ShadingGroup %s has no surfaceShader input", + GetTranslatorName().asChar(), MFnDependencyNode(shadingGroupPlug.node()).name().asChar()); /*AiMsgWarning("[mtoa] ShadingGroup %s has no surfaceShader input.", fnDGNode.name().asChar());*/ - AiNodeSetPtr ( procedural, "shader", NULL ); + AiNodeSetPtr(procedural, "shader", 0); } } } // THIS MAY NOT REALLY BE NEEDED ANYMORE BUT LEAVING IT FOR NOW -void CPartioVizTranslator::ExportBoundingBox ( AtNode* procedural ) +void CPartioVizTranslator::ExportBoundingBox(AtNode* procedural) { + cout << "ExportBoundingBox" << endl; MBoundingBox boundingBox = m_DagNode.boundingBox(); MPoint bbMin = boundingBox.min(); MPoint bbMax = boundingBox.max(); @@ -222,28 +210,30 @@ void CPartioVizTranslator::ExportBoundingBox ( AtNode* procedural ) float minCoords[4]; float maxCoords[4]; - bbMin.get ( minCoords ); - bbMax.get ( maxCoords ); + bbMin.get(minCoords); + bbMax.get(maxCoords); - AiNodeSetPnt ( procedural, "min", minCoords[0], minCoords[1], minCoords[2] ); - AiNodeSetPnt ( procedural, "max", maxCoords[0], maxCoords[1], maxCoords[2] ); + AiNodeSetPnt(procedural, "min", minCoords[0], minCoords[1], minCoords[2]); + AiNodeSetPnt(procedural, "max", maxCoords[0], maxCoords[1], maxCoords[2]); } -AtNode* CPartioVizTranslator::ExportProcedural ( AtNode* procedural, bool update ) +AtNode* CPartioVizTranslator::ExportProcedural(AtNode* procedural, bool update) { - m_DagNode.setObject ( m_dagPath.node() ); + cout << "ExportProcedural" << endl; + m_DagNode.setObject(m_dagPath.node()); - AiNodeSetStr ( procedural, "name", m_dagPath.partialPathName().asChar() ); + AiNodeSetStr(procedural, "name", m_dagPath.partialPathName().asChar()); - ExportMatrix ( procedural, 0 ); - ProcessRenderFlags ( procedural ); + //ExportMatrix(procedural, 0); + ExportMatrix(procedural); + ProcessRenderFlags(procedural); - ExportPartioVizShaders ( procedural ); - + ExportPartioVizShaders(procedural); - if ( !update ) + + if (!update) { /// TODO: figure out how to use a env variable to path just the .so name correctly //MFileObject envProcFilePath; @@ -251,34 +241,35 @@ AtNode* CPartioVizTranslator::ExportProcedural ( AtNode* procedural, bool update //MString envProcPath =envProcFilePath.resolvedPath(); //MString dso = envProcPath+(MString("/partioGenerator.so")); - MString dso = ( "partioGenerator.so" ); + //MString dso = "[PARTIO_ARNOLD_PROCEDURAL]"; + MString dso = "partioGenerator.so"; - // we add this here so we can add in a custom particle reading procedural instead of the default one - MString overrideProc = m_DagNode.findPlug ( "aiOverrideProcedural" ).asString(); + // we add this here so we can add in a custom particle reading procedural instead of the default one + MString overrideProc = m_DagNode.findPlug("aiOverrideProcedural").asString(); - if(overrideProc.length() > 0) - { - dso = overrideProc; - } + if (overrideProc.length() > 0) + dso = overrideProc; - MString formattedName = m_DagNode.findPlug ( "renderCachePath" ).asString(); - int frameNum = m_DagNode.findPlug ( "time" ).asInt(); - int frameOffset = m_DagNode.findPlug ( "cacheOffset" ).asInt(); - int byFrame = m_DagNode.findPlug ( "byFrame" ).asInt(); + MString formattedName = m_DagNode.findPlug("renderCachePath").asString(); + int frameNum = m_DagNode.findPlug("time").asInt(); + int frameOffset = m_DagNode.findPlug("cacheOffset").asInt(); + int byFrame = m_DagNode.findPlug("byFrame").asInt(); int finalFrame = (frameNum + frameOffset) * byFrame; + const int dotPosition = formattedName.rindexW('.'); + if (dotPosition == -1) + return 0; /// TODO: this is only temporary /// need to make the node actually update itself properly - MString formatExt = formattedName.substring ( ( formattedName.length()-3 ), ( formattedName.length()-1 ) ); - //cout << formatExt << endl; + MString formatExt = formattedName.substring(dotPosition + 1, (formattedName.length() - 1)); int cachePadding = 4; - MString formatString = "%0"; + MString formatString = "%0"; // special case for PDCs and maya nCache files because of the funky naming convention TODO: support substepped/retiming caches - if ( formatExt == "pdc" ) + if (formatExt == "pdc") { - finalFrame *= ( int ) ( 6000 / 24 ); + finalFrame *= 6000 / 24; cachePadding = 1; } @@ -289,141 +280,121 @@ AtNode* CPartioVizTranslator::ExportProcedural ( AtNode* procedural, bool update const char* fmt = formatString.asChar(); - sprintf ( frameString, fmt, finalFrame ); + sprintf(frameString, fmt, finalFrame); MString frameNumFormattedName; MStringArray foo; - formattedName.split ( '<',foo ); + formattedName.split('<', foo); MString newFoo; - if ( foo.length() > 1 ) + if (foo.length() > 1) { - foo[1] = foo[1].substring ( 6,foo[1].length()-1 ); - newFoo = foo[0]+MString ( frameString ) +foo[1]; + foo[1] = foo[1].substring(6, foo[1].length() - 1); + newFoo = foo[0] + MString(frameString) + foo[1]; } else - { newFoo = foo[0]; - } - if ( !fileCacheExists ( newFoo.asChar() ) ) + if (!fileCacheExists(newFoo.asChar())) { - AiMsgWarning ( "[mtoa] PartioVisualizer %s being skipped, can't find cache file.", m_DagNode.name().asChar() ); - return NULL; + AiMsgWarning("[mtoa] PartioVisualizer %s being skipped, can't find cache file.", m_DagNode.name().asChar()); + return 0; } - AiNodeSetStr ( procedural, "dso", dso.asChar() ); - AiNodeSetBool ( procedural, "load_at_init", true ); + // TODO: change these attributes to FindMayaPlug to support MtoA override nodes - AiNodeDeclare ( procedural, "arg_file", "constant STRING" ); - AiNodeSetStr ( procedural, "arg_file", newFoo.asChar() ); + AiNodeSetStr(procedural, "dso", dso.asChar()); + AiNodeSetBool(procedural, "load_at_init", true); - AiNodeDeclare ( procedural, "arg_radius", "constant FLOAT" ); - AiNodeSetFlt ( procedural, "arg_radius", m_DagNode.findPlug ( "defaultRadius" ).asFloat() ); + AiNodeDeclare(procedural, "arg_file", "constant STRING"); + AiNodeSetStr(procedural, "arg_file", newFoo.asChar()); - AiNodeDeclare ( procedural, "arg_maxParticleRadius", "constant FLOAT" ); - AiNodeSetFlt ( procedural, "arg_maxParticleRadius", m_DagNode.findPlug ( "aiMaxParticleRadius" ).asFloat() ); + AiNodeDeclare(procedural, "arg_radius", "constant FLOAT"); + AiNodeSetFlt(procedural, "arg_radius", m_DagNode.findPlug("defaultRadius").asFloat()); - AiNodeDeclare ( procedural, "overrideRadiusPP", "constant BOOL" ); - AiNodeSetBool ( procedural, "overrideRadiusPP", m_DagNode.findPlug ( "aiOverrideRadiusPP" ).asBool() ); + AiNodeDeclare(procedural, "arg_maxParticleRadius", "constant FLOAT"); + AiNodeSetFlt(procedural, "arg_maxParticleRadius", m_DagNode.findPlug("aiMaxParticleRadius").asFloat()); - AiNodeDeclare ( procedural, "global_motionBlurSteps", "constant INT" ); - AiNodeSetInt ( procedural, "global_motionBlurSteps", ( int ) GetNumMotionSteps() ); + AiNodeDeclare(procedural, "arg_minParticleRadius", "constant FLOAT"); + AiNodeSetFlt(procedural, "arg_minParticleRadius", m_DagNode.findPlug("aiMinParticleRadius").asFloat()); - AiNodeDeclare ( procedural, "global_motionByFrame", "constant FLOAT" ); - AiNodeSetFlt ( procedural, "global_motionByFrame", ( float ) GetMotionByFrame() ); + AiNodeDeclare(procedural, "arg_filterSmallParticles", "constant FLOAT"); + AiNodeSetFlt(procedural, "arg_filterSmallParticles", m_DagNode.findPlug("aiFilterSmallParticles").asFloat()); - MTime oneSec ( 1.0, MTime::kSeconds ); - float fps = ( float ) oneSec.asUnits ( MTime::uiUnit() ); - AiNodeDeclare ( procedural, "global_fps", "constant FLOAT" ); - AiNodeSetFlt ( procedural, "global_fps", fps ); + AiNodeDeclare(procedural, "overrideRadiusPP", "constant BOOL"); + AiNodeSetBool(procedural, "overrideRadiusPP", m_DagNode.findPlug("aiOverrideRadiusPP").asBool()); - AiNodeDeclare ( procedural, "arg_motionBlurMult", "constant FLOAT" ); - AiNodeSetFlt ( procedural, "arg_motionBlurMult", m_DagNode.findPlug ( "aiMotionBlurMultiplier" ).asFloat() ); + AiNodeDeclare(procedural, "global_motionBlurSteps", "constant INT"); + AiNodeSetInt(procedural, "global_motionBlurSteps", (int)GetNumMotionSteps()); - AiNodeDeclare ( procedural, "arg_renderType", "constant INT" ); - AiNodeSetInt ( procedural, "arg_renderType", m_DagNode.findPlug ( "aiRenderPointsAs" ).asInt() ); + AiNodeDeclare(procedural, "global_motionByFrame", "constant FLOAT"); + AiNodeSetFlt(procedural, "global_motionByFrame", (float)GetMotionByFrame()); - AiNodeDeclare ( procedural, "arg_radiusMult", "constant FLOAT" ); - AiNodeSetFlt ( procedural, "arg_radiusMult", m_DagNode.findPlug ( "aiRadiusMultiplier" ).asFloat() ); + MTime oneSec(1.0, MTime::kSeconds); + float fps = (float)oneSec.asUnits(MTime::uiUnit()); + AiNodeDeclare(procedural, "global_fps", "constant FLOAT"); + AiNodeSetFlt(procedural, "global_fps", fps); - AiNodeDeclare ( procedural, "arg_rgbFrom", "constant STRING" ); - AiNodeDeclare ( procedural, "arg_opacFrom", "constant STRING" ); - AiNodeDeclare ( procedural, "arg_radFrom", "constant STRING" ); - AiNodeDeclare ( procedural, "arg_incandFrom", "constant STRING" ); + AiNodeDeclare(procedural, "arg_motionBlurMult", "constant FLOAT"); + AiNodeSetFlt(procedural, "arg_motionBlurMult", m_DagNode.findPlug("aiMotionBlurMultiplier").asFloat()); - MPlug partioAttrs = m_DagNode.findPlug ( "partioCacheAttributes" ); + AiNodeDeclare(procedural, "arg_renderType", "constant INT"); + AiNodeSetInt(procedural, "arg_renderType", m_DagNode.findPlug("aiRenderPointsAs").asInt()); - int colorIndex = m_DagNode.findPlug ( "colorFrom" ).asInt(); - int opacIndex = m_DagNode.findPlug ( "opacityFrom" ).asInt(); - int radiusIndex = m_DagNode.findPlug ( "radiusFrom" ).asInt(); - int incandIndex = m_DagNode.findPlug ( "incandescenceFrom" ).asInt(); + AiNodeDeclare(procedural, "arg_radiusMult", "constant FLOAT"); + AiNodeSetFlt(procedural, "arg_radiusMult", m_DagNode.findPlug("aiRadiusMultiplier").asFloat()); - MString rgbFrom = ""; - MString opacFrom = ""; - MString radFrom = ""; - MString incaFrom = ""; - if ( colorIndex >=0 ) - { - MPlug rgbArrayEntry = partioAttrs.elementByLogicalIndex ( colorIndex ); - rgbArrayEntry.getValue ( rgbFrom ); - } - if ( incandIndex >=0 ) - { - MPlug incandArrayEntry = partioAttrs.elementByLogicalIndex ( incandIndex ); - incandArrayEntry.getValue ( incaFrom ); - } - if ( opacIndex >=0 ) - { - MPlug opacArrayEntry =partioAttrs.elementByLogicalIndex ( opacIndex ); - opacArrayEntry.getValue ( opacFrom ); - } - if ( radiusIndex >=0 ) - { - MPlug radiusArrayEntry =partioAttrs.elementByLogicalIndex ( radiusIndex ); - radiusArrayEntry.getValue ( radFrom ); - } + AiNodeDeclare(procedural, "arg_velFrom", "constant STRING"); + AiNodeDeclare(procedural, "arg_accFrom", "constant STRING"); + AiNodeDeclare(procedural, "arg_rgbFrom", "constant STRING"); + AiNodeDeclare(procedural, "arg_opacFrom", "constant STRING"); + AiNodeDeclare(procedural, "arg_radFrom", "constant STRING"); + AiNodeDeclare(procedural, "arg_incandFrom", "constant STRING"); + + MPlug partioAttrs = m_DagNode.findPlug("partioCacheAttributes"); - AiNodeSetStr ( procedural, "arg_rgbFrom", rgbFrom.asChar() ); - AiNodeSetStr ( procedural, "arg_opacFrom", opacFrom.asChar() ); - AiNodeSetStr ( procedural, "arg_radFrom", radFrom.asChar() ); - AiNodeSetStr ( procedural, "arg_incandFrom", incaFrom.asChar() ); + AiNodeSetStr(procedural, "arg_velFrom", m_DagNode.findPlug("velocityFrom").asString().asChar()); + AiNodeSetStr(procedural, "arg_accFrom", m_DagNode.findPlug("accelerationFrom").asString().asChar()); + AiNodeSetStr(procedural, "arg_rgbFrom", m_DagNode.findPlug("colorFrom").asString().asChar()); + AiNodeSetStr(procedural, "arg_opacFrom", m_DagNode.findPlug("opacityFrom").asString().asChar()); + AiNodeSetStr(procedural, "arg_radFrom", m_DagNode.findPlug("radiusFrom").asString().asChar()); + AiNodeSetStr(procedural, "arg_incandFrom", m_DagNode.findPlug("incandescenceFrom").asString().asChar()); MFloatVector defaultColor; - MPlug defaultColorPlug = m_DagNode.findPlug ( "defaultPointColor" ); + MPlug defaultColorPlug = m_DagNode.findPlug("defaultPointColor"); - MPlug defaultColorComp = defaultColorPlug.child ( 0 ); - defaultColorComp.getValue ( defaultColor.x ); - defaultColorComp = defaultColorPlug.child ( 1 ); - defaultColorComp.getValue ( defaultColor.y ); - defaultColorComp = defaultColorPlug.child ( 2 ); - defaultColorComp.getValue ( defaultColor.z ); + MPlug defaultColorComp = defaultColorPlug.child(0); + defaultColorComp.getValue(defaultColor.x); + defaultColorComp = defaultColorPlug.child(1); + defaultColorComp.getValue(defaultColor.y); + defaultColorComp = defaultColorPlug.child(2); + defaultColorComp.getValue(defaultColor.z); - float defaultOpac = m_DagNode.findPlug ( "defaultAlpha" ).asFloat(); - AiNodeDeclare ( procedural, "arg_defaultColor", "constant RGB" ); - AiNodeDeclare ( procedural, "arg_defaultOpac", "constant FLOAT" ); + float defaultOpac = m_DagNode.findPlug("defaultAlpha").asFloat(); + AiNodeDeclare(procedural, "arg_defaultColor", "constant RGB"); + AiNodeDeclare(procedural, "arg_defaultOpac", "constant FLOAT"); - AiNodeSetRGB ( procedural, "arg_defaultColor", defaultColor.x, defaultColor.y, defaultColor.z ); - AiNodeSetFlt ( procedural, "arg_defaultOpac", defaultOpac ); + AiNodeSetRGB(procedural, "arg_defaultColor", defaultColor.x, defaultColor.y, defaultColor.z); + AiNodeSetFlt(procedural, "arg_defaultOpac", defaultOpac); ///////////////////////////////////////// // support exporting volume step size - float stepSize = m_DagNode.findPlug ( "aiStepSize" ).asFloat(); - if ( stepSize > 0 ) + float stepSize = m_DagNode.findPlug("aiStepSize").asFloat(); + if (stepSize > 0) { - AiNodeDeclare ( procedural, "arg_stepSize", "constant FLOAT" ); - AiNodeSetFlt ( procedural, "arg_stepSize", stepSize ); + AiNodeDeclare(procedural, "arg_stepSize", "constant FLOAT"); + AiNodeSetFlt(procedural, "arg_stepSize", stepSize); } - m_customAttrs = m_DagNode.findPlug( "aiExportAttributes").asString(); + m_customAttrs = m_DagNode.findPlug("aiExportAttributes").asString(); if (m_customAttrs.length() > 0) - { - AiNodeDeclare ( procedural, "arg_extraPPAttrs", "constant STRING" ); - AiNodeSetStr ( procedural , "arg_extraPPAttrs", m_customAttrs.asChar()); - } + { + AiNodeDeclare(procedural, "arg_extraPPAttrs", "constant STRING"); + AiNodeSetStr(procedural, "arg_extraPPAttrs", m_customAttrs.asChar()); + } /// right now because we're using load at init, we don't need to export the bounding box //ExportBoundingBox(procedural); @@ -433,21 +404,18 @@ AtNode* CPartioVizTranslator::ExportProcedural ( AtNode* procedural, bool update } -bool CPartioVizTranslator::fileCacheExists ( const char* fileName ) +bool CPartioVizTranslator::fileCacheExists(const char* fileName) { struct stat fileInfo; bool statReturn; int intStat; - intStat = stat ( fileName, &fileInfo ); - if ( intStat == 0 ) - { + intStat = stat(fileName, &fileInfo); + if (intStat == 0) statReturn = true; - } else - { statReturn = false; - } - return ( statReturn ); + return (statReturn); } + diff --git a/contrib/partio4Arnold/plugin/PartioVizTranslator.h b/contrib/partio4Arnold/plugin/PartioVizTranslator.h index 19e62493..5a864636 100644 --- a/contrib/partio4Arnold/plugin/PartioVizTranslator.h +++ b/contrib/partio4Arnold/plugin/PartioVizTranslator.h @@ -1,43 +1,127 @@ +//#ifndef PARTIOVIZTRANSLATOR_H +//#define PARTIOVIZTRANSLATOR_H +// +//#include "translators/shape/ShapeTranslator.h" +// +//class CPartioVizTranslator : public CShapeTranslator { +//public: +// static void* creator(); +// +// //virtual AtNode* CreateArnoldNodes(); +// AtNode* CreateArnoldNodes(); +// +// +// //virtual void ProcessRenderFlags(AtNode* node); +// +// static void NodeInitializer(CAbTranslator context); +// +//// void Export(AtNode* anode); +//// +//// void ExportMotion(AtNode* anode); +//// +//// virtual void Update(AtNode* anode); +//// +//// virtual void UpdateMotion(AtNode* anode, uint step); +// +////protected: +//// CPartioVizTranslator() : +//// CShapeTranslator() +//// { +//// // Just for debug info, translator creates whatever arnold nodes are required +//// // through the CreateArnoldNodes method +//// //m_abstract.arnold = "procedural"; +//// +//// } +// +//// void ExportBoundingBox(AtNode* procedural); +//// +//// void ExportPartioVizShaders(AtNode* procedural); +//// +//// virtual void ExportShaders(); +//// +//// AtNode* ExportInstance(AtNode* instance, const MDagPath& masterInstance); +//// +//// AtNode* ExportProcedural(AtNode* procedural, bool update); +//// +//// bool fileCacheExists(const char* fileName); +//// +//// +//// MFnDagNode m_DagNode; +//// MString m_customAttrs; +//}; +// +//#endif // PARTIOVIZTRANSLATOR_H +// + #ifndef PARTIOVIZTRANSLATOR_H #define PARTIOVIZTRANSLATOR_H #include "translators/shape/ShapeTranslator.h" -class CPartioVizTranslator : public CShapeTranslator -{ +class CPartioVizTranslator : public CShapeTranslator { public: static void* creator(); - virtual AtNode* CreateArnoldNodes(); + //virtual AtNode* CreateArnoldNodes(); + AtNode* CreateArnoldNodes(); + + //virtual void ProcessRenderFlags(AtNode* node); - static void NodeInitializer ( CAbTranslator context ); - void Export ( AtNode* anode ); - void ExportMotion ( AtNode* anode, unsigned int step ); - virtual void Update ( AtNode* anode ); - virtual void UpdateMotion ( AtNode* anode, uint step ); - -protected: - CPartioVizTranslator() : - CShapeTranslator() - { - // Just for debug info, translator creates whatever arnold nodes are required - // through the CreateArnoldNodes method - m_abstract.arnold = "procedural"; - - } - void ExportBoundingBox ( AtNode* procedural ); - - void ExportPartioVizShaders ( AtNode* procedural ); + static void NodeInitializer(CAbTranslator context); + + void Export(AtNode* anode); + + void ExportMotion(AtNode* anode); + + //virtual void Update(AtNode* anode); + void Update(AtNode* anode); +// +// virtual void UpdateMotion(AtNode* anode, uint step); + +//protected: +// CPartioVizTranslator() : +// CShapeTranslator() +// { +// // Just for debug info, translator creates whatever arnold nodes are required +// // through the CreateArnoldNodes method +// //m_abstract.arnold = "procedural"; +// +// } + + void ExportBoundingBox(AtNode* procedural); + + void ExportPartioVizShaders(AtNode* procedural); + virtual void ExportShaders(); - AtNode* ExportInstance ( AtNode *instance, const MDagPath& masterInstance ); - AtNode* ExportProcedural ( AtNode* procedural, bool update ); - bool fileCacheExists ( const char* fileName ); + AtNode* ExportInstance(AtNode* instance, const MDagPath& masterInstance); + + AtNode* ExportProcedural(AtNode* procedural, bool update); + + bool fileCacheExists(const char* fileName); MFnDagNode m_DagNode; - MString m_customAttrs; + MString m_customAttrs; }; #endif // PARTIOVIZTRANSLATOR_H + + + + + + + + + + + + + + + + + + diff --git a/contrib/partio4Arnold/plugin/partioTranslator.py b/contrib/partio4Arnold/plugin/partioTranslator.py index 4e1d0cf1..2934321b 100644 --- a/contrib/partio4Arnold/plugin/partioTranslator.py +++ b/contrib/partio4Arnold/plugin/partioTranslator.py @@ -2,7 +2,6 @@ import mtoa.ui.ae.templates as templates from mtoa.ui.ae.templates import AttributeTemplate, registerTranslatorUI - class PartioVisualizerTemplate(templates.ShapeTranslatorTemplate): def setup(self): self.commonShapeAttributes() @@ -12,7 +11,7 @@ def setup(self): self.addControl("aiRenderPointsAs", label="Render Points As") self.addControl("aiOverrideRadiusPP", label="Override RadiusPP") self.addControl("aiRadiusMultiplier", label="Radius Multiplier") - self.addControl("aiMaxParticleRadius", label= "Clamp Max Radius") + self.addControl("aiMaxParticleRadius", label="Clamp Max Radius") self.addSeparator() self.addControl("aiStepSize",label="Volume Step Size") self.addSeparator() @@ -20,5 +19,9 @@ def setup(self): self.addSeparator() self.addControl("aiOverrideProcedural", label="Override render procedural" ) self.addControl("aiTranslator", label= "Override MTOA Translator") + self.beginLayout(label='Debug', collapse=True) + self.addControl("aiMinParticleRadius", label="Clamp Min Radius") + self.addControl("aiFilterSmallParticles", label="Filter Small Particles") + self.endLayout() templates.registerTranslatorUI(PartioVisualizerTemplate, "partioVisualizer", "partioTranslator") \ No newline at end of file diff --git a/contrib/partio4Arnold/plugin/plugin.cpp b/contrib/partio4Arnold/plugin/plugin.cpp index cba584e4..3ac9b280 100644 --- a/contrib/partio4Arnold/plugin/plugin.cpp +++ b/contrib/partio4Arnold/plugin/plugin.cpp @@ -1,25 +1,40 @@ #include "PartioVizTranslator.h" - #include "extension/Extension.h" -extern "C" -{ +//extern "C" +//{ - DLLEXPORT void initializeExtension ( CExtension& extension ) - { - MStatus status; +//DLLEXPORT void initializeExtension(CExtension& extension) +//{ +// MStatus status; +// +// extension.Requires("partio4Maya"); +// //extension.LoadArnoldPlugin("partioProcedural"); +// status = extension.RegisterTranslator("partioVisualizer", +// "", +// CPartioVizTranslator::creator, +// CPartioVizTranslator::NodeInitializer); +//} +// +//DLLEXPORT void deinitializeExtension(CExtension& extension) +//{ +//} +// +//} - extension.Requires ( "partio4Maya" ); - //extension.LoadArnoldPlugin("partioProcedural"); - status = extension.RegisterTranslator ( "partioVisualizer", - "", - CPartioVizTranslator::creator, - CPartioVizTranslator::NodeInitializer ); - } +extern "C" +{ - DLLEXPORT void deinitializeExtension ( CExtension& extension ) - { - } +DLLEXPORT void initializeExtension(CExtension &plugin) +{ + plugin.RegisterTranslator("partioVisualizer", + "", + CPartioVizTranslator::creator, + CPartioVizTranslator::NodeInitializer); +} +DLLEXPORT void deinitializeExtension(CExtension &plugin) +{ } +} diff --git a/contrib/partio4Arnold/procedurals/CMakeLists.txt b/contrib/partio4Arnold/procedurals/CMakeLists.txt index 8ff6f172..38629493 100644 --- a/contrib/partio4Arnold/procedurals/CMakeLists.txt +++ b/contrib/partio4Arnold/procedurals/CMakeLists.txt @@ -1,136 +1,74 @@ ##### THIS WILL NEED SOME HELP WITH NON-Linux compiles ## CMake compatibility issues: don't modify this, please! -CMAKE_MINIMUM_REQUIRED( VERSION 2.4.6 ) +cmake_minimum_required(VERSION 2.4.6) if(COMMAND cmake_policy) - cmake_policy(SET CMP0003 NEW) - cmake_policy(SET CMP0015 NEW) # to supress relative library directory warnings + cmake_policy(SET CMP0003 NEW) + cmake_policy(SET CMP0015 NEW) # to supress relative library directory warnings endif(COMMAND cmake_policy) -# old flags -#IF ( UNIX AND NOT APPLE ) -# ADD_DEFINITIONS(-DLINUX) -#ENDIF() -#if( APPLE ) -# ADD_DEFINITIONS(-DMAC_PLUGIN) -# ADD_DEFINITIONS(-DOSMac_) -# ADD_DEFINITIONS(-DOSMac_MachO) -#ENDIF() - -# Maya CFLAGS -IF (APPLE) - SET ( DEVKIT_LOCATION ${MAYA_LOCATION}/../../devkit ) - ADD_DEFINITIONS ( - -DMAC_PLUGIN - -D_BOOL - -DCC_GNU_ - -DOSMac_ - -DOSMacOSX_ - -DREQUIRE_IOSTREAM - -DOSMac_MachO_ - -D_LANGUAGE_C_PLUS_PLUS - -include "${DEVKIT_LOCATION}/include/maya/OpenMayaMac.h" - -fno-gnu-keywords - -fpascal-strings - -D_DARWIN # required by MtoA - ) -ELSE (APPLE) - ADD_DEFINITIONS ( - -DBits64_ - -m64 - -DUNIX - -D_BOOL - -DLINUX - -DFUNCPROTO - -D_GNU_SOURCE - -DLINUX_64 - -fPIC - -fno-strict-aliasing - -DREQUIRE_IOSTREAM - -Wno-deprecated - -Wall - -Wno-multichar - -Wno-comment - -Wno-sign-compare - -funsigned-char - -Wno-reorder - -fno-gnu-keywords - -ftemplate-depth-25 - -pthread - -DNDEBUG - -O3 - -D_LINUX # required by MtoA - ) -ENDIF (APPLE) - -SET(CMAKE_CXX_WARNING_LEVEL 4) - -SET(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../cmake) - - -MARK_AS_ADVANCED(CMAKE_BACKWARDS_COMPATIBILITY) +set(CMAKE_CXX_WARNING_LEVEL 4) + +mark_as_advanced(CMAKE_BACKWARDS_COMPATIBILITY) ## allow more human readable "if then else" constructs -SET( CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS TRUE ) +set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS TRUE) ## Use verbose make file -SET ( CMAKE_VERBOSE_MAKEFILE TRUE ) - -set (PLUGIN_NAME "partioGenerator") -set (CMAKE_PROJECT_NAME "partioGenerator") - -if(APPLE) - set (PLUGIN_SUFFIX ".bundle") - set (CMAKE_SHARED_LIBRARY_SUFFIX ".bundle") - set (SUFFIX ".bundle") -ENDIF() - -if(WIN32) - set (PLUGIN_SUFFIX ".dll") - set (CMAKE_SHARED_LIBRARY_SUFFIX ".dll") - set (SUFFIX ".dll") -ENDIF() - -if (UNIX) - set (PLUGIN_SUFFIX ".so") - set (CMAKE_SHARED_LIBRARY_SUFFIX ".so") - set (SUFFIX ".so") -ENDIF() +set(CMAKE_VERBOSE_MAKEFILE TRUE) -find_package(Arnold) -find_package(MtoA) +set(PLUGIN_NAME "partioGenerator") +set(CMAKE_PROJECT_NAME "partioGenerator") -SET (PARTIO_INCLUDE ${INCLUDE_OUTPUT_PATH} ) -SET (PARTIO_LIBDIR ${LIBRARY_OUTPUT_PATH} ) +# HDA +MESSAGE( STATUS "@@@@@@@@@@@@@@@@@@@ CMakeLists.txt partioArnold/procedural") +MESSAGE(${PLUGIN_NAME}) -set (STD_INCLUDES "." ".." "/usr/X11R6/include" "/usr/include" "/usr/include/CC") -set (STD_LIB "/usr/lib/") -include_directories (${STD_INCLUDES} ${partio4ArnoldINCLUDES} ${ARNOLD_INCLUDE_DIR} ${MTOA_INCLUDE_DIR} ${PARTIO_INCLUDE}) -link_directories ( ${STD_LIB} ${MtoA_mtoa_api_LIBRARY} ${ARNOLD_LIBRARY} ${PARTIO_LIBDIR} ${ZLIB_LIBRARY_DIR}) +if (APPLE) + set(PLUGIN_SUFFIX ".bundle") + set(CMAKE_SHARED_LIBRARY_SUFFIX ".bundle") + set(SUFFIX ".bundle") +endif() -FILE(GLOB partio4ArnoldCPP "*.cpp") -FILE(GLOB partio4ArnoldINCLUDES "*.h") +if (WIN32) + set(PLUGIN_SUFFIX ".dll") + set(CMAKE_SHARED_LIBRARY_SUFFIX ".dll") + set(SUFFIX ".dll") +endif () -SET(TARGET_H ${partio4ArnoldINCLUDES}) -SET(TARGET_SRC ${partio4ArnoldCPP}) - -IF (WIN32) - SET(PARTIO_LIB partio) -elseif(APPLE) - SET(PARTIO_LIB libpartio.a) -elseif(UNIX) - SET(PARTIO_LIB libpartio.a) -ENDIF() - -SET(ZLIB "z") - -ADD_LIBRARY(${PLUGIN_NAME} SHARED ${TARGET_H} ${TARGET_SRC}) +if (UNIX) + set(PLUGIN_SUFFIX ".so") + set(CMAKE_SHARED_LIBRARY_SUFFIX ".so") + set(SUFFIX ".so") +endif() + +set(STD_INCLUDES "/usr/include" "/usr/include/CC") +set(STD_LIB "/usr/lib/") + +include_directories(${STD_INCLUDES} ${ARNOLD_INCLUDE_DIR}) +link_directories(${STD_LIB} ${ARNOLD_LIBRARY}) +message(PARTIO_LIB_DIR) + +if (WIN32) + set(PARTIO_LIB partio) +elseif (APPLE) + set(PARTIO_LIB libpartio.a) +elseif (UNIX) + set(PARTIO_LIB libpartio.a) +endif () + +add_library(${PLUGIN_NAME} SHARED "partioGenerator.cpp") set_target_properties(${PLUGIN_NAME} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ./ ) set_target_properties(${PLUGIN_NAME} PROPERTIES PREFIX "") -TARGET_LINK_LIBRARIES(${PLUGIN_NAME} ${ZLIB} ${PARTIO_LIB} ${ARNOLD_LIBRARY} ${MtoA_mtoa_api_LIBRARY} ) +target_link_libraries(${PLUGIN_NAME} ${PARTIO_LIBRARIES} ${ARNOLD_LIBRARY}) + +set(PARTIO4ARNOLD_OUTPUT_PATH "arnold/procedurals") +if (BUILD_PARTIO_ARNOLD) + set(PARTIO4ARNOLD_OUTPUT_PATH "procedurals") +endif () -SET (PARTIO4ARNOLDPROC_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/arnold/mtoa-$ENV{MTOA_VERSION}/${PARTIO_BUILD_PLATFORM}/procedurals) +install(TARGETS ${PLUGIN_NAME} + DESTINATION ${PARTIO4ARNOLD_OUTPUT_PATH}) -INSTALL( TARGETS ${PLUGIN_NAME} DESTINATION ${PARTIO4ARNOLDPROC_OUTPUT_PATH} ) diff --git a/contrib/partio4Arnold/procedurals/partioGenerator.cpp b/contrib/partio4Arnold/procedurals/partioGenerator.cpp index 2ae3766a..33f851af 100644 --- a/contrib/partio4Arnold/procedurals/partioGenerator.cpp +++ b/contrib/partio4Arnold/procedurals/partioGenerator.cpp @@ -2,606 +2,652 @@ /// PARTIO GENERATOR an arnold procedural cache reader that uses the partio Library /// by John Cassella (redpawfx) for Luma Pictures (c) 2013 -#include "partioGenerator.h" +#include +#include +#include +#include +#include #include #include -#include #include +#include +#include +#include #include -using namespace std; -using namespace Partio; - -// -/* -inline bool lsHandleCudaErrorFunc(const char* fl, int ln) +template +void getParam(T& param, AtNode* node, const char* paramName) { - cudaError_t cet = cudaGetLastError(); - if(cet != cudaSuccess) - { - std::cout << "[" << fl << " : " << ln << "] : " << cudaGetErrorString(cet) << "\n"; - return true; - } - else return false; + // do nothing } -#define lsHandleCudaError() lsHandleCudaErrorFunc(__FILE__, __LINE__) -*/ - - - -bool partioCacheExists ( const char* fileName ) +template<> +void getParam(int& param, AtNode* node, const char* paramName) { - struct stat fileInfo; - bool statReturn; - int intStat; - - intStat = stat ( fileName, &fileInfo ); - if ( intStat == 0 ) - { - statReturn = true; - } - else - { - statReturn = false; - } + if (AiNodeLookUpUserParameter(node, paramName) != 0) + param = AiNodeGetInt(node, paramName); +} - return ( statReturn ); +template<> +void getParam(float& param, AtNode* node, const char* paramName) +{ + if (AiNodeLookUpUserParameter(node, paramName) != 0) + param = AiNodeGetFlt(node, paramName); +} +template<> +void getParam(bool& param, AtNode* node, const char* paramName) +{ + if (AiNodeLookUpUserParameter(node, paramName) != 0) + param = AiNodeGetBool(node, paramName); } -// read parameter values from node and load partio cache if it exists -static int MyInit ( AtNode *mynode, void **user_ptr ) +template<> +void getParam(std::string& param, AtNode* node, const char* paramName) { - //cout << "INIT" << endl; - *user_ptr = mynode; // make a copy of the parent procedural - - pointCount = 0; - cacheExists = false; - canMotionBlur = false; - hasRgbPP = false; - hasIncandPP = false; - hasOpacPP = false; - hasRadiusPP = false; - - // initialize the arg values - arg_file = ""; - arg_radius = 0.1f; - arg_maxParticleRadius = 1000000.0f; - arg_radiusMult = 1; - arg_renderType = 0; // 0 = points, 1 = sphere, 2 = plane - arg_motionBlurMult = 1; - arg_overrideRadiusPP = false; - arg_rgbFrom = ""; - arg_opacFrom = ""; - arg_radFrom = ""; - arg_incandFrom = ""; - arg_defaultColor = AI_RGB_WHITE; - arg_defaultOpac = 1.0f; - arg_stepSize = 0.0f; - arg_extraPPAttrs = ""; - global_motionBlurSteps = 1; - global_fps = 24; - global_motionByFrame = 0.5f; - - - // check for values on node - if ( AiNodeLookUpUserParameter ( mynode, "arg_file" ) != NULL ) - { - arg_file = AiNodeGetStr ( mynode, "arg_file" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "overrideRadiusPP" ) != NULL ) - { - arg_overrideRadiusPP = AiNodeGetBool ( mynode, "overrideRadiusPP" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_radius" ) != NULL ) - { - arg_radius = AiNodeGetFlt ( mynode, "arg_radius" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_maxParticleRadius" ) != NULL ) - { - arg_maxParticleRadius = AiNodeGetFlt ( mynode, "arg_maxParticleRadius" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_radiusMult" ) != NULL ) - { - arg_radiusMult = AiNodeGetFlt ( mynode, "arg_radiusMult" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_renderType" ) != NULL ) - { - arg_renderType = AiNodeGetInt ( mynode, "arg_renderType" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_motionBlurMult" ) != NULL ) - { - arg_motionBlurMult = AiNodeGetFlt ( mynode, "arg_motionBlurMult" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_rgbFrom" ) != NULL ) - { - arg_rgbFrom = AiNodeGetStr ( mynode, "arg_rgbFrom" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_incandFrom" ) != NULL ) - { - arg_incandFrom = AiNodeGetStr ( mynode, "arg_incandFrom" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_opacFrom" ) != NULL ) - { - arg_opacFrom = AiNodeGetStr ( mynode, "arg_opacFrom" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_radFrom" ) != NULL ) - { - arg_radFrom = AiNodeGetStr ( mynode, "arg_radFrom" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_defaultColor" ) != NULL ) - { - arg_defaultColor = AiNodeGetRGB ( mynode, "arg_defaultColor" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_defaultOpac" ) != NULL ) - { - arg_defaultOpac = AiNodeGetFlt ( mynode, "arg_defaultOpac" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "global_motionBlurSteps" ) != NULL ) - { - global_motionBlurSteps = AiNodeGetInt ( mynode, "global_motionBlurSteps" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "global_fps" ) != NULL ) - { - global_fps = AiNodeGetFlt ( mynode, "global_fps" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "global_motionByFrame" ) != NULL ) - { - global_motionByFrame = AiNodeGetFlt ( mynode, "global_motionByFrame" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_stepSize" ) != NULL ) - { - arg_stepSize = AiNodeGetFlt ( mynode, "arg_stepSize" ); - } - if ( AiNodeLookUpUserParameter ( mynode, "arg_extraPPAttrs" ) != NULL ) - { - arg_extraPPAttrs = AiNodeGetStr ( mynode, "arg_extraPPAttrs" ); - } + if (AiNodeLookUpUserParameter(node, paramName) != 0) + param = AiNodeGetStr(node, paramName); +} - AiMsgInfo ( "[partioGenerator] loading cache %s", arg_file ); +template<> +void getParam(AtRGB& param, AtNode* node, const char* paramName) +{ + if (AiNodeLookUpUserParameter(node, paramName) != 0) + param = AiNodeGetRGB(node, paramName); +} - if ( partioCacheExists ( arg_file ) ) - { - cacheExists = true; - points=read ( arg_file ); - if ( points ) +struct PartioData { + PARTIO::ParticlesData* points; + AtNode* mynode; + + PARTIO::ParticleAttribute positionAttr; + PARTIO::ParticleAttribute velocityAttr; + PARTIO::ParticleAttribute accelerationAttr; + PARTIO::ParticleAttribute rgbAttr; + PARTIO::ParticleAttribute opacityAttr; + PARTIO::ParticleAttribute radiusAttr; + PARTIO::ParticleAttribute incandAttr; + + std::string arg_velFrom; + std::string arg_accFrom; + std::string arg_rgbFrom; + std::string arg_incandFrom; + std::string arg_opacFrom; + std::string arg_radFrom; + std::string arg_extraPPAttrs; + std::string arg_file; + + AtRGB arg_defaultColor; + + float arg_radius; + float arg_maxParticleRadius; + float arg_minParticleRadius; + float arg_radiusMult; + float arg_defaultOpac; + float arg_stepSize; + float arg_motionBlurMult; + float arg_filterSmallParticles; + float global_motionByFrame; + float global_fps; + + int arg_renderType; + int global_motionBlurSteps; + + bool arg_overrideRadiusPP; + bool cacheExists; + bool canMotionBlur; + bool hasRadiusPP; + bool hasRgbPP; + bool hasOpacPP; + bool hasIncandPP; + + + PartioData() : arg_rgbFrom(""), arg_incandFrom(""), arg_opacFrom(""), + arg_radFrom(""), arg_extraPPAttrs(""), arg_file("") + { + points = 0; + mynode = 0; + + arg_defaultColor = AI_RGB_WHITE; + + arg_radius = 0.01f; + arg_maxParticleRadius = 1000000.0f; + arg_minParticleRadius = 0.0f; + arg_radiusMult = 1.0f; + arg_defaultOpac = 1.0f; + arg_stepSize = 0.0f; + arg_motionBlurMult = 1.0f; + arg_filterSmallParticles = 8.0f; + global_motionByFrame = 0.5f; + global_fps = 24.0f; + + arg_renderType = 0; + global_motionBlurSteps = 1; + + arg_overrideRadiusPP = false; + cacheExists = false; + canMotionBlur = false; + hasRadiusPP = false; + hasRgbPP = false; + hasOpacPP = false; + hasIncandPP = false; + + positionAttr.type = PARTIO::NONE; + accelerationAttr.type = PARTIO::NONE; + } + + ~PartioData() + { + if (points) + points->release(); + } + + bool init(AtNode* node) + { + mynode = node; + // check for values on node + getParam(arg_file, mynode, "arg_file"); + getParam(arg_overrideRadiusPP, mynode, "overrideRadiusPP"); + getParam(arg_radius, mynode, "arg_radius"); + getParam(arg_maxParticleRadius, mynode, "arg_maxParticleRadius"); + getParam(arg_minParticleRadius, mynode, "arg_minParticleRadius"); + getParam(arg_radiusMult, mynode, "arg_radiusMult"); + getParam(arg_renderType, mynode, "arg_renderType"); + getParam(arg_motionBlurMult, mynode, "arg_motionBlurMult"); + getParam(arg_velFrom, mynode, "arg_velFrom"); + getParam(arg_accFrom, mynode, "arg_accFrom"); + getParam(arg_rgbFrom, mynode, "arg_rgbFrom"); + getParam(arg_incandFrom, mynode, "arg_incandFrom"); + getParam(arg_opacFrom, mynode, "arg_opacFrom"); + getParam(arg_radFrom, mynode, "arg_radFrom"); + getParam(arg_defaultColor, mynode, "arg_defaultColor"); + getParam(arg_defaultOpac, mynode, "arg_defaultOpac"); + getParam(arg_filterSmallParticles, mynode, "arg_filterSmallParticles"); + getParam(global_motionBlurSteps, mynode, "global_motionBlurSteps"); + // no need to generate more than one steps + // when no acceleration data is used for interpolating the data + getParam(global_fps, mynode, "global_fps"); + getParam(global_motionByFrame, mynode, "global_motionByFrame"); + getParam(arg_stepSize, mynode, "arg_stepSize"); + getParam(arg_extraPPAttrs, mynode, "arg_extraPPAttrs"); + + AiMsgInfo("[partioGenerator] loading cache %s", arg_file.c_str()); + + if (partioCacheExists(arg_file)) { - pointCount = ( int ) points->numParticles(); - AiMsgInfo ( "[partioGenerator] loaded %d points", pointCount ); + cacheExists = true; + points = PARTIO::read(arg_file.c_str()); + if (points) + return true; + else + { + AiMsgInfo("[partioGenerator] skipping, no points"); + return false; + } } else { - AiMsgInfo ( "[partioGenerator] skipping, no points" ); - return false; + AiMsgInfo("[partioGenerator] %s cache doesn't exists.", arg_file.c_str()); + return false; } } - return true; -} -// close partio cache -static int MyCleanup ( void *user_ptr ) -{ - if ( points ) + AtNode* getNode() { - AiMsgInfo ( "[partioGenerator] releasing points!" ); - points->release(); - } - return true; -} + AtNode* currentInstance = AiNode("points"); // initialize node + if (!cacheExists) + return currentInstance; -static int MyNumNodes ( void *user_ptr ) -{ - return 1; -} + //////////////////////////////////////////////////////////////////////////////// + /// We at least have to have position, I mean come on throw us a bone here.... + if (!points->attributeInfo("position", positionAttr) && !points->attributeInfo("Position", positionAttr)) + { + AiMsgInfo("[partioGenerator] Could not find position attr maybe you should do something about that"); + return currentInstance; + } + int pointCount = static_cast(points->numParticles()); + AiMsgInfo("[partioGenerator] loaded %d points", pointCount); -// call function to copy values from cache read into AI-Arrays -static AtNode *MyGetNode ( void *user_ptr, int i ) -{ + // first we filter invalid particles properly + // then we try avoid very small ones + // to do that we need radius and position info - AtNode *currentInstance = AiNode ( "points" ); // initialize node - if ( !cacheExists ) - { - return currentInstance; - } + const float singleRadius = arg_radius * arg_radiusMult; -//////////////////////////////////////////////////////////////////////////////// -/// We at least have to have position, I mean come on throw us a bone here.... - if ( !points->attributeInfo ( "position",positionAttr ) && !points->attributeInfo ( "Position",positionAttr ) ) - { - AiMsgInfo ( "[partioGenerator] Could not find position attr maybe you should do something about that" ); - return currentInstance; - } + /////////////////////////////////////////////////////////////////////////////////// + /// RADIUS by default if "none" is defined it will look for radiusPP or radius + if (!arg_overrideRadiusPP) + { + if (((arg_radFrom.length() > 0) && points->attributeInfo(arg_radFrom.c_str(), radiusAttr))) + { + AiMsgInfo("[partioGenerator] found radius attr...%s", arg_radFrom.c_str()); + hasRadiusPP = true; + } + else if ((points->attributeInfo("radiusPP", radiusAttr) || points->attributeInfo("radius", radiusAttr))) + { + AiMsgInfo("[partioGenerator] found radius attr..."); + hasRadiusPP = true; + } + } - AtArray *pointarr; - AtArray *radarr; - AtArray *rgbArr; - AtArray *opacityArr; - AtArray *incandArr; - AtArray *floatArr; - AtArray *vecArr; - pointarr = AiArrayAllocate ( pointCount,global_motionBlurSteps,AI_TYPE_POINT ); - -//////////////// -/// Velocity - if ( points->attributeInfo ( "velocity",velocityAttr ) || points->attributeInfo ( "Velocity",velocityAttr ) ) - { - AiMsgInfo ( "[partioGenerator] found velocity attr, motion blur is a GO!!" ); - canMotionBlur = true; - } + std::vector pointsVector; + std::vector validPointsVector; + std::vector radiiVector; -//////////// -/// RGB + pointsVector.reserve(pointCount); + validPointsVector.reserve(pointCount); + if (hasRadiusPP) + radiiVector.reserve(pointCount); + const float filterSmallParticles = powf(10.0f, arg_filterSmallParticles); - if ( arg_rgbFrom && arg_rgbFrom[0] !='\0' && points->attributeInfo ( arg_rgbFrom, rgbAttr ) ) - { - AiNodeDeclare ( currentInstance, "rgbPP", "uniform RGB" ); - AiMsgInfo ( "[partioGenerator] found rgbPP attr..." ); - hasRgbPP = true; - rgbArr = AiArrayAllocate ( pointCount,1,AI_TYPE_RGB ); - } - else - { - AiNodeDeclare ( currentInstance, "rgbPP", "constant RGB" ); - AiNodeSetRGB ( currentInstance , "rgbPP", arg_defaultColor.r, arg_defaultColor.g, arg_defaultColor.b ); - } -//////////// -/// Incandescence + for (int i = 0; i < pointCount; ++i) + { + const float* partioPositions = points->data(positionAttr, i); + if (AiIsFinite(partioPositions[0]) && AiIsFinite(partioPositions[1]) && AiIsFinite(partioPositions[2])) + { + const AtVector position = {partioPositions[0], partioPositions[1], partioPositions[2]}; + // doing the radiuses here is a temporary workaround + // and an experiment to see how easily we can filter + // very small particles + float rad = 0.0f; + if (hasRadiusPP) + { + // const float* partioRadius = points->data(radiusAttr, id); + const float* partioRadius = points->data(radiusAttr, i); + if (radiusAttr.count == 1) + rad = partioRadius[0]; + else + rad = ABS(float((partioRadius[0] * 0.2126f) + (partioRadius[1] * 0.7152f) + + (partioRadius[2] * .0722f))); + + rad *= arg_radius * arg_radiusMult; + } + else + rad = singleRadius; + + // clamp the radius to maxParticleRadius just in case we have rogue particles + rad = CLAMP(rad, arg_minParticleRadius, arg_maxParticleRadius); + + // According to Thiago Ize, we have to filter particles + // where the ratio of the position from the origin + // and radius is bigger than 10^7 + if ((AiV3Length(position) / rad) > filterSmallParticles) + continue; + + //AiArraySetFlt(radarr , i, rad); + if (hasRadiusPP) + radiiVector.push_back(rad); + pointsVector.push_back(position); + validPointsVector.push_back(i); + } + } + const int newPointCount = static_cast(pointsVector.size()); + AiMsgInfo("[partioGenerator] Filtered %i of %i particles", pointCount - newPointCount, pointCount); + pointCount = newPointCount; + + if (pointCount == 0) + return currentInstance; + + AtArray* pointarr = 0; + AtArray* radarr = 0; + AtArray* rgbArr = 0; + AtArray* opacityArr = 0; + AtArray* incandArr = 0; + AtArray* floatArr = 0; + AtArray* vecArr = 0; + + //////////////// + /// Velocity + if ((global_motionBlurSteps > 1) && (arg_velFrom.length() > 0) && (points->attributeInfo(arg_velFrom.c_str(), velocityAttr) || + points->attributeInfo("velocity", velocityAttr) || points->attributeInfo("Velocity", velocityAttr)) && (velocityAttr.count > 2) && + (velocityAttr.type == PARTIO::FLOAT || velocityAttr.type == PARTIO::VECTOR)) + { + AiMsgInfo("[partioGenerator] found velocity attr, motion blur is a GO!!"); + canMotionBlur = true; - if ( arg_incandFrom && arg_incandFrom[0] !='\0' && points->attributeInfo ( arg_incandFrom, incandAttr ) ) - { - AiNodeDeclare ( currentInstance, "incandescencePP", "uniform RGB" ); - AiMsgInfo ( "[partioGenerator] found incandescencePP attr..." ); - hasIncandPP = true; - incandArr = AiArrayAllocate ( pointCount,1,AI_TYPE_RGB ); - } - else - { - AiNodeDeclare ( currentInstance, "incandescencePP", "constant RGB" ); - AiNodeSetRGB ( currentInstance , "incandescencePP", 0.0, 0.0, 0.0 ); - } + //////////////////// + /// Acceleration + if (points->attributeInfo(arg_accFrom.c_str(), accelerationAttr) && (accelerationAttr.count > 2) && + (accelerationAttr.type == PARTIO::FLOAT || accelerationAttr.type == PARTIO::VECTOR)) + { + AiMsgInfo("[partioGenerator] found acceleration attr, motion blur is a GO!!"); + canMotionBlur = true; + } + } -////////////// -/// OPACITY + //////////// + /// RGB + if ((arg_rgbFrom.length() > 0) && points->attributeInfo(arg_rgbFrom.c_str(), rgbAttr)) + { + AiNodeDeclare(currentInstance, "rgbPP", "uniform RGB"); + AiMsgInfo("[partioGenerator] found rgbPP attr..."); + hasRgbPP = true; + rgbArr = AiArrayAllocate(pointCount, 1, AI_TYPE_RGB); + } + else + { + AiNodeDeclare(currentInstance, "rgbPP", "constant RGB"); + AiNodeSetRGB(currentInstance, "rgbPP", arg_defaultColor.r, arg_defaultColor.g, arg_defaultColor.b); + } - if ( arg_opacFrom && arg_opacFrom[0] !='\0' && points->attributeInfo ( arg_opacFrom, opacityAttr ) ) - { - AiNodeDeclare ( currentInstance, "opacityPP", "uniform Float" ); - AiMsgInfo ( "[partioGenerator] found opacityPP attr..." ); - hasOpacPP = true; - opacityArr = AiArrayAllocate ( pointCount,1,AI_TYPE_FLOAT ); - } - else - { - AiNodeDeclare ( currentInstance, "opacityPP", "constant Float" ); - AiNodeSetFlt ( currentInstance , "opacityPP", arg_defaultOpac ); - } + //////////// + /// Incandescence + if ((arg_incandFrom.length() > 0) && points->attributeInfo(arg_incandFrom.c_str(), incandAttr)) + { + AiNodeDeclare(currentInstance, "incandescencePP", "uniform RGB"); + AiMsgInfo("[partioGenerator] found incandescencePP attr..."); + hasIncandPP = true; + incandArr = AiArrayAllocate(pointCount, 1, AI_TYPE_RGB); + } + else + { + AiNodeDeclare(currentInstance, "incandescencePP", "constant RGB"); + AiNodeSetRGB(currentInstance, "incandescencePP", 0.0f, 0.0f, 0.0f); + } -/////////////////////////////////////////////////////////////////////////////////// -/// RADIUS by default if "none" is defined it will look for radiusPP or radius - if ( ( arg_radFrom && arg_radFrom[0] !='\0' && points->attributeInfo ( arg_radFrom,radiusAttr ) ) && !arg_overrideRadiusPP ) - { - AiMsgInfo ( "[partioGenerator] found radius attr...%s", arg_radFrom ); - hasRadiusPP = true; - radarr = AiArrayAllocate ( pointCount,1,AI_TYPE_FLOAT ); - } - else if ( ( points->attributeInfo ( "radiusPP",radiusAttr ) || points->attributeInfo ( "radius",radiusAttr ) ) && !arg_overrideRadiusPP ) - { - AiMsgInfo ( "[partioGenerator] found radius attr..." ); - hasRadiusPP = true; - radarr = AiArrayAllocate ( pointCount,1,AI_TYPE_FLOAT ); - } - else - { - radarr = AiArrayAllocate ( 1,1,AI_TYPE_FLOAT ); - AiArraySetFlt ( radarr , 0, arg_radius*arg_radiusMult ); - } + ////////////// + /// OPACITY + if ((arg_opacFrom.length() > 0) && points->attributeInfo(arg_opacFrom.c_str(), opacityAttr)) + { + AiNodeDeclare(currentInstance, "opacityPP", "uniform Float"); + AiMsgInfo("[partioGenerator] found opacityPP attr..."); + hasOpacPP = true; + opacityArr = AiArrayAllocate(pointCount, 1, AI_TYPE_FLOAT); + } + else + { + AiNodeDeclare(currentInstance, "opacityPP", "constant Float"); + AiNodeSetFlt(currentInstance, "opacityPP", arg_defaultOpac); + } + const bool can_accelerate = accelerationAttr.type != PARTIO::NONE; -// now parse and include any extra attrs - - std::vector extraAttrs; - std::vector arnoldArrays; - - - char extraAttrStr[1000]; - strncpy(extraAttrStr, arg_extraPPAttrs, sizeof(extraAttrStr)); - char* parts[100] = {0}; - unsigned int index = 0; - parts[index] = strtok(extraAttrStr, " "); - while(parts[index] != 0) - { - ParticleAttribute user; - if (points->attributeInfo(parts[index],user)) - { - // we don't want to double export these - if( user.name != "position" && - user.name != "velocity" && - user.name != "rgbPP" && - user.name != "incandescencePP" && - user.name != "opacityPP" && - user.name != "radiusPP") - { - if (user.type == FLOAT || user.count == 1) - { - AiNodeDeclare ( currentInstance, parts[index], "uniform Float" ); - floatArr = AiArrayAllocate ( pointCount,1,AI_TYPE_FLOAT ); - arnoldArrays.push_back(floatArr); - } - else if (user.type == VECTOR || user.count == 3) - { - AiNodeDeclare ( currentInstance, parts[index], "uniform Vector" ); - vecArr = AiArrayAllocate ( pointCount,1,AI_TYPE_VECTOR ); - arnoldArrays.push_back(vecArr); - } - extraAttrs.push_back(user); - } - else - { - AiMsgWarning( "[partioGenerator] caught double export call for %s, skipping....", parts[index]); - } - } - else - { - AiMsgWarning( "[partioGenerator] export ppAttr %s skipped, it doesn't exist in the cache", parts[index]); - } - - ++index; - parts[index] = strtok(0," "); - - } - - -/////////////////////////////////////////////// -/// LOOP particles - - for ( int i = 0; i< pointCount; i++ ) - { - bool badParticle = false; - const float * partioPositions = points->data ( positionAttr,i ); - AtPoint point; - if ( AiIsFinite ( partioPositions[0] ) && AiIsFinite ( partioPositions[1] ) && AiIsFinite ( partioPositions[2] ) ) + if (canMotionBlur) { - point.x = partioPositions[0]; - point.y = partioPositions[1]; - point.z = partioPositions[2]; + if (can_accelerate) + pointarr = AiArrayAllocate(pointCount, global_motionBlurSteps, AI_TYPE_POINT); + else + pointarr = AiArrayAllocate(pointCount, 2, AI_TYPE_POINT); } + else + pointarr = AiArrayConvert(pointCount, 1, AI_TYPE_POINT, &pointsVector[0]); + + if (hasRadiusPP) + radarr = AiArrayConvert(pointCount, 1, AI_TYPE_FLOAT, &radiiVector[0]); else { - point.x = 0.0f; - point.y = 0.0f; - point.z = 0.0f; - badParticle = true; - AiMsgWarning ( "[partioGenerator] found INF or NAN particle, hiding it..." ); - } - - /// User Defined or default RadiusAttr - float rad; - if ( hasRadiusPP && !arg_overrideRadiusPP ) - { - const float * partioRadius = points->data ( radiusAttr,i ); - if ( radiusAttr.count == 1 ) - { - rad = partioRadius[0]; - } - else - { - rad = abs ( float ( ( partioRadius[0]*0.2126 ) + ( partioRadius[1]*0.7152 ) + ( partioRadius[2]*.0722 ) ) ); - } - - rad *= arg_radiusMult; - rad *= arg_radius; - // clamp the radius to maxParticleRadius just in case we have rogue particles - if ( rad > arg_maxParticleRadius ) - { - rad = arg_maxParticleRadius; - } - - // if we decide to support motion blur radius scale then re-enable here - //for (int s = 0; s < global_motionBlurSteps; s++) - //{ - // AiArraySetFlt(radarr , ((s*pointCount)+i), rad); - //} - AiArraySetFlt ( radarr , (i) , rad ); + radarr = AiArrayAllocate(1, 1, AI_TYPE_FLOAT); + AiArraySetFlt(radarr, 0, singleRadius); } - if ( canMotionBlur ) + + // now parse and include any extra attrs + std::vector extraAttrs; + std::vector arnoldArrays; + + char extraAttrStr[1000]; + strncpy(extraAttrStr, arg_extraPPAttrs.c_str(), sizeof(extraAttrStr)); + char* parts[100] = {0}; + unsigned int index = 0; + parts[index] = strtok(extraAttrStr, " "); + while (parts[index] != 0) { - const float * partioVelo = points->data ( velocityAttr,i ); - AtVector velocitySubstep; - AtVector velocity; - if ( badParticle ) + PARTIO::ParticleAttribute user; + if (points->attributeInfo(parts[index], user)) { - velocitySubstep.x = 0.0f; - velocitySubstep.y = 0.0f; - velocitySubstep.z = 0.0f; + // we don't want to double export these + if (user.name != "position" && + user.name != "velocity" && + user.name != "rgbPP" && + user.name != "incandescencePP" && + user.name != "opacityPP" && + user.name != "radiusPP") + { + if (user.type == PARTIO::FLOAT && user.count == 1) + { + AiNodeDeclare(currentInstance, parts[index], "uniform Float"); + floatArr = AiArrayAllocate(pointCount, 1, AI_TYPE_FLOAT); + arnoldArrays.push_back(floatArr); + } + else if (user.type == PARTIO::VECTOR || (user.type == PARTIO::FLOAT && user.count == 3)) + { + AiNodeDeclare(currentInstance, parts[index], "uniform Vector"); + vecArr = AiArrayAllocate(pointCount, 1, AI_TYPE_VECTOR); + arnoldArrays.push_back(vecArr); + } + extraAttrs.push_back(user); + } + else + AiMsgWarning("[partioGenerator] caught double export call for %s, skipping....", parts[index]); } else - { - velocitySubstep.x = partioVelo[0]; - velocitySubstep.y = partioVelo[1]; - velocitySubstep.z = partioVelo[2]; - } + AiMsgWarning("[partioGenerator] export ppAttr %s skipped, it doesn't exist in the cache", + parts[index]); - velocitySubstep /= global_fps; - velocitySubstep *= global_motionByFrame; // motion by frame + ++index; + parts[index] = strtok(0, " "); + } - // we need to use this to offset the position below to export the position on "Center" motion blur step - velocity = velocitySubstep; - if ( global_motionBlurSteps > 1 ) + const float motion_blur_time = (1.0f / global_fps) * global_motionByFrame * arg_motionBlurMult; + std::vector motion_step_times; + if (can_accelerate) + { + motion_step_times.resize(global_motionBlurSteps, 0.0f); + for (int st = 0; st < global_motionBlurSteps; ++st) { - velocitySubstep /= global_motionBlurSteps-1; + motion_step_times[st] = static_cast(-0.5 + ((double)st / ((double)global_motionBlurSteps - 1.0))) * motion_blur_time; } + } - velocitySubstep *= arg_motionBlurMult; + AiMsgDebug("[partioGenerator] about to final loop thru the particles"); - for ( int s = 0; s < global_motionBlurSteps; s++ ) - { - AtPoint newPoint = ( point- ( velocity*.5 ) ) + velocitySubstep*s; - AiArraySetPnt ( pointarr, ( ( s*pointCount ) +i ), newPoint ); - } - } - else + /////////////////////////////////////////////// + /// LOOP particles + for (int i = 0; i < pointCount; ++i) { - for ( int s = 0; s < global_motionBlurSteps; s++ ) + const int id = validPointsVector[i]; + + if (canMotionBlur) { - AiArraySetPnt ( pointarr, ( ( s*pointCount ) +i ), point ); + if (can_accelerate) + { + const AtVector point = pointsVector[i]; + const float* partioAcc = points->data(accelerationAttr, id); + const AtVector acceleration = {partioAcc[0], partioAcc[1], partioAcc[2]}; + const float* partioVelo = points->data(velocityAttr, id); + AtVector velocity = {partioVelo[0], partioVelo[1], partioVelo[2]}; + + for (int st = 0; st < global_motionBlurSteps; ++st) + { + const float current_time = motion_step_times[st]; + AiArraySetPnt(pointarr, i + st * pointCount, point + velocity * current_time + acceleration * current_time * current_time / 2.0); + } + } + else + { + const AtVector point = pointsVector[i]; + const float* partioVelo = points->data(velocityAttr, id); + AtVector velocity = {partioVelo[0], partioVelo[1], partioVelo[2]}; + velocity *= motion_blur_time * 0.5f; + // global fps inverse, motion by frame + // motion blur multiplier and half to have the original + // particle position as center + + AiArraySetPnt(pointarr, i, point - velocity); + AiArraySetPnt(pointarr, i + pointCount, point + velocity); + } } - } - /// RGBPP - if ( hasRgbPP ) - { - const float * partioRGB = points->data ( rgbAttr, i ); - AtRGB color; - if ( rgbAttr.count > 1 ) + /// RGBPP + if (hasRgbPP) { - color.r = partioRGB[0]; - color.g = partioRGB[1]; - color.b = partioRGB[2]; + const float* partioRGB = points->data(rgbAttr, id); + AtRGB color; + if (rgbAttr.count > 2) + { + color.r = partioRGB[0]; + color.g = partioRGB[1]; + color.b = partioRGB[2]; + } + else + { + color.r = partioRGB[0]; + color.g = partioRGB[0]; + color.b = partioRGB[0]; + } + AiArraySetRGB(rgbArr, i, color); } - else + /// INCANDESCENCE + if (hasIncandPP) { - color.r = partioRGB[0]; - color.g = partioRGB[0]; - color.b = partioRGB[0]; + const float* partioRGB = points->data(incandAttr, id); + AtRGB incand; + if (incandAttr.count > 2) + { + incand.r = partioRGB[0]; + incand.g = partioRGB[1]; + incand.b = partioRGB[2]; + } + else + { + incand.r = partioRGB[0]; + incand.g = partioRGB[0]; + incand.b = partioRGB[0]; + } + AiArraySetRGB(incandArr, i, incand); } - // currently no support for motion blur of arbitrary attrs in points - //for (int s = 0; s < global_motionBlurSteps; s++) - //{ - // AiArraySetRGB(rgbArr,((s*pointCount)+i), color); - //} - AiArraySetRGB ( rgbArr, i, color ); - } - /// INCANDESCENCE - if ( hasIncandPP ) - { - const float * partioRGB = points->data ( incandAttr, i ); - AtRGB incand; - if ( incandAttr.count > 1 ) + /// opacityPP + if (hasOpacPP) { - incand.r = partioRGB[0]; - incand.g = partioRGB[1]; - incand.b = partioRGB[2]; + const float* partioOpac = points->data(opacityAttr, id); + float opac; + if (opacityAttr.count > 2) + opac = float((partioOpac[0] * 0.2126f) + (partioOpac[1] * 0.7152f) + (partioOpac[2] * .0722f)); + else + opac = partioOpac[0]; + + + AiArraySetFlt(opacityArr, i, opac); } - else + for (size_t x = 0; x < extraAttrs.size(); ++x) { - incand.r = partioRGB[0]; - incand.g = partioRGB[0]; - incand.b = partioRGB[0]; + if (extraAttrs[x].type == PARTIO::FLOAT && extraAttrs[x].count == 1) + { + + const float* partioFLOAT = points->data(extraAttrs[x], id); + float floatVal = partioFLOAT[0]; + AiArraySetFlt(arnoldArrays[x], i, floatVal); + } + else if (extraAttrs[x].type == PARTIO::VECTOR || (extraAttrs[x].type == PARTIO::FLOAT && extraAttrs[x].count == 3)) + { + const float* partioVEC = points->data(extraAttrs[x], id); + AtVector vecVal; + vecVal.x = partioVEC[0]; + vecVal.y = partioVEC[1]; + vecVal.z = partioVEC[2]; + AiArraySetVec(arnoldArrays[x], i, vecVal); + } } + } // for loop per particle + + AiMsgDebug("[partioGenerator] Done looping thru particles"); - // currently no support for motion blur of arbitrary attrs in points - //for (int s = 0; s < global_motionBlurSteps; s++) - //{ - // AiArraySetRGB(rgbArr,((s*pointCount)+i), color); - //} - AiArraySetRGB ( incandArr, i, incand ); + if (hasRgbPP) + { + AiNodeSetArray(currentInstance, "rgbPP", rgbArr); + AiMsgDebug("[partioGenerator] rgbPP array set"); } - /// opacityPP - if ( hasOpacPP ) + if (hasIncandPP) { - const float * partioOpac = points->data ( opacityAttr,i ); - float opac; - if ( opacityAttr.count == 1 ) - { - opac = partioOpac[0]; - } - else - { - opac = float ( ( partioOpac[0]*0.2126 ) + ( partioOpac[1]*0.7152 ) + ( partioOpac[2]*.0722 ) ); - } + AiNodeSetArray(currentInstance, "incandescencePP", incandArr); + AiMsgDebug("[partioGenerator] incandescencePP array set"); + } - //for (int s = 0; s < global_motionBlurSteps; s++) - //{ - // hack to make bad particles which were set to 0,0,0 transparent - if ( badParticle ) - { - //AiArraySetFlt(opacityArr ,((s*pointCount)+i), 0.0f); - AiArraySetFlt ( opacityArr ,i , 0.0f ); - } - else - { - //AiArraySetFlt(opacityArr ,((s*pointCount)+i), opac); - AiArraySetFlt ( opacityArr ,i ,opac ); - } - //} + if (hasOpacPP) + { + AiNodeSetArray(currentInstance, "opacityPP", opacityArr); + AiMsgDebug("[partioGenerator] OpacityPP array set"); } - for (int x = 0; x < extraAttrs.size(); x++) + + AiNodeSetArray(currentInstance, "radius", radarr); + AiMsgDebug("[partioGenerator] radiusPP array set"); + + for (size_t x = 0; x < arnoldArrays.size(); ++x) { - if (extraAttrs[x].type == FLOAT) - { - - const float * partioFLOAT = points->data ( extraAttrs[x],i ); - float floatVal = partioFLOAT[0]; - AiArraySetFlt ( arnoldArrays[x] , i , floatVal ); - } - else if (extraAttrs[x].type == VECTOR) - { - const float * partioVEC = points->data ( extraAttrs[x], i ); - AtVector vecVal; - vecVal.x = partioVEC[0]; - vecVal.y = partioVEC[0]; - vecVal.z = partioVEC[0]; - AiArraySetVec( arnoldArrays[x], i, vecVal); - } + AiNodeSetArray(currentInstance, extraAttrs[x].name.c_str(), arnoldArrays[x]); + AiMsgDebug("[partioGenerator] %s array set", extraAttrs[x].name.c_str() ); } - } // for loop per particle + /// these will always be here + AiNodeSetArray(currentInstance, "points", pointarr); + AiMsgDebug("[partioGenerator] Points array set with %i points", pointarr->nelements ); + //AiNodeSetArray ( currentInstance, "position",pointarr ); // we want to enable this when they fix some stuff on particles - if ( hasRgbPP ) - { - AiNodeSetArray ( currentInstance, "rgbPP", rgbArr ); - } - if ( hasIncandPP ) - { - AiNodeSetArray ( currentInstance, "incandescencePP", incandArr ); - } - if ( hasOpacPP ) - { - AiNodeSetArray ( currentInstance, "opacityPP", opacityArr ); - } + AiNodeSetInt(currentInstance, "mode", arg_renderType); + AiNodeSetBool(currentInstance, "opaque", false); + + if (arg_stepSize > 0.0f) + AiNodeSetFlt(currentInstance, "step_size", arg_stepSize); - AiNodeSetArray ( currentInstance, "radius", radarr ); + AiMsgDebug("[partioGenerator] Done with partioGeneration! "); + return currentInstance; + } + bool partioCacheExists(const std::string& fileName) + { + struct stat fileInfo; - for (int x = 0; x < arnoldArrays.size(); x++) - { - AiNodeSetArray( currentInstance, extraAttrs[x].name.c_str(), arnoldArrays[x]); - } + const int intStat = stat(fileName.c_str(), &fileInfo); + if (intStat == 0) + return true; + else + return false; + } +}; - +// read parameter values from node and load partio cache if it exists +static int MyInit(AtNode* mynode, void** user_ptr) +{ + PartioData* data = new PartioData(); + *user_ptr = data; + return data->init(mynode); +} - /// these will always be here - AiNodeSetArray ( currentInstance, "points", pointarr ); - //AiNodeSetArray ( currentInstance, "position",pointarr ); // we want to enable this when they fix some stuff on particles +// close partio cache +static int MyCleanup(void* user_ptr) +{ + PartioData* data = reinterpret_cast(user_ptr); + delete data; + return true; +} - AiNodeSetInt ( currentInstance, "mode", arg_renderType ); - AiNodeSetBool ( currentInstance, "opaque", false ); +static int MyNumNodes(void* user_ptr) +{ + return 1; +} - if ( arg_stepSize > 0.0f ) - { - AiNodeSetFlt ( currentInstance, "step_size", arg_stepSize ); - } - return currentInstance; +// call function to copy values from cache read into AI-Arrays +static AtNode* MyGetNode(void* user_ptr, int i) +{ + return reinterpret_cast(user_ptr)->getNode(); } // vtable passed in by proc_loader macro define proc_loader { - vtable->Init = MyInit; - vtable->Cleanup = MyCleanup; + vtable->Init = MyInit; + vtable->Cleanup = MyCleanup; vtable->NumNodes = MyNumNodes; - vtable->GetNode = MyGetNode; - strcpy ( vtable->version, AI_VERSION ); + vtable->GetNode = MyGetNode; + strcpy(vtable->version, AI_VERSION); return true; } diff --git a/contrib/partio4Houdini/CMakeLists.txt b/contrib/partio4Houdini/CMakeLists.txt index e0091b5a..34f72876 100644 --- a/contrib/partio4Houdini/CMakeLists.txt +++ b/contrib/partio4Houdini/CMakeLists.txt @@ -41,61 +41,53 @@ # implied warranties of merchantability, fitness for a particular purpose and non- # infringement. - - ## CMake compatibility issues: don't modify this, please! -CMAKE_MINIMUM_REQUIRED( VERSION 2.8.0 ) - -if(COMMAND cmake_policy) - cmake_policy(SET CMP0003 NEW) - cmake_policy(SET CMP0015 NEW) # to supress relative library directory warnings - cmake_policy(SET CMP0005 NEW) -endif(COMMAND cmake_policy) - -SET(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../cmake) +cmake_minimum_required( VERSION 2.8.0 ) -set (PLUGIN_NAME "partio4Houdini") -set (CMAKE_PROJECT_NAME "partio4Houdini") +if (COMMAND cmake_policy) + cmake_policy(SET CMP0003 NEW) + cmake_policy(SET CMP0015 NEW) # to supress relative library directory warnings + cmake_policy(SET CMP0005 NEW) +endif (COMMAND cmake_policy) +set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../cmake) -# we want to override the Compiler here to use a newer version because maya's compiler and houdini's don't usually jive -SET( CMAKE_CXX_COMPILER /usr/bin/g++) -SET( CMAKE_C_COMPILER /usr/bin/gcc) -SET( SYS_INCLUDE /usr/lib/gcc/x86_64-redhat-linux/4.6.3/include ) +set(PLUGIN_NAME "partio4Houdini") +set(CMAKE_PROJECT_NAME "partio4Houdini") +# no need to setup the compiler by hand, rez takes care of that +# no need to find houdini here, it's taken care at a higher level -find_package(Houdini) +message(STATUS "Found HOUDINI version ${HOUDINI_VERSION}") +message(STATUS "running command ${PROJECT_SOURCE_DIR}/contrib/cmake/hdk-config.py") -if(HOUDINI_FOUND) - - message(STATUS "Found HOUDINI version ${HOUDINI_VERSION}") - message(STATUS "running command ${PROJECT_SOURCE_DIR}/contrib/cmake/hdk-config.py") - - add_custom_command(OUTPUT sesitag.C - DEPENDS src/ROP_partio.C +add_custom_command(OUTPUT sesitag.C + DEPENDS src/ROP_partio.C COMMAND ${PROJECT_SOURCE_DIR}/contrib/cmake/hdk-config.py --tagfile=${CMAKE_BINARY_DIR}/contrib/partio4Houdini/sesitag.C) - SET (HOUDINI_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/houdini/$ENV{HOUDINI_VERSION}/dso) - SET (HOUDINI_ICONS_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/houdini/$ENV{HOUDINI_VERSION}/Icons) - - SET (HOUDINI_INCS ${HOUDINI_INCLUDE_DIRS} ${SYS_INCLUDE}) - SET (HOUDINI_LIBDIR ${HOUDINI_LIBRARY_DIRS}) - SET (HOUDINI_LIBS HoudiniUI HoudiniOPZ HoudiniOP3 HoudiniOP2 HoudiniOP1 HoudiniSIM HoudiniGEO HoudiniPRM HoudiniUT) - ADD_DEFINITIONS (${HOUDINI_DEFINITIONS} -DHOUDINI_DEFINES -DHOUDINI_API_VERSION=$ENV{HOUDINI_VERSION} -D_REENTRANT -D_FILE_OFFSET_BITS=64 -DMAKING_DSO) - - - LINK_DIRECTORIES( ${HOUDINI_LIBDIR} ) - INCLUDE_DIRECTORIES( ${CMAKE_SOURCE_DIR}/contrib/partio4Houdini/include ${HOUDINI_INCS} ) - - ADD_LIBRARY(${PLUGIN_NAME} SHARED src/partio_houdini.C src/SOP_partio.C src/ROP_partio.C sesitag.C ) - set_target_properties(${PLUGIN_NAME} PROPERTIES PREFIX "") - target_link_libraries(${PLUGIN_NAME} ${PARTIO_LIBRARIES} ${HOUDINI_LIBS} ${HOUDINI_SYS_LIBS}) - - ## install everything - INSTALL(TARGETS ${PLUGIN_NAME} DESTINATION ${HOUDINI_OUTPUT_PATH} ) - - FILE(GLOB PARTIO4HOUDINI_ICONS "icons/*") - INSTALL( FILES ${PARTIO4HOUDINI_ICONS} DESTINATION ${HOUDINI_ICONS_PATH}) - -endif (HOUDINI_FOUND) - - +set(HOUDINI_INCS ${HOUDINI_INCLUDE_DIRS} ${SYS_INCLUDE}) +set(HOUDINI_LIBDIR ${HOUDINI_LIBRARY_DIRS}) +set(HOUDINI_LIBS HoudiniUI HoudiniOPZ HoudiniOP3 HoudiniOP2 HoudiniOP1 HoudiniSIM HoudiniGEO HoudiniPRM HoudiniUT) +add_definitions(${HOUDINI_DEFINITIONS} -DHOUDINI_DEFINES -DHOUDINI_API_VERSION=$ENV{HOUDINI_VERSION} -D_REENTRANT -D_FILE_OFFSET_BITS=64 -DMAKING_DSO) + +link_directories( ${HOUDINI_LIBDIR} ) +include_directories(${CMAKE_SOURCE_DIR}/contrib/partio4Houdini/include ${HOUDINI_INCS}) + +add_library(${PLUGIN_NAME} SHARED src/partio_houdini.C src/SOP_partio.C src/ROP_partio.C sesitag.C) +set_target_properties(${PLUGIN_NAME} PROPERTIES PREFIX "") +target_link_libraries(${PLUGIN_NAME} ${PARTIO_LIBRARIES} ${HOUDINI_LIBS} ${HOUDINI_SYS_LIBS}) + +## install everything +set(HOUDINI_OUTPUT_PATH houdini/dso) +set(HOUDINI_ICONS_PATH houdini/Icons) +if (BUILD_PARTIO_HOUDINI) + set(HOUDINI_OUTPUT_PATH dso) + set(HOUDINI_ICONS_PATH Icons) +elseif (${LOCAL_INSTALL}) + set(HOUDINI_OUTPUT_PATH houdini/$ENV{HOUDINI_VERSION}/dso) + set(HOUDINI_ICONS_PATH houdini/$ENV{HOUDINI_VERSION}/Icons) +endif () + +install(TARGETS ${PLUGIN_NAME} DESTINATION ${HOUDINI_OUTPUT_PATH}) + +file(GLOB PARTIO4HOUDINI_ICONS "icons/*") +install(FILES ${PARTIO4HOUDINI_ICONS} DESTINATION ${HOUDINI_ICONS_PATH}) diff --git a/contrib/partio4Maya/CMakeLists.txt b/contrib/partio4Maya/CMakeLists.txt index c082ab76..c5aa9319 100644 --- a/contrib/partio4Maya/CMakeLists.txt +++ b/contrib/partio4Maya/CMakeLists.txt @@ -1,134 +1,123 @@ ##### THIS WILL NEED SOME HELP WITH NON-Linux compiles ## CMake compatibility issues: don't modify this, please! -CMAKE_MINIMUM_REQUIRED( VERSION 2.4.6 ) +cmake_minimum_required(VERSION 2.4.6) -if(COMMAND cmake_policy) - cmake_policy(SET CMP0003 NEW) - cmake_policy(SET CMP0015 NEW) # to supress relative library directory warnings -endif(COMMAND cmake_policy) +if (COMMAND cmake_policy) + cmake_policy(SET CMP0003 NEW) + cmake_policy(SET CMP0015 NEW) # to supress relative library directory warnings +endif () -SET(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../cmake) +set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../cmake) -find_package(Maya) -if (MAYA_FOUND) +if (UNIX AND NOT APPLE) + add_definitions(-DLINUX) + add_definitions(-Werror) +endif () +if (APPLE ) + add_definitions(-DMAC_PLUGIN) + add_definitions(-DOSMac_) + add_definitions(-DOSMac_MachO) +endif () +set(CMAKE_CXX_WARNING_LEVEL 4) -IF ( UNIX AND NOT APPLE ) - ADD_DEFINITIONS(-DLINUX) -ENDIF() -if( APPLE ) - ADD_DEFINITIONS(-DMAC_PLUGIN) - ADD_DEFINITIONS(-DOSMac_) - ADD_DEFINITIONS(-DOSMac_MachO) -ENDIF() -SET(CMAKE_CXX_WARNING_LEVEL 4) - - -MARK_AS_ADVANCED(CMAKE_BACKWARDS_COMPATIBILITY) +mark_as_advanced(CMAKE_BACKWARDS_COMPATIBILITY) ## allow more human readable "if then else" constructs -SET( CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS TRUE ) +set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS TRUE) ## Use verbose make file -SET ( CMAKE_VERBOSE_MAKEFILE TRUE ) +set(CMAKE_VERBOSE_MAKEFILE TRUE) -set (PLUGIN_NAME "partio4Maya") -set (CMAKE_PROJECT_NAME "partio4Maya") +set(PLUGIN_NAME "partio4Maya") +set(CMAKE_PROJECT_NAME "partio4Maya") -if(APPLE) - set (PLUGIN_SUFFIX ".bundle") - set (CMAKE_SHARED_LIBRARY_SUFFIX ".bundle") - set (SUFFIX ".bundle") -ENDIF() +if (APPLE) + set(PLUGIN_SUFFIX ".bundle") + set(CMAKE_SHARED_LIBRARY_SUFFIX ".bundle") + set(SUFFIX ".bundle") +endif () -if(WIN32) - set (PLUGIN_SUFFIX ".mll") - set (CMAKE_SHARED_LIBRARY_SUFFIX ".mll") - set (SUFFIX ".mll") -ENDIF() +if (WIN32) + set(PLUGIN_SUFFIX ".mll") + set(CMAKE_SHARED_LIBRARY_SUFFIX ".mll") + set(SUFFIX ".mll") +endif () if (UNIX) - set (PLUGIN_SUFFIX ".so") - set (CMAKE_SHARED_LIBRARY_SUFFIX ".so") - set (SUFFIX ".so") -ENDIF() - + set(PLUGIN_SUFFIX ".so") + set(CMAKE_SHARED_LIBRARY_SUFFIX ".so") + set(SUFFIX ".so") +endif () -## if building from the default partio contrib dir you can leave this alone -SET (PARTIO_INCLUDE ${INCLUDE_OUTPUT_PATH} ) -SET (PARTIO_LIBDIR ${LIBRARY_OUTPUT_PATH} ) +# FIXME: why is this necessary? +set(STD_INCLUDES "." ".." "/usr/X11R6/include" "/usr/include" "/usr/include/CC") +set(STD_LIB "/usr/lib/") -set (STD_INCLUDES "." ".." "/usr/X11R6/include" "/usr/include" "/usr/include/CC") -set (STD_LIB "/usr/lib/") - -include_directories (${STD_INCLUDES} ${partio4MayaINCLUDES} ${MAYA_INCLUDE_DIRS} ${PARTIO_INCLUDE}) -link_directories ( ${STD_LIB} ${MAYA_LIBRARY_DIR} ${PARTIO_LIBDIR} ${ZLIB_LIBRARY_DIR}) +include_directories(${STD_INCLUDES} ${MAYA_INCLUDE_DIRS}) +link_directories(${STD_LIB} ${MAYA_LIBRARY_DIR}) add_definitions(-D_BOOL) add_definitions(-DREQUIRE_IOSTREAM) if (!WIN32) - add_definitions(-fPIC) - add_definitions(-O3) - add_definitions(-pthread) -endif() - + add_definitions(-fPIC) + add_definitions(-pthread) +endif () -FILE(GLOB partio4MayaCPP "*.cpp") -FILE(GLOB partio4MayaINCLUDES "*.h") +file(GLOB partio4MayaCPP "*.cpp") -SET(TARGET_H ${partio4MayaINCLUDES}) -SET(TARGET_SRC ${partio4MayaCPP}) +if (APPLE) + set(OPENGL_gl_LIBRARY "-framework OpenGL") + set(OPENGL_glu_LIBRARY "-framework GLUT") +elseif (WIN32) + set(OPENGL_gl_LIBRARY "openGL32") + set(OPENGL_glu_LIBRARY "glu32") +else () + set(OPENGL_gl_LIBRARY "GL") + set(OPENGL_glu_LIBRARY "GLU") +endif () -if(APPLE) - SET(OPENGL_gl_LIBRARY "-framework OpenGL") - SET(OPENGL_glu_LIBRARY "-framework GLUT") - SET(ZLIB "libzlib.a") -elseif(WIN32) +set(MAYA_LIBS OpenMaya Foundation OpenMayaAnim OpenMayaFX OpenMayaUI OpenMayaRender) - SET(OPENGL_gl_LIBRARY "openGL32") - SET(OPENGL_glu_LIBRARY "glu32") - SET(ZLIB "zlib.lib") -else() - SET(OPENGL_gl_LIBRARY "GL") - SET(OPENGL_glu_LIBRARY "GLU") - SET(ZLIB "z") -endif() -SET(MAYA_LIBS OpenMaya Foundation OpenMayaAnim OpenMayaFX OpenMayaUI OpenMayaRender) - -IF (WIN32) - SET(PARTIO_LIB partio) -elseif(APPLE) - SET(PARTIO_LIB libpartio.a) -elseif(UNIX) - SET(PARTIO_LIB libpartio.a) -ENDIF() - - -ADD_LIBRARY(${PLUGIN_NAME} SHARED ${TARGET_H} ${TARGET_SRC}) +ADD_LIBRARY(${PLUGIN_NAME} SHARED ${partio4MayaCPP}) set_target_properties(${PLUGIN_NAME} PROPERTIES PREFIX "") ## need these to build for windows or else the plugin won't load -IF(WIN32) - set_target_properties(${PLUGIN_NAME} PROPERTIES LINK_FLAGS "/export:initializePlugin /export:uninitializePlugin") -ENDIF() - -TARGET_LINK_LIBRARIES(${PLUGIN_NAME} ${ZLIB} ${PARTIO_LIB} ${MAYA_LIBS} ${OPENGL_gl_LIBRARY} ${OPENGL_glu_LIBRARY}) - -SET (PARTIO4MAYA_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/maya/${MAYA_VERSION}/plug-ins/${PARTIO_BUILD_PLATFORM}) -SET (PARTIO4MAYA_OUTPUTSCRIPTS_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/maya/${MAYA_VERSION}/scripts) -SET (PARTIO4MAYA_OUTPUTICONS_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/maya/${MAYA_VERSION}/icons) - - -INSTALL( TARGETS ${PLUGIN_NAME} DESTINATION ${PARTIO4MAYA_OUTPUT_PATH}) - -FILE(GLOB PARTIO4MAYA_SCRIPTS "scripts/*.mel") -INSTALL( FILES ${PARTIO4MAYA_SCRIPTS} DESTINATION ${PARTIO4MAYA_OUTPUTSCRIPTS_PATH}) - -FILE(GLOB PARTIO4MAYA_ICONS "icons/*") -INSTALL( FILES ${PARTIO4MAYA_ICONS} DESTINATION ${PARTIO4MAYA_OUTPUTICONS_PATH}) - - -ENDIF(MAYA_FOUND) - +if (WIN32) + set_target_properties(${PLUGIN_NAME} PROPERTIES LINK_FLAGS "/export:initializePlugin /export:uninitializePlugin") +endif () + +find_library(GLEW_STATIC_LIBRARY NAMES libGLEW.a) + +TARGET_LINK_LIBRARIES(${PLUGIN_NAME} + ${GLEW_STATIC_LIBRARY} + ${ZLIB} + ${PARTIO_LIBRARIES} + ${MAYA_LIBS} + ${OPENGL_gl_LIBRARY} + ${OPENGL_glu_LIBRARY}) + +file(GLOB PARTIO4MAYA_SCRIPTS "scripts/*.mel") +file(GLOB PARTIO4MAYA_ICONS "icons/*") + +set(MAYA_INST_DIR "maya/") +set(MAYA_PLUGIN_DIR "maya/plug-ins") + +if (${LOCAL_INSTALL}) + set(MAYA_INST_DIR "maya/${MAYA_VERSION}/") + set(MAYA_PLUGIN_DIR "maya/${MAYA_VERSION}/plug-ins/${PARTIO_BUILD_PLATFORM}") +else () + set(MAYA_INST_DIR "") + set(MAYA_PLUGIN_DIR "plug-ins") +endif () + +install(TARGETS ${PLUGIN_NAME} + DESTINATION ${MAYA_PLUGIN_DIR}) + +install(FILES ${PARTIO4MAYA_SCRIPTS} + DESTINATION ${MAYA_INST_DIR}scripts) + +install(FILES ${PARTIO4MAYA_ICONS} + DESTINATION ${MAYA_INST_DIR}icons) diff --git a/contrib/partio4Maya/partio4MayaShared.cpp b/contrib/partio4Maya/partio4MayaShared.cpp index 95f0681e..c0264d6c 100644 --- a/contrib/partio4Maya/partio4MayaShared.cpp +++ b/contrib/partio4Maya/partio4MayaShared.cpp @@ -28,13 +28,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. */ #include "partio4MayaShared.h" +#include "iconArrays.h" #define TABLE_SIZE 256 -using namespace Partio; -using namespace std; - ////////////////////////////////// MVector partio4Maya::jitterPoint(int id, float freq, float offset, float jitterMag) ///* generate a constant noise offset for this ID @@ -270,7 +268,7 @@ void partio4Maya::updateFileName (MString cacheFile, MString cacheDir, if (cacheStatic) { - stringstream s_str; + std::stringstream s_str; s_str << origFrameString.asChar(); s_str >> cacheFrame; } @@ -457,7 +455,61 @@ void partio4Maya::drawPartioLogo(float multiplier) } } glEnd(); +} + +MBoundingBox partio4Maya::partioLogoBoundingBox() +{ + MBoundingBox bbox; + + int i,d; + + int last = P1Count - 1; + for (i = 0; i < last; ++i) + bbox.expand(MPoint(P1[i][0], P1[i][1], P1[i][2], 1.0)); + + last = P2Count - 1; + for (i = 0; i < last; ++i) + bbox.expand(MPoint(P2[i][0], P2[i][1], P2[i][2], 1.0)); + + last = a1Count - 1; + for (i = 0; i < last; ++i) + bbox.expand(MPoint(a1[i][0], a1[i][1], a1[i][2], 1.0)); + last = a2Count - 1; + for (i = 0; i < last; ++i) + bbox.expand(MPoint(a2[i][0], a2[i][1], a2[i][2], 1.0)); + + last = rCount - 1; + for (i = 0; i < last; ++i) + bbox.expand(MPoint(r[i][0], r[i][1], r[i][2], 1.0)); + + last = tCount - 1; + for (i = 0; i < last; ++i) + bbox.expand(MPoint(t[i][0], t[i][1], t[i][2], 1.0)); + + last = i1Count - 1; + for (i = 0; i < last; ++i) + bbox.expand(MPoint(i1[i][0], i1[i][1], i1[i][2], 1.0)); + + last = i2Count - 1; + for (i = 0; i < last; ++i) + bbox.expand(MPoint(i2[i][0], i2[i][1], i2[i][2], 1.0)); + + last = o1Count - 1; + for (i = 0; i < last; ++i) + bbox.expand(MPoint(o1[i][0], o1[i][1], o1[i][2], 1.0)); + + last = o2Count - 1; + for (i = 0; i < last; ++i) + bbox.expand(MPoint(o2[i][0], o2[i][1], o2[i][2], 1.0)); + + + for (d = 0; d < debrisCount; d++) + { + for (i = 0; i < (debrisPointCount - 1); ++i) + bbox.expand(MPoint(circles[d][i][0], circles[d][i][1], circles[d][i][2])); + } + return bbox; } //////////////////////////////////////////////////// diff --git a/contrib/partio4Maya/partio4MayaShared.h b/contrib/partio4Maya/partio4MayaShared.h index a3b61732..19937299 100644 --- a/contrib/partio4Maya/partio4MayaShared.h +++ b/contrib/partio4Maya/partio4MayaShared.h @@ -65,8 +65,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include #include +#include -#include "iconArrays.h" #include "Partio.h" extern const int kTableMask; @@ -87,6 +87,7 @@ class partio4Maya static MString setExt(short extNum); static void buildSupportedExtensionList(std::map &formatExtMap,bool write); static void drawPartioLogo(float multiplier); + static MBoundingBox partioLogoBoundingBox(); static MVector jitterPoint(int id, float freq, float offset, float jitterMag); static float noiseAtValue( float x); static void initTable( long seed ); diff --git a/contrib/partio4Maya/partioEmitter.cpp b/contrib/partio4Maya/partioEmitter.cpp index a779d156..31c1dcfd 100644 --- a/contrib/partio4Maya/partioEmitter.cpp +++ b/contrib/partio4Maya/partioEmitter.cpp @@ -32,21 +32,17 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #define ID_PARTIOEMITTER 0x00116ED0 // id is registered with autodesk no need to change #define McheckErr(stat, msg)\ - if ( MS::kSuccess != stat )\ - {\ - cerr << msg;\ - return MS::kFailure;\ - } + if ( MS::kSuccess != stat )\ + {\ + cerr << msg;\ + return MS::kFailure;\ + } #define ATTR_TYPE_INT 0 #define ATTR_TYPE_DOUBLE 1 #define ATTR_TYPE_VECTOR 2 -using namespace Partio; -using namespace std; - - -MTypeId partioEmitter::id ( ID_PARTIOEMITTER ); +MTypeId partioEmitter::id(ID_PARTIOEMITTER); //// OBJECT Attributes MObject partioEmitter::aCacheDir; @@ -64,8 +60,8 @@ MObject partioEmitter::aPartioAttributes; MObject partioEmitter::aMayaPPAttributes; MObject partioEmitter::aByFrame; -partioEmitter::partioEmitter(): - lastWorldPoint ( 0, 0, 0, 1 ), +partioEmitter::partioEmitter() : + lastWorldPoint(0, 0, 0, 1), mLastFileLoaded(""), mLastPath(""), mLastFile(""), @@ -76,13 +72,13 @@ partioEmitter::partioEmitter(): partioEmitter::~partioEmitter() { - MSceneMessage::removeCallback( partioEmitterOpenCallback); - MSceneMessage::removeCallback( partioEmitterImportCallback); - MSceneMessage::removeCallback( partioEmitterReferenceCallback); - MDGMessage::removeCallback( partioEmitterConnectionMade ); + MSceneMessage::removeCallback(partioEmitterOpenCallback); + MSceneMessage::removeCallback(partioEmitterImportCallback); + MSceneMessage::removeCallback(partioEmitterReferenceCallback); + MDGMessage::removeCallback(partioEmitterConnectionMade); } -void *partioEmitter::creator() +void* partioEmitter::creator() { return new partioEmitter; } @@ -92,8 +88,9 @@ void partioEmitter::postConstructor() MStatus stat; partioEmitterOpenCallback = MSceneMessage::addCallback(MSceneMessage::kAfterOpen, partioEmitter::reInit, this); partioEmitterImportCallback = MSceneMessage::addCallback(MSceneMessage::kAfterImport, partioEmitter::reInit, this); - partioEmitterReferenceCallback = MSceneMessage::addCallback(MSceneMessage::kAfterReference, partioEmitter::reInit, this); - partioEmitterConnectionMade = MDGMessage::addConnectionCallback ( partioEmitter::connectionMadeCallbk, NULL, &stat ); + partioEmitterReferenceCallback = MSceneMessage::addCallback(MSceneMessage::kAfterReference, partioEmitter::reInit, + this); + partioEmitterConnectionMade = MDGMessage::addConnectionCallback(partioEmitter::connectionMadeCallbk, NULL, &stat); } @@ -115,27 +112,28 @@ void partioEmitter::initCallback() cacheChanged = false; } -void partioEmitter::reInit(void *data) +void partioEmitter::reInit(void* data) { - partioEmitter *emitterNode = (partioEmitter*) data; + partioEmitter* emitterNode = (partioEmitter*)data; emitterNode->initCallback(); } /// Creates the tracking ID attribute on the particle object -void partioEmitter::connectionMadeCallbk(MPlug &srcPlug, MPlug &destPlug, bool made, void *clientData) +void partioEmitter::connectionMadeCallbk(MPlug& srcPlug, MPlug& destPlug, bool made, void* clientData) { MStatus status; MFnDependencyNode srcNode(srcPlug.node()); MFnDependencyNode destNode(destPlug.node()); - if (srcNode.typeId() == partioEmitter::id && (destNode.typeName() =="particle" || destNode.typeName() =="nParticle" ) ) + if (srcNode.typeId() == partioEmitter::id && + (destNode.typeName() == "particle" || destNode.typeName() == "nParticle")) { //cout << "connection made" << srcPlug.name() << " -> " << destPlug.name() << endl; - MObject particleShapeNode = destPlug.node(&status); + MObject particleShapeNode = destPlug.node(&status); MFnParticleSystem part(particleShapeNode, &status); - createPPAttr( part, "partioID", "pioID", 1); + createPPAttr(part, "partioID", "pioID", 1); } } @@ -151,23 +149,23 @@ MStatus partioEmitter::initialize() MFnTypedAttribute tAttr; MFnUnitAttribute uAttr; MFnNumericAttribute nAttr; - MFnEnumAttribute eAttr; - - aCacheDir = tAttr.create ( "cacheDir", "cachD", MFnStringData::kString ); - tAttr.setReadable ( true ); - tAttr.setWritable ( true ); - tAttr.setKeyable ( false ); - tAttr.setConnectable ( true ); - tAttr.setStorable ( true ); - - aCacheFile = tAttr.create ( "cachePrefix", "cachP", MFnStringData::kString ); - tAttr.setReadable ( true ); - tAttr.setWritable ( true ); - tAttr.setKeyable ( false ); - tAttr.setConnectable ( true ); - tAttr.setStorable ( true ); - - aCacheOffset = nAttr.create("cacheOffset", "coff", MFnNumericData::kInt, 0, &status ); + MFnEnumAttribute eAttr; + + aCacheDir = tAttr.create("cacheDir", "cachD", MFnStringData::kString); + tAttr.setReadable(true); + tAttr.setWritable(true); + tAttr.setKeyable(false); + tAttr.setConnectable(true); + tAttr.setStorable(true); + + aCacheFile = tAttr.create("cachePrefix", "cachP", MFnStringData::kString); + tAttr.setReadable(true); + tAttr.setWritable(true); + tAttr.setKeyable(false); + tAttr.setConnectable(true); + tAttr.setStorable(true); + + aCacheOffset = nAttr.create("cacheOffset", "coff", MFnNumericData::kInt, 0, &status); nAttr.setKeyable(true); aCacheActive = nAttr.create("cacheActive", "cAct", MFnNumericData::kBoolean, 1, &status); @@ -176,21 +174,21 @@ MStatus partioEmitter::initialize() aCacheStatic = nAttr.create("staticCache", "statC", MFnNumericData::kBoolean, 0, &status); nAttr.setKeyable(true); - aByFrame = nAttr.create( "byFrame", "byf", MFnNumericData::kInt ,1); - nAttr.setKeyable( true ); - nAttr.setReadable( true ); - nAttr.setWritable( true ); - nAttr.setConnectable( true ); - nAttr.setStorable( true ); + aByFrame = nAttr.create("byFrame", "byf", MFnNumericData::kInt, 1); + nAttr.setKeyable(true); + nAttr.setReadable(true); + nAttr.setWritable(true); + nAttr.setConnectable(true); + nAttr.setStorable(true); nAttr.setMin(1); nAttr.setMax(100); - aCacheFormat = eAttr.create( "cacheFormat", "cachFmt"); - std::map formatExtMap; - partio4Maya::buildSupportedExtensionList(formatExtMap,false); - for (unsigned short i = 0; i< formatExtMap.size(); i++) + aCacheFormat = eAttr.create("cacheFormat", "cachFmt"); + std::map formatExtMap; + partio4Maya::buildSupportedExtensionList(formatExtMap, false); + for (unsigned short i = 0; i < formatExtMap.size(); i++) { - eAttr.addField(formatExtMap[i].toUpperCase(), i); + eAttr.addField(formatExtMap[i].toUpperCase(), i); } eAttr.setDefault(4); // PDC @@ -200,14 +198,14 @@ MStatus partioEmitter::initialize() aUseEmitterTransform = nAttr.create("useEmitterTransform", "uet", MFnNumericData::kBoolean, false, &status); nAttr.setKeyable(true); - aSize = uAttr.create( "iconSize", "isz", MFnUnitAttribute::kDistance ); - uAttr.setDefault( 0.25 ); + aSize = uAttr.create("iconSize", "isz", MFnUnitAttribute::kDistance); + uAttr.setDefault(0.25); - aFlipYZ = nAttr.create( "flipYZ", "fyz", MFnNumericData::kBoolean); - nAttr.setDefault ( false ); - nAttr.setKeyable ( true ); + aFlipYZ = nAttr.create("flipYZ", "fyz", MFnNumericData::kBoolean); + nAttr.setDefault(false); + nAttr.setKeyable(true); - aJitterPos = nAttr.create("jitterPos", "jpos", MFnNumericData::kFloat,0.0, &status ); + aJitterPos = nAttr.create("jitterPos", "jpos", MFnNumericData::kFloat, 0.0, &status); nAttr.setDefault(0); nAttr.setMin(0); nAttr.setSoftMax(999); @@ -217,74 +215,73 @@ MStatus partioEmitter::initialize() nAttr.setDefault(1.0); nAttr.setKeyable(true); - aPartioAttributes = tAttr.create ("partioCacheAttributes", "pioCAts", MFnStringData::kString); + aPartioAttributes = tAttr.create("partioCacheAttributes", "pioCAts", MFnStringData::kString); tAttr.setArray(true); //tAttr.setUsesArrayDataBuilder( true ); - aMayaPPAttributes = tAttr.create("mayaPPAttributes", "pioMPPAts" , MFnStringData::kString); + aMayaPPAttributes = tAttr.create("mayaPPAttributes", "pioMPPAts", MFnStringData::kString); tAttr.setArray(true); //nAttr.setUsesArrayDataBuilder( true ); - status = addAttribute ( aCacheDir ); - status = addAttribute ( aCacheFile ); - status = addAttribute ( aCacheOffset ); - status = addAttribute ( aCacheActive ); - status = addAttribute ( aCacheStatic ); - status = addAttribute ( aCacheFormat ); - status = addAttribute ( aUseEmitterTransform ); - status = addAttribute ( aSize ); - status = addAttribute ( aFlipYZ ); - status = addAttribute ( aJitterPos ); - status = addAttribute ( aJitterFreq ); - status = addAttribute ( aPartioAttributes ); - status = addAttribute ( aMayaPPAttributes ); - status = addAttribute ( aByFrame ); - status = attributeAffects ( aCacheDir, mOutput ); - status = attributeAffects ( aCacheFile, mOutput ); - status = attributeAffects ( aCacheOffset, mOutput ); - status = attributeAffects ( aCacheStatic, mOutput ); - status = attributeAffects ( aCacheFormat, mOutput ); - status = attributeAffects ( aUseEmitterTransform, mOutput ); - status = attributeAffects ( aJitterPos, mOutput ); - status = attributeAffects ( aJitterFreq, mOutput ); - status = attributeAffects ( aByFrame, mOutput ); - return ( status ); + status = addAttribute(aCacheDir); + status = addAttribute(aCacheFile); + status = addAttribute(aCacheOffset); + status = addAttribute(aCacheActive); + status = addAttribute(aCacheStatic); + status = addAttribute(aCacheFormat); + status = addAttribute(aUseEmitterTransform); + status = addAttribute(aSize); + status = addAttribute(aFlipYZ); + status = addAttribute(aJitterPos); + status = addAttribute(aJitterFreq); + status = addAttribute(aPartioAttributes); + status = addAttribute(aMayaPPAttributes); + status = addAttribute(aByFrame); + status = attributeAffects(aCacheDir, mOutput); + status = attributeAffects(aCacheFile, mOutput); + status = attributeAffects(aCacheOffset, mOutput); + status = attributeAffects(aCacheStatic, mOutput); + status = attributeAffects(aCacheFormat, mOutput); + status = attributeAffects(aUseEmitterTransform, mOutput); + status = attributeAffects(aJitterPos, mOutput); + status = attributeAffects(aJitterFreq, mOutput); + status = attributeAffects(aByFrame, mOutput); + return (status); } -MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) - +MStatus partioEmitter::compute(const MPlug& plug, MDataBlock& block) { MStatus status, stat; bool cacheActive = block.inputValue(aCacheActive).asBool(); if (!cacheActive) { - return ( MS::kSuccess ); + return (MS::kSuccess); } - int cacheOffset = block.inputValue( aCacheOffset ).asInt(); - short cacheFormat = block.inputValue( aCacheFormat ).asShort(); - float jitterPos = block.inputValue( aJitterPos ).asFloat(); - float jitterFreq = block.inputValue( aJitterFreq ).asFloat(); - bool useEmitterTxfm = block.inputValue( aUseEmitterTransform ).asBool(); - bool cacheStatic = block.inputValue( aCacheStatic ).asBool(); - int byFrame = block.inputValue( aByFrame ).asInt(); + int cacheOffset = block.inputValue(aCacheOffset).asInt(); + short cacheFormat = block.inputValue(aCacheFormat).asShort(); + float jitterPos = block.inputValue(aJitterPos).asFloat(); + float jitterFreq = block.inputValue(aJitterFreq).asFloat(); + bool useEmitterTxfm = block.inputValue(aUseEmitterTransform).asBool(); + bool cacheStatic = block.inputValue(aCacheStatic).asBool(); + int byFrame = block.inputValue(aByFrame).asInt(); MString cacheDir = block.inputValue(aCacheDir).asString(); MString cacheFile = block.inputValue(aCacheFile).asString(); // Determine if we are requesting the output plug for this emitter node. // - if ( !( plug == mOutput ) ) - return ( MS::kUnknownParameter ); + if (!(plug == mOutput)) + return (MS::kUnknownParameter); - MPlugArray connectionArray; + MPlugArray connectionArray; plug.connectedTo(connectionArray, false, true, &stat); - MPlug particleShapeOutPlug = connectionArray[0]; - MObject particleShapeNode = particleShapeOutPlug.node(&stat); + MPlug particleShapeOutPlug = connectionArray[0]; + MObject particleShapeNode = particleShapeOutPlug.node(&stat); MFnParticleSystem part(particleShapeNode, &stat); MString partName = part.particleName(); @@ -294,57 +291,57 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) if (!part.isPerParticleDoubleAttribute("partioID")) { MGlobal::displayWarning("PartioEmitter->error: was unable to create/find partioID attr"); - return ( MS::kFailure ); + return (MS::kFailure); } - if (cacheDir == "" || cacheFile == "" ) + if (cacheDir == "" || cacheFile == "") { // Too Much noise! //MGlobal::displayError("PartioEmitter->Error: Please specify cache file!"); - return ( MS::kFailure ); + return (MS::kFailure); } // Get the logical index of the element this plug refers to, // because the node can be emitting particles into more // than one particle shape. - int multiIndex = plug.logicalIndex ( &status ); - McheckErr ( status, "ERROR in plug.logicalIndex.\n" ); + int multiIndex = plug.logicalIndex(&status); + McheckErr (status, "ERROR in plug.logicalIndex.\n"); // Get output data arrays (position, velocity, or parentId) // that the particle shape is holding from the previous frame. - MArrayDataHandle hOutArray = block.outputArrayValue ( mOutput, &status ); - McheckErr ( status, "ERROR in hOutArray = block.outputArrayValue.\n" ); + MArrayDataHandle hOutArray = block.outputArrayValue(mOutput, &status); + McheckErr (status, "ERROR in hOutArray = block.outputArrayValue.\n"); // Create a builder to aid in the array construction efficiently. - MArrayDataBuilder bOutArray = hOutArray.builder ( &status ); - McheckErr ( status, "ERROR in bOutArray = hOutArray.builder.\n" ); + MArrayDataBuilder bOutArray = hOutArray.builder(&status); + McheckErr (status, "ERROR in bOutArray = hOutArray.builder.\n"); // Get the appropriate data array that is being currently evaluated. - MDataHandle hOut = bOutArray.addElement ( multiIndex, &status ); - McheckErr ( status, "ERROR in hOut = bOutArray.addElement.\n" ); + MDataHandle hOut = bOutArray.addElement(multiIndex, &status); + McheckErr (status, "ERROR in hOut = bOutArray.addElement.\n"); // Create the data and apply the function set, // particle array initialized to length zero, // fnOutput.clear() MFnArrayAttrsData fnOutput; - MObject dOutput = fnOutput.create ( &status ); - McheckErr ( status, "ERROR in fnOutput.create.\n" ); + MObject dOutput = fnOutput.create(&status); + McheckErr (status, "ERROR in fnOutput.create.\n"); // Check if the particle object has reached it's maximum, // hence is full. If it is full then just return with zero particles. - bool beenFull = isFullValue ( multiIndex, block ); - if ( beenFull ) + bool beenFull = isFullValue(multiIndex, block); + if (beenFull) { - return ( MS::kSuccess ); + return (MS::kSuccess); } // Get deltaTime, currentTime and startTime. // If deltaTime <= 0.0, or currentTime <= startTime, // do not emit new pariticles and return. - MTime cT = currentTimeValue ( block ); - MTime sT = startTimeValue ( multiIndex, block ); - MTime dT = deltaTimeValue ( multiIndex, block ); - if ( ( cT <= sT )) + MTime cT = currentTimeValue(block); + MTime sT = startTimeValue(multiIndex, block); + MTime dT = deltaTimeValue(multiIndex, block); + if ((cT <= sT)) { // We do not emit particles before the start time, // we do support emitting / killing of particles if we scroll backward in time. @@ -352,15 +349,15 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) // establish the new data arrays allocated, and since we have // already set the data array to length zero it does // not generate any new particles. - hOut.set ( dOutput ); - block.setClean ( plug ); + hOut.set(dOutput); + block.setClean(plug); - return ( MS::kSuccess ); + return (MS::kSuccess); } bool motionBlurStep = false; - int integerTime = (int)floor(cT.value()+.52); + int integerTime = (int)floor(cT.value() + .52); // parse and get the new file name MString formatExt = ""; @@ -369,22 +366,22 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) MString newCacheFile = ""; MString renderCacheFile = ""; - partio4Maya::updateFileName( cacheFile, cacheDir, - cacheStatic, cacheOffset, - cacheFormat, integerTime, byFrame, - cachePadding, formatExt, - newCacheFile, renderCacheFile - ); + partio4Maya::updateFileName(cacheFile, cacheDir, + cacheStatic, cacheOffset, + cacheFormat, integerTime, byFrame, + cachePadding, formatExt, + newCacheFile, renderCacheFile + ); - float deltaTime = float(cT.value() - integerTime); + float deltaTime = float(cT.value() - integerTime); // motion blur rounding frame logic - if ((deltaTime < 1 || deltaTime > -1)&& deltaTime !=0) // motion blur step? + if ((deltaTime < 1 || deltaTime > -1) && deltaTime != 0) // motion blur step? { motionBlurStep = true; } - long seed = seedValue( multiIndex, block ); + long seed = seedValue(multiIndex, block); /// get the emitter offset MPoint emitterOffset; @@ -392,13 +389,16 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) double inheritFactor = inheritFactorValue(multiIndex, block); // using std:map to give us a nice fast binary search - map particleIDMap; + std::map particleIDMap; cacheChanged = false; if (mLastExt != formatExt || mLastPath != cacheDir || mLastFile != cacheFile) { - cacheChanged = true; + + if (!(mLastExt == "" && mLastPath == "" && mLastFile == "")) + cacheChanged = true; + mLastExt = formatExt; mLastPath = cacheDir; mLastFile = cacheFile; @@ -406,67 +406,71 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) // check if a Partio cache filepath exists and is not the same as last frame //if ( cacheFile != "" && partioCacheExists(cacheFile.asChar()) && cacheFile != mLastFileLoaded) - if ( newCacheFile != "" && partio4Maya::partioCacheExists(newCacheFile.asChar())) + if (newCacheFile != "" && partio4Maya::partioCacheExists(newCacheFile.asChar())) { MGlobal::displayInfo(MString("partioEmitter->Loading: " + newCacheFile)); - ParticlesDataMutable* particles= NULL; - ParticleAttribute IdAttribute; - ParticleAttribute posAttribute; - ParticleAttribute velAttribute; + PARTIO::ParticlesDataMutable* particles = NULL; + PARTIO::ParticleAttribute IdAttribute; + PARTIO::ParticleAttribute posAttribute; + PARTIO::ParticleAttribute velAttribute; - particles=read(newCacheFile.asChar()); + particles = PARTIO::read(newCacheFile.asChar()); if (particles) { //mLastFileLoaded = cacheFile; // SETUP THE MAP! - for (int i=0;inumParticles();i++) + for (int i = 0; i < particles->numParticles(); i++) { int id = -1; - if (particles->attributeInfo("id",IdAttribute) || particles->attributeInfo("Id",IdAttribute)) + if (particles->attributeInfo("id", IdAttribute) || particles->attributeInfo("Id", IdAttribute)) { - const int* partioID = particles->data(IdAttribute,i); + const int* partioID = particles->data(IdAttribute, i); id = partioID[0]; } - else if (particles->attributeInfo("particleId",IdAttribute) || particles->attributeInfo("ParticleId",IdAttribute)) + else if (particles->attributeInfo("particleId", IdAttribute) || + particles->attributeInfo("ParticleId", IdAttribute)) { - const int* partioID = particles->data(IdAttribute,i); + const int* partioID = particles->data(IdAttribute, i); id = partioID[0]; } else { // we attempt to use the array index as our only last resort - MGlobal::displayWarning("Loaded Partio cache has a non-standard or non-existant id attribute, this may render things unstable"); + MGlobal::displayWarning( + "Loaded Partio cache has a non-standard or non-existant id attribute, this may render things unstable"); id = i; } particleIDMap[id] = i; } - if (!particles->attributeInfo("position",posAttribute) && !particles->attributeInfo("Position",posAttribute)) + if (!particles->attributeInfo("position", posAttribute) && + !particles->attributeInfo("Position", posAttribute)) { - std::cerr<<"Failed to find position attribute "<attributeInfo("velocity",velAttribute) && !particles->attributeInfo("Velocity",velAttribute)) + if (!particles->attributeInfo("velocity", velAttribute) && + !particles->attributeInfo("Velocity", velAttribute)) { - hasVelo = false; + hasVelo = false; //std::cerr<<"Failed to find velocity attribute "<::iterator it; + std::map::iterator it; it = particleIDMap.begin(); it = particleIDMap.end(); - unsigned int numAttr=particles->numAttributes(); + unsigned int numAttr = particles->numAttributes(); - MPlug zPlug (thisMObject(), aPartioAttributes); - MPlug yPlug (thisMObject(), aMayaPPAttributes); + MPlug zPlug(thisMObject(), aPartioAttributes); + MPlug yPlug(thisMObject(), aMayaPPAttributes); if (cacheChanged || zPlug.numElements() != numAttr) // update the AE Controls for attrs in the cache { @@ -498,26 +502,26 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) */ - for (unsigned int i=0;iattributeInfo(i,attr); + PARTIO::ParticleAttribute attr; + particles->attributeInfo(i, attr); // crazy casting string to char - char *temp; - temp = new char[(attr.name).length()+1]; - strcpy (temp, attr.name.c_str()); + char* temp; + temp = new char[(attr.name).length() + 1]; + strcpy(temp, attr.name.c_str()); - MString mStringAttrName(""); + MString mStringAttrName(""); mStringAttrName += MString(temp); - zPlug.selectAncestorLogicalIndex(i,aPartioAttributes); + zPlug.selectAncestorLogicalIndex(i, aPartioAttributes); zPlug.setValue(MString(temp)); - yPlug.selectAncestorLogicalIndex(i,aMayaPPAttributes); + yPlug.selectAncestorLogicalIndex(i, aMayaPPAttributes); yPlug.setValue(MString("")); - delete [] temp; + delete[] temp; } /* this crashes MArrayDataHandle hPartioAttrs = block.inputArrayValue(aPartioAttributes); @@ -544,7 +548,7 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) MString command = ""; MString zPlugName = zPlug.name(); MString yPlugName = yPlug.name(); - for (unsigned int x = numAttr; x vectorAttrArrays; - std::map doubleAttrArrays; + std::map vectorAttrArrays; + std::map doubleAttrArrays; // we use this mapping to allow for direct writing of attrs to PP variables - std::map userPPMapping; + std::map userPPMapping; - for (unsigned int i=0;iattributeInfo(i,attr); + PARTIO::ParticleAttribute attr; + particles->attributeInfo(i, attr); - yPlug.selectAncestorLogicalIndex(i,aMayaPPAttributes); + yPlug.selectAncestorLogicalIndex(i, aMayaPPAttributes); userPPMapping[yPlug.asString().asChar()] = attr.name; - yPlug.selectAncestorLogicalIndex(i,aMayaPPAttributes); + yPlug.selectAncestorLogicalIndex(i, aMayaPPAttributes); if (yPlug.asString() != "") { MString ppAttrName = yPlug.asString(); @@ -587,7 +591,7 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) { if (!part.isPerParticleVectorAttribute(ppAttrName)) { - MGlobal::displayInfo(MString("partioEmitter->adding ppAttr " + ppAttrName) ); + MGlobal::displayInfo(MString("partioEmitter->adding ppAttr " + ppAttrName)); // moving this to an outside mel proc MString command; @@ -604,7 +608,7 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) { MVectorArray vAttribute; part.getPerParticleAttribute(ppAttrName, vAttribute, &status); - if ( !status ) + if (!status) { MGlobal::displayError("PartioEmitter->could not get vector PP array "); } @@ -630,7 +634,7 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) { MDoubleArray dAttribute; part.getPerParticleAttribute(ppAttrName, dAttribute, &status); - if ( !status ) + if (!status) { MGlobal::displayError("PartioEmitter->could not get double PP array "); } @@ -661,50 +665,51 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) MDoubleArray partioIDs; part.getPerParticleAttribute("partioID", partioIDs); - MIntArray deletePoints; + MIntArray deletePoints; - std::map ::iterator vecIt; - std::map ::iterator doubleIt; + std::map::iterator vecIt; + std::map::iterator doubleIt; - for (unsigned int x = 0; xmoving existing particles" << endl; it = particleIDMap.find((int)partioIDs[x]); if (it != particleIDMap.end()) // move the existing particles { - const float* pos=particles->data(posAttribute,it->second); + const float* pos = particles->data(posAttribute, it->second); MVector jitter = partio4Maya::jitterPoint(it->second, jitterFreq, float(seed), jitterPos); - positions[x] = MVector(pos[0],pos[1],pos[2])+(jitter); - if (useEmitterTxfm) { + positions[x] = MVector(pos[0], pos[1], pos[2]) + (jitter); + if (useEmitterTxfm) + { positions[x] += emitterOffset; } - MVector velo(0,0,0); - if(hasVelo) - { - const float* vel=particles->data(velAttribute,it->second); - velo = MVector(vel[0],vel[1],vel[2]); - } + MVector velo(0, 0, 0); + if (hasVelo) + { + const float* vel = particles->data(velAttribute, it->second); + velo = MVector(vel[0], vel[1], vel[2]); + } if (motionBlurStep) { - positions[x] += (velo/24)*deltaTime; + positions[x] += (velo / 24) * deltaTime; } velocities[x] = velo; for (doubleIt = doubleAttrArrays.begin(); doubleIt != doubleAttrArrays.end(); doubleIt++) { - ParticleAttribute doubleAttr; - particles->attributeInfo(userPPMapping[doubleIt->first].c_str(),doubleAttr); - const float* doubleVal = particles->data(doubleAttr, it->second); + PARTIO::ParticleAttribute doubleAttr; + particles->attributeInfo(userPPMapping[doubleIt->first].c_str(), doubleAttr); + const float* doubleVal = particles->data(doubleAttr, it->second); doubleAttrArrays[doubleIt->first][x] = doubleVal[0]; } for (vecIt = vectorAttrArrays.begin(); vecIt != vectorAttrArrays.end(); vecIt++) { - ParticleAttribute vectorAttr; + PARTIO::ParticleAttribute vectorAttr; particles->attributeInfo(userPPMapping[vecIt->first].c_str(), vectorAttr); const float* vecVal = particles->data(vectorAttr, it->second); - vectorAttrArrays[vecIt->first][x] = MVector(vecVal[0],vecVal[1],vecVal[2]); + vectorAttrArrays[vecIt->first][x] = MVector(vecVal[0], vecVal[1], vecVal[2]); } particleIDMap.erase(it); @@ -716,23 +721,23 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) } // TODO: handle a "release" attribute list to allow expressions to force partio emitter to forget or skip over certain particles - for (unsigned int y = 0; y< deletePoints.length(); y++) + for (unsigned int y = 0; y < deletePoints.length(); y++) { //cout << "partioEmitterDebug->deleting particles" << endl; - positions.remove(deletePoints[y]-y); - velocities.remove(deletePoints[y]-y); - lifespans.remove(deletePoints[y]-y); + positions.remove(deletePoints[y] - y); + velocities.remove(deletePoints[y] - y); + lifespans.remove(deletePoints[y] - y); for (doubleIt = doubleAttrArrays.begin(); doubleIt != doubleAttrArrays.end(); doubleIt++) { - doubleAttrArrays[doubleIt->first].remove(deletePoints[y]-y); + doubleAttrArrays[doubleIt->first].remove(deletePoints[y] - y); } for (vecIt = vectorAttrArrays.begin(); vecIt != vectorAttrArrays.end(); vecIt++) { - vectorAttrArrays[vecIt->first].remove(deletePoints[y]-y); + vectorAttrArrays[vecIt->first].remove(deletePoints[y] - y); } - part.setCount (particles->numParticles()); + part.setCount(particles->numParticles()); } // everything left is new particles @@ -741,44 +746,45 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) { //cout << "partioEmitterDebug->emitting new particles" << endl; - const float* pos=particles->data(posAttribute,it->second); + const float* pos = particles->data(posAttribute, it->second); /// TODO: this will break if we're dealing with a format type that has no "id" attribute or one is not found using the /// standard nomenclature "id" or "particleId" - const int* id=particles->data(IdAttribute,it->second); + const int* id = particles->data(IdAttribute, it->second); MVector temp(pos[0], pos[1], pos[2]); MVector jitter = partio4Maya::jitterPoint(it->second, jitterFreq, float(seed), jitterPos); - if (useEmitterTxfm) { + if (useEmitterTxfm) + { temp += emitterOffset; } - MVector velo(0,0,0); - if (hasVelo) - { - const float* vel=particles->data(velAttribute,it->second); - velo = MVector(vel[0],vel[1],vel[2]); - } + MVector velo(0, 0, 0); + if (hasVelo) + { + const float* vel = particles->data(velAttribute, it->second); + velo = MVector(vel[0], vel[1], vel[2]); + } - inPosArray.append(temp+(jitter)); - inVelArray.append(velo*inheritFactor); + inPosArray.append(temp + (jitter)); + inVelArray.append(velo * inheritFactor); partioIDs.append(id[0]); for (doubleIt = doubleAttrArrays.begin(); doubleIt != doubleAttrArrays.end(); doubleIt++) { - ParticleAttribute doubleAttr; - particles->attributeInfo(userPPMapping[doubleIt->first].c_str(),doubleAttr); - const float* doubleVal = particles->data(doubleAttr, it->second); + PARTIO::ParticleAttribute doubleAttr; + particles->attributeInfo(userPPMapping[doubleIt->first].c_str(), doubleAttr); + const float* doubleVal = particles->data(doubleAttr, it->second); doubleAttrArrays[doubleIt->first].append(doubleVal[0]); } for (vecIt = vectorAttrArrays.begin(); vecIt != vectorAttrArrays.end(); vecIt++) { - ParticleAttribute vectorAttr; + PARTIO::ParticleAttribute vectorAttr; particles->attributeInfo(userPPMapping[vecIt->first].c_str(), vectorAttr); const float* vecVal = particles->data(vectorAttr, it->second); - vectorAttrArrays[vecIt->first].append(MVector(vecVal[0],vecVal[1],vecVal[2])); + vectorAttrArrays[vecIt->first].append(MVector(vecVal[0], vecVal[1], vecVal[2])); } } @@ -788,7 +794,8 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) part.setPerParticleAttribute("lifespanPP", lifespans); - MGlobal::displayInfo (MString ("PartioEmitter->Emitting ") + inPosArray.length() + MString( " new particles")); + MGlobal::displayInfo( + MString("PartioEmitter->Emitting ") + inPosArray.length() + MString(" new particles")); part.emit(inPosArray, inVelArray); part.setPerParticleAttribute("partioID", partioIDs); @@ -814,21 +821,21 @@ MStatus partioEmitter::compute ( const MPlug& plug, MDataBlock& block ) } else { - MGlobal::displayError("PartioEmitter->Error loading the Cache file, it does not exist on disk, check path/file."); + MGlobal::displayError( + "PartioEmitter->Error loading the Cache file, it does not exist on disk, check path/file."); //cout << "partioEmitter->No File at: " << newCacheFile << endl; } // Update the data block with new dOutput and set plug clean. - hOut.set ( dOutput ); - block.setClean ( plug ); - return ( MS::kSuccess ); + hOut.set(dOutput); + block.setClean(plug); + return (MS::kSuccess); } - -MStatus partioEmitter::getWorldPosition ( MPoint &point ) +MStatus partioEmitter::getWorldPosition(MPoint& point) // // Descriptions: // get the emitter position in the world space. @@ -838,68 +845,68 @@ MStatus partioEmitter::getWorldPosition ( MPoint &point ) MStatus status; MObject thisNode = thisMObject(); - MFnDependencyNode fnThisNode ( thisNode ); + MFnDependencyNode fnThisNode(thisNode); // get worldMatrix attribute. - MObject worldMatrixAttr = fnThisNode.attribute ( "worldMatrix" ); + MObject worldMatrixAttr = fnThisNode.attribute("worldMatrix"); // build worldMatrix plug, and specify which element the plug refers to. // We use the first element(the first dagPath of this emitter). - MPlug matrixPlug ( thisNode, worldMatrixAttr ); - matrixPlug = matrixPlug.elementByLogicalIndex ( 0 ); + MPlug matrixPlug(thisNode, worldMatrixAttr); + matrixPlug = matrixPlug.elementByLogicalIndex(0); // Get the value of the 'worldMatrix' attribute MObject matrixObject; - status = matrixPlug.getValue ( matrixObject ); - if ( !status ) + status = matrixPlug.getValue(matrixObject); + if (!status) { - status.perror ( "partioEmitter::getWorldPosition: get matrixObject" ); - return ( status ); + status.perror("partioEmitter::getWorldPosition: get matrixObject"); + return (status); } - MFnMatrixData worldMatrixData ( matrixObject, &status ); - if ( !status ) + MFnMatrixData worldMatrixData(matrixObject, &status); + if (!status) { - status.perror ( "partioEmitter::getWorldPosition: get worldMatrixData" ); - return ( status ); + status.perror("partioEmitter::getWorldPosition: get worldMatrixData"); + return (status); } - MMatrix worldMatrix = worldMatrixData.matrix ( &status ); - if ( !status ) + MMatrix worldMatrix = worldMatrixData.matrix(&status); + if (!status) { - status.perror ( "partioEmitter::getWorldPosition: get worldMatrix" ); - return ( status ); + status.perror("partioEmitter::getWorldPosition: get worldMatrix"); + return (status); } // assign the translate to the given vector. - point[0] = worldMatrix ( 3, 0 ); - point[1] = worldMatrix ( 3, 1 ); - point[2] = worldMatrix ( 3, 2 ); + point[0] = worldMatrix(3, 0); + point[1] = worldMatrix(3, 1); + point[2] = worldMatrix(3, 2); - return ( status ); + return (status); } ////////// DRAW the Partio Logo helper -void partioEmitter::draw ( M3dView& view, const MDagPath& path, M3dView::DisplayStyle style, M3dView:: DisplayStatus ) +void partioEmitter::draw(M3dView& view, const MDagPath& path, M3dView::DisplayStyle style, M3dView::DisplayStatus) { view.beginGL(); MObject thisNode = thisMObject(); - MPlug sizePlug( thisNode, aSize ); + MPlug sizePlug(thisNode, aSize); MDistance sizeVal; - sizePlug.getValue( sizeVal ); + sizePlug.getValue(sizeVal); - float multiplier = (float) sizeVal.asCentimeters(); + float multiplier = (float)sizeVal.asCentimeters(); partio4Maya::drawPartioLogo(multiplier); - view.endGL (); + view.endGL(); } ////////////////////////////////////////////////// -MStatus partioEmitter::createPPAttr( MFnParticleSystem &part, MString attrName, MString shortName, int type) +MStatus partioEmitter::createPPAttr(MFnParticleSystem& part, MString attrName, MString shortName, int type) { // type = 0 = int // type = 1 = double @@ -909,59 +916,62 @@ MStatus partioEmitter::createPPAttr( MFnParticleSystem &part, MString attrName, MFnTypedAttribute initialStateAttr; MFnTypedAttribute ppAttr; - MStatus stat1,stat2 = MS::kFailure; + MStatus stat1, stat2 = MS::kFailure; MObject initialStateAttrObj; MObject attrObj; switch (type) { - case 0: - { - if (!part.isPerParticleIntAttribute((attrName+"0")) && !part.isPerParticleIntAttribute(attrName)) + case 0: { - initialStateAttrObj = initialStateAttr.create ((attrName+"0"), (shortName+"0"), MFnData::kIntArray, &stat1); - attrObj = ppAttr.create ((attrName), (shortName), MFnData::kIntArray, &stat2); + if (!part.isPerParticleIntAttribute((attrName + "0")) && !part.isPerParticleIntAttribute(attrName)) + { + initialStateAttrObj = initialStateAttr.create((attrName + "0"), (shortName + "0"), MFnData::kIntArray, + &stat1); + attrObj = ppAttr.create((attrName), (shortName), MFnData::kIntArray, &stat2); + } } - } - break; - case 1: - { - if (!part.isPerParticleDoubleAttribute((attrName+"0")) && !part.isPerParticleDoubleAttribute(attrName)) + break; + case 1: { - initialStateAttrObj = initialStateAttr.create ((attrName+"0"), (shortName+"0"), MFnData::kDoubleArray, &stat1); - attrObj = ppAttr.create ((attrName), (shortName), MFnData::kDoubleArray, &stat2); + if (!part.isPerParticleDoubleAttribute((attrName + "0")) && !part.isPerParticleDoubleAttribute(attrName)) + { + initialStateAttrObj = initialStateAttr.create((attrName + "0"), (shortName + "0"), + MFnData::kDoubleArray, &stat1); + attrObj = ppAttr.create((attrName), (shortName), MFnData::kDoubleArray, &stat2); + } } - } - break; - case 2: - { - if (!part.isPerParticleVectorAttribute((attrName+"0")) && !part.isPerParticleVectorAttribute(attrName)) + break; + case 2: + { + if (!part.isPerParticleVectorAttribute((attrName + "0")) && !part.isPerParticleVectorAttribute(attrName)) + { + initialStateAttrObj = initialStateAttr.create((attrName + "0"), (shortName + "0"), + MFnData::kVectorArray, &stat1); + attrObj = ppAttr.create((attrName), (shortName), MFnData::kVectorArray, &stat2); + } + } + break; + default: { - initialStateAttrObj = initialStateAttr.create ((attrName+"0"), (shortName+"0"), MFnData::kVectorArray, &stat1); - attrObj = ppAttr.create ((attrName), (shortName), MFnData::kVectorArray, &stat2); } - } - break; - default: - {} } if (stat1 == MStatus::kSuccess && stat2 == MStatus::kSuccess) { - initialStateAttr.setStorable (true); - ppAttr.setStorable (true); - ppAttr.setKeyable (true); - stat1 = part.addAttribute (initialStateAttrObj, MFnDependencyNode::kLocalDynamicAttr); + initialStateAttr.setStorable(true); + ppAttr.setStorable(true); + ppAttr.setKeyable(true); + stat1 = part.addAttribute(initialStateAttrObj, MFnDependencyNode::kLocalDynamicAttr); if (!stat1) { - MGlobal::displayWarning("PartioEmitter->error: was unable to create "+attrName+"0"+ " attr"); + MGlobal::displayWarning("PartioEmitter->error: was unable to create " + attrName + "0" + " attr"); } - stat2 = part.addAttribute (attrObj, MFnDependencyNode::kLocalDynamicAttr); + stat2 = part.addAttribute(attrObj, MFnDependencyNode::kLocalDynamicAttr); if (!stat2) { - MGlobal::displayWarning("PartioEmitter->error: was unable to create "+ (attrName)+ " attr"); + MGlobal::displayWarning("PartioEmitter->error: was unable to create " + (attrName) + " attr"); } } if (stat1 != MStatus::kSuccess || stat2 != MStatus::kSuccess) - { return MStatus::kFailure; } diff --git a/contrib/partio4Maya/partioExport.cpp b/contrib/partio4Maya/partioExport.cpp index 49d867a4..f08a7948 100644 --- a/contrib/partio4Maya/partioExport.cpp +++ b/contrib/partio4Maya/partioExport.cpp @@ -29,29 +29,26 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "partioExport.h" -#define kAttributeFlagS "-atr" -#define kAttributeFlagL "-attribute" -#define kMinFrameFlagS "-mnf" -#define kMinFrameFlagL "-minFrame" -#define kMaxFrameFlagS "-mxf" -#define kMaxFrameFlagL "-maxFrame" -#define kHelpFlagS "-h" -#define kHelpFlagL "-help" -#define kPathFlagS "-p" -#define kPathFlagL "-path" -#define kFlipFlagS "-flp" -#define kFlipFlagL "-flip" -#define kFormatFlagS "-f" -#define kFormatFlagL "-format" -#define kFilePrefixFlagS "-fp" -#define kFilePrefixFlagL "-filePrefix" +#include + +#define kAttributeFlagS "-atr" +#define kAttributeFlagL "-attribute" +#define kMinFrameFlagS "-mnf" +#define kMinFrameFlagL "-minFrame" +#define kMaxFrameFlagS "-mxf" +#define kMaxFrameFlagL "-maxFrame" +#define kHelpFlagS "-h" +#define kHelpFlagL "-help" +#define kPathFlagS "-p" +#define kPathFlagL "-path" +#define kFlipFlagS "-flp" +#define kFlipFlagL "-flip" +#define kFormatFlagS "-f" +#define kFormatFlagL "-format" +#define kFilePrefixFlagS "-fp" +#define kFilePrefixFlagL "-filePrefix" #define kPerFrameFlagS "-pf" -#define kPerFrameFlagL "-perFrame" - - -using namespace std; - - +#define kPerFrameFlagL "-perFrame" bool PartioExport::hasSyntax() { @@ -65,16 +62,16 @@ MSyntax PartioExport::createSyntax() MSyntax syntax; - syntax.addFlag(kHelpFlagS, kHelpFlagL, MSyntax::kNoArg); - syntax.addFlag(kPathFlagS, kPathFlagL, MSyntax::kString); + syntax.addFlag(kHelpFlagS, kHelpFlagL, MSyntax::kNoArg); + syntax.addFlag(kPathFlagS, kPathFlagL, MSyntax::kString); syntax.addFlag(kAttributeFlagS, kAttributeFlagL, MSyntax::kString); - syntax.makeFlagMultiUse( kAttributeFlagS ); + syntax.makeFlagMultiUse(kAttributeFlagS); syntax.addFlag(kFlipFlagS, kFlipFlagL, MSyntax::kNoArg); syntax.addFlag(kFormatFlagS, kFormatFlagL, MSyntax::kString); - syntax.addFlag(kMinFrameFlagS,kMinFrameFlagL, MSyntax::kLong); + syntax.addFlag(kMinFrameFlagS, kMinFrameFlagL, MSyntax::kLong); syntax.addFlag(kMaxFrameFlagS, kMaxFrameFlagL, MSyntax::kLong); - syntax.addFlag(kFilePrefixFlagS,kFilePrefixFlagL, MSyntax::kString); - syntax.addFlag(kPerFrameFlagS,kPerFrameFlagL, MSyntax::kString); + syntax.addFlag(kFilePrefixFlagS, kFilePrefixFlagL, MSyntax::kString); + syntax.addFlag(kPerFrameFlagS, kPerFrameFlagL, MSyntax::kString); syntax.addArg(MSyntax::kString); syntax.enableQuery(false); syntax.enableEdit(false); @@ -82,29 +79,26 @@ MSyntax PartioExport::createSyntax() return syntax; } - void* PartioExport::creator() { return new PartioExport; } - MStatus PartioExport::doIt(const MArgList& Args) { - MStatus status; MArgDatabase argData(syntax(), Args, &status); - if ( argData.isFlagSet(kHelpFlagL)) + if (argData.isFlagSet(kHelpFlagL)) { printUsage(); return MStatus::kFailure; } - - if ( Args.length() < 3) + if (Args.length() < 3) { - MGlobal::displayError("PartioExport-> need the EXPORT PATH and a PARTICLESHAPE's NAME, and at least one ATTRIBUTE's NAME you want to export." ); + MGlobal::displayError( + "PartioExport-> need the EXPORT PATH and a PARTICLESHAPE's NAME, and at least one ATTRIBUTE's NAME you want to export."); printUsage(); return MStatus::kFailure; } @@ -113,62 +107,54 @@ MStatus PartioExport::doIt(const MArgList& Args) MString Format; MString fileNamePrefix; bool hasFilePrefix = false; - bool perFrame = false; + bool perFrame = false; if (argData.isFlagSet(kPathFlagL)) - { argData.getFlagArgument(kPathFlagL, 0, Path); - } if (argData.isFlagSet(kFormatFlagL)) - { argData.getFlagArgument(kFormatFlagL, 0, Format); - } if (argData.isFlagSet(kFilePrefixFlagL)) { argData.getFlagArgument(kFilePrefixFlagL, 0, fileNamePrefix); if (fileNamePrefix.length() > 0) - { hasFilePrefix = true; - } } Format = Format.toLowerCase(); if (Format != "pda" && - Format != "pdb" && - Format != "pdc" && - Format != "prt" && - Format != "bin" && - Format != "bgeo" && - Format != "geo" && - Format != "ptc" && - Format != "mc" && - Format != "rib" && - Format != "pts" && - Format != "xyz" && - Format != "pcd" && - Format != "rpc" && - //Format != "icecache" && - Format != "rib" ) + Format != "pdb" && + Format != "pdc" && + Format != "prt" && + Format != "bin" && + Format != "bgeo" && + Format != "geo" && + Format != "ptc" && + Format != "mc" && + Format != "rib" && + Format != "pts" && + Format != "xyz" && + Format != "pcd" && + Format != "rpc" && + //Format != "icecache" && + Format != "rib") { //MGlobal::displayError("PartioExport-> format is one of: pda,pdb,pdc,prt,bin,bgeo,geo,ptc,mc,icecache,rib,ass"); - MGlobal::displayError("PartioExport-> format is one of: pda,pdb,pdc,prt,bin,rpc,bgeo,geo,ptc,mc,rib,ass"); + MGlobal::displayError("PartioExport-> format is one of: pda,pdb,pdc,prt,bin,rpc,bgeo,geo,ptc,mc,rib,ass"); return MStatus::kFailure; } bool startFrameSet = false; bool endFrameSet = false; - int startFrame, endFrame; + int startFrame, endFrame; if (argData.isFlagSet(kMinFrameFlagL)) { argData.getFlagArgument(kMinFrameFlagL, 0, startFrame); startFrameSet = true; } else - { startFrame = -123456; - } if (argData.isFlagSet(kMaxFrameFlagL)) { @@ -176,24 +162,15 @@ MStatus PartioExport::doIt(const MArgList& Args) endFrameSet = true; } else - { endFrame = -123456; - } + const bool swapUP = argData.isFlagSet(kFlipFlagL); - bool swapUP = false; - - - if (argData.isFlagSet(kFlipFlagL)) + if (argData.isFlagSet(kPerFrameFlagL)) { - swapUP = true; + perFrame = true; } - if (argData.isFlagSet(kPerFrameFlagL)) - { - perFrame = true; - } - MString PSName; // particle shape name argData.getCommandArgument(0, PSName); MSelectionList list; @@ -202,33 +179,37 @@ MStatus PartioExport::doIt(const MArgList& Args) list.getDependNode(0, objNode); MFnDependencyNode depNode(objNode, &status); - if ( objNode.apiType() != MFn::kParticle && objNode.apiType() != MFn::kNParticle ) + if (objNode.apiType() != MFn::kParticle && objNode.apiType() != MFn::kNParticle) { MGlobal::displayError("PartioExport-> can't find your PARTICLESHAPE."); return MStatus::kFailure; } /// parse attribute flags - unsigned int numUses = argData.numberOfFlagUses( kAttributeFlagL ); + unsigned int numUses = argData.numberOfFlagUses(kAttributeFlagL); /// loop thru the rest of the attributes given - MStringArray attrNames; + MStringArray attrNames; attrNames.append(MString("id")); attrNames.append(MString("position")); bool worldVeloCheck = false; - for ( unsigned int i = 0; i < numUses; i++ ) + for (unsigned int i = 0; i < numUses; i++) { MArgList argList; - status = argData.getFlagArgumentList( kAttributeFlagL, i, argList ); - if ( !status ) return status; + status = argData.getFlagArgumentList(kAttributeFlagL, i, argList); + if (!status) + return status; - MString AttrName = argList.asString( 0, &status ); - if ( !status ) return status; + MString AttrName = argList.asString(0, &status); + if (!status) + return status; - if ( AttrName == "position" || AttrName == "worldPosition" || AttrName == "id" || AttrName == "particleId") {} - else if ( AttrName == "worldVelocity" || AttrName == "velocity" ) + if (AttrName == "position" || AttrName == "worldPosition" || AttrName == "id" || AttrName == "particleId") + { + } + else if (AttrName == "worldVelocity" || AttrName == "velocity") { if (!worldVeloCheck) { @@ -237,10 +218,7 @@ MStatus PartioExport::doIt(const MArgList& Args) } } else - { attrNames.append(AttrName); - } - } /// ARGS PARSED @@ -248,295 +226,277 @@ MStatus PartioExport::doIt(const MArgList& Args) computation.beginComputation(); MFnParticleSystem PS(objNode); - MFnParticleSystem DPS(objNode); - bool isDeformed = false; - - if (PS.isDeformedParticleShape()) - { - MObject origObj = PS.originalParticleShape(); - PS.setObject(origObj); - isDeformed = true; - } - else - { - MObject defObj = PS.deformedParticleShape(&status); - DPS.setObject(defObj); - isDeformed = true; - } - //cout << "Orig Particle system -> " << PS.name() << endl; - //cout << "Deformed Particle system -> " << DPS.name() << endl; - - int outFrame= -123456; - - for (int frame = startFrame; frame<=endFrame; frame++) + MFnParticleSystem DPS(objNode); + + if (PS.isDeformedParticleShape()) { - MTime dynTime; - dynTime.setValue(frame); - if (frame == startFrame && startFrame < endFrame) - { - PS.evaluateDynamics(dynTime,true); - if (isDeformed) - { - DPS.evaluateDynamics(dynTime,true); - } - } - else - { - PS.evaluateDynamics(dynTime,false); - if (isDeformed) - { - DPS.evaluateDynamics(dynTime,false); - } - } - - /// why is this being done AFTER the evaluate dynamics stuff? - if (startFrameSet && endFrameSet && startFrame < endFrame) + MObject origObj = PS.originalParticleShape(); + PS.setObject(origObj); + } + else + { + MObject defObj = PS.deformedParticleShape(&status); + DPS.setObject(defObj); + } + + //std::cout << "Orig Particle system -> " << PS.name() << std::endl; + //std::cout << "Deformed Particle system -> " << DPS.name() << std::endl; + + int outFrame = -123456; + + for (int frame = startFrame; frame <= endFrame; frame++) + { + MTime dynTime; + dynTime.setValue(frame); + // for some reason nParticles have started to not eval properly using lifespan unless you turn this off. + if (objNode.apiType() != MFn::kNParticle) { - MGlobal::viewFrame(frame); - outFrame = frame; + if (frame == startFrame && startFrame < endFrame) + { + PS.evaluateDynamics(dynTime,true); + DPS.evaluateDynamics(dynTime, true); + } + else + { + PS.evaluateDynamics(dynTime,false); + DPS.evaluateDynamics(dynTime, false); + } } else { - outFrame = (int)MAnimControl::currentTime().as(MTime::kFilm); + // NParticles needs to frame advance and update a different way + // neither of these work with NParticles+viewport2.0 for some reason + + MGlobal::viewFrame(dynTime); + + //char frameNum[10]; + //sprintf(frameNum, "%i", frame); + //MGlobal::executeCommand(MString("currentTime ")+frameNum, true, false ); + } + + /// why is this being done AFTER the evaluate dynamics stuff? + if (startFrameSet && endFrameSet && startFrame < endFrame) + { + outFrame = frame; } + else + outFrame = (int)MAnimControl::currentTime().as(MTime::uiUnit()); - char padNum [10]; + char padNum[10]; // temp usage for this.. PDC's are counted by 250s.. TODO: implement "substeps" setting if (Format == "pdc") { int substepFrame = outFrame; - substepFrame = outFrame*250; + substepFrame = outFrame * 250; sprintf(padNum, "%d", substepFrame); } else - { sprintf(padNum, "%04d", outFrame); - } - MString outputPath = Path; + MString outputPath = Path; outputPath += "/"; // if we have supplied a fileName prefix, then use it instead of the particle shape name if (hasFilePrefix) - { outputPath += fileNamePrefix; - } else - { outputPath += PSName; - } outputPath += "."; outputPath += padNum; outputPath += "."; outputPath += Format; - MGlobal::displayInfo("PartioExport-> exporting: "+ outputPath); - - unsigned int particleCount = PS.count(); - + MGlobal::displayInfo("PartioExport-> exporting: " + outputPath); + const unsigned int particleCount = PS.count(); + + const unsigned int numAttributes = attrNames.length(); + + // In some cases, especially whenever particles are dying + // the length of the attribute vector returned + // from maya is smaller than the total number of particles. + // So we have to first read all the attributes, then + // determine the minimum amount of particles that all have valid data + // then write the data out for them in one go. This introduces + // code complexity, but still better than zeroing out the data + // wherever we don't have valid data. Using zeroes could potentially + // create popping artifacts especially if the particle system is + // used for an instancer. + if ((particleCount > 0) && (numAttributes > 0)) + { + PARTIO::ParticlesDataMutable* p = PARTIO::createInterleave(); - Partio::ParticlesDataMutable* p = Partio::createInterleave(); - p->addParticles((const int)particleCount); - Partio::ParticlesDataMutable::iterator it=p->begin(); + std::vector > intAttributes; + std::vector > doubleAttributes; + std::vector > vectorAttributes; - if (particleCount > 0) - { + unsigned int minParticleCount = particleCount; + intAttributes.reserve(numAttributes); + doubleAttributes.reserve(numAttributes); + vectorAttributes.reserve(numAttributes); - for (unsigned int i = 0; i< attrNames.length(); i++) + for (unsigned int i = 0; (i < numAttributes) && (minParticleCount > 0); ++i) { - // you must reset the iterator before adding new attributes or accessors - it=p->begin(); - MString attrName = attrNames[i]; - //cout << attrName ; - + MString attrName = attrNames[i]; /// INT Attribute found if (PS.isPerParticleIntAttribute(attrName) || attrName == "id" || attrName == "particleId") { - - //cout << "-> INT " << endl; - MIntArray IA; - - if ( attrName == "id" || attrName == "particleId" ) + MIntArray* IA = new MIntArray(); + if (attrName == "id" || attrName == "particleId") { - PS.particleIds( IA ); + PS.particleIds(*IA); attrName = "id"; if (Format == "pdc") - { attrName = "particleId"; - } } else - { - PS.getPerParticleAttribute( attrName , IA, &status); - } - - Partio::ParticleAttribute intAttribute = p->addAttribute(attrName.asChar(), Partio::INT, 1); - //cout << "partio add Int attribute" << endl; - - Partio::ParticleAccessor intAccess(intAttribute); - it.addAccessor(intAccess); - int a = 0; - - for (it=p->begin();it!=p->end();++it) - { - Partio::Data& intAttr=intAccess.data >(it); - intAttr[0] = IA[a]; - a++; - } - - }/// add INT attribute - - /// DOUBLE Attribute found - else if (PS.isPerParticleDoubleAttribute(attrName)) + PS.getPerParticleAttribute(attrName, *IA, &status); + PARTIO::ParticleAttribute intAttribute = p->addAttribute(attrName.asChar(), PARTIO::INT, 1); + intAttributes.push_back(std::make_pair(IA, intAttribute)); + minParticleCount = std::min(minParticleCount, IA->length()); + } + else if (PS.isPerParticleDoubleAttribute(attrName)) // DOUBLE Attribute found { - //cout << "-> FLOAT " << endl; - MDoubleArray DA; + MDoubleArray* DA = new MDoubleArray(); - if ( attrName == "radius" || attrName == "radiusPP") + if (attrName == "radius" || attrName == "radiusPP") { attrName = "radiusPP"; - PS.radius( DA ); - } - if ( attrName == "age" ) - { - PS.age( DA ); + PS.radius(*DA); } - else if ( attrName == "opacity" || attrName == "opacityPP") + if (attrName == "age") + PS.age(*DA); + else if (attrName == "opacity" || attrName == "opacityPP") { attrName = "opacityPP"; - PS.opacity( DA ); + PS.opacity(*DA); } else - { - PS.getPerParticleAttribute( attrName , DA, &status); - } - - Partio::ParticleAttribute floatAttribute = p->addAttribute(attrName.asChar(), Partio::FLOAT, 1); - Partio::ParticleAccessor floatAccess(floatAttribute); - it.addAccessor(floatAccess); - int a = 0; - - for (it=p->begin();it!=p->end();++it) - { - - Partio::Data& floatAttr=floatAccess.data >(it); - floatAttr[0] = float(DA[a]); - a++; - - } - - } /// add double attr + PS.getPerParticleAttribute(attrName, *DA, &status); - /// VECTOR Attribute found - else if (PS.isPerParticleVectorAttribute(attrName)) + PARTIO::ParticleAttribute floatAttribute = p->addAttribute(attrName.asChar(), PARTIO::FLOAT, 1); + doubleAttributes.push_back(std::make_pair(DA, floatAttribute)); + minParticleCount = std::min(minParticleCount, DA->length()); + } // add double attr + else if (PS.isPerParticleVectorAttribute(attrName)) // VECTOR Attribute found { - - //cout << "-> VECTOR " << endl; - MVectorArray VA; - - if ( attrName == "position" ) - { - if (isDeformed) - { - //cout << "trying deformed position attr" << endl; - //cout << "counts match ? " << PS.count() << "<->" << DPS.count() << endl; - DPS.position( VA ); - } - else - { - cout << " using undeformed position attr" << endl; - PS.position( VA ); - } - } - else if ( attrName == "velocity") - { - PS.velocity( VA ); - } - else if (attrName == "acceleration" ) - { - PS.acceleration( VA ); - } - else if (attrName == "rgbPP" ) - { - PS.rgb( VA ); - } + MVectorArray* VA = new MVectorArray(); + if (attrName == "position") + DPS.position(*VA); + else if (attrName == "velocity") + PS.velocity(*VA); + else if (attrName == "acceleration") + PS.acceleration(*VA); + else if (attrName == "rgbPP") + PS.rgb(*VA); else if (attrName == "incandescencePP") - { - PS.emission( VA ); - } + PS.emission(*VA); else - { - PS.getPerParticleAttribute( attrName , VA, &status); - } - - Partio::ParticleAttribute vectorAttribute = p->addAttribute(attrName.asChar(), Partio::VECTOR, 3); + PS.getPerParticleAttribute(attrName, *VA, &status); - Partio::ParticleAccessor vectorAccess(vectorAttribute); + PARTIO::ParticleAttribute vectorAttribute = p->addAttribute(attrName.asChar(), PARTIO::VECTOR, 3); + vectorAttributes.push_back(std::make_pair(VA, vectorAttribute)); + minParticleCount = std::min(minParticleCount, VA->length()); + } + } - it.addAccessor(vectorAccess); + // check if directory exists, and if not, create it + struct stat st; + if (stat(Path.asChar(), &st) < 0) + { +#ifdef WIN32 + HWND hwnd = NULL; + const SECURITY_ATTRIBUTES *psa = NULL; + SHCreateDirectoryEx(hwnd, Path.asChar(), psa); +#else + mode_t userMask = umask(0); + umask(userMask); + mode_t DIR_MODE = ((0777) ^ userMask); + mkdir(Path.asChar(), DIR_MODE); +#endif + } - int a = 0; + if (minParticleCount > 0) + { + p->addParticles(minParticleCount); - for (it=p->begin();it!=p->end();++it) + for (std::vector >::iterator it = intAttributes.begin(); + it != intAttributes.end(); ++it) + { + PARTIO::ParticleIterator pit = p->begin(); + PARTIO::ParticleAccessor intAccessor(it->second); + pit.addAccessor(intAccessor); + for (int id = 0; pit != p->end(); ++pit) + intAccessor.data >(pit)[0] = it->first->operator[](id++); + } + + for (std::vector >::iterator it = doubleAttributes.begin(); + it != doubleAttributes.end(); ++it) + { + PARTIO::ParticleIterator pit = p->begin(); + PARTIO::ParticleAccessor doubleAccessor(it->second); + pit.addAccessor(doubleAccessor); + for (int id = 0; pit != p->end(); ++pit) + doubleAccessor.data >(pit)[0] = static_cast(it->first->operator[]( + id++)); + } + + for (std::vector >::iterator it = vectorAttributes.begin(); + it != vectorAttributes.end(); ++it) + { + PARTIO::ParticleIterator pit = p->begin(); + PARTIO::ParticleAccessor vectorAccessor(it->second); + pit.addAccessor(vectorAccessor); + const bool doSwap = swapUP && + ((it->second.name == "position") || (it->second.name == "velocity") || + (it->second.name == "acceleration")); + for (int id = 0; pit != p->end(); ++pit) { + PARTIO::Data& vecAttr = vectorAccessor.data >(pit); + const MVector& P = it->first->operator[](id++); + vecAttr[0] = static_cast(P.x); - Partio::Data& vecAttr=vectorAccess.data >(it); - - MVector P = VA[a]; - vecAttr[0] = (float)P.x; - - if (swapUP && (attrName == "position" || attrName == "velocity" || attrName == "acceleration" )) + if (doSwap) { - vecAttr[1] = -(float)P.z; - vecAttr[2] = (float)P.y; + vecAttr[1] = -static_cast(P.z); + vecAttr[2] = static_cast(P.y); } else { - vecAttr[1] = (float)P.y; - vecAttr[2] = (float)P.z; + vecAttr[1] = static_cast(P.y); + vecAttr[2] = static_cast(P.z); } - a++; } + } - } /// add vector attr + PARTIO::write(outputPath.asChar(), *p); + } + else + std::cout << "[partioExport] There are no particles with valid data." << std::endl; - } /// loop attributes + for (std::vector >::iterator it = intAttributes.begin(); + it != intAttributes.end(); ++it) + delete it->first; - // check if directory exists, and if not, create it - struct stat st; - if (stat(Path.asChar(),&st) < 0) - { -#ifdef WIN32 - HWND hwnd = NULL; - const SECURITY_ATTRIBUTES *psa = NULL; - SHCreateDirectoryEx(hwnd, Path.asChar(), psa); -#else - mode_t userMask = umask(0); - umask(userMask); - mode_t DIR_MODE = ((0777) ^ userMask); - mkdir (Path.asChar(), DIR_MODE ); -#endif - } + for (std::vector >::iterator it = doubleAttributes.begin(); + it != doubleAttributes.end(); ++it) + delete it->first; - Partio::write(outputPath.asChar(), *p ); - //cout << "partioCount" << endl; - //cout << "end FRAME: " << outFrame << endl; - //cout << "num particles" << p->numParticles() << endl; - //cout << "num Attributes" << p->numAttributes() << endl; + for (std::vector >::iterator it = vectorAttributes.begin(); + it != vectorAttributes.end(); ++it) + delete it->first; p->release(); - //cout << "released memory" << endl; - } /// if particle count > 0 + } // support escaping early in export command - if (computation.isInterruptRequested()) - { MGlobal::displayWarning("PartioExport detected escape being pressed, ending export early!" ) ; - break; - } - - } /// loop frames + if (computation.isInterruptRequested()) + { + MGlobal::displayWarning("PartioExport detected escape being pressed, ending export early!"); + break; + } + } return MStatus::kSuccess; } @@ -551,10 +511,10 @@ void PartioExport::printUsage() usage += "\t\t-mnf/minFrame \n"; usage += "\t\t-mxf/maxFrame \n"; //usage += "\t\t-f/format (format is one of: pda,pdb,pdc,prt,bin,bgeo,geo,ptc,mc,pts,xyz,pcd,icecache,rib,ass)\n"; - usage += "\t\t-f/format (format is one of: pda,pdb,pdc,prt,bin,rpc,bgeo,geo,ptc,mc,pts,xyz,pcd,rib,ass)\n"; + usage += "\t\t-f/format (format is one of: pda,pdb,pdc,prt,bin,rpc,bgeo,geo,ptc,mc,pts,xyz,pcd,rib,ass)\n"; usage += "\t\t-atr/attribute (multi use) \n"; usage += "\t\t (position/id) are always exported \n"; - usage += "\t\t-p/path \n"; + usage += "\t\t-p/path \n"; usage += "\t\t-fp/filePrefix \n"; usage += "\t\t-flp/flip (flip y->z axis to go to Z up packages) \n"; usage += "\n"; @@ -563,7 +523,4 @@ void PartioExport::printUsage() usage += "partioExport -mnf 1 -mxf 10 -f prt -atr position -atr rgbPP -at opacityPP -fp \"SmokeShapepart1of20\" -p \"/file/path/to/output/directory\" particleShape1 \n\n"; MGlobal::displayInfo(usage); - } - - diff --git a/contrib/partio4Maya/partioImport.cpp b/contrib/partio4Maya/partioImport.cpp index 399651cb..5c655a4c 100644 --- a/contrib/partio4Maya/partioImport.cpp +++ b/contrib/partio4Maya/partioImport.cpp @@ -29,17 +29,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "partioImport.h" -static const char *kAttributeFlagS = "-atr"; -static const char *kAttributeFlagL = "-attribute"; -static const char *kFlipFlagS = "-flp"; -static const char *kFlipFlagL = "-flip"; -static const char *kHelpFlagS = "-h"; -static const char *kHelpFlagL = "-help"; -static const char *kParticleL = "-particle"; -static const char *kParticleS = "-p"; - -using namespace std; -using namespace Partio; +static const char* kAttributeFlagS = "-atr"; +static const char* kAttributeFlagL = "-attribute"; +static const char* kFlipFlagS = "-flp"; +static const char* kFlipFlagL = "-flip"; +static const char* kHelpFlagS = "-h"; +static const char* kHelpFlagL = "-help"; +static const char* kParticleL = "-particle"; +static const char* kParticleS = "-p"; bool PartioImport::hasSyntax() { @@ -51,10 +48,10 @@ MSyntax PartioImport::createSyntax() MSyntax syntax; - syntax.addFlag(kParticleS, kParticleL , MSyntax::kString); - syntax.addFlag(kHelpFlagS, kHelpFlagL , MSyntax::kNoArg); + syntax.addFlag(kParticleS, kParticleL, MSyntax::kString); + syntax.addFlag(kHelpFlagS, kHelpFlagL, MSyntax::kNoArg); syntax.addFlag(kAttributeFlagS, kAttributeFlagL, MSyntax::kString, MSyntax::kString); - syntax.makeFlagMultiUse( kAttributeFlagS ); + syntax.makeFlagMultiUse(kAttributeFlagS); syntax.addFlag(kFlipFlagS, kFlipFlagL, MSyntax::kNoArg); syntax.addArg(MSyntax::kString); syntax.enableQuery(false); @@ -64,7 +61,6 @@ MSyntax PartioImport::createSyntax() } - void* PartioImport::creator() { return new PartioImport; @@ -79,23 +75,23 @@ MStatus PartioImport::doIt(const MArgList& Args) if (status == MStatus::kFailure) { - MGlobal::displayError("Error parsing arguments" ); + MGlobal::displayError("Error parsing arguments"); } - if ( argData.isFlagSet(kHelpFlagL) ) + if (argData.isFlagSet(kHelpFlagL)) { printUsage(); return MStatus::kFailure; } MString particleShape; - if (argData.isFlagSet(kParticleL) ) + if (argData.isFlagSet(kParticleL)) { - argData.getFlagArgument(kParticleL, 0, particleShape ); + argData.getFlagArgument(kParticleL, 0, particleShape); if (particleShape == "") { printUsage(); - MGlobal::displayError("Please supply particleShape argument" ); + MGlobal::displayError("Please supply particleShape argument"); return MStatus::kFailure; } } @@ -104,33 +100,36 @@ MStatus PartioImport::doIt(const MArgList& Args) makeParticle = true; } - if ( argData.isFlagSet(kFlipFlagL) || argData.isFlagSet(kFlipFlagS)) + if (argData.isFlagSet(kFlipFlagL) || argData.isFlagSet(kFlipFlagS)) { } /// parse attribute flags - unsigned int numUses = argData.numberOfFlagUses( kAttributeFlagL ); + unsigned int numUses = argData.numberOfFlagUses(kAttributeFlagL); /// loop thru the rest of the attributes given - MStringArray attrNames; - MStringArray mayaAttrNames; + MStringArray attrNames; + MStringArray mayaAttrNames; bool worldVeloCheck = false; - for ( unsigned int i = 0; i < numUses; i++ ) + for (unsigned int i = 0; i < numUses; i++) { MArgList argList; - status = argData.getFlagArgumentList( kAttributeFlagL, i, argList ); - if ( !status ) return status; + status = argData.getFlagArgumentList(kAttributeFlagL, i, argList); + if (!status) + return status; - MString AttrName = argList.asString( 0, &status ); - if ( !status ) return status; + MString AttrName = argList.asString(0, &status); + if (!status) + return status; - if ( AttrName == "position" || AttrName == "worldPosition" || - AttrName == "id" || AttrName == "particleId") - {} + if (AttrName == "position" || AttrName == "worldPosition" || + AttrName == "id" || AttrName == "particleId") + { + } - else if ( AttrName == "worldVelocity" || AttrName == "velocity" ) + else if (AttrName == "worldVelocity" || AttrName == "velocity") { if (!worldVeloCheck) { @@ -143,7 +142,7 @@ MStatus PartioImport::doIt(const MArgList& Args) attrNames.append(AttrName); if (argList.length() > 1) { - mayaAttrNames.append(argList.asString( 1 )); + mayaAttrNames.append(argList.asString(1)); } else { @@ -175,7 +174,7 @@ MStatus PartioImport::doIt(const MArgList& Args) MObject objNode; list.getDependNode(0, objNode); - if ( objNode.apiType() != MFn::kParticle && objNode.apiType() != MFn::kNParticle ) + if (objNode.apiType() != MFn::kParticle && objNode.apiType() != MFn::kNParticle) { MGlobal::displayError("PartioImport-> can't find your PARTICLESHAPE."); return MStatus::kFailure; @@ -197,35 +196,35 @@ MStatus PartioImport::doIt(const MArgList& Args) if (stat == MStatus::kSuccess) // particle object was found and attached to { - Partio::ParticlesDataMutable* particles; - Partio::ParticleAttribute positionAttr; - Partio::ParticleAttribute velocityAttr; + PARTIO::ParticlesDataMutable* particles; + PARTIO::ParticleAttribute positionAttr; + PARTIO::ParticleAttribute velocityAttr; - MGlobal::displayInfo(MString ("PartioImport-> LOADING: ") + particleCache); - particles=read(particleCache.asChar()); + MGlobal::displayInfo(MString("PartioImport-> LOADING: ") + particleCache); + particles = PARTIO::read(particleCache.asChar()); bool hasVelo = true; - if (!particles || particles->numParticles() <=0) + if (!particles || particles->numParticles() <= 0) { MGlobal::displayError("Particle Cache cannot be read, or does not Contain any particles"); return MStatus::kFailure; } char partCount[50]; - sprintf (partCount, "%d", particles->numParticles()); - MGlobal::displayInfo(MString ("PartioImport-> LOADED: ") + partCount + MString (" particles")); + sprintf(partCount, "%d", particles->numParticles()); + MGlobal::displayInfo(MString("PartioImport-> LOADED: ") + partCount + MString(" particles")); - if (!particles->attributeInfo("position",positionAttr) && - !particles->attributeInfo("Position",positionAttr)) + if (!particles->attributeInfo("position", positionAttr) && + !particles->attributeInfo("Position", positionAttr)) { MGlobal::displayError("PartioImport->Failed to find position attribute "); - return ( MS::kFailure ); + return (MS::kFailure); } - if (!particles->attributeInfo("velocity",velocityAttr) && - !particles->attributeInfo("Velocity",velocityAttr) && - !particles->attributeInfo("vel",velocityAttr) && - !particles->attributeInfo("Vel",velocityAttr)) + if (!particles->attributeInfo("velocity", velocityAttr) && + !particles->attributeInfo("Velocity", velocityAttr) && + !particles->attributeInfo("vel", velocityAttr) && + !particles->attributeInfo("Vel", velocityAttr)) { MGlobal::displayWarning("PartioImport->Failed to find Velocity attribute "); hasVelo = false; @@ -233,14 +232,14 @@ MStatus PartioImport::doIt(const MArgList& Args) MPointArray positions; MVectorArray velocities; - std::map vectorAttrArrays; - std::map doubleAttrArrays; + std::map vectorAttrArrays; + std::map doubleAttrArrays; // we use this mapping to allow for direct writing of attrs to PP variables - std::map userPPMapping; + std::map userPPMapping; - for (unsigned int i=0;iattributeInfo(attrNames[i].asChar(), testAttr)) { @@ -248,7 +247,7 @@ MStatus PartioImport::doIt(const MArgList& Args) { if (!partSys.isPerParticleVectorAttribute(mayaAttrNames[i])) { - MGlobal::displayInfo(MString("partioImport->adding ppAttr " + mayaAttrNames[i]) ); + MGlobal::displayInfo(MString("partioImport->adding ppAttr " + mayaAttrNames[i])); MString command; command += "pioEmAddPPAttr "; command += mayaAttrNames[i]; @@ -292,18 +291,18 @@ MStatus PartioImport::doIt(const MArgList& Args) //////////////////////////////////////////////// /// final particle loop - std::map ::iterator vecIt; - std::map ::iterator doubleIt; + std::map::iterator vecIt; + std::map::iterator doubleIt; - for (int i=0;inumParticles();i++) + for (int i = 0; i < particles->numParticles(); i++) { - const float * partioPositions = particles->data(positionAttr,i); - MPoint pos (partioPositions[0], partioPositions[1], partioPositions[2]); + const float* partioPositions = particles->data(positionAttr, i); + MPoint pos(partioPositions[0], partioPositions[1], partioPositions[2]); positions.append(pos); if (hasVelo) { - const float * partioVelocities = particles->data(velocityAttr,i); - MPoint vel (partioVelocities[0], partioVelocities[1], partioVelocities[2]); + const float* partioVelocities = particles->data(velocityAttr, i); + MPoint vel(partioVelocities[0], partioVelocities[1], partioVelocities[2]); velocities.append(vel); } @@ -311,26 +310,25 @@ MStatus PartioImport::doIt(const MArgList& Args) { for (vecIt = vectorAttrArrays.begin(); vecIt != vectorAttrArrays.end(); vecIt++) { - ParticleAttribute vectorAttr; + PARTIO::ParticleAttribute vectorAttr; particles->attributeInfo(vecIt->first.c_str(), vectorAttr); const float* vecVal = particles->data(vectorAttr, i); - vectorAttrArrays[vecIt->first][i] = MVector(vecVal[0],vecVal[1],vecVal[2]); + vectorAttrArrays[vecIt->first][i] = MVector(vecVal[0], vecVal[1], vecVal[2]); } } if (doubleAttrArrays.size() > 0) { for (doubleIt = doubleAttrArrays.begin(); doubleIt != doubleAttrArrays.end(); doubleIt++) { - ParticleAttribute doubleAttr; - particles->attributeInfo(doubleIt->first.c_str(),doubleAttr); - const float* doubleVal = particles->data(doubleAttr, i); + PARTIO::ParticleAttribute doubleAttr; + particles->attributeInfo(doubleIt->first.c_str(), doubleAttr); + const float* doubleVal = particles->data(doubleAttr, i); doubleAttrArrays[doubleIt->first][i] = doubleVal[0]; } } } if (!hasVelo) - { velocities.setLength(particles->numParticles()); } @@ -343,15 +341,17 @@ MStatus PartioImport::doIt(const MArgList& Args) } partSys.setCount(positions.length()); - stat = partSys.emit(positions,velocities); + stat = partSys.emit(positions, velocities); for (doubleIt = doubleAttrArrays.begin(); doubleIt != doubleAttrArrays.end(); doubleIt++) { - partSys.setPerParticleAttribute(MString(userPPMapping[doubleIt->first].c_str()), doubleAttrArrays[doubleIt->first]); + partSys.setPerParticleAttribute(MString(userPPMapping[doubleIt->first].c_str()), + doubleAttrArrays[doubleIt->first]); } for (vecIt = vectorAttrArrays.begin(); vecIt != vectorAttrArrays.end(); vecIt++) { - partSys.setPerParticleAttribute(MString(userPPMapping[vecIt->first].c_str()), vectorAttrArrays[vecIt->first]); + partSys.setPerParticleAttribute(MString(userPPMapping[vecIt->first].c_str()), + vectorAttrArrays[vecIt->first]); } partSys.saveInitialState(); diff --git a/contrib/partio4Maya/partioInstancer.cpp b/contrib/partio4Maya/partioInstancer.cpp index cfdd1949..65026ca1 100644 --- a/contrib/partio4Maya/partioInstancer.cpp +++ b/contrib/partio4Maya/partioInstancer.cpp @@ -29,21 +29,23 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "partioInstancer.h" -static MGLFunctionTable *gGLFT = NULL; +#include +#include + +static MGLFunctionTable* gGLFT = NULL; #define ID_PARTIOINSTANCER 0x00116ED5 // id is registered with autodesk no need to change -#define LEAD_COLOR 18 // green -#define ACTIVE_COLOR 15 // white -#define ACTIVE_AFFECTED_COLOR 8 // purple -#define DORMANT_COLOR 4 // blue -#define HILITE_COLOR 17 // pale blue +#define LEAD_COLOR 18 // green +#define ACTIVE_COLOR 15 // white +#define ACTIVE_AFFECTED_COLOR 8 // purple +#define DORMANT_COLOR 4 // blue +#define HILITE_COLOR 17 // pale blue #define DRAW_STYLE_POINTS 0 #define DRAW_STYLE_LABEL 1 #define DRAW_STYLE_BOUNDING_BOX 3 +#define USE_SLERP_FOR_QUATERIONS -using namespace Partio; -using namespace std; /// PARTIO INSTANCER /* @@ -65,7 +67,7 @@ age (doubleArray) id (doubleArray) * */ -MTypeId partioInstancer::id( ID_PARTIOINSTANCER ); +MTypeId partioInstancer::id(ID_PARTIOINSTANCER); /// ATTRS MObject partioInstancer::time; @@ -88,394 +90,561 @@ MObject partioInstancer::aRenderCachePath; /// point position / velocity MObject partioInstancer::aComputeVeloPos; -MObject partioInstancer::aVeloMult; +MObject partioInstancer::aVelocityMult; /// attributes MObject partioInstancer::aPartioAttributes; MObject partioInstancer::aScaleFrom; +MObject partioInstancer::aLastScaleFrom; + MObject partioInstancer::aRotationType; MObject partioInstancer::aRotationFrom; +MObject partioInstancer::aLastRotationFrom; + MObject partioInstancer::aAimDirectionFrom; +MObject partioInstancer::aLastAimDirectionFrom; + MObject partioInstancer::aAimPositionFrom; +MObject partioInstancer::aLastAimPositionFrom; + MObject partioInstancer::aAimAxisFrom; MObject partioInstancer::aAimUpAxisFrom; MObject partioInstancer::aAimWorldUpFrom; -MObject partioInstancer::aLastScaleFrom; -MObject partioInstancer::aLastRotationFrom; -MObject partioInstancer::aLastAimDirectionFrom; -MObject partioInstancer::aLastAimPositionFrom; + +MObject partioInstancer::aLastPositionFrom; +MObject partioInstancer::aVelocityFrom; +MObject partioInstancer::aAngularVelocityFrom; +MObject partioInstancer::aAngularVelocityMult; MObject partioInstancer::aIndexFrom; /// not implemented yet -// MObject partioInstancer::aShaderIndexFrom; -// MObject partioInstancer::aInMeshInstances; -// MObject partioInstancer::aOutMesh; +// MObject partioInstancer::aShaderIndexFrom; +// MObject partioInstancer::aInMeshInstances; +// MObject partioInstancer::aOutMesh; // output data to instancer MObject partioInstancer::aInstanceData; +MObject partioInstancer::aExportAttributes; +MObject partioInstancer::aVelocitySource; +MObject partioInstancer::aAngularVelocitySource; + +namespace { + // these two functions check and clean out the instance array members if they exist or make them if they don't + // cleaning out the arrays returned by getVectorData doesn't make any sense + // because that returns a copy, rather than a reference, and both functions + // are creating the arrays + void updateInstanceDataVector(partioInstReaderCache& pvCache, MVectorArray& arrayToCheck, + const MString& arrayChannel, unsigned int numParticles) + { + MStatus stat; + MFnArrayAttrsData::Type vectorType; + arrayToCheck = pvCache.instanceData.vectorArray(arrayChannel, &stat); + CHECK_MSTATUS(stat); + arrayToCheck.setLength(numParticles); + } + + void updateInstanceDataDouble(partioInstReaderCache& pvCache, MDoubleArray& arrayToCheck, + const MString& arrayChannel, unsigned int numParticles) + { + MStatus stat; + MFnArrayAttrsData::Type doubleType; + arrayToCheck = pvCache.instanceData.doubleArray(arrayChannel, &stat); + CHECK_MSTATUS(stat); + arrayToCheck.setLength(numParticles); + } + enum VelocitySource { + VS_BUILTIN = 0, + VS_CUSTOM_CHANNEL, + VS_LAST_POSITION + }; + + enum AngularVelocitySource { + AVS_LAST_ROTATION, + AVS_ANGULAR_VELOCITY + }; + + enum FloatTupleSize { + FLOAT_TUPLE_NONE = 0, + FLOAT_TUPLE_SINGLE, + FLOAT_TUPLE_TRIPLE, + FLOAT_TUPLE_QUAD + }; + + FloatTupleSize getFloatTupleSize(const PARTIO::ParticleAttribute& attribute) + { + if (attribute.type == PARTIO::FLOAT) + { + if (attribute.count == 1) + return FLOAT_TUPLE_SINGLE; + else if (attribute.count == 3) + return FLOAT_TUPLE_TRIPLE; + else if (attribute.count == 4) + return FLOAT_TUPLE_QUAD; + else + return FLOAT_TUPLE_NONE; + } + else if (attribute.type == PARTIO::VECTOR && attribute.count == 3) + return FLOAT_TUPLE_TRIPLE; + else + return FLOAT_TUPLE_NONE; + } + void writeOutVectorAttribute(PARTIO::ParticlesDataMutable* particles, const PARTIO::ParticleAttribute& attr, MVectorArray& outArray) + { + const int numParticles = particles->numParticles(); + const FloatTupleSize tupleSize = getFloatTupleSize(attr); -partioInstReaderCache::partioInstReaderCache(): - bbox(MBoundingBox(MPoint(0,0,0,0),MPoint(0,0,0,0))), - dList(0), - particles(NULL), - flipPos(NULL) + if (tupleSize == FLOAT_TUPLE_SINGLE) // single float value for aimDirection + { + for (int i = 0; i < numParticles; ++i) + { + const float* attrVal = particles->data(attr, i); + float valVec = attrVal[0]; + outArray[i] = MVector(valVec, valVec, valVec); + } + } + else if (tupleSize == FLOAT_TUPLE_TRIPLE) + { + for (int i = 0; i < numParticles; ++i) + { + const float* attrVal = particles->data(attr, i); + MVector valVec = MVector(attrVal[0], attrVal[1], attrVal[2]); + outArray[i] = valVec; + } + } + } + void writeOutBlurredVectorAttribute(PARTIO::ParticlesDataMutable* particles, const PARTIO::ParticleAttribute& attr, + const PARTIO::ParticleAttribute& lastAttr, MVectorArray& outArray, float deltaTime) + { + const int numParticles = particles->numParticles(); + const FloatTupleSize tupleSize = getFloatTupleSize(attr); + const FloatTupleSize lastTupleSize = getFloatTupleSize(attr); + if (tupleSize == FLOAT_TUPLE_SINGLE) + { + if (lastTupleSize == FLOAT_TUPLE_SINGLE) + { + for (int i = 0; i < numParticles; ++i) + { + const float* attrVal = particles->data(attr, i); + const float* lastAttrVal = particles->data(attr, i); + float val = attrVal[0]; + val += (val - lastAttrVal[0]) * deltaTime; + outArray[i] = MVector(val, val, val); + } + } + else + { + for (int i = 0; i < numParticles; ++i) + { + const float* attrVal = particles->data(attr, i); + float val = attrVal[0]; + outArray[i] = MVector(val, val, val); + } + } + } + else if (tupleSize == FLOAT_TUPLE_TRIPLE) + { + if (lastTupleSize == FLOAT_TUPLE_TRIPLE) + { + for (int i = 0; i < numParticles; ++i) + { + const float* attrVal = particles->data(attr, i); + const float* lastAttrVal = particles->data(attr, i); + outArray[i] = MVector(attrVal[0] + (attrVal[0] - lastAttrVal[0]) * deltaTime, + attrVal[1] + (attrVal[1] - lastAttrVal[1]) * deltaTime, + attrVal[2] + (attrVal[2] - lastAttrVal[2]) * deltaTime); + } + } + else + { + for (int i = 0; i < numParticles; ++i) + { + const float* attrVal = particles->data(attr, i); + outArray[i] = MVector(attrVal[0], attrVal[1], attrVal[2]); + } + } + } + } +} + +partioInstReaderCache::partioInstReaderCache() : + bbox(MBoundingBox(MPoint(0, 0, 0, 0), MPoint(0, 0, 0, 0))), + particles(NULL) { } /// Constructor -partioInstancer::partioInstancer() - : mLastFileLoaded(""), - mLastPath(""), - mLastFile(""), - mLastExt(""), - mLastFlipStatus(false), - mFlipped(false), - frameChanged(false), - attributeList(MStringArray()), - mLastRotationTypeIndex(-1), - mLastRotationFromIndex(-1), - mLastLastRotationFromIndex(-1), - mLastAimDirectionFromIndex(-1), - mLastLastAimDirecitonFromIndex(-1), - mLastAimPositionFromIndex(-1), - mLastLastAimPositionFromIndex(-1), - mLastAimAxisFromIndex(-1), - mLastAimUpAxisFromIndex(-1), - mLastAimWorldUpFromIndex(-1), - mLastScaleFromIndex(-1), - mLastLastScaleFromIndex(-1), - mLastIndexFromIndex(-1), - cacheChanged(false), - multiplier(1.0), - canMotionBlur(false), - drawError(0) - +partioInstancer::partioInstancer() : + m_attributeList(MStringArray()), + m_lastFileLoaded(""), + m_lastPath(""), + m_lastFile(""), + m_lastExt(""), + m_lastExportAttributes(""), + m_lastRotationType(""), + m_lastRotationFrom(""), + m_lastLastRotationFrom(""), + m_lastAimDirectionFrom(""), + m_lastLastAimDirectionFrom(""), + m_lastAimPositionFrom(""), + m_lastLastAimPositionFrom(""), + m_lastAimAxisFrom(""), + m_lastAimUpAxisFrom(""), + m_lastAimWorldUpFrom(""), + m_lastScaleFrom(""), + m_lastLastScaleFrom(""), + m_lastIndexFrom(""), + m_lastAngularVelocityFrom(""), + m_lastAngularVelocityMult(-1.0f), + m_lastAngularVelocitySource(-1), + m_lastFlipStatus(false), + m_flipped(false), + m_frameChanged(false), + m_canMotionBlur(false), + m_multiplier(1.0f), + m_drawError(0), + m_cacheChanged(false) { - pvCache.particles = NULL; - pvCache.flipPos = (float *) malloc(sizeof(float)); + pvCache.particles = 0; // create the instanceData object MStatus stat; - pvCache.instanceDataObj = pvCache.instanceData.create ( &stat ); + pvCache.instanceDataObj = pvCache.instanceData.create(&stat); CHECK_MSTATUS(stat); } + /// DESTRUCTOR partioInstancer::~partioInstancer() { - if (pvCache.particles) - { pvCache.particles->release(); - } - free(pvCache.flipPos); - pvCache.instanceData.clear(); - pvCache.instanceDataObj.~MObject(); - - - MSceneMessage::removeCallback( partioInstancerOpenCallback ); - MSceneMessage::removeCallback( partioInstancerImportCallback ); - MSceneMessage::removeCallback( partioInstancerReferenceCallback ); + pvCache.instanceData.clear(); + pvCache.instanceDataObj.~MObject(); + MSceneMessage::removeCallback(partioInstancerOpenCallback); + MSceneMessage::removeCallback(partioInstancerImportCallback); + MSceneMessage::removeCallback(partioInstancerReferenceCallback); } void* partioInstancer::creator() { - //cout << "creator " << endl; return new partioInstancer; } /// POST CONSTRUCTOR void partioInstancer::postConstructor() { - //cout << "postConstructor " << endl; + //cout << "postConstructor " << endl; setRenderable(true); partioInstancerOpenCallback = MSceneMessage::addCallback(MSceneMessage::kAfterOpen, partioInstancer::reInit, this); - partioInstancerImportCallback = MSceneMessage::addCallback(MSceneMessage::kAfterImport, partioInstancer::reInit, this); - partioInstancerReferenceCallback = MSceneMessage::addCallback(MSceneMessage::kAfterReference, partioInstancer::reInit, this); + partioInstancerImportCallback = MSceneMessage::addCallback(MSceneMessage::kAfterImport, partioInstancer::reInit, + this); + partioInstancerReferenceCallback = MSceneMessage::addCallback(MSceneMessage::kAfterReference, + partioInstancer::reInit, this); } /////////////////////////////////// /// init after opening /////////////////////////////////// - void partioInstancer::initCallback() { - //cout << "initCallback " << endl; MObject tmo = thisMObject(); short extENum; MPlug(tmo, aCacheFormat).getValue(extENum); - mLastExt = partio4Maya::setExt(extENum); + m_lastExt = partio4Maya::setExt(extENum); - MPlug(tmo,aCacheDir).getValue(mLastPath); - MPlug(tmo,aCacheFile).getValue(mLastFile); - MPlug(tmo,aSize).getValue(multiplier); - cacheChanged = false; + MPlug(tmo, aCacheDir).getValue(m_lastPath); + MPlug(tmo, aCacheFile).getValue(m_lastFile); + MPlug(tmo, aSize).getValue(m_multiplier); + m_cacheChanged = false; } -void partioInstancer::reInit(void *data) +void partioInstancer::reInit(void* data) { - partioInstancer *instNode = (partioInstancer*) data; + partioInstancer* instNode = (partioInstancer*)data; instNode->initCallback(); } MStatus partioInstancer::initialize() { - //cout << "initialize" << endl; - MFnEnumAttribute eAttr; - MFnUnitAttribute uAttr; + MFnEnumAttribute eAttr; + MFnUnitAttribute uAttr; MFnNumericAttribute nAttr; - MFnTypedAttribute tAttr; - MStatus stat; - - time = uAttr.create("time", "tm", MFnUnitAttribute::kTime, 0.0, &stat ); - uAttr.setKeyable( true ); - - aByFrame = nAttr.create( "byFrame", "byf", MFnNumericData::kInt ,1); - nAttr.setKeyable( true ); - nAttr.setReadable( true ); - nAttr.setWritable( true ); - nAttr.setConnectable( true ); - nAttr.setStorable( true ); + MFnTypedAttribute tAttr; + MStatus stat; + + time = uAttr.create("time", "tm", MFnUnitAttribute::kTime, 0.0, &stat); + uAttr.setKeyable(true); + + aByFrame = nAttr.create("byFrame", "byf", MFnNumericData::kInt, 1); + nAttr.setKeyable(true); + nAttr.setReadable(true); + nAttr.setWritable(true); + nAttr.setConnectable(true); + nAttr.setStorable(true); nAttr.setMin(1); nAttr.setMax(100); - aSize = uAttr.create( "iconSize", "isz", MFnUnitAttribute::kDistance ); - uAttr.setDefault( 0.25 ); + aSize = uAttr.create("iconSize", "isz", MFnUnitAttribute::kDistance); + uAttr.setDefault(0.25); - aFlipYZ = nAttr.create( "flipYZ", "fyz", MFnNumericData::kBoolean); - nAttr.setDefault ( false ); - nAttr.setKeyable ( true ); + aFlipYZ = nAttr.create("flipYZ", "fyz", MFnNumericData::kBoolean); + nAttr.setDefault(false); + nAttr.setKeyable(true); + + aDrawStyle = eAttr.create("drawStyle", "drwStyl"); + eAttr.addField("points", 0); + eAttr.addField("index#", 1); + //eAttr.addField("spheres", 2); + eAttr.addField("boundingBox", 3); + eAttr.setDefault(0); + eAttr.setChannelBox(true); + + aPointSize = nAttr.create("pointSize", "ptsz", MFnNumericData::kInt, 2, &stat); + nAttr.setDefault(2); + nAttr.setKeyable(true); - aCacheDir = tAttr.create ( "cacheDir", "cachD", MFnStringData::kString ); - tAttr.setReadable ( true ); - tAttr.setWritable ( true ); - tAttr.setKeyable ( true ); - tAttr.setConnectable ( true ); - tAttr.setStorable ( true ); + aUpdateCache = nAttr.create("updateCache", "upc", MFnNumericData::kInt, 0); + nAttr.setHidden(true); - aCacheFile = tAttr.create ( "cachePrefix", "cachP", MFnStringData::kString ); - tAttr.setReadable ( true ); - tAttr.setWritable ( true ); - tAttr.setKeyable ( true ); - tAttr.setConnectable ( true ); - tAttr.setStorable ( true ); + aCacheDir = tAttr.create("cacheDir", "cachD", MFnStringData::kString); + tAttr.setReadable(true); + tAttr.setWritable(true); + tAttr.setKeyable(true); + tAttr.setConnectable(true); + tAttr.setStorable(true); + + aCacheFile = tAttr.create("cachePrefix", "cachP", MFnStringData::kString); + tAttr.setReadable(true); + tAttr.setWritable(true); + tAttr.setKeyable(true); + tAttr.setConnectable(true); + tAttr.setStorable(true); - aCacheOffset = nAttr.create("cacheOffset", "coff", MFnNumericData::kInt, 0, &stat ); + aCacheActive = nAttr.create("cacheActive", "cAct", MFnNumericData::kBoolean, 1, &stat); nAttr.setKeyable(true); - aCacheStatic = nAttr.create("staticCache", "statC", MFnNumericData::kBoolean, false, &stat); + aCacheOffset = nAttr.create("cacheOffset", "coff", MFnNumericData::kInt, 0, &stat); nAttr.setKeyable(true); - aCacheActive = nAttr.create("cacheActive", "cAct", MFnNumericData::kBoolean, 1, &stat); + aCacheStatic = nAttr.create("staticCache", "statC", MFnNumericData::kBoolean, false, &stat); nAttr.setKeyable(true); - aCacheFormat = eAttr.create( "cacheFormat", "cachFmt"); - std::map formatExtMap; - partio4Maya::buildSupportedExtensionList(formatExtMap,false); - for (unsigned short i = 0; i< formatExtMap.size(); i++) + aCacheFormat = eAttr.create("cacheFormat", "cachFmt"); + std::map formatExtMap; + partio4Maya::buildSupportedExtensionList(formatExtMap, false); + for (unsigned short i = 0; i < formatExtMap.size(); i++) { - eAttr.addField(formatExtMap[i].toUpperCase(), i); + eAttr.addField(formatExtMap[i].toUpperCase(), i); } eAttr.setDefault(4); // PDC eAttr.setChannelBox(true); - aDrawStyle = eAttr.create( "drawStyle", "drwStyl"); - eAttr.addField("points", 0); - eAttr.addField("index#", 1); - //eAttr.addField("spheres", 2); - eAttr.addField("boundingBox", 3); - eAttr.setDefault(0); - eAttr.setChannelBox(true); + aForceReload = nAttr.create("forceReload", "frel", MFnNumericData::kBoolean, false, &stat); + nAttr.setDefault(false); + nAttr.setKeyable(false); + aRenderCachePath = tAttr.create("renderCachePath", "rcp", MFnStringData::kString); + tAttr.setHidden(true); - aPartioAttributes = tAttr.create ("partioCacheAttributes", "pioCAts", MFnStringData::kString); - tAttr.setArray(true); - tAttr.setUsesArrayDataBuilder( true ); + aComputeVeloPos = nAttr.create("computeVeloPos", "cvp", MFnNumericData::kBoolean, false, &stat); + nAttr.setKeyable(false); - aPointSize = nAttr.create("pointSize", "ptsz", MFnNumericData::kInt, 2, &stat); - nAttr.setDefault(2); + aVelocityMult = nAttr.create("veloMult", "vmul", MFnNumericData::kFloat, 1.0, &stat); nAttr.setKeyable(true); + nAttr.setStorable(true); + nAttr.setHidden(false); + nAttr.setReadable(true); - aForceReload = nAttr.create("forceReload", "frel", MFnNumericData::kBoolean, false, &stat); - nAttr.setDefault(false); - nAttr.setKeyable(false); - - aUpdateCache = nAttr.create("updateCache", "upc", MFnNumericData::kInt, 0); - nAttr.setHidden(true); + aPartioAttributes = tAttr.create("partioCacheAttributes", "pioCAts", MFnStringData::kString); + tAttr.setArray(true); + tAttr.setUsesArrayDataBuilder(true); - aRenderCachePath = tAttr.create ( "renderCachePath", "rcp", MFnStringData::kString ); - tAttr.setHidden(true); - aScaleFrom = nAttr.create("scaleFrom", "sfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aScaleFrom = tAttr.create("scaleFrom", "sfrm", MFnStringData::kString); nAttr.setKeyable(true); - aLastScaleFrom = nAttr.create("lastScaleFrom", "lsfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aLastScaleFrom = tAttr.create("lastScaleFrom", "lsfrm", MFnStringData::kString); nAttr.setKeyable(true); // ROTATION attrs - aRotationType = nAttr.create( "rotationType", "rottyp", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aRotationType = tAttr.create("rotationType", "rottyp", MFnStringData::kString); nAttr.setKeyable(true); - aRotationFrom = nAttr.create("rotationFrom", "rfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aRotationFrom = tAttr.create("rotationFrom", "rfrm", MFnStringData::kString); nAttr.setKeyable(true); - aLastRotationFrom = nAttr.create("lastRotationFrom", "lrfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aLastRotationFrom = tAttr.create("lastRotationFrom", "lrfrm", MFnStringData::kString); nAttr.setKeyable(true); - aAimDirectionFrom = nAttr.create("aimDirectionFrom", "adfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aAimDirectionFrom = tAttr.create("aimDirectionFrom", "adfrm", MFnStringData::kString); nAttr.setKeyable(true); - aLastAimDirectionFrom = nAttr.create("lastAimDirectionFrom", "ladfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aLastAimDirectionFrom = tAttr.create("lastAimDirectionFrom", "ladfrm", MFnStringData::kString); nAttr.setKeyable(true); - aAimPositionFrom = nAttr.create("aimPositionFrom", "apfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aAimPositionFrom = tAttr.create("aimPositionFrom", "apfrm", MFnStringData::kString); nAttr.setKeyable(true); - aLastAimPositionFrom = nAttr.create("lastAimPositionFrom", "lapfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aLastAimPositionFrom = tAttr.create("lastAimPositionFrom", "lapfrm", MFnStringData::kString); nAttr.setKeyable(true); - aAimAxisFrom = nAttr.create("aimAxisFrom", "aaxfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aAimAxisFrom = tAttr.create("aimAxisFrom", "aaxfrm", MFnStringData::kString); nAttr.setKeyable(true); - aAimUpAxisFrom = nAttr.create("aimUpAxisFrom", "auaxfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aAimUpAxisFrom = tAttr.create("aimUpAxisFrom", "auaxfrm", MFnStringData::kString); nAttr.setKeyable(true); - aAimWorldUpFrom = nAttr.create("aimWorldUpFrom", "awufrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aAimWorldUpFrom = tAttr.create("aimWorldUpFrom", "awufrm", MFnStringData::kString); nAttr.setKeyable(true); - aIndexFrom = nAttr.create("indexFrom", "ifrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aLastPositionFrom = tAttr.create("lastPositionFrom", "lpfrm", MFnStringData::kString); nAttr.setKeyable(true); - aInstanceData = tAttr.create( "instanceData", "instd", MFnArrayAttrsData::kDynArrayAttrs, &stat); - tAttr.setKeyable(false); - tAttr.setStorable(false); - tAttr.setHidden(false); - tAttr.setReadable(true); + aVelocityFrom = tAttr.create("velocityFrom", "velfrm", MFnStringData::kString); + nAttr.setKeyable(true); - aComputeVeloPos = nAttr.create("computeVeloPos", "cvp", MFnNumericData::kBoolean, false, &stat); - nAttr.setKeyable(false); + aAngularVelocityFrom = tAttr.create("angularVelocityFrom", "avelfrm", MFnStringData::kString); + nAttr.setKeyable(true); - aVeloMult = nAttr.create("veloMult", "vmul", MFnNumericData::kFloat, 1.0, &stat); + aAngularVelocityMult = nAttr.create("angVeloMult", "avmul", MFnNumericData::kFloat, 1.0, &stat); nAttr.setKeyable(true); - nAttr.setStorable(true); + nAttr.setStorable(true); nAttr.setHidden(false); nAttr.setReadable(true); + + aIndexFrom = tAttr.create("indexFrom", "ifrm", MFnStringData::kString); + nAttr.setKeyable(true); + aInstanceData = tAttr.create("instanceData", "instd", MFnArrayAttrsData::kDynArrayAttrs, &stat); + tAttr.setKeyable(false); + tAttr.setStorable(false); + tAttr.setHidden(false); + tAttr.setReadable(true); -// add attributes - - addAttribute ( aSize ); - addAttribute ( aFlipYZ ); - addAttribute ( aDrawStyle ); - addAttribute ( aPointSize ); - - addAttribute ( aUpdateCache ); - addAttribute ( aCacheDir ); - addAttribute ( aCacheFile ); - addAttribute ( aCacheActive ); - addAttribute ( aCacheOffset ); - addAttribute ( aCacheStatic ); - addAttribute ( aCacheFormat ); - addAttribute ( aForceReload ); - addAttribute ( aRenderCachePath ); - - addAttribute ( aComputeVeloPos ); - addAttribute ( aVeloMult ); - - addAttribute ( aPartioAttributes ); - addAttribute ( aScaleFrom ); - addAttribute ( aRotationType ); - addAttribute ( aRotationFrom ); - addAttribute ( aAimDirectionFrom ); - addAttribute ( aAimPositionFrom ); - addAttribute ( aAimAxisFrom ); - addAttribute ( aAimUpAxisFrom ); - addAttribute ( aAimWorldUpFrom ); - - addAttribute ( aLastScaleFrom ); - addAttribute ( aLastRotationFrom ); - addAttribute ( aLastAimDirectionFrom ); - addAttribute ( aLastAimPositionFrom ); - - addAttribute ( aIndexFrom ); - - addAttribute ( aInstanceData ); - - addAttribute ( aByFrame ); - addAttribute ( time ); - -// attribute affects - - attributeAffects ( aSize, aUpdateCache ); - attributeAffects ( aFlipYZ, aUpdateCache ); - attributeAffects ( aPointSize, aUpdateCache ); - attributeAffects ( aDrawStyle, aUpdateCache ); - - attributeAffects ( aCacheDir, aUpdateCache ); - attributeAffects ( aCacheFile, aUpdateCache ); - attributeAffects ( aCacheActive, aUpdateCache ); - attributeAffects ( aCacheOffset, aUpdateCache ); - attributeAffects ( aCacheStatic, aUpdateCache ); - attributeAffects ( aCacheFormat, aUpdateCache ); - attributeAffects ( aForceReload, aUpdateCache ); - - attributeAffects ( aComputeVeloPos, aUpdateCache ); - attributeAffects ( aVeloMult, aUpdateCache ); - - attributeAffects ( aScaleFrom, aUpdateCache ); - attributeAffects ( aRotationType, aUpdateCache ); - - attributeAffects ( aRotationFrom, aUpdateCache ); - attributeAffects ( aAimDirectionFrom, aUpdateCache ); - attributeAffects ( aAimPositionFrom, aUpdateCache ); - attributeAffects ( aAimAxisFrom, aUpdateCache ); - attributeAffects ( aAimUpAxisFrom, aUpdateCache ); - attributeAffects ( aAimWorldUpFrom, aUpdateCache ); - - attributeAffects ( aLastScaleFrom, aUpdateCache ); - attributeAffects ( aLastRotationFrom, aUpdateCache ); - attributeAffects ( aLastAimDirectionFrom, aUpdateCache ); - attributeAffects ( aLastAimPositionFrom, aUpdateCache ); - - attributeAffects ( aIndexFrom, aUpdateCache ); - - attributeAffects ( aInstanceData, aUpdateCache ); - attributeAffects (time, aUpdateCache); - attributeAffects (time, aInstanceData); - attributeAffects (aByFrame, aUpdateCache); - attributeAffects (aByFrame, aInstanceData); - + aExportAttributes = tAttr.create("exportAttributes", "expattr", MFnStringData::kString); + + aVelocitySource = eAttr.create("velocitySource", "vsrc"); + eAttr.addField("Built-in", 0); + eAttr.addField("Custom Channel", 1); + eAttr.addField("Last Position", 2); + + aAngularVelocitySource = eAttr.create("angularVelocitySource", "avsrc"); + eAttr.addField("Last Rotation", 0); + eAttr.addField("Angular Velocity", 1); + + // add attributes + addAttribute(time); + addAttribute(aByFrame); + + addAttribute(aSize); + addAttribute(aFlipYZ); + addAttribute(aDrawStyle); + addAttribute(aPointSize); + + addAttribute(aUpdateCache); + addAttribute(aCacheDir); + addAttribute(aCacheFile); + addAttribute(aCacheActive); + addAttribute(aCacheOffset); + addAttribute(aCacheStatic); + addAttribute(aCacheFormat); + addAttribute(aForceReload); + addAttribute(aRenderCachePath); + + addAttribute(aComputeVeloPos); + addAttribute(aVelocityMult); + + addAttribute(aPartioAttributes); + addAttribute(aScaleFrom); + addAttribute(aRotationType); + addAttribute(aRotationFrom); + addAttribute(aAimDirectionFrom); + addAttribute(aAimPositionFrom); + addAttribute(aAimAxisFrom); + addAttribute(aAimUpAxisFrom); + addAttribute(aAimWorldUpFrom); + + addAttribute(aLastScaleFrom); + addAttribute(aLastRotationFrom); + addAttribute(aLastAimDirectionFrom); + addAttribute(aLastAimPositionFrom); + addAttribute(aLastPositionFrom); + addAttribute(aVelocityFrom); + addAttribute(aAngularVelocityFrom); + addAttribute(aAngularVelocityMult); + + addAttribute(aIndexFrom); + + addAttribute(aInstanceData); + + addAttribute(aExportAttributes); + addAttribute(aVelocitySource); + addAttribute(aAngularVelocitySource); + + + + // attribute affects + attributeAffects(aSize, aUpdateCache); + attributeAffects(aFlipYZ, aUpdateCache); + attributeAffects(aPointSize, aUpdateCache); + attributeAffects(aDrawStyle, aUpdateCache); + + attributeAffects(aCacheDir, aUpdateCache); + attributeAffects(aCacheFile, aUpdateCache); + attributeAffects(aCacheActive, aUpdateCache); + attributeAffects(aCacheOffset, aUpdateCache); + attributeAffects(aCacheStatic, aUpdateCache); + attributeAffects(aCacheFormat, aUpdateCache); + attributeAffects(aForceReload, aUpdateCache); + + attributeAffects(aComputeVeloPos, aUpdateCache); + attributeAffects(aVelocityMult, aUpdateCache); + attributeAffects(aAngularVelocityMult, aUpdateCache); + + attributeAffects(aScaleFrom, aUpdateCache); + attributeAffects(aRotationType, aUpdateCache); + + attributeAffects(aRotationFrom, aUpdateCache); + attributeAffects(aAimDirectionFrom, aUpdateCache); + attributeAffects(aAimPositionFrom, aUpdateCache); + attributeAffects(aAimAxisFrom, aUpdateCache); + attributeAffects(aAimUpAxisFrom, aUpdateCache); + attributeAffects(aAimWorldUpFrom, aUpdateCache); + attributeAffects(aExportAttributes, aUpdateCache); + attributeAffects(aVelocitySource, aUpdateCache); + attributeAffects(aAngularVelocitySource, aUpdateCache); + + attributeAffects(aLastScaleFrom, aUpdateCache); + attributeAffects(aLastRotationFrom, aUpdateCache); + attributeAffects(aLastAimDirectionFrom, aUpdateCache); + attributeAffects(aLastAimPositionFrom, aUpdateCache); + attributeAffects(aLastPositionFrom, aUpdateCache); + attributeAffects(aVelocityFrom, aUpdateCache); + + attributeAffects(aIndexFrom, aUpdateCache); + + attributeAffects(aInstanceData, aUpdateCache); + attributeAffects(time, aUpdateCache); + attributeAffects(time, aInstanceData); + attributeAffects(aByFrame, aUpdateCache); + attributeAffects(aByFrame, aInstanceData); return MS::kSuccess; } - partioInstReaderCache* partioInstancer::updateParticleCache() { GetPlugData(); // force update to run compute function where we want to do all the work @@ -483,76 +652,55 @@ partioInstReaderCache* partioInstancer::updateParticleCache() } // COMPUTE FUNCTION - -MStatus partioInstancer::compute( const MPlug& plug, MDataBlock& block ) +MStatus partioInstancer::compute(const MPlug& plug, MDataBlock& block) { - //cout << "compute" << endl; - MStatus stat; - int rotationType = block.inputValue( aRotationType ).asInt(); - int rotationFromIndex = block.inputValue( aRotationFrom ).asInt(); - int lastRotFromIndex = block.inputValue( aLastRotationFrom ).asInt(); - int scaleFromIndex = block.inputValue( aScaleFrom ).asInt(); - int lastScaleFromIndex = block.inputValue( aLastScaleFrom ).asInt(); - int aimDirectionFromIndex = block.inputValue( aAimDirectionFrom ).asInt(); - int lastAimDirectionFromIndex = block.inputValue( aLastAimDirectionFrom ).asInt(); - int aimPositionFromIndex = block.inputValue( aAimPositionFrom ).asInt(); - int lastAimPositionFromIndex = block.inputValue( aLastAimPositionFrom ).asInt(); - int aimAxisFromIndex = block.inputValue( aAimAxisFrom ).asInt(); - int aimUpAxisFromIndex = block.inputValue( aAimUpAxisFrom ).asInt(); - int aimWorldUpFromIndex = block.inputValue( aAimWorldUpFrom ).asInt(); - int indexFromIndex = block.inputValue( aIndexFrom ).asInt(); - - drawError = 0; + const MString exportAttributes = block.inputValue(aExportAttributes).asString(); + const MString velocityFrom = block.inputValue(aVelocityFrom).asString(); + const MString lastPositionFrom = block.inputValue(aLastPositionFrom).asString(); + + m_drawError = 0; bool cacheActive = block.inputValue(aCacheActive).asBool(); if (!cacheActive) { - drawError = 2; - return ( MS::kSuccess ); + m_drawError = 2; + return (MS::kSuccess); } // Determine if we are requesting the output plug for this node. // if (plug != aUpdateCache && plug != aInstanceData) - { - return ( MS::kUnknownParameter ); - } - + return (MS::kUnknownParameter); else { - - MString cacheDir = block.inputValue(aCacheDir).asString(); + MString cacheDir = block.inputValue(aCacheDir).asString(); MString cacheFile = block.inputValue(aCacheFile).asString(); - if (cacheDir == "" || cacheFile == "" ) + if (cacheDir == "" || cacheFile == "") { - drawError = 1; - // too much noise! - //MGlobal::displayError("PartioEmitter->Error: Please specify cache file!"); - return ( MS::kFailure ); + m_drawError = 1; + return (MS::kFailure); } - bool cacheStatic = block.inputValue( aCacheStatic ).asBool(); - int cacheOffset = block.inputValue( aCacheOffset ).asInt(); - short cacheFormat = block.inputValue( aCacheFormat ).asShort(); - bool forceReload = block.inputValue( aForceReload ).asBool(); - MTime inputTime = block.inputValue( time ).asTime(); - int byFrame = block.inputValue( aByFrame ).asInt(); - bool flipYZ = block.inputValue( aFlipYZ ).asBool(); - MString renderCachePath = block.inputValue( aRenderCachePath ).asString(); - bool computeMotionBlur =block.inputValue( aComputeVeloPos ).asBool(); - float veloMult = block.inputValue ( aVeloMult ).asFloat(); - - int fps = (int)(MTime(1.0, MTime::kSeconds).asUnits(MTime::uiUnit())); - int integerTime = (int)floor((inputTime.value())+.52); - float deltaTime = float(inputTime.value() - integerTime); + bool cacheStatic = block.inputValue(aCacheStatic).asBool(); + int cacheOffset = block.inputValue(aCacheOffset).asInt(); + short cacheFormat = block.inputValue(aCacheFormat).asShort(); + bool forceReload = block.inputValue(aForceReload).asBool(); + MTime inputTime = block.inputValue(time).asTime(); + int byFrame = block.inputValue(aByFrame).asInt(); + bool flipYZ = block.inputValue(aFlipYZ).asBool(); + MString renderCachePath = block.inputValue(aRenderCachePath).asString(); + bool computeMotionBlur = block.inputValue(aComputeVeloPos).asBool(); + float veloMult = block.inputValue(aVelocityMult).asFloat(); + + float fps = static_cast((MTime(1.0, MTime::kSeconds).asUnits(MTime::uiUnit()))); + int integerTime = (int)floor((inputTime.value()) + .52); + float deltaTime = inputTime.value() - (float)integerTime; bool motionBlurStep = false; // motion blur rounding frame logic - if ((deltaTime < 1 || deltaTime > -1)&& deltaTime !=0) // motion blur step? - { + if (deltaTime != 0.0f) // motion blur step? motionBlurStep = true; - } MString formatExt = ""; int cachePadding = 0; @@ -560,30 +708,30 @@ MStatus partioInstancer::compute( const MPlug& plug, MDataBlock& block ) MString newCacheFile = ""; MString renderCacheFile = ""; - partio4Maya::updateFileName( cacheFile, cacheDir, - cacheStatic, cacheOffset, - cacheFormat, integerTime, byFrame, - cachePadding, formatExt, - newCacheFile, renderCacheFile - ); - + partio4Maya::updateFileName(cacheFile, cacheDir, + cacheStatic, cacheOffset, + cacheFormat, integerTime, byFrame, + cachePadding, formatExt, + newCacheFile, renderCacheFile + ); - if (renderCachePath != newCacheFile || renderCachePath != mLastFileLoaded ) + if (renderCachePath != newCacheFile || renderCachePath != m_lastFileLoaded) { block.outputValue(aRenderCachePath).setString(newCacheFile); } - cacheChanged = false; + m_cacheChanged = false; ////////////////////////////////////////////// /// Cache can change manually by changing one of the parts of the cache input... - if (mLastExt != formatExt || mLastPath != cacheDir || mLastFile != cacheFile || mLastFlipStatus != flipYZ || forceReload ) + if (m_lastExt != formatExt || m_lastPath != cacheDir || m_lastFile != cacheFile || m_lastFlipStatus != flipYZ || + forceReload) { - cacheChanged = true; - mFlipped = false; - mLastFlipStatus = flipYZ; - mLastExt = formatExt; - mLastPath = cacheDir; - mLastFile = cacheFile; + m_cacheChanged = true; + m_flipped = false; + m_lastFlipStatus = flipYZ; + m_lastExt = formatExt; + m_lastPath = cacheDir; + m_lastFile = cacheFile; block.outputValue(aForceReload).setBool(false); } @@ -592,52 +740,53 @@ MStatus partioInstancer::compute( const MPlug& plug, MDataBlock& block ) if (!partio4Maya::partioCacheExists(newCacheFile.asChar())) { - if (pvCache.particles != NULL) - { - ParticlesDataMutable* newParticles; - newParticles = pvCache.particles; - pvCache.particles=NULL; // resets the pointer - - if (newParticles != NULL) - { - newParticles->release(); // frees the mem - } - } + if (pvCache.particles != NULL) + { + PARTIO::ParticlesDataMutable* newParticles; + newParticles = pvCache.particles; + pvCache.particles = NULL; // resets the pointer + + if (newParticles != NULL) + { + newParticles->release(); // frees the mem + } + } pvCache.bbox.clear(); - pvCache.instanceData.clear(); - mLastFileLoaded = ""; - drawError = 1; + pvCache.instanceData.clear(); + m_lastFileLoaded = ""; + m_drawError = 1; } - if ( newCacheFile != "" && partio4Maya::partioCacheExists(newCacheFile.asChar()) && (newCacheFile != mLastFileLoaded || forceReload) ) + if (newCacheFile != "" && partio4Maya::partioCacheExists(newCacheFile.asChar()) && + (newCacheFile != m_lastFileLoaded || forceReload)) { - cacheChanged = true; - mFlipped = false; + m_cacheChanged = true; + m_flipped = false; MGlobal::displayWarning(MString("PartioInstancer->Loading: " + newCacheFile)); - if (pvCache.particles != NULL) - { - ParticlesDataMutable* newParticles; - newParticles = pvCache.particles; - pvCache.particles=NULL; // resets the pointer + if (pvCache.particles != NULL) + { + PARTIO::ParticlesDataMutable* newParticles; + newParticles = pvCache.particles; + pvCache.particles = NULL; // resets the pointer - if (newParticles != NULL) - { - newParticles->release(); // frees the mem - } - } - pvCache.particles=read(newCacheFile.asChar()); + if (newParticles != NULL) + { + newParticles->release(); // frees the mem + } + } + pvCache.particles = PARTIO::read(newCacheFile.asChar()); - mLastFileLoaded = newCacheFile; + m_lastFileLoaded = newCacheFile; if (pvCache.particles->numParticles() == 0) { - pvCache.instanceData.clear(); + pvCache.instanceData.clear(); return (MS::kSuccess); } char partCount[50]; - sprintf (partCount, "%d", pvCache.particles->numParticles()); - MGlobal::displayInfo(MString ("PartioInstancer-> LOADED: ") + partCount + MString (" particles")); + sprintf(partCount, "%d", pvCache.particles->numParticles()); + MGlobal::displayInfo(MString("PartioInstancer-> LOADED: ") + partCount + MString(" particles")); block.outputValue(aForceReload).setBool(false); block.setClean(aForceReload); @@ -648,412 +797,424 @@ MStatus partioInstancer::compute( const MPlug& plug, MDataBlock& block ) if (pvCache.particles) { - if (!pvCache.particles->attributeInfo("id",pvCache.idAttr) && - !pvCache.particles->attributeInfo("ID",pvCache.idAttr) && - !pvCache.particles->attributeInfo("particleId",pvCache.idAttr) && - !pvCache.particles->attributeInfo("ParticleId",pvCache.idAttr)) + if (!pvCache.particles->attributeInfo("id", pvCache.idAttr) && + !pvCache.particles->attributeInfo("ID", pvCache.idAttr) && + !pvCache.particles->attributeInfo("particleId", pvCache.idAttr) && + !pvCache.particles->attributeInfo("ParticleId", pvCache.idAttr)) { MGlobal::displayError("PartioInstancer->Failed to find id attribute "); - return ( MS::kFailure ); + return (MS::kFailure); } - if (!pvCache.particles->attributeInfo("position",pvCache.positionAttr) && - !pvCache.particles->attributeInfo("Position",pvCache.positionAttr)) + if (!pvCache.particles->attributeInfo("position", pvCache.positionAttr) && + !pvCache.particles->attributeInfo("Position", pvCache.positionAttr)) { MGlobal::displayError("PartioInstancer->Failed to find position attribute "); - return ( MS::kFailure ); + return (MS::kFailure); } - // instanceData arrays - MVectorArray positionArray; - MDoubleArray idArray; + // instanceData arrays + MVectorArray positionArray; + MDoubleArray idArray; - // this creates or gets an existing handles to the instanceData and then clears it to be ready to fill + // this creates or gets an existing handles to the instanceData and then clears it to be ready to fill - updateInstanceDataVector( pvCache, positionArray, MString("position")); - updateInstanceDataDouble( pvCache, idArray, MString("id")); + const int numParticles = pvCache.particles->numParticles(); + updateInstanceDataVector(pvCache, positionArray, "position", numParticles); + updateInstanceDataDouble(pvCache, idArray, "id", numParticles); + const short velocitySource = block.inputValue(aVelocitySource).asShort(); - canMotionBlur = false; + m_canMotionBlur = false; if (computeMotionBlur) { - if ((pvCache.particles->attributeInfo("velocity",pvCache.velocityAttr) || - pvCache.particles->attributeInfo("Velocity",pvCache.velocityAttr))|| - pvCache.particles->attributeInfo("V" ,pvCache.velocityAttr)) + if (velocitySource == VS_BUILTIN) { - canMotionBlur = true; + if ((pvCache.particles->attributeInfo("velocity", pvCache.velocityAttr) || + pvCache.particles->attributeInfo("Velocity", pvCache.velocityAttr)) || + pvCache.particles->attributeInfo("V", pvCache.velocityAttr)) + { + if (pvCache.velocityAttr.type == PARTIO::VECTOR) + m_canMotionBlur = true; + } + } + else if (velocitySource == VS_CUSTOM_CHANNEL) + { + if (pvCache.particles->attributeInfo(velocityFrom.asChar(), pvCache.velocityAttr) && + (pvCache.velocityAttr.type == PARTIO::VECTOR)) + m_canMotionBlur = true; } else { - MGlobal::displayWarning("PartioInstancer->Failed to find velocity attribute motion blur will be impaired "); + if (pvCache.particles->attributeInfo(lastPositionFrom.asChar(), pvCache.lastPosAttr) && + (pvCache.lastPosAttr.type == PARTIO::VECTOR)) + m_canMotionBlur = true; } + + if (!m_canMotionBlur) + MGlobal::displayWarning( + "PartioInstancer->Failed to find velocity attribute motion blur will be impaired "); } pvCache.bbox.clear(); + const float velocityMultiplier = veloMult * deltaTime / fps; - // first we do position and ID because we need those two for sure - for (int i=0;inumParticles();i++) - { - const float * partioPositions = pvCache.particles->data(pvCache.positionAttr,i); - MPoint pos (partioPositions[0], partioPositions[1], partioPositions[2]); - - if (canMotionBlur) - { - const float * vel = pvCache.particles->data(pvCache.velocityAttr,i); - - MVector velo(vel[0],vel[1],vel[2]); - if (motionBlurStep) - { - int mFps = (int)(MTime(1.0, MTime::kSeconds).asUnits(MTime::uiUnit())); - pos += ((velo*veloMult)/mFps)*deltaTime; - } - } - - positionArray.append(pos); - - const int* attrVal = pvCache.particles->data(pvCache.idAttr,i); - idArray.append((double)attrVal[0]); - - // resize the bounding box - pvCache.bbox.expand(pos); - } - - - if ( motionBlurStep || cacheChanged || - scaleFromIndex != mLastScaleFromIndex || - rotationFromIndex != mLastRotationFromIndex || - aimDirectionFromIndex != mLastAimDirectionFromIndex || - aimPositionFromIndex != mLastAimPositionFromIndex || - aimAxisFromIndex != mLastAimAxisFromIndex || - aimUpAxisFromIndex != mLastAimUpAxisFromIndex || - aimWorldUpFromIndex != mLastAimWorldUpFromIndex || - indexFromIndex != mLastIndexFromIndex || - lastScaleFromIndex != mLastLastScaleFromIndex || - lastRotFromIndex != mLastLastRotationFromIndex || - lastAimDirectionFromIndex!= mLastLastAimDirecitonFromIndex || - lastAimPositionFromIndex!= mLastLastAimPositionFromIndex - ) + // first we do position and ID because we need those two for sure + for (int i = 0; i < pvCache.particles->numParticles(); ++i) { + const float* partioPositions = pvCache.particles->data(pvCache.positionAttr, i); + MPoint pos(partioPositions[0], partioPositions[1], partioPositions[2]); - MDoubleArray indexArray; - MVectorArray scaleArray; - MVectorArray rotationArray; - MDoubleArray visibiltyArray; - MVectorArray aimDirectionArray; - MVectorArray aimPositionArray; - MVectorArray aimAxisArray; - MVectorArray aimUpAxisArray; - MVectorArray aimWorldUpArray; - - // clear these out to update on any change - pvCache.rotationAttr.type = NONE; - pvCache.aimDirAttr.type = NONE; - pvCache.aimPosAttr.type = NONE; - pvCache.aimAxisAttr.type = NONE; - pvCache.aimUpAttr.type = NONE; - pvCache.aimWorldUpAttr.type = NONE; - pvCache.lastRotationAttr.type = NONE; - pvCache.scaleAttr.type = NONE; - pvCache.lastScaleAttr.type = NONE; - pvCache.lastAimDirAttr.type = NONE; - pvCache.lastAimPosAttr.type = NONE; - pvCache.indexAttr.type = NONE; - - // Index - if (indexFromIndex >=0) - { - updateInstanceDataDouble( pvCache, indexArray, MString("objectIndex")); - pvCache.particles->attributeInfo(indexFromIndex,pvCache.indexAttr); - } - // Scale - if (scaleFromIndex >=0) + if (m_canMotionBlur) { - updateInstanceDataVector( pvCache, scaleArray, MString("scale")); - pvCache.particles->attributeInfo(scaleFromIndex,pvCache.scaleAttr); - if (lastScaleFromIndex >=0) - { - pvCache.particles->attributeInfo(lastScaleFromIndex,pvCache.lastScaleAttr); - } - else - { - pvCache.particles->attributeInfo(scaleFromIndex,pvCache.lastScaleAttr); - } - } - // Rotation - if (rotationFromIndex >= 0) - { - updateInstanceDataVector( pvCache, rotationArray, MString("rotation")); - pvCache.particles->attributeInfo(rotationFromIndex,pvCache.rotationAttr); - if (lastRotFromIndex >= 0) - { - pvCache.particles->attributeInfo(lastRotFromIndex,pvCache.lastRotationAttr); - } - else - { - pvCache.particles->attributeInfo(rotationFromIndex,pvCache.lastRotationAttr); - } - - } - - // Aim Direction - if (aimDirectionFromIndex >= 0) - { - updateInstanceDataVector( pvCache, aimDirectionArray, MString("aimDirection")); - pvCache.particles->attributeInfo(aimDirectionFromIndex,pvCache.aimDirAttr); - if (lastAimDirectionFromIndex >= 0) - { - pvCache.particles->attributeInfo(lastAimDirectionFromIndex,pvCache.lastAimDirAttr); - } - else - { - pvCache.particles->attributeInfo(aimDirectionFromIndex,pvCache.lastAimDirAttr); - } - } - // Aim Position - if (aimPositionFromIndex >= 0) - { - updateInstanceDataVector( pvCache, aimPositionArray, MString("aimPosition")); - pvCache.particles->attributeInfo(aimPositionFromIndex,pvCache.aimPosAttr); - if (lastAimPositionFromIndex >= 0) - { - pvCache.particles->attributeInfo(lastAimPositionFromIndex,pvCache.lastAimPosAttr); - } - else - { - pvCache.particles->attributeInfo(aimPositionFromIndex,pvCache.lastAimPosAttr); - } - } - // Aim Axis - if (aimAxisFromIndex >= 0) - { - updateInstanceDataVector( pvCache, aimAxisArray, MString("aimAxis")); - pvCache.particles->attributeInfo(aimAxisFromIndex,pvCache.aimAxisAttr); - } - // Aim Up Axis - if (aimUpAxisFromIndex >= 0) - { - updateInstanceDataVector( pvCache, aimUpAxisArray, MString("aimUpAxis")); - pvCache.particles->attributeInfo(aimUpAxisFromIndex,pvCache.aimUpAttr); - } - // World Up Axis - if (aimWorldUpFromIndex >= 0) - { - updateInstanceDataVector( pvCache, aimWorldUpArray, MString("aimWorldUp")); - pvCache.particles->attributeInfo(aimWorldUpFromIndex,pvCache.aimWorldUpAttr); - } - - // MAIN LOOP ON PARTICLES - for (int i=0;inumParticles();i++) - { - // SCALE - if (pvCache.scaleAttr.type == Partio::FLOAT ) // single float value for scale + if (motionBlurStep) { - const float * attrVal = pvCache.particles->data(pvCache.scaleAttr,i); - float scale = attrVal[0]; - if (canMotionBlur) - { - if (pvCache.lastScaleAttr.type == Partio::FLOAT ) - { - const float * lastAttrVal = pvCache.particles->data(pvCache.lastScaleAttr,i); - scale += (attrVal[0] - lastAttrVal[0])*deltaTime; - } - } - scaleArray.append(MVector(scale,scale,scale)); + if (velocitySource == VS_LAST_POSITION) + { + const float* lastPos = pvCache.particles->data(pvCache.lastPosAttr, i); + const MVector lPos(lastPos[0], lastPos[1], lastPos[2]); + pos += (pos - lPos) * deltaTime; + } + else + { + const float* vel = pvCache.particles->data(pvCache.velocityAttr, i); + const MVector velo(vel[0], vel[1], vel[2]); + pos += velo * velocityMultiplier; + } } - else if (pvCache.scaleAttr.type == Partio::VECTOR ) // we have a 4 float attribute ? - { + } - const float * attrVal = pvCache.particles->data(pvCache.scaleAttr,i); - MVector scale = MVector(attrVal[0],attrVal[1],attrVal[2]); - if (canMotionBlur) - { - if (pvCache.lastScaleAttr.type == Partio::VECTOR ) - { - const float * lastAttrVal = pvCache.particles->data(pvCache.lastScaleAttr,i); - scale.x += (attrVal[0] - lastAttrVal[0])*deltaTime; - scale.y += (attrVal[1] - lastAttrVal[1])*deltaTime; - scale.z += (attrVal[2] - lastAttrVal[2])*deltaTime; - } - } - scaleArray.append(scale); - } - // ROTATION - if (pvCache.rotationAttr.type == Partio::FLOAT ) // single float value for rotation - { - const float * attrVal = pvCache.particles->data(pvCache.rotationAttr,i); - float rot = attrVal[0]; - if (canMotionBlur && lastRotFromIndex >= 0) - { - if (pvCache.lastRotationAttr.type == Partio::FLOAT ) - { - const float * lastAttrVal = pvCache.particles->data(pvCache.lastRotationAttr,i); - rot += (attrVal[0] - lastAttrVal[0])*deltaTime; - } - } - rotationArray.append(MVector(rot,rot,rot)); - } - else if (pvCache.rotationAttr.type == Partio::VECTOR ) // we have a 4 float attribute ? - { - const float * attrVal = pvCache.particles->data(pvCache.rotationAttr,i); - MVector rot = MVector(attrVal[0],attrVal[1],attrVal[2]); - if (canMotionBlur && lastRotFromIndex >= 0) - { - if (pvCache.lastRotationAttr.type == Partio::VECTOR ) - { - const float * lastAttrVal = pvCache.particles->data(pvCache.lastRotationAttr,i); - rot.x += (attrVal[0] - lastAttrVal[0])*deltaTime; - rot.y += (attrVal[1] - lastAttrVal[1])*deltaTime; - rot.z += (attrVal[2] - lastAttrVal[2])*deltaTime; - } - } - rotationArray.append(rot); - } + positionArray[i] = pos; - // AIM DIRECTION - if (pvCache.aimDirAttr.type == Partio::FLOAT ) // single float value for aimDirection - { - const float * attrVal = pvCache.particles->data(pvCache.aimDirAttr,i); - float aimDir = attrVal[0]; - if (canMotionBlur) - { - if (pvCache.lastAimDirAttr.type == Partio::FLOAT ) - { - const float * lastAttrVal = pvCache.particles->data(pvCache.lastAimDirAttr,i); - aimDir += (attrVal[0] - lastAttrVal[0])*deltaTime; - } - } - aimDirectionArray.append(MVector(aimDir,aimDir,aimDir)); - } - else if (pvCache.aimDirAttr.type == Partio::VECTOR ) // we have a 4 float attribute ? - { - const float * attrVal = pvCache.particles->data(pvCache.aimDirAttr,i); - MVector aimDir = MVector(attrVal[0],attrVal[1],attrVal[2]); - if (canMotionBlur) - { - if (pvCache.lastAimDirAttr.type == Partio::VECTOR ) - { - const float * lastAttrVal = pvCache.particles->data(pvCache.lastAimDirAttr,i); - aimDir.x += (attrVal[0] - lastAttrVal[0])*deltaTime; - aimDir.y += (attrVal[1] - lastAttrVal[1])*deltaTime; - aimDir.z += (attrVal[2] - lastAttrVal[2])*deltaTime; - /// TODO: figure out why this is not working on subframes correctly - //cout << lastAttrVal[0] << " " << lastAttrVal[1] << " " << lastAttrVal[2] << endl; - } - } - aimDirectionArray.append(aimDir); - } - // AIM POSITION - if (pvCache.aimPosAttr.type == Partio::FLOAT ) // single float value for aimDirection - { - const float * attrVal = pvCache.particles->data(pvCache.aimPosAttr,i); - float aimPos = attrVal[0]; - if (canMotionBlur) - { - if (pvCache.lastAimPosAttr.type == Partio::FLOAT ) - { - const float * lastAttrVal = pvCache.particles->data(pvCache.lastAimPosAttr,i); - aimPos += (attrVal[0] - lastAttrVal[0])*deltaTime; - } - } - aimPositionArray.append(MVector(aimPos,aimPos,aimPos)); - } - else if (pvCache.aimPosAttr.type == Partio::VECTOR ) // we have a 4 float attribute ? + const int* attrVal = pvCache.particles->data(pvCache.idAttr, i); + idArray[i] = (double)attrVal[0]; + + // resize the bounding box + pvCache.bbox.expand(pos); + } + + // export custom attributes for the particle instancer + if (motionBlurStep || m_cacheChanged || + m_lastExportAttributes != exportAttributes) + { + MStringArray attrs; + + exportAttributes.split(' ', attrs); + + const unsigned int numAttrs = attrs.length(); + for (unsigned int i = 0; i < numAttrs; ++i) + { + MString attrName = attrs[i]; + PARTIO::ParticleAttribute particleAttr; + if (pvCache.particles->attributeInfo(attrName.asChar(), particleAttr)) { - const float * attrVal = pvCache.particles->data(pvCache.aimPosAttr,i); - MVector aimPos = MVector(attrVal[0],attrVal[1],attrVal[2]); - if (canMotionBlur) - { - if (pvCache.lastAimPosAttr.type == Partio::VECTOR ) - { - const float * lastAttrVal = pvCache.particles->data(pvCache.lastAimPosAttr,i); - aimPos.x += (attrVal[0] - lastAttrVal[0])*deltaTime; - aimPos.y += (attrVal[1] - lastAttrVal[1])*deltaTime; - aimPos.z += (attrVal[2] - lastAttrVal[2])*deltaTime; - } - } - aimPositionArray.append(aimPos); + if (((particleAttr.type == PARTIO::VECTOR) || (particleAttr.type == PARTIO::FLOAT)) + && (particleAttr.count == 3)) + { + MVectorArray arr = pvCache.instanceData.vectorArray(attrName); + arr.setLength(numParticles); + + for (int p = 0; p < numParticles; ++p) + { + const float* data = pvCache.particles->data(particleAttr, p); + arr[p] = MVector(static_cast(data[0]), + static_cast(data[1]), + static_cast(data[2])); + } + } + else if ((particleAttr.type == PARTIO::FLOAT) && (particleAttr.count == 1)) + { + MDoubleArray arr = pvCache.instanceData.doubleArray(attrName); + arr.setLength(numParticles); + + for (int p = 0; p < numParticles; ++p) + { + const float* data = pvCache.particles->data(particleAttr, p); + arr[p] = static_cast(data[0]); + } + } + else if ((particleAttr.type == PARTIO::INT) && (particleAttr.count == 1)) + { + MIntArray arr = pvCache.instanceData.intArray(attrName); + arr.setLength(numParticles); + + for (int p = 0; p < numParticles; ++p) + { + const int* data = pvCache.particles->data(particleAttr, p); + arr[p] = data[0]; + } + } } - // AIM Axis - if (pvCache.aimAxisAttr.type == Partio::FLOAT ) // single float value for aimDirection + } + + m_lastExportAttributes = exportAttributes; + } + + const MString rotationFrom = block.inputValue(aRotationFrom).asString(); + const MString lastRotFrom = block.inputValue(aLastRotationFrom).asString(); + const MString scaleFrom = block.inputValue(aScaleFrom).asString(); + const MString lastScaleFrom = block.inputValue(aLastScaleFrom).asString(); + const MString aimDirectionFrom = block.inputValue(aAimDirectionFrom).asString(); + const MString lastAimDirectionFrom = block.inputValue(aLastAimDirectionFrom).asString(); + const MString aimPositionFrom = block.inputValue(aAimPositionFrom).asString(); + const MString lastAimPositionFrom = block.inputValue(aLastAimPositionFrom).asString(); + const MString aimAxisFrom = block.inputValue(aAimAxisFrom).asString(); + const MString aimUpAxisFrom = block.inputValue(aAimUpAxisFrom).asString(); + const MString aimWorldUpFrom = block.inputValue(aAimWorldUpFrom).asString(); + const MString indexFrom = block.inputValue(aIndexFrom).asString(); + const MString angularVelocityFrom = block.inputValue(aAngularVelocityFrom).asString(); + + const float angularVelocityMult = block.inputValue(aAngularVelocityMult).asFloat(); + const short angularVelocitySource = block.inputValue(aAngularVelocitySource).asShort(); + + if (motionBlurStep || m_cacheChanged || + scaleFrom != m_lastScaleFrom || + rotationFrom != m_lastRotationFrom || + aimDirectionFrom != m_lastAimDirectionFrom || + aimPositionFrom != m_lastAimPositionFrom || + aimAxisFrom != m_lastAimAxisFrom || + aimUpAxisFrom != m_lastAimUpAxisFrom || + aimWorldUpFrom != m_lastAimWorldUpFrom || + indexFrom != m_lastIndexFrom || + lastScaleFrom != m_lastLastScaleFrom || + lastRotFrom != m_lastLastRotationFrom || + lastAimDirectionFrom != m_lastLastAimDirectionFrom || + lastAimPositionFrom != m_lastLastAimPositionFrom || + angularVelocityFrom != m_lastAngularVelocityFrom || + angularVelocityMult != m_lastAngularVelocityMult || + angularVelocitySource != m_lastAngularVelocitySource) + { + m_lastScaleFrom = scaleFrom; + m_lastRotationFrom = rotationFrom; + m_lastAimDirectionFrom = aimDirectionFrom; + m_lastAimPositionFrom = aimPositionFrom; + m_lastAimAxisFrom = aimAxisFrom; + m_lastAimUpAxisFrom = aimUpAxisFrom; + m_lastAimWorldUpFrom = aimWorldUpFrom; + m_lastIndexFrom = indexFrom; + m_lastLastScaleFrom = lastScaleFrom; + m_lastLastRotationFrom = lastRotFrom; + m_lastLastAimDirectionFrom = lastAimDirectionFrom; + m_lastLastAimPositionFrom = lastAimPositionFrom; + m_lastAngularVelocityFrom = angularVelocityFrom; + m_lastAngularVelocityMult = angularVelocityMult; + m_lastAngularVelocitySource = angularVelocitySource; + + MDoubleArray indexArray; + MVectorArray scaleArray; + MVectorArray rotationArray; + MVectorArray aimDirectionArray; + MVectorArray aimPositionArray; + MVectorArray aimAxisArray; + MVectorArray aimUpAxisArray; + MVectorArray aimWorldUpArray; + + // clear these out to update on any change + pvCache.rotationAttr.type = PARTIO::NONE; + pvCache.angularVelocityAttr.type = PARTIO::NONE; + pvCache.aimDirAttr.type = PARTIO::NONE; + pvCache.aimPosAttr.type = PARTIO::NONE; + pvCache.aimAxisAttr.type = PARTIO::NONE; + pvCache.aimUpAttr.type = PARTIO::NONE; + pvCache.aimWorldUpAttr.type = PARTIO::NONE; + pvCache.lastRotationAttr.type = PARTIO::NONE; + pvCache.scaleAttr.type = PARTIO::NONE; + pvCache.lastScaleAttr.type = PARTIO::NONE; + pvCache.lastAimDirAttr.type = PARTIO::NONE; + pvCache.lastAimPosAttr.type = PARTIO::NONE; + pvCache.indexAttr.type = PARTIO::NONE; + + // Index + if (pvCache.particles->attributeInfo(indexFrom.asChar(), pvCache.indexAttr)) + { + updateInstanceDataDouble(pvCache, indexArray, "objectIndex", numParticles); + if (pvCache.indexAttr.type == PARTIO::FLOAT || + pvCache.indexAttr.type == PARTIO::INT) // single float value for index { - const float * attrVal = pvCache.particles->data(pvCache.aimAxisAttr,i); - float aimAxis = attrVal[0]; - aimAxisArray.append(MVector(aimAxis,aimAxis,aimAxis)); + if (pvCache.indexAttr.type == PARTIO::FLOAT) + { + for (int i = 0; i < numParticles; ++i) + { + const float* attrVal = pvCache.particles->data(pvCache.indexAttr, i); + indexArray[i] = (double)(int)attrVal[0]; + } + } + else if (pvCache.indexAttr.type == PARTIO::INT) + { + for (int i = 0; i < numParticles; ++i) + { + const int* attrVal = pvCache.particles->data(pvCache.indexAttr, i); + indexArray[i] = (double)attrVal[0]; + } + } } - else if (pvCache.aimAxisAttr.type == Partio::VECTOR ) // we have a 4 float attribute ? + else if (pvCache.indexAttr.type == PARTIO::VECTOR) // we have a 3or4 float attribute { - const float * attrVal = pvCache.particles->data(pvCache.aimAxisAttr,i); - MVector aimAxis = MVector(attrVal[0],attrVal[1],attrVal[2]); - aimAxisArray.append(aimAxis); + for (int i = 0; i < numParticles; ++i) + { + const float* attrVal = pvCache.particles->data(pvCache.indexAttr, i); + indexArray[i] = (double)(int)attrVal[0]; + } } - // AIM Up Axis - if (pvCache.aimUpAttr.type == Partio::FLOAT ) // single float value for aimDirection + } + + // Scale + if (pvCache.particles->attributeInfo(scaleFrom.asChar(), pvCache.scaleAttr)) + { + updateInstanceDataVector(pvCache, scaleArray, "scale", numParticles); + if (m_canMotionBlur) + pvCache.particles->attributeInfo(lastScaleFrom.asChar(), pvCache.lastScaleAttr); + writeOutBlurredVectorAttribute(pvCache.particles, pvCache.scaleAttr, pvCache.lastScaleAttr, scaleArray, deltaTime); + } + + // Aim Direction + if (pvCache.particles->attributeInfo(aimDirectionFrom.asChar(), pvCache.aimDirAttr)) + { + updateInstanceDataVector(pvCache, aimDirectionArray, "aimDirection", numParticles); + if (m_canMotionBlur) + pvCache.particles->attributeInfo(lastAimDirectionFrom.asChar(), pvCache.lastAimDirAttr); + writeOutBlurredVectorAttribute(pvCache.particles, pvCache.aimDirAttr, pvCache.lastAimDirAttr, aimDirectionArray, deltaTime); + } + + // Aim Position + if (pvCache.particles->attributeInfo(aimPositionFrom.asChar(), pvCache.aimPosAttr)) + { + updateInstanceDataVector(pvCache, aimPositionArray, "aimPosition", numParticles); + if (m_canMotionBlur) + pvCache.particles->attributeInfo(lastAimPositionFrom.asChar(), pvCache.lastAimPosAttr); + writeOutBlurredVectorAttribute(pvCache.particles, pvCache.aimPosAttr, pvCache.lastAimPosAttr, aimPositionArray, deltaTime); + } + + // Aim Axis + if (pvCache.particles->attributeInfo(aimAxisFrom.asChar(), pvCache.aimAxisAttr)) + { + updateInstanceDataVector(pvCache, aimAxisArray, "aimAxis", numParticles); + writeOutVectorAttribute(pvCache.particles, pvCache.aimAxisAttr, aimAxisArray); + } + + // Aim Up Axis + if (pvCache.particles->attributeInfo(aimUpAxisFrom.asChar(), pvCache.aimUpAttr)) + { + updateInstanceDataVector(pvCache, aimUpAxisArray, "aimUpAxis", numParticles); + writeOutVectorAttribute(pvCache.particles, pvCache.aimUpAttr, aimUpAxisArray); + } + + // World Up Axis + if (pvCache.particles->attributeInfo(aimWorldUpFrom.asChar(), pvCache.aimWorldUpAttr)) + { + updateInstanceDataVector(pvCache, aimWorldUpArray, "aimWorldUp", numParticles); + writeOutVectorAttribute(pvCache.particles, pvCache.aimWorldUpAttr, aimWorldUpArray); + } + + // Rotation + if (pvCache.particles->attributeInfo(rotationFrom.asChar(), pvCache.rotationAttr)) + { + updateInstanceDataVector(pvCache, rotationArray, "rotation", numParticles); + if (m_canMotionBlur) { - const float * attrVal = pvCache.particles->data(pvCache.aimUpAttr,i); - float aimUp = attrVal[0]; - aimUpAxisArray.append(MVector(aimUp,aimUp,aimUp)); + if (angularVelocitySource == AVS_LAST_ROTATION) + pvCache.particles->attributeInfo(lastRotFrom.asChar(), pvCache.lastRotationAttr); + else if (angularVelocitySource == AVS_ANGULAR_VELOCITY) + pvCache.particles->attributeInfo(angularVelocityFrom.asChar(), pvCache.angularVelocityAttr); } - else if (pvCache.aimUpAttr.type == Partio::VECTOR ) // we have a 4 float attribute ? + } + + const FloatTupleSize rotationTupleSize = getFloatTupleSize(pvCache.rotationAttr); + const FloatTupleSize lastRotationTupleSize = getFloatTupleSize(pvCache.lastRotationAttr); + const FloatTupleSize angularVelocityTupleSize = getFloatTupleSize(pvCache.angularVelocityAttr); + + // usually this comes in radians... because reasons + const float angularVelocityMultiplierDegrees = (angularVelocityMult * 180.0f * deltaTime) / (fps * static_cast(M_PI)); + const float angularVelocityMultiplierRadians = (angularVelocityMult * deltaTime) / fps; + + // ROTATION + if (rotationTupleSize == FLOAT_TUPLE_SINGLE) // single float value for rotation + { + const bool motion_blur = m_canMotionBlur && lastRotationTupleSize == FLOAT_TUPLE_SINGLE; + for (int i = 0; i < numParticles; ++i) { - const float * attrVal = pvCache.particles->data(pvCache.aimUpAttr,i); - MVector aimUp = MVector(attrVal[0],attrVal[1],attrVal[2]); - aimUpAxisArray.append(aimUp); + const float* attrVal = pvCache.particles->data(pvCache.rotationAttr, i); + float rot = attrVal[0]; + if (motion_blur) + { + const float* lastAttrVal = pvCache.particles->data(pvCache.lastRotationAttr, i); + rot += (attrVal[0] - lastAttrVal[0]) * deltaTime; + } + rotationArray[i] = MVector(rot, rot, rot); } - // World Up Axis - if (pvCache.aimWorldUpAttr.type == Partio::FLOAT) // single float value for aimDirection + } + else if (rotationTupleSize == FLOAT_TUPLE_TRIPLE) + { + const bool motion_blur_last = m_canMotionBlur && angularVelocitySource == AVS_LAST_ROTATION && + lastRotationTupleSize == FLOAT_TUPLE_TRIPLE; + const bool motion_blur_avs = m_canMotionBlur && angularVelocitySource == AVS_ANGULAR_VELOCITY && + angularVelocityTupleSize == FLOAT_TUPLE_TRIPLE; + for (int i = 0; i < numParticles; ++i) { - const float * attrVal = pvCache.particles->data(pvCache.aimWorldUpAttr,i); - float worldUp = attrVal[0]; - aimWorldUpArray.append(MVector(worldUp,worldUp,worldUp)); + const float* attrVal = pvCache.particles->data(pvCache.rotationAttr, i); + MVector rot = MVector(attrVal[0], attrVal[1], attrVal[2]); + if (motion_blur_last) + { + const float* lastAttrVal = pvCache.particles->data(pvCache.lastRotationAttr, i); + rot.x += (attrVal[0] - lastAttrVal[0]) * deltaTime; + rot.y += (attrVal[1] - lastAttrVal[1]) * deltaTime; + rot.z += (attrVal[2] - lastAttrVal[2]) * deltaTime; + } + else if (motion_blur_avs) + { + const float* attrValBlur = pvCache.particles->data(pvCache.angularVelocityAttr, + i); + rot.x += attrValBlur[0] * angularVelocityMultiplierDegrees; + rot.y += attrValBlur[1] * angularVelocityMultiplierDegrees; + rot.z += attrValBlur[2] * angularVelocityMultiplierDegrees; + } + rotationArray[i] = rot; } - else if (pvCache.aimWorldUpAttr.type == Partio::VECTOR) // we have a 4 float attribute ? + } + else if (rotationTupleSize == FLOAT_TUPLE_QUAD) + { + const bool motion_blur_last = m_canMotionBlur && angularVelocitySource == AVS_LAST_ROTATION && lastRotationTupleSize == FLOAT_TUPLE_QUAD; + const bool motion_blur_avs = m_canMotionBlur && angularVelocitySource == AVS_ANGULAR_VELOCITY && angularVelocityTupleSize == FLOAT_TUPLE_TRIPLE; + for (int i = 0; i < numParticles; ++i) { - const float * attrVal = pvCache.particles->data(pvCache.aimWorldUpAttr,i); - MVector worldUp = MVector(attrVal[0],attrVal[1],attrVal[2]); - aimWorldUpArray.append(worldUp); + const float* attrVal = pvCache.particles->data(pvCache.rotationAttr, i); + MQuaternion rotQ(attrVal[0], attrVal[1], attrVal[2], attrVal[3]); + if (motion_blur_last) + { + const float* lastAttrVal = pvCache.particles->data(pvCache.lastRotationAttr, i); + MQuaternion lastRotQ(lastAttrVal[0], lastAttrVal[1], lastAttrVal[2], lastAttrVal[3]); + //slerp has input params between 0 and 1, while our delta time is -1 .. 1 +#ifdef USE_SLERP_FOR_QUATERIONS + if (deltaTime < 0.0f) + rotQ = slerp(lastRotQ, rotQ, 1.0 - deltaTime); + else + rotQ = slerp(rotQ, rotQ + rotQ - lastRotQ, deltaTime); +#else + rotQ = rotQ + deltaTime * (rotQ - lastRotQ); +#endif + rotationArray[i] = rotQ.asEulerRotation().asVector() * 180.0 / M_PI; + } + // angular velocity is always eulers ATM + else if (motion_blur_avs) + { + MVector rot = rotQ.asEulerRotation().asVector(); + const float* attrValBlur = pvCache.particles->data(pvCache.angularVelocityAttr, + i); + rot.x += attrValBlur[0] * angularVelocityMultiplierRadians; + rot.y += attrValBlur[1] * angularVelocityMultiplierRadians; + rot.z += attrValBlur[2] * angularVelocityMultiplierRadians; + rotationArray[i] = rot * 180.0 / M_PI; + } + else + rotationArray[i] = rotQ.asEulerRotation().asVector() * 180.0 / M_PI; } - // INDEX - if (pvCache.indexAttr.type == Partio::FLOAT || pvCache.indexAttr.type == Partio::INT) // single float value for index - { - if (pvCache.indexAttr.type == Partio::FLOAT) - { - const float * attrVal = pvCache.particles->data(pvCache.indexAttr,i); - indexArray.append((double)(int)attrVal[0]); - } - else if (pvCache.indexAttr.type == Partio::INT) - { - const int * attrVal = pvCache.particles->data(pvCache.indexAttr,i); - indexArray.append((double)attrVal[0]); - } - } - else if (pvCache.indexAttr.type == Partio::VECTOR) // we have a 3or4 float attribute - { - const float * attrVal = pvCache.particles->data(pvCache.indexAttr,i); - indexArray.append((double)(int)attrVal[0]); - } - } // end frame loop - - mLastScaleFromIndex = scaleFromIndex; - mLastRotationFromIndex = rotationFromIndex; - mLastAimDirectionFromIndex = aimDirectionFromIndex; - mLastAimPositionFromIndex = aimPositionFromIndex; - mLastAimAxisFromIndex = aimAxisFromIndex; - mLastAimUpAxisFromIndex = aimUpAxisFromIndex; - mLastAimWorldUpFromIndex = aimWorldUpFromIndex; - mLastIndexFromIndex = indexFromIndex; - mLastLastScaleFromIndex = lastScaleFromIndex; - mLastLastRotationFromIndex = lastRotFromIndex; - mLastLastAimDirecitonFromIndex = lastAimDirectionFromIndex; - mLastLastAimPositionFromIndex = lastAimPositionFromIndex; - + } } // end if frame/attrs changed } // end if particles - else - { - pvCache.instanceData.clear(); - } + else + pvCache.instanceData.clear(); //cout << pvCache.instanceData.list()<< endl; block.outputValue(aInstanceData).set(pvCache.instanceDataObj); block.setClean(aInstanceData); @@ -1062,70 +1223,36 @@ MStatus partioInstancer::compute( const MPlug& plug, MDataBlock& block ) if (pvCache.particles) // update the AE Controls for attrs in the cache { - unsigned int numAttr=pvCache.particles->numAttributes(); - MPlug zPlug (thisMObject(), aPartioAttributes); + unsigned int numAttr = pvCache.particles->numAttributes(); + MPlug zPlug(thisMObject(), aPartioAttributes); - if ((rotationFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aRotationFrom).setInt(-1); - } - if ((scaleFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aScaleFrom).setInt(-1); - } - if ((lastRotFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aLastRotationFrom).setInt(-1); - } - if ((lastScaleFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aLastScaleFrom).setInt(-1); - } - if ((indexFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aIndexFrom).setInt(-1); - } - if ((aimDirectionFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aAimDirectionFrom).setInt(-1); - } - if ((aimPositionFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aAimPositionFrom).setInt(-1); - } - if ((aimAxisFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aAimAxisFrom).setInt(-1); - } - if ((aimWorldUpFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aAimWorldUpFrom).setInt(-1); - } + // no need to reset attributes, again invalid attributes are fine, as they might + // not be present on all frames - if (cacheChanged || zPlug.numElements() != numAttr) // update the AE Controls for attrs in the cache + if (m_cacheChanged || zPlug.numElements() != numAttr) // update the AE Controls for attrs in the cache { //cout << "partioInstancer->refreshing AE controls" << endl; - attributeList.clear(); + m_attributeList.clear(); - for (unsigned int i=0;iattributeInfo(i,attr); + PARTIO::ParticleAttribute attr; + pvCache.particles->attributeInfo(i, attr); // crazy casting string to char - char *temp; - temp = new char[(attr.name).length()+1]; - strcpy (temp, attr.name.c_str()); + char* temp; + temp = new char[(attr.name).length() + 1]; + strcpy(temp, attr.name.c_str()); - MString mStringAttrName(""); + MString mStringAttrName(""); mStringAttrName += MString(temp); - zPlug.selectAncestorLogicalIndex(i,aPartioAttributes); + zPlug.selectAncestorLogicalIndex(i, aPartioAttributes); zPlug.setValue(MString(temp)); - attributeList.append(mStringAttrName); + m_attributeList.append(mStringAttrName); - delete [] temp; + delete[] temp; } MArrayDataHandle hPartioAttrs = block.inputArrayValue(aPartioAttributes); @@ -1169,62 +1296,23 @@ MBoundingBox partioInstancer::boundingBox() const #endif MPoint corner1 = geom->bbox.min(); MPoint corner2 = geom->bbox.max(); - return MBoundingBox( corner1, corner2 ); -} - -// these two functions check and clean out the instance array members if they exist or make them if they don't - -void partioInstancer::updateInstanceDataVector ( partioInstReaderCache &pvCache, MVectorArray &arrayToCheck, MString arrayChannel ) -{ - MStatus stat; - MFnArrayAttrsData::Type vectorType(MFnArrayAttrsData::kVectorArray); - - if (pvCache.instanceData.checkArrayExist(arrayChannel,vectorType)) - { - arrayToCheck = pvCache.instanceData.getVectorData(arrayChannel,&stat); - CHECK_MSTATUS(stat); - } - else - { - arrayToCheck = pvCache.instanceData.vectorArray(arrayChannel,&stat); - CHECK_MSTATUS(stat); - } - arrayToCheck.clear(); + return MBoundingBox(corner1, corner2); } -void partioInstancer::updateInstanceDataDouble ( partioInstReaderCache &pvCache, MDoubleArray &arrayToCheck, MString arrayChannel ) -{ - MStatus stat; - MFnArrayAttrsData::Type doubleType(MFnArrayAttrsData::kDoubleArray); - - if (pvCache.instanceData.checkArrayExist(arrayChannel,doubleType)) - { - arrayToCheck = pvCache.instanceData.getDoubleData(arrayChannel,&stat); - CHECK_MSTATUS(stat); - } - else - { - arrayToCheck = pvCache.instanceData.doubleArray(arrayChannel,&stat); - CHECK_MSTATUS(stat); - } - arrayToCheck.clear(); -} - - // // Select function. Gets called when the bbox for the object is selected. // This function just selects the object without doing any intersection tests. // -bool partioInstancerUI::select( MSelectInfo &selectInfo, - MSelectionList &selectionList, - MPointArray &worldSpaceSelectPts ) const +bool partioInstancerUI::select(MSelectInfo& selectInfo, + MSelectionList& selectionList, + MPointArray& worldSpaceSelectPts) const { - MSelectionMask priorityMask( MSelectionMask::kSelectObjectsMask ); + MSelectionMask priorityMask(MSelectionMask::kSelectObjectsMask); MSelectionList item; - item.add( selectInfo.selectPath() ); + item.add(selectInfo.selectPath()); MPoint xformedPt; - selectInfo.addSelection( item, xformedPt, selectionList, - worldSpaceSelectPts, priorityMask, false ); + selectInfo.addSelection(item, xformedPt, selectionList, + worldSpaceSelectPts, priorityMask, false); return true; } @@ -1235,11 +1323,11 @@ bool partioInstancer::GetPlugData() { MObject thisNode = thisMObject(); int update = 0; - MPlug updatePlug(thisNode, aUpdateCache ); - updatePlug.getValue( update ); - if (update != dUpdate) + MPlug updatePlug(thisNode, aUpdateCache); + updatePlug.getValue(update); + if (update != m_dUpdate) { - dUpdate = update; + m_dUpdate = update; return true; } else @@ -1251,46 +1339,46 @@ bool partioInstancer::GetPlugData() } // note the "const" at the end, its different than other draw calls -void partioInstancerUI::draw( const MDrawRequest& request, M3dView& view ) const +void partioInstancerUI::draw(const MDrawRequest& request, M3dView& view) const { MDrawData data = request.drawData(); - partioInstancer* shapeNode = (partioInstancer*) surfaceShape(); + partioInstancer* shapeNode = (partioInstancer*)surfaceShape(); - partioInstReaderCache* cache = (partioInstReaderCache*) data.geometry(); + partioInstReaderCache* cache = (partioInstReaderCache*)data.geometry(); MObject thisNode = shapeNode->thisMObject(); - MPlug sizePlug( thisNode, shapeNode->aSize ); + MPlug sizePlug(thisNode, shapeNode->aSize); MDistance sizeVal; - sizePlug.getValue( sizeVal ); + sizePlug.getValue(sizeVal); - shapeNode->multiplier= (float) sizeVal.asCentimeters(); + shapeNode->m_multiplier = (float)sizeVal.asCentimeters(); int drawStyle = 0; - MPlug drawStylePlug( thisNode, shapeNode->aDrawStyle ); - drawStylePlug.getValue( drawStyle ); + MPlug drawStylePlug(thisNode, shapeNode->aDrawStyle); + drawStylePlug.getValue(drawStyle); view.beginGL(); - if (drawStyle < 3 && view.displayStyle() != M3dView::kBoundingBox ) + if (drawStyle < 3 && view.displayStyle() != M3dView::kBoundingBox) { - drawPartio(cache,drawStyle,view); + drawPartio(cache, drawStyle, view); } else { drawBoundingBox(); } - if (shapeNode->drawError == 1) - { - glColor3f(.75f,0.0f,0.0f); - } - else if (shapeNode->drawError == 2) - { - glColor3f(0.0f,0.0f,0.0f); - } + if (shapeNode->m_drawError == 1) + { + glColor3f(.75f, 0.0f, 0.0f); + } + else if (shapeNode->m_drawError == 2) + { + glColor3f(0.0f, 0.0f, 0.0f); + } - partio4Maya::drawPartioLogo(shapeNode->multiplier); + partio4Maya::drawPartioLogo(shapeNode->m_multiplier); view.endGL(); } @@ -1300,10 +1388,10 @@ void partioInstancerUI::draw( const MDrawRequest& request, M3dView& view ) const void partioInstancerUI::drawBoundingBox() const { - partioInstancer* shapeNode = (partioInstancer*) surfaceShape(); + partioInstancer* shapeNode = (partioInstancer*)surfaceShape(); - MPoint bboxMin = shapeNode->pvCache.bbox.min(); - MPoint bboxMax = shapeNode->pvCache.bbox.max(); + MPoint bboxMin = shapeNode->pvCache.bbox.min(); + MPoint bboxMax = shapeNode->pvCache.bbox.max(); float xMin = float(bboxMin.x); float yMin = float(bboxMin.y); @@ -1313,114 +1401,111 @@ void partioInstancerUI::drawBoundingBox() const float zMax = float(bboxMax.z); /// draw the bounding box - glBegin (GL_LINES); + glBegin(GL_LINES); - glColor3f(1.0f,0.5f,0.5f); + glColor3f(1.0f, 0.5f, 0.5f); - glVertex3f (xMin,yMin,zMax); - glVertex3f (xMax,yMin,zMax); + glVertex3f(xMin, yMin, zMax); + glVertex3f(xMax, yMin, zMax); - glVertex3f (xMin,yMin,zMin); - glVertex3f (xMax,yMin,zMin); + glVertex3f(xMin, yMin, zMin); + glVertex3f(xMax, yMin, zMin); - glVertex3f (xMin,yMin,zMax); - glVertex3f (xMin,yMin,zMin); + glVertex3f(xMin, yMin, zMax); + glVertex3f(xMin, yMin, zMin); - glVertex3f (xMax,yMin,zMax); - glVertex3f (xMax,yMin,zMin); + glVertex3f(xMax, yMin, zMax); + glVertex3f(xMax, yMin, zMin); - glVertex3f (xMin,yMax,zMin); - glVertex3f (xMin,yMax,zMax); + glVertex3f(xMin, yMax, zMin); + glVertex3f(xMin, yMax, zMax); - glVertex3f (xMax,yMax,zMax); - glVertex3f (xMax,yMax,zMin); + glVertex3f(xMax, yMax, zMax); + glVertex3f(xMax, yMax, zMin); - glVertex3f (xMin,yMax,zMax); - glVertex3f (xMax,yMax,zMax); + glVertex3f(xMin, yMax, zMax); + glVertex3f(xMax, yMax, zMax); - glVertex3f (xMin,yMax,zMin); - glVertex3f (xMax,yMax,zMin); + glVertex3f(xMin, yMax, zMin); + glVertex3f(xMax, yMax, zMin); - glVertex3f (xMin,yMax,zMin); - glVertex3f (xMin,yMin,zMin); + glVertex3f(xMin, yMax, zMin); + glVertex3f(xMin, yMin, zMin); - glVertex3f (xMax,yMax,zMin); - glVertex3f (xMax,yMin,zMin); + glVertex3f(xMax, yMax, zMin); + glVertex3f(xMax, yMin, zMin); - glVertex3f (xMin,yMax,zMax); - glVertex3f (xMin,yMin,zMax); + glVertex3f(xMin, yMax, zMax); + glVertex3f(xMin, yMin, zMax); - glVertex3f (xMax,yMax,zMax); - glVertex3f (xMax,yMin,zMax); + glVertex3f(xMax, yMax, zMax); + glVertex3f(xMax, yMin, zMax); glEnd(); - } - //////////////////////////////////////////// /// DRAW PARTIO -void partioInstancerUI::drawPartio(partioInstReaderCache* pvCache, int drawStyle, M3dView &view) const +void partioInstancerUI::drawPartio(partioInstReaderCache* pvCache, int drawStyle, M3dView& view) const { - partioInstancer* shapeNode = (partioInstancer*) surfaceShape(); + partioInstancer* shapeNode = (partioInstancer*)surfaceShape(); MObject thisNode = shapeNode->thisMObject(); -// MPlug flipYZPlug( thisNode, shapeNode->aFlipYZ ); -// bool flipYZVal; -// flipYZPlug.getValue( flipYZVal ); + // MPlug flipYZPlug( thisNode, shapeNode->aFlipYZ); + // bool flipYZVal; + // flipYZPlug.getValue( flipYZVal); - MPlug pointSizePlug( thisNode, shapeNode->aPointSize ); + MPlug pointSizePlug(thisNode, shapeNode->aPointSize); float pointSizeVal; - pointSizePlug.getValue( pointSizeVal ); + pointSizePlug.getValue(pointSizeVal); if (pvCache->particles) { glPushAttrib(GL_CURRENT_BIT); - /// looping thru particles one by one... - + /// looping thru particles one by one... glPointSize(pointSizeVal); - glColor3f(1.0,1.0,1.0); + glColor3f(1.0, 1.0, 1.0); glBegin(GL_POINTS); - MVectorArray positions = pvCache->instanceData.vectorArray("position"); - for (unsigned int i=0; i < positions.length(); i++) + MVectorArray positions = pvCache->instanceData.vectorArray("position"); + for (unsigned int i = 0; i < positions.length(); i++) { glVertex3f(positions[i].x, positions[i].y, positions[i].z); } - glEnd( ); + glEnd(); glDisable(GL_POINT_SMOOTH); if (drawStyle == DRAW_STYLE_LABEL) { - glColor3f(0.0,0.0,0.0); - for (unsigned int i=0; i < positions.length();i++) + glColor3f(0.0, 0.0, 0.0); + for (unsigned int i = 0; i < positions.length(); i++) { - MString idVal; - if (pvCache->indexAttr.type == Partio::FLOAT) - { - const float * attrVal = pvCache->particles->data(pvCache->indexAttr,i); - idVal = (double)(int)attrVal[0]; - } - else if (pvCache->indexAttr.type == Partio::INT) - { - const int * attrVal = pvCache->particles->data(pvCache->indexAttr,i); - idVal = (double)attrVal[0]; - } - else if (pvCache->indexAttr.type == Partio::VECTOR) - { - const float * attrVal = pvCache->particles->data(pvCache->indexAttr,i); - char idString[100]; - sprintf(idString,"(%.2f,%.2f,%.2f)", (double)attrVal[0], (double)attrVal[1], (double)attrVal[2]); - idVal = idString; - } - else - { - idVal = ""; - } + MString idVal; + if (pvCache->indexAttr.type == PARTIO::FLOAT) + { + const float* attrVal = pvCache->particles->data(pvCache->indexAttr, i); + idVal = (double)(int)attrVal[0]; + } + else if (pvCache->indexAttr.type == PARTIO::INT) + { + const int* attrVal = pvCache->particles->data(pvCache->indexAttr, i); + idVal = (double)attrVal[0]; + } + else if (pvCache->indexAttr.type == PARTIO::VECTOR) + { + const float* attrVal = pvCache->particles->data(pvCache->indexAttr, i); + char idString[100]; + sprintf(idString, "(%.2f,%.2f,%.2f)", (double)attrVal[0], (double)attrVal[1], (double)attrVal[2]); + idVal = idString; + } + else + { + idVal = ""; + } /// TODO: draw text label per particle here view.drawText(idVal, MPoint(positions[i].x, positions[i].y, positions[i].z), M3dView::kLeft); } @@ -1434,6 +1519,7 @@ void partioInstancerUI::drawPartio(partioInstReaderCache* pvCache, int drawStyle partioInstancerUI::partioInstancerUI() { } + partioInstancerUI::~partioInstancerUI() { } @@ -1443,14 +1529,12 @@ void* partioInstancerUI::creator() return new partioInstancerUI(); } - -void partioInstancerUI::getDrawRequests(const MDrawInfo & info, - bool /*objectAndActiveOnly*/, MDrawRequestQueue & queue) +void partioInstancerUI::getDrawRequests(const MDrawInfo& info, + bool /*objectAndActiveOnly*/, MDrawRequestQueue& queue) { - MDrawData data; MDrawRequest request = info.getPrototype(*this); - partioInstancer* shapeNode = (partioInstancer*) surfaceShape(); + partioInstancer* shapeNode = (partioInstancer*)surfaceShape(); partioInstReaderCache* geom = shapeNode->updateParticleCache(); getDrawData(geom, data); @@ -1465,25 +1549,23 @@ void partioInstancerUI::getDrawRequests(const MDrawInfo & info, M3dView::ColorTable dormantColorTable = M3dView::kDormantColors; switch (displayStatus) { - case M3dView::kLead: - request.setColor(LEAD_COLOR, activeColorTable); - break; - case M3dView::kActive: - request.setColor(ACTIVE_COLOR, activeColorTable); - break; - case M3dView::kActiveAffected: - request.setColor(ACTIVE_AFFECTED_COLOR, activeColorTable); - break; - case M3dView::kDormant: - request.setColor(DORMANT_COLOR, dormantColorTable); - break; - case M3dView::kHilite: - request.setColor(HILITE_COLOR, activeColorTable); - break; - default: - break; + case M3dView::kLead: + request.setColor(LEAD_COLOR, activeColorTable); + break; + case M3dView::kActive: + request.setColor(ACTIVE_COLOR, activeColorTable); + break; + case M3dView::kActiveAffected: + request.setColor(ACTIVE_AFFECTED_COLOR, activeColorTable); + break; + case M3dView::kDormant: + request.setColor(DORMANT_COLOR, dormantColorTable); + break; + case M3dView::kHilite: + request.setColor(HILITE_COLOR, activeColorTable); + break; + default: + break; } queue.add(request); - } - diff --git a/contrib/partio4Maya/partioInstancer.h b/contrib/partio4Maya/partioInstancer.h index db1eddac..d6ed25ed 100644 --- a/contrib/partio4Maya/partioInstancer.h +++ b/contrib/partio4Maya/partioInstancer.h @@ -89,173 +89,184 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "partio4MayaShared.h" #include "iconArrays.h" -class partioInstReaderCache -{ +class partioInstReaderCache { public: partioInstReaderCache(); + MBoundingBox bbox; int dList; - Partio::ParticlesDataMutable* particles; - Partio::ParticleAttribute positionAttr; - Partio::ParticleAttribute idAttr; - Partio::ParticleAttribute velocityAttr; - Partio::ParticleAttribute rotationAttr; - Partio::ParticleAttribute aimDirAttr; - Partio::ParticleAttribute aimPosAttr; - Partio::ParticleAttribute aimAxisAttr; - Partio::ParticleAttribute aimUpAttr; - Partio::ParticleAttribute aimWorldUpAttr; - Partio::ParticleAttribute lastRotationAttr; - Partio::ParticleAttribute scaleAttr; - Partio::ParticleAttribute lastScaleAttr; - Partio::ParticleAttribute lastAimDirAttr; - Partio::ParticleAttribute lastAimPosAttr; - Partio::ParticleAttribute indexAttr; -// Partio::ParticleAttribute shaderIndexAttr; - float* flipPos; + PARTIO::ParticlesDataMutable* particles; + PARTIO::ParticleAttribute positionAttr; + PARTIO::ParticleAttribute idAttr; + PARTIO::ParticleAttribute velocityAttr; + PARTIO::ParticleAttribute angularVelocityAttr; + PARTIO::ParticleAttribute rotationAttr; + PARTIO::ParticleAttribute aimDirAttr; + PARTIO::ParticleAttribute aimPosAttr; + PARTIO::ParticleAttribute aimAxisAttr; + PARTIO::ParticleAttribute aimUpAttr; + PARTIO::ParticleAttribute aimWorldUpAttr; + PARTIO::ParticleAttribute lastRotationAttr; + PARTIO::ParticleAttribute scaleAttr; + PARTIO::ParticleAttribute lastScaleAttr; + PARTIO::ParticleAttribute lastAimDirAttr; + PARTIO::ParticleAttribute lastAimPosAttr; + PARTIO::ParticleAttribute lastPosAttr; + PARTIO::ParticleAttribute indexAttr; +// PARTIO::ParticleAttribute shaderIndexAttr; MFnArrayAttrsData instanceData; MObject instanceDataObj; - - }; -class partioInstancerUI : public MPxSurfaceShapeUI -{ +class partioInstancerUI : public MPxSurfaceShapeUI { public: partioInstancerUI(); + virtual ~partioInstancerUI(); - virtual void draw(const MDrawRequest & request, M3dView & view) const; - virtual void getDrawRequests(const MDrawInfo & info, bool objectAndActiveOnly, MDrawRequestQueue & requests); - void drawBoundingBox() const; - void drawPartio(partioInstReaderCache* pvCache, int drawStyle, M3dView &view) const; - static void * creator(); - virtual bool select( MSelectInfo &selectInfo, - MSelectionList &selectionList, - MPointArray &worldSpaceSelectPts ) const; + + virtual void draw(const MDrawRequest& request, M3dView& view) const; + + virtual void getDrawRequests(const MDrawInfo& info, bool objectAndActiveOnly, MDrawRequestQueue& requests); + + void drawBoundingBox() const; + + void drawPartio(partioInstReaderCache* pvCache, int drawStyle, M3dView& view) const; + + static void* creator(); + + virtual bool select(MSelectInfo& selectInfo, + MSelectionList& selectionList, + MPointArray& worldSpaceSelectPts) const; }; -class partioInstancer : public MPxSurfaceShape -{ +class partioInstancer : public MPxSurfaceShape { public: partioInstancer(); + virtual ~partioInstancer(); - virtual MStatus compute( const MPlug& plug, MDataBlock& block ); - virtual bool isBounded() const; - virtual MBoundingBox boundingBox() const; - static void * creator(); - static MStatus initialize(); - static void reInit(void *data); - void initCallback(); - virtual void postConstructor(); + virtual MStatus compute(const MPlug& plug, MDataBlock& block); - bool GetPlugData(); - void addParticleAttr(int attrIndex, MString attrName ); - partioInstReaderCache* updateParticleCache(); + virtual bool isBounded() const; + + virtual MBoundingBox boundingBox() const; + + static void* creator(); + + static MStatus initialize(); - void updateInstanceDataVector ( partioInstReaderCache &pvCache, MVectorArray &arrayToCheck, MString arrayChannel ); - void updateInstanceDataDouble ( partioInstReaderCache &pvCache, MDoubleArray &arrayToCheck, MString arrayChannel ); + static void reInit(void* data); + void initCallback(); + + virtual void postConstructor(); + + bool GetPlugData(); + + partioInstReaderCache* updateParticleCache(); MCallbackId partioInstancerOpenCallback; MCallbackId partioInstancerImportCallback; MCallbackId partioInstancerReferenceCallback; - - /// ATTRS - static MObject time; - static MObject aByFrame; - static MObject aSize; // The size of the logo - static MObject aFlipYZ; - static MObject aDrawStyle; - static MObject aPointSize; + static MObject time; + static MObject aByFrame; + static MObject aSize; // The size of the logo + static MObject aFlipYZ; + static MObject aDrawStyle; + static MObject aPointSize; /// Cache file related stuff - static MObject aUpdateCache; - static MObject aCacheDir; - static MObject aCacheFile; - static MObject aCacheActive; - static MObject aCacheOffset; - static MObject aCacheStatic; - static MObject aCacheFormat; - static MObject aForceReload; - static MObject aRenderCachePath; + static MObject aUpdateCache; + static MObject aCacheDir; + static MObject aCacheFile; + static MObject aCacheActive; + static MObject aCacheOffset; + static MObject aCacheStatic; + static MObject aCacheFormat; + static MObject aForceReload; + static MObject aRenderCachePath; /// point position / velocity - static MObject aComputeVeloPos; - static MObject aVeloMult; + static MObject aComputeVeloPos; + static MObject aVelocityMult; /// attributes - static MObject aPartioAttributes; - static MObject aScaleFrom; - static MObject aRotationType; - - static MObject aRotationFrom; - static MObject aAimDirectionFrom; - static MObject aAimPositionFrom; - static MObject aAimAxisFrom; - static MObject aAimUpAxisFrom; - static MObject aAimWorldUpFrom; - - static MObject aLastScaleFrom; - static MObject aLastRotationFrom; - static MObject aLastAimDirectionFrom; - static MObject aLastAimPositionFrom; - - static MObject aIndexFrom; + static MObject aPartioAttributes; + static MObject aScaleFrom; + static MObject aRotationType; + + static MObject aRotationFrom; + static MObject aAimDirectionFrom; + static MObject aAimPositionFrom; + static MObject aAimAxisFrom; + static MObject aAimUpAxisFrom; + static MObject aAimWorldUpFrom; + + static MObject aLastScaleFrom; + static MObject aLastRotationFrom; + static MObject aLastAimDirectionFrom; + static MObject aLastAimPositionFrom; + static MObject aLastPositionFrom; + static MObject aVelocityFrom; + static MObject aAngularVelocityFrom; + static MObject aAngularVelocityMult; + + static MObject aIndexFrom; /// not implemented yet -// static MObject aJitterPos; -// static MObject aJitterFreq; -// static MObject aShaderIndexFrom; -// static MObject aInMeshInstances; -// static MObject aOutMesh; +// static MObject aJitterPos; +// static MObject aJitterFreq; +// static MObject aShaderIndexFrom; +// static MObject aInMeshInstances; +// static MObject aOutMesh; // output data to instancer - static MObject aInstanceData; - - - static MTypeId id; - float multiplier; - bool cacheChanged; - partioInstReaderCache pvCache; - int drawError; - + static MObject aInstanceData; + static MObject aExportAttributes; + static MObject aVelocitySource; + static MObject aAngularVelocitySource; + static MTypeId id; + partioInstReaderCache pvCache; private: + MStringArray m_attributeList; + MString m_lastFileLoaded; + MString m_lastPath; + MString m_lastFile; + MString m_lastExt; + MString m_lastExportAttributes; + MString m_lastRotationType; + MString m_lastRotationFrom; + MString m_lastLastRotationFrom; + MString m_lastAimDirectionFrom; + MString m_lastLastAimDirectionFrom; + MString m_lastAimPositionFrom; + MString m_lastLastAimPositionFrom; + MString m_lastAimAxisFrom; + MString m_lastAimUpAxisFrom; + MString m_lastAimWorldUpFrom; + MString m_lastScaleFrom; + MString m_lastLastScaleFrom; + MString m_lastIndexFrom; + MString m_lastAngularVelocityFrom; + float m_lastAngularVelocityMult; + short m_lastAngularVelocitySource; + bool m_lastFlipStatus; + bool m_flipped; + bool m_frameChanged; + bool m_canMotionBlur; - MString mLastFileLoaded; - MString mLastPath; - MString mLastFile; - MString mLastExt; - bool mLastFlipStatus; - bool mFlipped; - bool frameChanged; - MStringArray attributeList; - int mLastRotationTypeIndex; - int mLastRotationFromIndex; - int mLastLastRotationFromIndex; - int mLastAimDirectionFromIndex; - int mLastLastAimDirecitonFromIndex; - int mLastAimPositionFromIndex; - int mLastLastAimPositionFromIndex; - int mLastAimAxisFromIndex; - int mLastAimUpAxisFromIndex; - int mLastAimWorldUpFromIndex; - int mLastScaleFromIndex; - int mLastLastScaleFromIndex; - int mLastIndexFromIndex; - bool canMotionBlur; - // int mLastShaderIndexFromIndex; +public: + float m_multiplier; + int m_drawError; + bool m_cacheChanged; protected: - - int dUpdate; - GLuint dList; - + int m_dUpdate; }; #endif diff --git a/contrib/partio4Maya/partioVisualizer.cpp b/contrib/partio4Maya/partioVisualizer.cpp index e610a55e..ca3c3ce5 100644 --- a/contrib/partio4Maya/partioVisualizer.cpp +++ b/contrib/partio4Maya/partioVisualizer.cpp @@ -29,30 +29,29 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "partioVisualizer.h" -static MGLFunctionTable *gGLFT = NULL; +static MGLFunctionTable* gGLFT = NULL; // id is registered with autodesk no need to change #define ID_PARTIOVISUALIZER 0x00116ECF -#define LEAD_COLOR 18 // green -#define ACTIVE_COLOR 15 // white -#define ACTIVE_AFFECTED_COLOR 8 // purple -#define DORMANT_COLOR 4 // blue -#define HILITE_COLOR 17 // pale blue +#define LEAD_COLOR 18 // green +#define ACTIVE_COLOR 15 // white +#define ACTIVE_AFFECTED_COLOR 8 // purple +#define DORMANT_COLOR 4 // blue +#define HILITE_COLOR 17 // pale blue -#define DRAW_STYLE_POINTS 0 -#define DRAW_STYLE_RADIUS 1 -#define DRAW_STYLE_DISK 2 -#define DRAW_STYLE_BOUNDING_BOX 3 - -using namespace Partio; -using namespace std; +#ifdef min +#undef min +#endif +#ifdef max +#undef max +#endif /// /////////////////////////////////////////////////// /// PARTIO VISUALIZER -MTypeId partioVisualizer::id( ID_PARTIOVISUALIZER ); +MTypeId partioVisualizer::id(ID_PARTIOVISUALIZER); MObject partioVisualizer::time; MObject partioVisualizer::aByFrame; @@ -70,6 +69,8 @@ MObject partioVisualizer::aCacheFormat; MObject partioVisualizer::aJitterPos; MObject partioVisualizer::aJitterFreq; MObject partioVisualizer::aPartioAttributes; +MObject partioVisualizer::aVelocityFrom; +MObject partioVisualizer::aAccelerationFrom; MObject partioVisualizer::aColorFrom; MObject partioVisualizer::aRadiusFrom; MObject partioVisualizer::aAlphaFrom; @@ -83,60 +84,137 @@ MObject partioVisualizer::aDrawStyle; MObject partioVisualizer::aForceReload; MObject partioVisualizer::aRenderCachePath; +MString partioVisualizer::drawDbClassification("drawdb/geometry/partio/visualizer"); + +namespace { + struct BillboardDrawData { + std::vector vertices; + const size_t num_segments; + float last_radius; + + BillboardDrawData(size_t _num_segments) : num_segments(_num_segments), last_radius(-1.0f) + { + vertices.resize(num_segments * 2); + } + }; + + void drawBillboardCircleAtPoint(const float* position, float radius, int drawType, BillboardDrawData& data) + { + glPushMatrix(); + glTranslatef(position[0], position[1], position[2]); + glMatrixMode(GL_MODELVIEW_MATRIX); + float m[16]; + glGetFloatv(GL_MODELVIEW_MATRIX, m); + m[0] = 1.0f; + m[1] = 0.0f; + m[2] = 0.0f; + m[4] = 0.0f; + m[5] = 1.0f; + m[6] = 0.0f; + m[8] = 0.0f; + m[9] = 0.0f; + m[10] = 1.0f; + glLoadMatrixf(m); + + // TODO: setup radius using the scale of the Matrix + // also get rid of all this gl matrix tingamagic, and do it manually + + if (radius != data.last_radius) + { + data.last_radius = radius; + + const float theta = 2.0f * 3.1415926f / float(data.num_segments); + const float tangetial_factor = tanf(theta);//calculate the tangential factor + const float radial_factor = cosf(theta);//calculate the radial factor + + float x = radius;//we start at angle = 0 + float y = 0; -partioVizReaderCache::partioVizReaderCache(): - bbox(MBoundingBox(MPoint(0,0,0,0),MPoint(0,0,0,0))), - dList(0), - particles(NULL), - rgb(NULL), - rgba(NULL), - flipPos(NULL) + for (size_t i = 0, vid = 0; i < data.num_segments; ++i) + { + data.vertices[vid++] = x; + data.vertices[vid++] = y; + + const float tx = -y; + const float ty = x; + + //add the tangential vector + x += tx * tangetial_factor; + y += ty * tangetial_factor; + + //correct using the radial factor + x *= radial_factor; + y *= radial_factor; + } + } + + if (drawType == PARTIO_DRAW_STYLE_RADIUS) + glDrawArrays(GL_LINE_LOOP, 0, data.num_segments); + else + glDrawArrays(GL_POLYGON, 0, data.num_segments); + + glPopMatrix(); + } +} + +partioVizReaderCache::partioVizReaderCache() : + particles(0) { + clear(); } +void partioVizReaderCache::clear() +{ + if (particles != 0) + { + particles->release(); + // partio does an internal caching of the data, + // so it will free the pointer accordingly + particles = 0; + } + bbox.clear(); + positionAttr.attributeIndex = -1; + colorAttr.attributeIndex = -1; + opacityAttr.attributeIndex = -1; + radiusAttr.attributeIndex = -1; + incandescenceAttr.attributeIndex = -1; + + // http://www.cplusplus.com/reference/vector/vector/clear/ + // clear is not guaranteed to free up memory! + std::vector().swap(rgba); + std::vector().swap(radius); +} /// CREATOR partioVisualizer::partioVisualizer() - : mLastFileLoaded(""), - mLastAlpha(0.0), - mLastInvertAlpha(false), - mLastPath(""), - mLastFile(""), - mLastExt(""), - mLastColorFromIndex(-1), - mLastAlphaFromIndex(-1), - mLastRadiusFromIndex(-1), - mLastIncandFromIndex(-1), - mLastColor(1,0,0), - mLastRadius(1.0), - cacheChanged(false), - frameChanged(false), - multiplier(1.0), - mFlipped(false), - drawError(0) + : mLastFileLoaded(""), + mLastAlpha(0.0), + mLastInvertAlpha(false), + mLastPath(""), + mLastFile(""), + mLastExt(""), + mLastColorFromIndex(""), + mLastAlphaFromIndex(""), + mLastRadiusFromIndex(""), + mLastIncandFromIndex(""), + mLastColor(1.0, 0.0, 0.0), + mLastRadius(1.0), + cacheChanged(false), + mFrameChanged(false), + multiplier(1.0), + mFlipped(false), + drawError(0) { - pvCache.particles = NULL; - pvCache.flipPos = (float *) malloc(sizeof(float)); - pvCache.rgb = (float *) malloc (sizeof(float)); - pvCache.rgba = (float *) malloc(sizeof(float)); - pvCache.radius = MFloatArray(); } + /// DESTRUCTOR partioVisualizer::~partioVisualizer() { - if (pvCache.particles) - { pvCache.particles->release(); - } - free(pvCache.flipPos); - free(pvCache.rgb); - free(pvCache.rgba); - pvCache.radius.clear(); - MSceneMessage::removeCallback( partioVisualizerOpenCallback); - MSceneMessage::removeCallback( partioVisualizerImportCallback); - MSceneMessage::removeCallback( partioVisualizerReferenceCallback); - + MSceneMessage::removeCallback(partioVisualizerOpenCallback); + MSceneMessage::removeCallback(partioVisualizerImportCallback); + MSceneMessage::removeCallback(partioVisualizerReferenceCallback); } void* partioVisualizer::creator() @@ -148,9 +226,12 @@ void* partioVisualizer::creator() void partioVisualizer::postConstructor() { setRenderable(true); - partioVisualizerOpenCallback = MSceneMessage::addCallback(MSceneMessage::kAfterOpen, partioVisualizer::reInit, this); - partioVisualizerImportCallback = MSceneMessage::addCallback(MSceneMessage::kAfterImport, partioVisualizer::reInit, this); - partioVisualizerReferenceCallback = MSceneMessage::addCallback(MSceneMessage::kAfterReference, partioVisualizer::reInit, this); + partioVisualizerOpenCallback = MSceneMessage::addCallback(MSceneMessage::kAfterOpen, partioVisualizer::reInit, + this); + partioVisualizerImportCallback = MSceneMessage::addCallback(MSceneMessage::kAfterImport, partioVisualizer::reInit, + this); + partioVisualizerReferenceCallback = MSceneMessage::addCallback(MSceneMessage::kAfterReference, + partioVisualizer::reInit, this); } /////////////////////////////////// @@ -159,7 +240,6 @@ void partioVisualizer::postConstructor() void partioVisualizer::initCallback() { - MObject tmo = thisMObject(); short extENum; @@ -167,80 +247,77 @@ void partioVisualizer::initCallback() mLastExt = partio4Maya::setExt(extENum); - MPlug(tmo,aCacheDir).getValue(mLastPath); - MPlug(tmo,aCacheFile).getValue(mLastFile); - MPlug(tmo,aDefaultAlpha).getValue(mLastAlpha); - MPlug(tmo,aDefaultRadius).getValue(mLastRadius); - MPlug(tmo,aColorFrom).getValue(mLastColorFromIndex); - MPlug(tmo,aAlphaFrom).getValue(mLastAlphaFromIndex); - MPlug(tmo,aRadiusFrom).getValue(mLastRadiusFromIndex); - MPlug(tmo,aIncandFrom).getValue(mLastIncandFromIndex); - MPlug(tmo,aSize).getValue(multiplier); - MPlug(tmo,aInvertAlpha).getValue(mLastInvertAlpha); - MPlug(tmo,aCacheStatic).getValue(mLastStatic); + MPlug(tmo, aCacheDir).getValue(mLastPath); + MPlug(tmo, aCacheFile).getValue(mLastFile); + MPlug(tmo, aDefaultAlpha).getValue(mLastAlpha); + MPlug(tmo, aDefaultRadius).getValue(mLastRadius); + MPlug(tmo, aColorFrom).getValue(mLastColorFromIndex); + MPlug(tmo, aAlphaFrom).getValue(mLastAlphaFromIndex); + MPlug(tmo, aRadiusFrom).getValue(mLastRadiusFromIndex); + MPlug(tmo, aIncandFrom).getValue(mLastIncandFromIndex); + MPlug(tmo, aSize).getValue(multiplier); + MPlug(tmo, aInvertAlpha).getValue(mLastInvertAlpha); + MPlug(tmo, aCacheStatic).getValue(mLastStatic); cacheChanged = false; - } -void partioVisualizer::reInit(void *data) +void partioVisualizer::reInit(void* data) { - partioVisualizer *vizNode = (partioVisualizer*) data; + partioVisualizer* vizNode = (partioVisualizer*)data; vizNode->initCallback(); } - MStatus partioVisualizer::initialize() { - - MFnEnumAttribute eAttr; - MFnUnitAttribute uAttr; + MFnEnumAttribute eAttr; + MFnUnitAttribute uAttr; MFnNumericAttribute nAttr; - MFnTypedAttribute tAttr; - MStatus stat; - - time = nAttr.create( "time", "tm", MFnNumericData::kLong ,0); - uAttr.setKeyable( true ); - - aByFrame = nAttr.create( "byFrame", "byf", MFnNumericData::kInt ,1); - nAttr.setKeyable( true ); - nAttr.setReadable( true ); - nAttr.setWritable( true ); - nAttr.setConnectable( true ); - nAttr.setStorable( true ); + MFnTypedAttribute tAttr; + MStatus stat; + + time = nAttr.create("time", "tm", MFnNumericData::kLong, 0); + uAttr.setKeyable(true); + + aByFrame = nAttr.create("byFrame", "byf", MFnNumericData::kInt, 1); + nAttr.setKeyable(true); + nAttr.setReadable(true); + nAttr.setWritable(true); + nAttr.setConnectable(true); + nAttr.setStorable(true); nAttr.setMin(1); nAttr.setMax(100); - aSize = uAttr.create( "iconSize", "isz", MFnUnitAttribute::kDistance ); - uAttr.setDefault( 0.25 ); + aSize = uAttr.create("iconSize", "isz", MFnUnitAttribute::kDistance); + uAttr.setDefault(0.25); - aFlipYZ = nAttr.create( "flipYZ", "fyz", MFnNumericData::kBoolean); - nAttr.setDefault ( false ); - nAttr.setKeyable ( true ); + aFlipYZ = nAttr.create("flipYZ", "fyz", MFnNumericData::kBoolean); + nAttr.setDefault(false); + nAttr.setKeyable(true); - aDrawSkip = nAttr.create( "drawSkip", "dsk", MFnNumericData::kLong ,0); - nAttr.setKeyable( true ); - nAttr.setReadable( true ); - nAttr.setWritable( true ); - nAttr.setConnectable( true ); - nAttr.setStorable( true ); + aDrawSkip = nAttr.create("drawSkip", "dsk", MFnNumericData::kLong, 0); + nAttr.setKeyable(true); + nAttr.setReadable(true); + nAttr.setWritable(true); + nAttr.setConnectable(true); + nAttr.setStorable(true); nAttr.setMin(0); nAttr.setMax(1000); - aCacheDir = tAttr.create ( "cacheDir", "cachD", MFnStringData::kString ); - tAttr.setReadable ( true ); - tAttr.setWritable ( true ); - tAttr.setKeyable ( true ); - tAttr.setConnectable ( true ); - tAttr.setStorable ( true ); - - aCacheFile = tAttr.create ( "cachePrefix", "cachP", MFnStringData::kString ); - tAttr.setReadable ( true ); - tAttr.setWritable ( true ); - tAttr.setKeyable ( true ); - tAttr.setConnectable ( true ); - tAttr.setStorable ( true ); - - aCacheOffset = nAttr.create("cacheOffset", "coff", MFnNumericData::kInt, 0, &stat ); + aCacheDir = tAttr.create("cacheDir", "cachD", MFnStringData::kString); + tAttr.setReadable(true); + tAttr.setWritable(true); + tAttr.setKeyable(true); + tAttr.setConnectable(true); + tAttr.setStorable(true); + + aCacheFile = tAttr.create("cachePrefix", "cachP", MFnStringData::kString); + tAttr.setReadable(true); + tAttr.setWritable(true); + tAttr.setKeyable(true); + tAttr.setConnectable(true); + tAttr.setStorable(true); + + aCacheOffset = nAttr.create("cacheOffset", "coff", MFnNumericData::kInt, 0, &stat); nAttr.setKeyable(true); aCacheStatic = nAttr.create("staticCache", "statC", MFnNumericData::kBoolean, false, &stat); @@ -249,51 +326,49 @@ MStatus partioVisualizer::initialize() aCacheActive = nAttr.create("cacheActive", "cAct", MFnNumericData::kBoolean, 1, &stat); nAttr.setKeyable(true); - - aCacheFormat = eAttr.create( "cacheFormat", "cachFmt"); - std::map formatExtMap; - partio4Maya::buildSupportedExtensionList(formatExtMap,false); - for (unsigned short i = 0; i< formatExtMap.size(); i++) - { - eAttr.addField(formatExtMap[i].toUpperCase(), i); - } + aCacheFormat = eAttr.create("cacheFormat", "cachFmt"); + std::map formatExtMap; + partio4Maya::buildSupportedExtensionList(formatExtMap, false); + for (unsigned short i = 0; i < formatExtMap.size(); i++) + eAttr.addField(formatExtMap[i].toUpperCase(), i); eAttr.setDefault(4); // PDC eAttr.setChannelBox(true); - aDrawStyle = eAttr.create( "drawStyle", "drwStyl"); - eAttr.addField("points", 0); - eAttr.addField("radius", 1); - eAttr.addField("disk", 2); - eAttr.addField("boundingBox", 3); + aDrawStyle = eAttr.create("drawStyle", "drwStyl"); + eAttr.addField("points", PARTIO_DRAW_STYLE_POINTS); + eAttr.addField("radius", PARTIO_DRAW_STYLE_RADIUS); + eAttr.addField("disk", PARTIO_DRAW_STYLE_DISK); + eAttr.addField("boundingBox", PARTIO_DRAW_STYLE_BOUNDING_BOX); //eAttr.addField("sphere", 4); //eAttr.addField("velocity", 5); eAttr.setDefault(0); eAttr.setChannelBox(true); - aUseTransform = nAttr.create("useTransform", "utxfm", MFnNumericData::kBoolean, false, &stat); nAttr.setKeyable(true); - aPartioAttributes = tAttr.create ("partioCacheAttributes", "pioCAts", MFnStringData::kString); + aPartioAttributes = tAttr.create("partioCacheAttributes", "pioCAts", MFnStringData::kString); tAttr.setArray(true); - tAttr.setUsesArrayDataBuilder( true ); + tAttr.setUsesArrayDataBuilder(true); + + aVelocityFrom = tAttr.create("velocityFrom", "vfrm", MFnStringData::kString); + nAttr.setKeyable(true); - aColorFrom = nAttr.create("colorFrom", "cfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aAccelerationFrom = tAttr.create("accelerationFrom", "afrm", MFnStringData::kString); nAttr.setKeyable(true); - aAlphaFrom = nAttr.create("opacityFrom", "ofrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aColorFrom = tAttr.create("colorFrom", "cfrm", MFnStringData::kString); nAttr.setKeyable(true); - - aIncandFrom= nAttr.create("incandescenceFrom", "ifrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + + aAlphaFrom = tAttr.create("opacityFrom", "ofrm", MFnStringData::kString); nAttr.setKeyable(true); - aRadiusFrom = nAttr.create("radiusFrom", "rfrm", MFnNumericData::kInt, -1, &stat); - nAttr.setDefault(-1); + aIncandFrom = tAttr.create("incandescenceFrom", "ifrm", MFnStringData::kString); + nAttr.setKeyable(true); + + aRadiusFrom = tAttr.create("radiusFrom", "rfrm", MFnStringData::kString); nAttr.setKeyable(true); aPointSize = nAttr.create("pointSize", "ptsz", MFnNumericData::kInt, 2, &stat); @@ -310,7 +385,7 @@ MStatus partioVisualizer::initialize() nAttr.setMax(1.0); nAttr.setKeyable(true); - aInvertAlpha= nAttr.create("invertAlpha", "ialph", MFnNumericData::kBoolean, false, &stat); + aInvertAlpha = nAttr.create("invertAlpha", "ialph", MFnNumericData::kBoolean, false, &stat); nAttr.setDefault(false); nAttr.setKeyable(true); @@ -326,65 +401,64 @@ MStatus partioVisualizer::initialize() aUpdateCache = nAttr.create("updateCache", "upc", MFnNumericData::kInt, 0); nAttr.setHidden(true); - aRenderCachePath = tAttr.create ( "renderCachePath", "rcp", MFnStringData::kString ); + aRenderCachePath = tAttr.create("renderCachePath", "rcp", MFnStringData::kString); nAttr.setHidden(true); - - addAttribute ( aUpdateCache ); - addAttribute ( aSize ); - addAttribute ( aFlipYZ ); - addAttribute ( aDrawSkip ); - addAttribute ( aCacheDir ); - addAttribute ( aCacheFile ); - addAttribute ( aCacheOffset ); - addAttribute ( aCacheStatic ); - addAttribute ( aCacheActive ); - addAttribute ( aCacheFormat ); - addAttribute ( aPartioAttributes ); - addAttribute ( aColorFrom ); - addAttribute ( aIncandFrom ); - addAttribute ( aAlphaFrom ); - addAttribute ( aRadiusFrom ); - addAttribute ( aPointSize ); - addAttribute ( aDefaultPointColor ); - addAttribute ( aDefaultAlpha ); - addAttribute ( aInvertAlpha ); - addAttribute ( aDefaultRadius ); - addAttribute ( aDrawStyle ); - addAttribute ( aForceReload ); - addAttribute ( aRenderCachePath ); - addAttribute ( aByFrame ); - addAttribute ( time ); - - attributeAffects ( aCacheActive, aUpdateCache); - attributeAffects ( aCacheDir, aUpdateCache ); - attributeAffects ( aSize, aUpdateCache ); - attributeAffects ( aFlipYZ, aUpdateCache ); - attributeAffects ( aCacheFile, aUpdateCache ); - attributeAffects ( aCacheOffset, aUpdateCache ); - attributeAffects ( aCacheStatic, aUpdateCache ); - attributeAffects ( aCacheFormat, aUpdateCache ); - attributeAffects ( aColorFrom, aUpdateCache ); - attributeAffects ( aIncandFrom, aUpdateCache ); - attributeAffects ( aAlphaFrom, aUpdateCache ); - attributeAffects ( aRadiusFrom, aUpdateCache ); - attributeAffects ( aPointSize, aUpdateCache ); - attributeAffects ( aDefaultPointColor, aUpdateCache ); - attributeAffects ( aDefaultAlpha, aUpdateCache ); - attributeAffects ( aInvertAlpha, aUpdateCache ); - attributeAffects ( aDefaultRadius, aUpdateCache ); - attributeAffects ( aDrawStyle, aUpdateCache ); - attributeAffects ( aForceReload, aUpdateCache ); - attributeAffects ( aByFrame, aUpdateCache ); - attributeAffects ( aByFrame, aRenderCachePath ); - attributeAffects (time, aUpdateCache); - attributeAffects (time,aRenderCachePath); - + addAttribute(aUpdateCache); + addAttribute(aSize); + addAttribute(aFlipYZ); + addAttribute(aDrawSkip); + addAttribute(aCacheDir); + addAttribute(aCacheFile); + addAttribute(aCacheOffset); + addAttribute(aCacheStatic); + addAttribute(aCacheActive); + addAttribute(aCacheFormat); + addAttribute(aPartioAttributes); + addAttribute(aVelocityFrom); + addAttribute(aAccelerationFrom); + addAttribute(aColorFrom); + addAttribute(aIncandFrom); + addAttribute(aAlphaFrom); + addAttribute(aRadiusFrom); + addAttribute(aPointSize); + addAttribute(aDefaultPointColor); + addAttribute(aDefaultAlpha); + addAttribute(aInvertAlpha); + addAttribute(aDefaultRadius); + addAttribute(aDrawStyle); + addAttribute(aForceReload); + addAttribute(aRenderCachePath); + addAttribute(aByFrame); + addAttribute(time); + + attributeAffects(aCacheActive, aUpdateCache); + attributeAffects(aCacheDir, aUpdateCache); + attributeAffects(aSize, aUpdateCache); + attributeAffects(aFlipYZ, aUpdateCache); + attributeAffects(aCacheFile, aUpdateCache); + attributeAffects(aCacheOffset, aUpdateCache); + attributeAffects(aCacheStatic, aUpdateCache); + attributeAffects(aCacheFormat, aUpdateCache); + attributeAffects(aColorFrom, aUpdateCache); + attributeAffects(aIncandFrom, aUpdateCache); + attributeAffects(aAlphaFrom, aUpdateCache); + attributeAffects(aRadiusFrom, aUpdateCache); + attributeAffects(aPointSize, aUpdateCache); + attributeAffects(aDefaultPointColor, aUpdateCache); + attributeAffects(aDefaultAlpha, aUpdateCache); + attributeAffects(aInvertAlpha, aUpdateCache); + attributeAffects(aDefaultRadius, aUpdateCache); + attributeAffects(aDrawStyle, aUpdateCache); + attributeAffects(aForceReload, aUpdateCache); + attributeAffects(aByFrame, aUpdateCache); + attributeAffects(aByFrame, aRenderCachePath); + attributeAffects(time, aUpdateCache); + attributeAffects(time, aRenderCachePath); return MS::kSuccess; } - partioVizReaderCache* partioVisualizer::updateParticleCache() { GetPlugData(); // force update to run compute function where we want to do all the work @@ -392,81 +466,68 @@ partioVizReaderCache* partioVisualizer::updateParticleCache() } // COMPUTE FUNCTION - -MStatus partioVisualizer::compute( const MPlug& plug, MDataBlock& block ) +MStatus partioVisualizer::compute(const MPlug& plug, MDataBlock& block) { - - int colorFromIndex = block.inputValue( aColorFrom ).asInt(); - int incandFromIndex = block.inputValue( aIncandFrom ).asInt(); - int opacityFromIndex= block.inputValue( aAlphaFrom ).asInt(); - int radiusFromIndex = block.inputValue( aRadiusFrom ).asInt(); - bool cacheActive = block.inputValue(aCacheActive).asBool(); - - // Determine if we are requesting the output plug for this node. // - if (plug != aUpdateCache) - { - return ( MS::kUnknownParameter ); - } - - else + if (plug == aUpdateCache) { - MStatus stat; + MString colorFromIndex = block.inputValue(aColorFrom).asString(); + MString incandFromIndex = block.inputValue(aIncandFrom).asString(); + MString opacityFromIndex = block.inputValue(aAlphaFrom).asString(); + MString radiusFromIndex = block.inputValue(aRadiusFrom).asString(); + bool cacheActive = block.inputValue(aCacheActive).asBool(); - MString cacheDir = block.inputValue(aCacheDir).asString(); + MString cacheDir = block.inputValue(aCacheDir).asString(); MString cacheFile = block.inputValue(aCacheFile).asString(); drawError = 0; - if (cacheDir == "" || cacheFile == "" ) + if (cacheDir == "" || cacheFile == "") { drawError = 1; // too much printing rather force draw of icon to red or something //MGlobal::displayError("PartioVisualizer->Error: Please specify cache file!"); - return ( MS::kFailure ); + return (MS::kFailure); } - bool cacheStatic = block.inputValue( aCacheStatic ).asBool(); - int cacheOffset = block.inputValue( aCacheOffset ).asInt(); - short cacheFormat = block.inputValue( aCacheFormat ).asShort(); - MFloatVector defaultColor = block.inputValue( aDefaultPointColor ).asFloatVector(); - float defaultAlpha = block.inputValue( aDefaultAlpha ).asFloat(); - bool invertAlpha = block.inputValue( aInvertAlpha ).asBool(); - float defaultRadius = block.inputValue( aDefaultRadius).asFloat(); - bool forceReload = block.inputValue( aForceReload ).asBool(); - int integerTime = block.inputValue(time).asInt(); - int byFrame = block.inputValue( aByFrame ).asInt(); - bool flipYZ = block.inputValue( aFlipYZ ).asBool(); - MString renderCachePath = block.inputValue( aRenderCachePath ).asString(); - + const bool cacheStatic = block.inputValue(aCacheStatic).asBool(); + const int cacheOffset = block.inputValue(aCacheOffset).asInt(); + const short cacheFormat = block.inputValue(aCacheFormat).asShort(); + const MFloatVector defaultColor = block.inputValue(aDefaultPointColor).asFloatVector(); + const float defaultAlpha = block.inputValue(aDefaultAlpha).asFloat(); + const bool invertAlpha = block.inputValue(aInvertAlpha).asBool(); + const float defaultRadius = block.inputValue(aDefaultRadius).asFloat(); + const int integerTime = block.inputValue(time).asInt(); + const int byFrame = block.inputValue(aByFrame).asInt(); + const bool flipYZ = block.inputValue(aFlipYZ).asBool(); + const MString renderCachePath = block.inputValue(aRenderCachePath).asString(); + + bool forceReload = block.inputValue(aForceReload).asBool(); MString formatExt = ""; int cachePadding = 0; MString newCacheFile = ""; MString renderCacheFile = ""; - partio4Maya::updateFileName( cacheFile, cacheDir, - cacheStatic, cacheOffset, - cacheFormat, integerTime, byFrame, - cachePadding, formatExt, - newCacheFile, renderCacheFile - ); + partio4Maya::updateFileName(cacheFile, cacheDir, + cacheStatic, cacheOffset, + cacheFormat, integerTime, byFrame, + cachePadding, formatExt, + newCacheFile, renderCacheFile); - if (renderCachePath != renderCacheFile || forceReload ) - { + if (renderCachePath != renderCacheFile || forceReload) block.outputValue(aRenderCachePath).setString(renderCacheFile); - } cacheChanged = false; ////////////////////////////////////////////// /// Cache can change manually by changing one of the parts of the cache input... if (mLastExt != formatExt || - mLastPath != cacheDir || - mLastFile != cacheFile || - mLastFlipStatus != flipYZ || - mLastStatic != cacheStatic || - forceReload ) + mLastPath != cacheDir || + mLastFile != cacheFile || + mLastFlipStatus != flipYZ || + mLastStatic != cacheStatic || + forceReload) { cacheChanged = true; mFlipped = false; @@ -480,72 +541,36 @@ MStatus partioVisualizer::compute( const MPlug& plug, MDataBlock& block ) ////////////////////////////////////////////// /// or it can change from a time input change - - if (!partio4Maya::partioCacheExists(newCacheFile.asChar())) { - if (pvCache.particles != NULL) - { - ParticlesDataMutable* newParticles; - newParticles = pvCache.particles; - pvCache.particles=NULL; // resets the particles - - if (newParticles != NULL) - { - //cout << "releasing" << endl; - newParticles->release(); - } - } - pvCache.bbox.clear(); - mLastFileLoaded = ""; - drawError = 1; + pvCache.clear(); + mLastFileLoaded = ""; + drawError = 1; } // after updating all the file path stuff, exit here if we don't want to actually load any new data - if (!cacheActive) - { - forceReload = true; - if (pvCache.particles != NULL) - { - ParticlesDataMutable* newParticles; - newParticles = pvCache.particles; - pvCache.particles=NULL; // resets the pointer - - if (newParticles != NULL) - { - newParticles->release(); - } - } - pvCache.bbox.clear(); - mLastFileLoaded = ""; - drawError = 2; - return ( MS::kSuccess ); - } - - if ( newCacheFile != "" && - partio4Maya::partioCacheExists(newCacheFile.asChar()) && - (newCacheFile != mLastFileLoaded || forceReload) - ) + if (!cacheActive) + { + forceReload = true; + pvCache.clear(); + mLastFileLoaded = ""; + drawError = 2; + return (MS::kSuccess); + } + + if (newCacheFile != "" && + partio4Maya::partioCacheExists(newCacheFile.asChar()) && + (newCacheFile != mLastFileLoaded || forceReload) + ) { cacheChanged = true; mFlipped = false; MGlobal::displayWarning(MString("PartioVisualizer->Loading: " + newCacheFile)); - if(pvCache.particles != NULL) - { - ///////////////////////////////////////////// - /// This seems to work to solve the mem leak - ParticlesDataMutable* newParticles; - newParticles = pvCache.particles; - pvCache.particles=NULL; // resets the pointer - - if (newParticles != NULL) - { - newParticles->release(); // frees the mem - } - } - pvCache.particles = read(newCacheFile.asChar()); - /////////////////////////////////////// + pvCache.clear(); + + pvCache.particles = PARTIO::read(newCacheFile.asChar()); + /////////////////////////////////////// mLastFileLoaded = newCacheFile; if (pvCache.particles->numParticles() == 0) @@ -554,310 +579,251 @@ MStatus partioVisualizer::compute( const MPlug& plug, MDataBlock& block ) } char partCount[50]; - sprintf (partCount, "%d", pvCache.particles->numParticles()); - MGlobal::displayInfo(MString ("PartioVisualizer-> LOADED: ") + partCount + MString (" particles")); - + sprintf(partCount, "%d", pvCache.particles->numParticles()); + MGlobal::displayInfo(MString("PartioVisualizer-> LOADED: ") + partCount + MString(" particles")); - float * floatToRGB = (float *) realloc(pvCache.rgb, pvCache.particles->numParticles()*sizeof(float)*3); - if (floatToRGB != NULL) + try { - pvCache.rgb = floatToRGB; + pvCache.rgba.resize(pvCache.particles->numParticles() * 4ul); + pvCache.radius.resize(pvCache.particles->numParticles()); } - else + catch (...) { - free(pvCache.rgb); MGlobal::displayError("PartioVisualizer->unable to allocate new memory for particles"); return (MS::kFailure); } - float * newRGBA = (float *) realloc(pvCache.rgba,pvCache.particles->numParticles()*sizeof(float)*4); - if (newRGBA != NULL) - { - pvCache.rgba = newRGBA; - } - else - { - free(pvCache.rgba); - MGlobal::displayError("PartioVisualizer->unable to allocate new memory for particles"); - return (MS::kFailure); - } - - pvCache.radius.clear(); - pvCache.radius.setLength(pvCache.particles->numParticles()); - pvCache.bbox.clear(); - if (!pvCache.particles->attributeInfo("position",pvCache.positionAttr) && - !pvCache.particles->attributeInfo("Position",pvCache.positionAttr)) + if (!pvCache.particles->attributeInfo("position", pvCache.positionAttr) && + !pvCache.particles->attributeInfo("Position", pvCache.positionAttr)) { + pvCache.positionAttr.attributeIndex = -1; MGlobal::displayError("PartioVisualizer->Failed to find position attribute "); - return ( MS::kFailure ); + return (MS::kFailure); } else { /// TODO: possibly move this down to take into account the radius as well for a true bounding volume // resize the bounding box - for (int i=0;inumParticles();i++) + for (int i = 0; i < pvCache.particles->numParticles(); ++i) { - const float * partioPositions = pvCache.particles->data(pvCache.positionAttr,i); - MPoint pos (partioPositions[0], partioPositions[1], partioPositions[2]); + const float* partioPositions = pvCache.particles->data(pvCache.positionAttr, i); + MPoint pos(partioPositions[0], partioPositions[1], partioPositions[2]); pvCache.bbox.expand(pos); } } block.outputValue(aForceReload).setBool(false); block.setClean(aForceReload); - } if (pvCache.particles) { // something changed.. - if (cacheChanged || mLastColorFromIndex != colorFromIndex || mLastColor != defaultColor) + if (cacheChanged || mLastColorFromIndex != colorFromIndex || mLastColor != defaultColor) { - int numAttrs = pvCache.particles->numAttributes(); - if (colorFromIndex+1 > numAttrs || opacityFromIndex+1 > numAttrs || radiusFromIndex+1 > numAttrs || incandFromIndex+1 > numAttrs) - { - // reset the attrs - block.outputValue(aColorFrom).setInt(-1); - block.setClean(aColorFrom); - block.outputValue(aAlphaFrom).setInt(-1); - block.setClean(aAlphaFrom); - block.outputValue(aRadiusFrom).setInt(-1); - block.setClean(aRadiusFrom); - block.outputValue(aIncandFrom).setInt(-1); - block.setClean(aIncandFrom); - - colorFromIndex = block.inputValue( aColorFrom ).asInt(); - opacityFromIndex= block.inputValue( aAlphaFrom ).asInt(); - radiusFromIndex = block.inputValue( aRadiusFrom ).asInt(); - incandFromIndex = block.inputValue( aIncandFrom ).asInt(); - } - - if (colorFromIndex >=0) + if (pvCache.particles->attributeInfo(colorFromIndex.asChar(), pvCache.colorAttr)) { - pvCache.particles->attributeInfo(colorFromIndex,pvCache.colorAttr); - // VECTOR or 4+ element float attrs - if (pvCache.colorAttr.type == VECTOR || pvCache.colorAttr.count > 3) // assuming first 3 elements are rgb + // VECTOR or 3+ element float attrs + if (pvCache.colorAttr.type != PARTIO::INT && + pvCache.colorAttr.count > 2) // assuming first 3 elements are rgb { - for (int i=0;inumParticles();i++) + for (int i = 0; i < pvCache.particles->numParticles(); ++i) { - const float * attrVal = pvCache.particles->data(pvCache.colorAttr,i); - pvCache.rgb[(i*3)] = attrVal[0]; - pvCache.rgb[((i*3)+1)] = attrVal[1]; - pvCache.rgb[((i*3)+2)] = attrVal[2]; - pvCache.rgba[i*4] = attrVal[0]; - pvCache.rgba[(i*4)+1] = attrVal[1]; - pvCache.rgba[(i*4)+2] = attrVal[2]; + const float* attrVal = pvCache.particles->data(pvCache.colorAttr, i); + pvCache.rgba[i * 4] = attrVal[0]; + pvCache.rgba[i * 4 + 1] = attrVal[1]; + pvCache.rgba[i * 4 + 2] = attrVal[2]; } } else // single FLOAT { - for (int i=0;inumParticles();i++) + for (int i = 0; i < pvCache.particles->numParticles(); ++i) { - const float * attrVal = pvCache.particles->data(pvCache.colorAttr,i); - - pvCache.rgb[(i*3)] = pvCache.rgb[((i*3)+1)] = pvCache.rgb[((i*3)+2)] = attrVal[0]; - pvCache.rgba[i*4] = pvCache.rgba[(i*4)+1] = pvCache.rgba[(i*4)+2] = attrVal[0]; + const float* attrVal = pvCache.particles->data(pvCache.colorAttr, i); + pvCache.rgba[i * 4] = pvCache.rgba[i * 4 + 1] = pvCache.rgba[i * 4 + 2] = attrVal[0]; } } } - else { - for (int i=0;inumParticles();i++) + pvCache.colorAttr.attributeIndex = -1; + for (int i = 0; i < pvCache.particles->numParticles(); ++i) { - pvCache.rgb[(i*3)] = defaultColor[0]; - pvCache.rgb[((i*3)+1)] = defaultColor[1]; - pvCache.rgb[((i*3)+2)] = defaultColor[2]; - pvCache.rgba[i*4] = defaultColor[0]; - pvCache.rgba[(i*4)+1] = defaultColor[1]; - pvCache.rgba[(i*4)+2] = defaultColor[2]; + pvCache.rgba[i * 4] = defaultColor[0]; + pvCache.rgba[i * 4 + 1] = defaultColor[1]; + pvCache.rgba[i * 4 + 2] = defaultColor[2]; } - } mLastColorFromIndex = colorFromIndex; mLastColor = defaultColor; } - if (cacheChanged || opacityFromIndex != mLastAlphaFromIndex || defaultAlpha != mLastAlpha || invertAlpha != mLastInvertAlpha) + if (cacheChanged || opacityFromIndex != mLastAlphaFromIndex || defaultAlpha != mLastAlpha || + invertAlpha != mLastInvertAlpha) { - if (opacityFromIndex >=0) + if (pvCache.particles->attributeInfo(opacityFromIndex.asChar(), pvCache.opacityAttr)) { - pvCache.particles->attributeInfo(opacityFromIndex,pvCache.opacityAttr); if (pvCache.opacityAttr.count == 1) // single float value for opacity { - for (int i=0;inumParticles();i++) + for (int i = 0; i < pvCache.particles->numParticles(); ++i) { - const float * attrVal = pvCache.particles->data(pvCache.opacityAttr,i); - float temp = attrVal[0]; - if (invertAlpha) - { - temp = float(1.0-temp); - - } - pvCache.rgba[(i*4)+3] = temp; + const float* attrVal = pvCache.particles->data(pvCache.opacityAttr, i); + pvCache.rgba[i * 4 + 3] = invertAlpha ? 1.0f - attrVal[0] : attrVal[0]; } } else { if (pvCache.opacityAttr.count == 4) // we have an RGBA 4 float attribute ? { - for (int i=0;inumParticles();i++) + for (int i = 0; i < pvCache.particles->numParticles(); ++i) { - const float * attrVal = pvCache.particles->data(pvCache.opacityAttr,i); - float temp = attrVal[3]; - if (invertAlpha) - { - temp = float(1.0-temp); - } - pvCache.rgba[(i*4)+3] = temp; + const float* attrVal = pvCache.particles->data(pvCache.opacityAttr, i); + pvCache.rgba[i * 4 + 3] = invertAlpha ? 1.0f - attrVal[3] : attrVal[3]; } } else { - for (int i=0;inumParticles();i++) + for (int i = 0; i < pvCache.particles->numParticles(); ++i) { - const float * attrVal = pvCache.particles->data(pvCache.opacityAttr,i); - float lum = float((attrVal[0]*0.2126)+(attrVal[1]*0.7152)+(attrVal[2]*.0722)); - if (invertAlpha) - { - lum = float(1.0-lum); - } - pvCache.rgba[(i*4)+3] = lum; + const float* attrVal = pvCache.particles->data(pvCache.opacityAttr, i); + const float lum = attrVal[0] * 0.2126f + attrVal[1] * 0.7152f + attrVal[2] * .0722f; + pvCache.rgba[i * 4 + 3] = invertAlpha ? 1.0f - lum : lum; } } } } else { - mLastAlpha = defaultAlpha; - if (invertAlpha) - { - mLastAlpha= 1-defaultAlpha; - } - for (int i=0;inumParticles();i++) - { - pvCache.rgba[(i*4)+3] = mLastAlpha; - } + pvCache.opacityAttr.attributeIndex = -1; + mLastAlpha = invertAlpha ? 1.0f - defaultAlpha : defaultAlpha; + for (int i = 0; i < pvCache.particles->numParticles(); ++i) + pvCache.rgba[i * 4 + 3] = mLastAlpha; } mLastAlpha = defaultAlpha; - mLastAlphaFromIndex =opacityFromIndex; + mLastAlphaFromIndex = opacityFromIndex; mLastInvertAlpha = invertAlpha; } - if (cacheChanged || radiusFromIndex != mLastRadiusFromIndex || defaultRadius != mLastRadius ) + if (cacheChanged || radiusFromIndex != mLastRadiusFromIndex || defaultRadius != mLastRadius) { - if (radiusFromIndex >=0) + if (pvCache.particles->attributeInfo(radiusFromIndex.asChar(), pvCache.radiusAttr)) { - pvCache.particles->attributeInfo(radiusFromIndex,pvCache.radiusAttr); if (pvCache.radiusAttr.count == 1) // single float value for radius { - for (int i=0;inumParticles();i++) + for (int i = 0; i < pvCache.particles->numParticles(); ++i) { - const float * attrVal = pvCache.particles->data(pvCache.radiusAttr,i); + const float* attrVal = pvCache.particles->data(pvCache.radiusAttr, i); pvCache.radius[i] = attrVal[0] * defaultRadius; } } else { - for (int i=0;inumParticles();i++) + for (int i = 0; i < pvCache.particles->numParticles(); ++i) { - const float * attrVal = pvCache.particles->data(pvCache.radiusAttr,i); - float lum = float((attrVal[0]*0.2126)+(attrVal[1]*0.7152)+(attrVal[2]*.0722)); - pvCache.radius[i] = lum * defaultRadius; + const float* attrVal = pvCache.particles->data(pvCache.radiusAttr, i); + float lum = attrVal[0] * 0.2126f + attrVal[1] * 0.7152f + attrVal[2] * .0722f; + pvCache.radius[i] = std::max(0.0f, lum * defaultRadius); } - } } else { mLastRadius = defaultRadius; - for (int i=0;inumParticles();i++) - { + for (int i = 0; i < pvCache.particles->numParticles(); ++i) pvCache.radius[i] = mLastRadius; - } } mLastRadius = defaultRadius; mLastRadiusFromIndex = radiusFromIndex; } - if (cacheChanged || incandFromIndex != mLastIncandFromIndex ) // incandescence does not affect viewport draw for now - { - mLastIncandFromIndex = incandFromIndex; - } - } - } - - if (pvCache.particles) // update the AE Controls for attrs in the cache - { - unsigned int numAttr=pvCache.particles->numAttributes(); - MPlug zPlug (thisMObject(), aPartioAttributes); - - if ((colorFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aColorFrom).setInt(-1); - } - if ((opacityFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aAlphaFrom).setInt(-1); - } - if ((radiusFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aRadiusFrom).setInt(-1); - } - if ((incandFromIndex+1) > (int)zPlug.numElements()) - { - block.outputValue(aIncandFrom).setInt(-1); + if (cacheChanged || + incandFromIndex != mLastIncandFromIndex) // incandescence does not affect viewport draw for now + mLastIncandFromIndex = incandFromIndex; } - if (cacheChanged || zPlug.numElements() != numAttr) // update the AE Controls for attrs in the cache + if (pvCache.particles) // update the AE Controls for attrs in the cache { - //cout << "partioVisualizer->refreshing AE controls" << endl; + const unsigned int numAttr = static_cast(pvCache.particles->numAttributes()); + MPlug zPlug(thisMObject(), aPartioAttributes); - attributeList.clear(); + // no need to reset attributes as not all attributes are guaranteed to be + // on all frames - for (unsigned int i=0;iattributeInfo(i,attr); - - // crazy casting string to char - char *temp; - temp = new char[(attr.name).length()+1]; - strcpy (temp, attr.name.c_str()); + attributeList.clear(); - MString mStringAttrName(""); - mStringAttrName += MString(temp); - - zPlug.selectAncestorLogicalIndex(i,aPartioAttributes); - zPlug.setValue(MString(temp)); - attributeList.append(mStringAttrName); - - delete [] temp; - } + for (unsigned int i = 0; i < numAttr; ++i) + { + PARTIO::ParticleAttribute attr; + pvCache.particles->attributeInfo(i, attr); - MArrayDataHandle hPartioAttrs = block.inputArrayValue(aPartioAttributes); - MArrayDataBuilder bPartioAttrs = hPartioAttrs.builder(); - // do we need to clean up some attributes from our array? - if (bPartioAttrs.elementCount() > numAttr) - { - unsigned int current = bPartioAttrs.elementCount(); - //unsigned int attrArraySize = current - 1; + const MString mstring_attr_name(attr.name.c_str()); + zPlug.selectAncestorLogicalIndex(i, aPartioAttributes); + zPlug.setValue(mstring_attr_name); + attributeList.append(mstring_attr_name); + } - // remove excess elements from the end of our attribute array - for (unsigned int x = numAttr; x < current; x++) + MArrayDataHandle hPartioAttrs = block.inputArrayValue(aPartioAttributes); + MArrayDataBuilder bPartioAttrs = hPartioAttrs.builder(); + // do we need to clean up some attributes from our array? + if (bPartioAttrs.elementCount() > numAttr) { - bPartioAttrs.removeElement(x); + unsigned int current = bPartioAttrs.elementCount(); + //unsigned int attrArraySize = current - 1; + + // remove excess elements from the end of our attribute array + for (unsigned int x = numAttr; x < current; x++) + { + bPartioAttrs.removeElement(x); + } } } } } + else if (plug == aRenderCachePath) + { + MString cacheDir = block.inputValue(aCacheDir).asString(); + MString cacheFile = block.inputValue(aCacheFile).asString(); + + if (cacheDir == "" || cacheFile == "") + return (MS::kFailure); + + const bool cacheStatic = block.inputValue(aCacheStatic).asBool(); + const int cacheOffset = block.inputValue(aCacheOffset).asInt(); + const short cacheFormat = block.inputValue(aCacheFormat).asShort(); + const MFloatVector defaultColor = block.inputValue(aDefaultPointColor).asFloatVector(); + const float defaultAlpha = block.inputValue(aDefaultAlpha).asFloat(); + const bool invertAlpha = block.inputValue(aInvertAlpha).asBool(); + const float defaultRadius = block.inputValue(aDefaultRadius).asFloat(); + const int integerTime = block.inputValue(time).asInt(); + const int byFrame = block.inputValue(aByFrame).asInt(); + const bool flipYZ = block.inputValue(aFlipYZ).asBool(); + + bool forceReload = block.inputValue(aForceReload).asBool(); + MString formatExt = ""; + int cachePadding = 0; + + MString newCacheFile = ""; + MString renderCacheFile = ""; + + partio4Maya::updateFileName(cacheFile, cacheDir, + cacheStatic, cacheOffset, + cacheFormat, integerTime, byFrame, + cachePadding, formatExt, + newCacheFile, renderCacheFile); + + block.outputValue(aRenderCachePath).setString(renderCacheFile); + } + else + return MS::kUnknownParameter; + block.setClean(plug); return MS::kSuccess; } - ///////////////////////////////////////////////////// /// procs to override bounding box mode... bool partioVisualizer::isBounded() const @@ -870,31 +836,25 @@ MBoundingBox partioVisualizer::boundingBox() const // Returns the bounding box for the shape. partioVisualizer* nonConstThis = const_cast(this); partioVizReaderCache* geom = nonConstThis->updateParticleCache(); -#ifdef min -#undef min -#endif -#ifdef max -#undef max -#endif MPoint corner1 = geom->bbox.min(); MPoint corner2 = geom->bbox.max(); - return MBoundingBox( corner1, corner2 ); + return MBoundingBox(corner1, corner2); } // // Select function. Gets called when the bbox for the object is selected. // This function just selects the object without doing any intersection tests. // -bool partioVisualizerUI::select( MSelectInfo &selectInfo, - MSelectionList &selectionList, - MPointArray &worldSpaceSelectPts ) const +bool partioVisualizerUI::select(MSelectInfo& selectInfo, + MSelectionList& selectionList, + MPointArray& worldSpaceSelectPts) const { - MSelectionMask priorityMask( MSelectionMask::kSelectObjectsMask ); + MSelectionMask priorityMask(MSelectionMask::kSelectObjectsMask); MSelectionList item; - item.add( selectInfo.selectPath() ); + item.add(selectInfo.selectPath()); MPoint xformedPt; - selectInfo.addSelection( item, xformedPt, selectionList, - worldSpaceSelectPts, priorityMask, false ); + selectInfo.addSelection(item, xformedPt, selectionList, + worldSpaceSelectPts, priorityMask, false); return true; } @@ -905,63 +865,48 @@ bool partioVisualizer::GetPlugData() { MObject thisNode = thisMObject(); int update = 0; - MPlug updatePlug(thisNode, aUpdateCache ); - updatePlug.getValue( update ); + MPlug(thisNode, aUpdateCache).getValue(update); if (update != dUpdate) { dUpdate = update; return true; } else - { return false; - } - return false; - } // note the "const" at the end, its different than other draw calls -void partioVisualizerUI::draw( const MDrawRequest& request, M3dView& view ) const +void partioVisualizerUI::draw(const MDrawRequest& request, M3dView& view) const { MDrawData data = request.drawData(); - partioVisualizer* shapeNode = (partioVisualizer*) surfaceShape(); - - partioVizReaderCache* cache = (partioVizReaderCache*) data.geometry(); + partioVisualizer* shapeNode = (partioVisualizer*)surfaceShape(); + partioVizReaderCache* cache = (partioVizReaderCache*)data.geometry(); MObject thisNode = shapeNode->thisMObject(); - MPlug sizePlug( thisNode, shapeNode->aSize ); + MPlug sizePlug(thisNode, shapeNode->aSize); MDistance sizeVal; - sizePlug.getValue( sizeVal ); + sizePlug.getValue(sizeVal); - shapeNode->multiplier= (float) sizeVal.asCentimeters(); + shapeNode->multiplier = (float)sizeVal.asCentimeters(); int drawStyle = 0; - MPlug drawStylePlug( thisNode, shapeNode->aDrawStyle ); - drawStylePlug.getValue( drawStyle ); + MPlug drawStylePlug(thisNode, shapeNode->aDrawStyle); + drawStylePlug.getValue(drawStyle); view.beginGL(); - if (drawStyle == 3 || view.displayStyle() == M3dView::kBoundingBox ) - { + if (drawStyle == PARTIO_DRAW_STYLE_BOUNDING_BOX || view.displayStyle() == M3dView::kBoundingBox) drawBoundingBox(); - } else - { - drawPartio(cache,drawStyle); - } - - if (shapeNode->drawError == 1) - { - glColor3f(.75f,0.0f,0.0f); - } - else if (shapeNode->drawError == 2) - { - glColor3f(0.0f,0.0f,0.0f); - } + drawPartio(cache, drawStyle); - partio4Maya::drawPartioLogo(shapeNode->multiplier); + if (shapeNode->drawError == 1) + glColor3f(.75f, 0.0f, 0.0f); + else if (shapeNode->drawError == 2) + glColor3f(0.0f, 0.0f, 0.0f); + partio4Maya::drawPartioLogo(shapeNode->multiplier); view.endGL(); } @@ -969,202 +914,144 @@ void partioVisualizerUI::draw( const MDrawRequest& request, M3dView& view ) cons /// DRAW Bounding box void partioVisualizerUI::drawBoundingBox() const { + partioVisualizer* shapeNode = reinterpret_cast(surfaceShape()); - partioVisualizer* shapeNode = (partioVisualizer*) surfaceShape(); + const MPoint bboxMin = shapeNode->pvCache.bbox.min(); + const MPoint bboxMax = shapeNode->pvCache.bbox.max(); - MPoint bboxMin = shapeNode->pvCache.bbox.min(); - MPoint bboxMax = shapeNode->pvCache.bbox.max(); - - float xMin = float(bboxMin.x); - float yMin = float(bboxMin.y); - float zMin = float(bboxMin.z); - float xMax = float(bboxMax.x); - float yMax = float(bboxMax.y); - float zMax = float(bboxMax.z); + const float xMin = float(bboxMin.x); + const float yMin = float(bboxMin.y); + const float zMin = float(bboxMin.z); + const float xMax = float(bboxMax.x); + const float yMax = float(bboxMax.y); + const float zMax = float(bboxMax.z); /// draw the bounding box - glBegin (GL_LINES); - - glColor3f(1.0f,0.5f,0.5f); + glBegin(GL_LINES); - glVertex3f (xMin,yMin,zMax); - glVertex3f (xMax,yMin,zMax); + glColor3f(1.0f, 0.5f, 0.5f); - glVertex3f (xMin,yMin,zMin); - glVertex3f (xMax,yMin,zMin); + glVertex3f(xMin, yMin, zMax); + glVertex3f(xMax, yMin, zMax); - glVertex3f (xMin,yMin,zMax); - glVertex3f (xMin,yMin,zMin); + glVertex3f(xMin, yMin, zMin); + glVertex3f(xMax, yMin, zMin); - glVertex3f (xMax,yMin,zMax); - glVertex3f (xMax,yMin,zMin); + glVertex3f(xMin, yMin, zMax); + glVertex3f(xMin, yMin, zMin); - glVertex3f (xMin,yMax,zMin); - glVertex3f (xMin,yMax,zMax); + glVertex3f(xMax, yMin, zMax); + glVertex3f(xMax, yMin, zMin); - glVertex3f (xMax,yMax,zMax); - glVertex3f (xMax,yMax,zMin); + glVertex3f(xMin, yMax, zMin); + glVertex3f(xMin, yMax, zMax); - glVertex3f (xMin,yMax,zMax); - glVertex3f (xMax,yMax,zMax); + glVertex3f(xMax, yMax, zMax); + glVertex3f(xMax, yMax, zMin); - glVertex3f (xMin,yMax,zMin); - glVertex3f (xMax,yMax,zMin); + glVertex3f(xMin, yMax, zMax); + glVertex3f(xMax, yMax, zMax); + glVertex3f(xMin, yMax, zMin); + glVertex3f(xMax, yMax, zMin); - glVertex3f (xMin,yMax,zMin); - glVertex3f (xMin,yMin,zMin); + glVertex3f(xMin, yMax, zMin); + glVertex3f(xMin, yMin, zMin); - glVertex3f (xMax,yMax,zMin); - glVertex3f (xMax,yMin,zMin); + glVertex3f(xMax, yMax, zMin); + glVertex3f(xMax, yMin, zMin); - glVertex3f (xMin,yMax,zMax); - glVertex3f (xMin,yMin,zMax); + glVertex3f(xMin, yMax, zMax); + glVertex3f(xMin, yMin, zMax); - glVertex3f (xMax,yMax,zMax); - glVertex3f (xMax,yMin,zMax); + glVertex3f(xMax, yMax, zMax); + glVertex3f(xMax, yMin, zMax); glEnd(); - } - //////////////////////////////////////////// /// DRAW PARTIO - void partioVisualizerUI::drawPartio(partioVizReaderCache* pvCache, int drawStyle) const { - partioVisualizer* shapeNode = (partioVisualizer*) surfaceShape(); + if (pvCache->particles == 0 || pvCache->positionAttr.attributeIndex == -1) + return; + partioVisualizer* shapeNode = (partioVisualizer*)surfaceShape(); MObject thisNode = shapeNode->thisMObject(); - MPlug drawSkipPlug( thisNode, shapeNode->aDrawSkip ); - int drawSkipVal; - drawSkipPlug.getValue( drawSkipVal ); - - MPlug flipYZPlug( thisNode, shapeNode->aFlipYZ ); - bool flipYZVal; - flipYZPlug.getValue( flipYZVal ); - - int stride = 3*sizeof(float)*(drawSkipVal); - - MPlug pointSizePlug( thisNode, shapeNode->aPointSize ); - float pointSizeVal; - pointSizePlug.getValue( pointSizeVal ); + const int drawSkipVal = MPlug(thisNode, shapeNode->aDrawSkip).asInt(); - MPlug colorFromPlug( thisNode, shapeNode->aColorFrom); - int colorFromVal; - colorFromPlug.getValue( colorFromVal ); + const int stride_position = 3 * (int)sizeof(float) * (drawSkipVal); + const int stride_color = 4 * (int)sizeof(float) * (drawSkipVal); - MPlug alphaFromPlug( thisNode, shapeNode->aAlphaFrom); - int alphaFromVal; - alphaFromPlug.getValue( alphaFromVal ); + const float pointSizeVal = MPlug(thisNode, shapeNode->aPointSize).asFloat(); + const float defaultAlphaVal = MPlug(thisNode, shapeNode->aDefaultAlpha).asFloat(); - MPlug defaultAlphaPlug( thisNode, shapeNode->aDefaultAlpha); - float defaultAlphaVal; - defaultAlphaPlug.getValue( defaultAlphaVal ); + // these three are not used + // const int colorFromVal = MPlug(thisNode, shapeNode->aColorFrom).asInt(); + // const int incandFromVal = MPlug(thisNode, shapeNode->aIncandFrom).asInt(); + // const bool flipYZVal = MPlug(thisNode, shapeNode->aFlipYZ).asBool(); - MPlug incandFromPlug( thisNode, shapeNode->aIncandFrom); - int incandFromVal; - incandFromPlug.getValue( incandFromVal ); - - if (pvCache->particles) + const bool use_per_particle_alpha = pvCache->opacityAttr.attributeIndex != -1 || defaultAlphaVal < 1.0f; + // no need to disable anything, we are pushing ALL the bits + glPushAttrib(GL_ALL_ATTRIB_BITS); + if (use_per_particle_alpha) //testing settings { - glPushAttrib(GL_ALL_ATTRIB_BITS); - // Store the current blend types - GLint blendAttrs[2]; - glGetIntegerv(GL_BLEND_SRC, & blendAttrs[0]); - glGetIntegerv(GL_BLEND_DST, & blendAttrs[1]); - if (alphaFromVal >=0 || defaultAlphaVal < 1) //testing settings - { + // TESTING AROUND with depth/transparency sorting issues.. + glDepthMask(true); + glEnable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glEnable(GL_POINT_SMOOTH); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } - // TESTING AROUND with depth/transparency sorting issues.. - glDepthMask(true); - //cout << "depthMask"<< glGetError() << endl; - glEnable(GL_DEPTH_TEST); - //cout << "depth test" << glGetError() << endl; - glEnable(GL_BLEND); - //cout << "blend" << glGetError() << endl; -// glBlendEquation(GL_FUNC_ADD); - //cout << "blend eq" << glGetError() << endl; - glEnable(GL_POINT_SMOOTH); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - //cout << "blend func" << glGetError() << endl; - //glAlphaFunc(GL_GREATER, .01); - //glEnable(GL_ALPHA_TEST); - } + if (drawStyle == PARTIO_DRAW_STYLE_POINTS) + { + glDisable(GL_POINT_SMOOTH); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_COLOR_ARRAY); - if ( drawStyle == 0 ) + glPointSize(pointSizeVal); + if (pvCache->particles->numParticles() > 0) { - glDisable(GL_POINT_SMOOTH); - glEnableClientState( GL_VERTEX_ARRAY ); - glEnableClientState( GL_COLOR_ARRAY ); - - glPointSize(pointSizeVal); - if (pvCache->particles->numParticles() > 0) - { - // now setup the position/color/alpha output pointers - - const float * partioPositions = pvCache->particles->data(pvCache->positionAttr,0); - - glVertexPointer( 3, GL_FLOAT, stride, partioPositions ); - - - if (defaultAlphaVal < 1 || alphaFromVal >=0) // use transparency switch - { - glColorPointer( 4, GL_FLOAT, stride, pvCache->rgba ); - } - else - { - glColorPointer( 3, GL_FLOAT, stride, pvCache->rgb ); - } - glDrawArrays( GL_POINTS, 0, (pvCache->particles->numParticles()/(drawSkipVal+1)) ); - } - glDisableClientState( GL_VERTEX_ARRAY ); - glDisableClientState( GL_COLOR_ARRAY ); + // now setup the position/color/alpha output pointers + const float* partioPositions = pvCache->particles->data(pvCache->positionAttr, 0); + glVertexPointer(3, GL_FLOAT, stride_position, partioPositions); + glColorPointer(4, GL_FLOAT, stride_color, pvCache->rgba.data()); + glDrawArrays(GL_POINTS, 0, (pvCache->particles->numParticles() / (drawSkipVal + 1))); } - else - { - /// looping thru particles one by one... + glDisableClientState(GL_VERTEX_ARRAY); + glDisableClientState(GL_COLOR_ARRAY); // even though we are pushing and popping + // attribs disabling the color array is required or else it will freak out maya + // interestingly it's not needed for VP2... + } + else if (drawStyle == PARTIO_DRAW_STYLE_DISK || drawStyle == PARTIO_DRAW_STYLE_RADIUS) + { + // if this is accessed from multiple threads + // we already screwed because of OpenGL + static BillboardDrawData billboard_data(10); - glPointSize(pointSizeVal); + glEnableClientState(GL_VERTEX_ARRAY); + glVertexPointer(2, GL_FLOAT, 0, &billboard_data.vertices[0]); - for (int i=0;iparticles->numParticles();i+=(drawSkipVal+1)) - { - if (defaultAlphaVal < 1 || alphaFromVal >=0) // use transparency switch - { - glColor4f(pvCache->rgb[i*3],pvCache->rgb[(i*3)+1],pvCache->rgb[(i*3)+2], pvCache->rgba[(i*4)+3] ); - } - else - { - glColor3f(pvCache->rgb[i*3],pvCache->rgb[(i*3)+1],pvCache->rgb[(i*3)+2]); - } + for (int i = 0; i < pvCache->particles->numParticles(); i += (drawSkipVal + 1)) + { + glColor4fv(&pvCache->rgba[i * 4]); + const float* partioPositions = pvCache->particles->data(pvCache->positionAttr, i); + drawBillboardCircleAtPoint(partioPositions, pvCache->radius[i], drawStyle, billboard_data); + } - const float * partioPositions = pvCache->particles->data(pvCache->positionAttr,i); - if (drawStyle == 1 || drawStyle == 2) // unfilled circles, disks, or spheres - { - MVector position(partioPositions[0], partioPositions[1], partioPositions[2]); - float radius = pvCache->radius[i]; - drawBillboardCircleAtPoint(position, radius, 10, drawStyle); - } - else // points - { - glVertex3f(partioPositions[0], partioPositions[1], partioPositions[2]); - } - } - } - glDisable(GL_BLEND); - glDisable(GL_POINT_SMOOTH); - // Restore blend settings - glBlendFunc(blendAttrs[0], blendAttrs[1]); - glPopAttrib(); - } // if (particles) + glDisableClientState(GL_VERTEX_ARRAY); + } + glPopAttrib(); } partioVisualizerUI::partioVisualizerUI() { } + partioVisualizerUI::~partioVisualizerUI() { } @@ -1174,14 +1061,13 @@ void* partioVisualizerUI::creator() return new partioVisualizerUI(); } - -void partioVisualizerUI::getDrawRequests(const MDrawInfo & info, - bool /*objectAndActiveOnly*/, MDrawRequestQueue & queue) +void partioVisualizerUI::getDrawRequests(const MDrawInfo& info, + bool /*objectAndActiveOnly*/, MDrawRequestQueue& queue) { MDrawData data; MDrawRequest request = info.getPrototype(*this); - partioVisualizer* shapeNode = (partioVisualizer*) surfaceShape(); + partioVisualizer* shapeNode = (partioVisualizer*)surfaceShape(); partioVizReaderCache* geom = shapeNode->updateParticleCache(); getDrawData(geom, data); @@ -1196,92 +1082,24 @@ void partioVisualizerUI::getDrawRequests(const MDrawInfo & info, M3dView::ColorTable dormantColorTable = M3dView::kDormantColors; switch (displayStatus) { - case M3dView::kLead: - request.setColor(LEAD_COLOR, activeColorTable); - break; - case M3dView::kActive: - request.setColor(ACTIVE_COLOR, activeColorTable); - break; - case M3dView::kActiveAffected: - request.setColor(ACTIVE_AFFECTED_COLOR, activeColorTable); - break; - case M3dView::kDormant: - request.setColor(DORMANT_COLOR, dormantColorTable); - break; - case M3dView::kHilite: - request.setColor(HILITE_COLOR, activeColorTable); - break; - default: - break; + case M3dView::kLead: + request.setColor(LEAD_COLOR, activeColorTable); + break; + case M3dView::kActive: + request.setColor(ACTIVE_COLOR, activeColorTable); + break; + case M3dView::kActiveAffected: + request.setColor(ACTIVE_AFFECTED_COLOR, activeColorTable); + break; + case M3dView::kDormant: + request.setColor(DORMANT_COLOR, dormantColorTable); + break; + case M3dView::kHilite: + request.setColor(HILITE_COLOR, activeColorTable); + break; + default: + break; } - request.setIsTransparent( true ); + request.setIsTransparent(true); queue.add(request); - -} - -void partioVisualizerUI::drawBillboardCircleAtPoint(MVector position, float radius, int num_segments, int drawType) const -{ - float m[16]; - int j,k; - glPushMatrix(); - glTranslatef( (GLfloat) position.x, (GLfloat) position.y, (GLfloat) position.z); - glGetFloatv(GL_MODELVIEW_MATRIX, m); - - for (j = 0; j<3; j++) - { - for (k = 0; k<3; k++) - { - if (j==k) - { - m[j*4+k] = 1.0; - } - else - { - m[j*4+k] = 0.0; - } - } - } - glLoadMatrixf(m); - - float theta =(float)( 2 * 3.1415926 / float(num_segments) ); - float tangetial_factor = tanf(theta);//calculate the tangential factor - - float radial_factor = cosf(theta);//calculate the radial factor - - float x = radius;//we start at angle = 0 - float y = 0; - - if (drawType == 1) - { - glBegin(GL_LINE_LOOP); - } - else if (drawType == 2) - { - glBegin(GL_POLYGON); - } - for (int ii = 0; ii < num_segments; ii++) - { - glVertex2f(x, y);//output vertex - - //calculate the tangential vector - //remember, the radial vector is (x, y) - //to get the tangential vector we flip those coordinates and negate one of them - - float tx = -y; - float ty = x; - - //add the tangential vector - - x += tx * tangetial_factor; - y += ty * tangetial_factor; - - //correct using the radial factor - - x *= radial_factor; - y *= radial_factor; - } - glEnd(); - glTranslatef( (GLfloat)-position.x, (GLfloat)-position.y, (GLfloat)-position.z); - glPopMatrix(); } - diff --git a/contrib/partio4Maya/partioVisualizer.h b/contrib/partio4Maya/partioVisualizer.h index 7244a281..5c560cca 100644 --- a/contrib/partio4Maya/partioVisualizer.h +++ b/contrib/partio4Maya/partioVisualizer.h @@ -85,44 +85,46 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include "partio4MayaShared.h" -#include "iconArrays.h" + +enum { + PARTIO_DRAW_STYLE_POINTS = 0, + PARTIO_DRAW_STYLE_RADIUS, + PARTIO_DRAW_STYLE_DISK, + PARTIO_DRAW_STYLE_BOUNDING_BOX, + PARTIO_DRAW_STYLE_SPHERE, + PARTIO_DRAW_STYLE_VELOCITY +}; class partioVizReaderCache { public: partioVizReaderCache(); + void clear(); MBoundingBox bbox; - int dList; - Partio::ParticlesDataMutable* particles; - Partio::ParticleAttribute positionAttr; - Partio::ParticleAttribute colorAttr; - Partio::ParticleAttribute opacityAttr; - Partio::ParticleAttribute radiusAttr; - Partio::ParticleAttribute incandescenceAttr; - float* rgb; - float* rgba; - MFloatArray radius; - float* flipPos; - + PARTIO::ParticlesDataMutable* particles; + PARTIO::ParticleAttribute positionAttr; + PARTIO::ParticleAttribute colorAttr; + PARTIO::ParticleAttribute opacityAttr; + PARTIO::ParticleAttribute radiusAttr; + PARTIO::ParticleAttribute incandescenceAttr; + std::vector rgba; + std::vector radius; }; - class partioVisualizerUI : public MPxSurfaceShapeUI { public: partioVisualizerUI(); virtual ~partioVisualizerUI(); - virtual void draw(const MDrawRequest & request, M3dView & view) const; - virtual void getDrawRequests(const MDrawInfo & info, bool objectAndActiveOnly, MDrawRequestQueue & requests); - void drawBoundingBox() const; - void drawBillboardCircleAtPoint(MVector position, float radius, int num_segments, int drawType) const; - void drawPartio(partioVizReaderCache* pvCache, int drawStyle) const; - static void * creator(); - virtual bool select( MSelectInfo &selectInfo, - MSelectionList &selectionList, - MPointArray &worldSpaceSelectPts ) const; - + virtual void draw(const MDrawRequest& request, M3dView& view) const; + virtual void getDrawRequests(const MDrawInfo& info, bool objectAndActiveOnly, MDrawRequestQueue& requests); + void drawBoundingBox() const; + void drawPartio(partioVizReaderCache* pvCache, int drawStyle) const; + static void* creator(); + virtual bool select(MSelectInfo &selectInfo, + MSelectionList &selectionList, + MPointArray &worldSpaceSelectPts) const; }; class partioVisualizer : public MPxSurfaceShape @@ -147,69 +149,63 @@ class partioVisualizer : public MPxSurfaceShape MCallbackId partioVisualizerImportCallback; MCallbackId partioVisualizerReferenceCallback; - static MObject time; - static MObject aByFrame; - static MObject aSize; // The size of the logo - static MObject aDrawSkip; - static MObject aFlipYZ; - static MObject aUpdateCache; - static MObject aCacheDir; - static MObject aCacheFile; - static MObject aUseTransform; - static MObject aCacheActive; - static MObject aCacheOffset; - static MObject aCacheStatic; - static MObject aCacheFormat; - static MObject aJitterPos; - static MObject aJitterFreq; - static MObject aPartioAttributes; - static MObject aColorFrom; - static MObject aAlphaFrom; - static MObject aIncandFrom; - static MObject aRadiusFrom; - static MObject aPointSize; - static MObject aDefaultPointColor; - static MObject aDefaultAlpha; - static MObject aDefaultRadius; - static MObject aInvertAlpha; - static MObject aDrawStyle; - static MObject aForceReload; - static MObject aRenderCachePath; - + static MObject time; + static MObject aByFrame; + static MObject aSize; // The size of the logo + static MObject aDrawSkip; + static MObject aFlipYZ; + static MObject aUpdateCache; + static MObject aCacheDir; + static MObject aCacheFile; + static MObject aUseTransform; + static MObject aCacheActive; + static MObject aCacheOffset; + static MObject aCacheStatic; + static MObject aCacheFormat; + static MObject aJitterPos; + static MObject aJitterFreq; + static MObject aPartioAttributes; + static MObject aVelocityFrom; + static MObject aAccelerationFrom; + static MObject aColorFrom; + static MObject aAlphaFrom; + static MObject aIncandFrom; + static MObject aRadiusFrom; + static MObject aPointSize; + static MObject aDefaultPointColor; + static MObject aDefaultAlpha; + static MObject aDefaultRadius; + static MObject aInvertAlpha; + static MObject aDrawStyle; + static MObject aForceReload; + static MObject aRenderCachePath; static MTypeId id; float multiplier; bool cacheChanged; partioVizReaderCache pvCache; int drawError; - - + static MString drawDbClassification; private: - MString mLastFileLoaded; MString mLastPath; MString mLastFile; MString mLastExt; bool mLastStatic; - int mLastColorFromIndex; - int mLastAlphaFromIndex; - int mLastRadiusFromIndex; - int mLastIncandFromIndex; + MString mLastColorFromIndex; + MString mLastAlphaFromIndex; + MString mLastRadiusFromIndex; + MString mLastIncandFromIndex; MFloatVector mLastColor; float mLastAlpha; bool mLastInvertAlpha; float mLastRadius; bool mLastFlipStatus; bool mFlipped; - bool frameChanged; + bool mFrameChanged; MStringArray attributeList; - - protected: - int dUpdate; - GLuint dList; - }; #endif diff --git a/contrib/partio4Maya/partioVisualizerDrawOverride.cpp b/contrib/partio4Maya/partioVisualizerDrawOverride.cpp new file mode 100644 index 00000000..0d130288 --- /dev/null +++ b/contrib/partio4Maya/partioVisualizerDrawOverride.cpp @@ -0,0 +1,495 @@ +/* + * The idea here is to have an initial implementation, then incrementally start adding new functions. + * The initial one should use the same functions as in partioVisualizer (though cleaned up). + * Later on we can start using VBOs, and avoid re-uploading the data every frame. This approach + * is supported on all the configuration (if you don't have VBOs, you can't run VP2), and should + * be the fallback option for older GPUs and OSX. + * After the fallback option, we can start playing around with some proper instancing for the billboard display, + * OpenGL has a number of instancing pipelines, most likely the easiest approach + * (draw instanced, and transforming the vertices using the gl_instanceId and a mapped buffer of position and colors) + * will be enough to be efficient enough, and it will still require a fairly old OpenGL (around 3.1). GLEW can be used + * to check the GL version and find the function pointers. + * MultiDrawIndirect is most likely faster, but it might not worth the extra effort to implement. + * + * After some thinking, it's debatable if it's a good idea to use VBOs for displaying the points. + * Usually we work with rather large point sets, and they could use up a lots of memory for the + * point display. Around 28 bytes per particle, and it's fairly common to + * have tens or hundreds of millions of particles. + * + * - Pal + */ + +#include + +#include "partioVisualizerDrawOverride.h" + +#include +#include +#include +#include + +namespace { + const char* vertex_shader_code = "#version 110\n" \ + "uniform mat4 world_view;\n" \ + "uniform mat4 proj;\n" \ + "void main(void) { gl_Position = proj * world_view * gl_Vertex; gl_FrontColor = gl_Color; gl_BackColor = gl_Color; }\n"; + const char* pixel_shader_code = "#version 110\n" \ + "void main(void) { gl_FragColor = gl_Color; }\n"; + + GLuint INVALID_GL_OBJECT = static_cast(-1); + GLuint vertex_shader = INVALID_GL_OBJECT; + GLuint pixel_shader = INVALID_GL_OBJECT; + GLuint shader_program = INVALID_GL_OBJECT; + GLint world_view_location = INVALID_GL_OBJECT; + GLint proj_location = INVALID_GL_OBJECT; + + template + bool create_shader(GLuint& shader, const char* shader_code) + { + shader = glCreateShader(shader_type); + + GLint code_size = static_cast(strlen(shader_code)); + glShaderSource(shader, 1, &shader_code, &code_size); + glCompileShader(shader); + GLint success = 0; + glGetShaderiv(shader, GL_COMPILE_STATUS, &success); + if (success == GL_FALSE) + { + std::cout << "[partioVisualizer] Error building shader : " << std::endl; + std::cout << shader_code << std::endl; + GLint max_length = 0; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &max_length); + std::vector info_log(max_length); + glGetShaderInfoLog(shader, max_length, &max_length, &info_log[0]); + std::cout << &info_log[0] << std::endl; + glDeleteShader(shader); shader = INVALID_GL_OBJECT; + return false; + } + else + return true; + } + + // TODO: make partioVisualizer use the code from here + struct DrawData : public MUserData { + private: + MObject m_object; + partioVizReaderCache* p_reader_cache; + int m_draw_skip; + int m_draw_style; + float m_point_size; + float m_default_alpha; + float m_icon_size; + + struct BillboardDrawData { + std::vector vertices; + const size_t num_segments; + float last_radius; + + BillboardDrawData(size_t _num_segments) : num_segments(_num_segments), last_radius(-1.0f) + { + vertices.resize(num_segments * 2); + } + }; + + static void drawBillboardCircleAtPoint(const float* position, float radius, int drawType, BillboardDrawData& data, const MMatrix& world_view_matrix) + { + static MMatrix world_view_source = MMatrix::identity; + world_view_source[3][0] = position[0]; + world_view_source[3][1] = position[1]; + world_view_source[3][2] = position[2]; + static __thread float world_view[4][4]; + (world_view_source * world_view_matrix).get(world_view); + world_view[0][0] = 1.0f; + world_view[0][1] = 0.0f; + world_view[0][2] = 0.0f; + world_view[1][0] = 0.0f; + world_view[1][1] = 1.0f; + world_view[1][2] = 0.0f; + world_view[2][0] = 0.0f; + world_view[2][1] = 0.0f; + world_view[2][2] = 1.0f; + + MPoint world_view_pos = world_view_matrix * MPoint(position[0], position[1], position[2], 1.0); + + glUniformMatrix4fv(world_view_location, 1, false, &world_view[0][0]); + + // TODO: setup radius using the scale of the Matrix + if (radius != data.last_radius) + { + data.last_radius = radius; + + const float theta = 2.0f * 3.1415926f / float(data.num_segments); + const float tangetial_factor = tanf(theta);//calculate the tangential factor + const float radial_factor = cosf(theta);//calculate the radial factor + + float x = radius;//we start at angle = 0 + float y = 0; + + for (size_t i = 0, vid = 0; i < data.num_segments; ++i) + { + data.vertices[vid++] = x; + data.vertices[vid++] = y; + + const float tx = -y; + const float ty = x; + + //add the tangential vector + x += tx * tangetial_factor; + y += ty * tangetial_factor; + + //correct using the radial factor + x *= radial_factor; + y *= radial_factor; + } + } + + if (drawType == PARTIO_DRAW_STYLE_RADIUS) + glDrawArrays(GL_LINE_LOOP, 0, data.num_segments); + else + glDrawArrays(GL_POLYGON, 0, data.num_segments); + + glPopMatrix(); + } + + void draw_bounding_box() const + { + const MPoint bboxMin = p_reader_cache->bbox.min(); + const MPoint bboxMax = p_reader_cache->bbox.max(); + + const float xMin = static_cast(bboxMin.x); + const float yMin = static_cast(bboxMin.y); + const float zMin = static_cast(bboxMin.z); + const float xMax = static_cast(bboxMax.x); + const float yMax = static_cast(bboxMax.y); + const float zMax = static_cast(bboxMax.z); + + glColor4fv(m_wireframe_color); + /// draw the bounding box + glBegin(GL_LINES); + + glVertex3f(xMin, yMin, zMax); + glVertex3f(xMax, yMin, zMax); + + glVertex3f(xMin, yMin, zMin); + glVertex3f(xMax, yMin, zMin); + + glVertex3f(xMin, yMin, zMax); + glVertex3f(xMin, yMin, zMin); + + glVertex3f(xMax, yMin, zMax); + glVertex3f(xMax, yMin, zMin); + + glVertex3f(xMin, yMax, zMin); + glVertex3f(xMin, yMax, zMax); + + glVertex3f(xMax, yMax, zMax); + glVertex3f(xMax, yMax, zMin); + + glVertex3f(xMin, yMax, zMax); + glVertex3f(xMax, yMax, zMax); + + glVertex3f(xMin, yMax, zMin); + glVertex3f(xMax, yMax, zMin); + + glVertex3f(xMin, yMax, zMin); + glVertex3f(xMin, yMin, zMin); + + glVertex3f(xMax, yMax, zMin); + glVertex3f(xMax, yMin, zMin); + + glVertex3f(xMin, yMax, zMax); + glVertex3f(xMin, yMin, zMax); + + glVertex3f(xMax, yMax, zMax); + glVertex3f(xMax, yMin, zMax); + + glEnd(); + } + + void clear() + { + // this is empty so far, could be extended later on + } + public: + // attributes below are configured differently for VP1 and VP2 + MBoundingBox m_cache_bbox; + MBoundingBox m_logo_bbox; + float m_wireframe_color[4]; + int m_draw_error; + + DrawData() : MUserData(false), p_reader_cache(0) + { + + } + + // FIXME: mostly likely we don't need to update the m_object and p_reader_cache + // because these are constant values, so move these to the constructor + void update_data(const MObject& object, partioVizReaderCache* pv_cache) + { + clear(); + m_object = object; + p_reader_cache = pv_cache; + m_draw_skip = MPlug(m_object, partioVisualizer::aDrawSkip).asInt(); + m_draw_style = MPlug(m_object, partioVisualizer::aDrawStyle).asShort(); + m_point_size = MPlug(m_object, partioVisualizer::aPointSize).asFloat(); + m_default_alpha = MPlug(m_object, partioVisualizer::aDefaultAlpha).asFloat(); + m_icon_size = MPlug(m_object, partioVisualizer::aSize).asFloat(); + + if (p_reader_cache) + m_cache_bbox = p_reader_cache->bbox; + + static const MBoundingBox logo_bbox = partio4Maya::partioLogoBoundingBox(); + m_logo_bbox.clear(); + m_logo_bbox.expand(logo_bbox.min() * m_icon_size); + m_logo_bbox.expand(logo_bbox.max() * m_icon_size); + } + + void draw(bool as_bounding_box, const MMatrix& world_view_matrix) const + { + if (p_reader_cache == 0 || p_reader_cache->particles == 0 || p_reader_cache->positionAttr.attributeIndex == -1) + return; + + // check for viewport draw mode + if (m_draw_style == PARTIO_DRAW_STYLE_BOUNDING_BOX || as_bounding_box) + draw_bounding_box(); + else + { + if (p_reader_cache->opacityAttr.attributeIndex != -1 || m_default_alpha < 1.0f) + { + glDepthMask(true); + glEnable(GL_DEPTH_TEST); + glEnable(GL_BLEND); + glEnable(GL_POINT_SMOOTH); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + + if (m_draw_style == PARTIO_DRAW_STYLE_POINTS) + { + const int stride_position = 3 * static_cast(sizeof(float)) * m_draw_skip; + const int stride_color = 4 * static_cast(sizeof(float)) * m_draw_skip; + + glDisable(GL_POINT_SMOOTH); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_COLOR_ARRAY); + + glPointSize(m_point_size); + if (p_reader_cache->particles->numParticles() > 0) + { + const float* partioPositions = p_reader_cache->particles->data(p_reader_cache->positionAttr, 0); + + glVertexPointer(3, GL_FLOAT, stride_position, partioPositions); + glColorPointer(4, GL_FLOAT, stride_color, p_reader_cache->rgba.data()); + glDrawArrays(GL_POINTS, 0, (p_reader_cache->particles->numParticles() / (m_draw_skip + 1))); + } + + glDisableClientState(GL_VERTEX_ARRAY); + glDisableClientState(GL_COLOR_ARRAY); // even though we are pushing and popping + // attribs disabling the color array is required or else it will freak out VP1 + // interestingly it's not needed for VP2... + } + else if (m_draw_style == PARTIO_DRAW_STYLE_RADIUS || m_draw_style == PARTIO_DRAW_STYLE_DISK) + { + // if this is accessed from multiple threads + // we already screwed because of OpenGL + static BillboardDrawData billboard_data(10); + + glEnableClientState(GL_VERTEX_ARRAY); + glVertexPointer(2, GL_FLOAT, 0, &billboard_data.vertices[0]); + + for (int i = 0; i < p_reader_cache->particles->numParticles(); i += (m_draw_skip + 1)) + { + glColor4fv(&p_reader_cache->rgba[i * 4]); + const float* partioPositions = p_reader_cache->particles->data(p_reader_cache->positionAttr, i); + drawBillboardCircleAtPoint(partioPositions, p_reader_cache->radius[i], m_draw_style, billboard_data, world_view_matrix); + } + + glDisableClientState(GL_VERTEX_ARRAY); + glDisableClientState(GL_COLOR_ARRAY); + } + } + + return; + } + + void draw_icon() const + { + partio4Maya::drawPartioLogo(m_icon_size); + } + }; +} + +namespace MHWRender { + MString partioVisualizerDrawOverride::registrantId("partioVisualizerDrawOverride"); + + MPxDrawOverride* partioVisualizerDrawOverride::creator(const MObject& obj) + { + return new partioVisualizerDrawOverride(obj); + } + + partioVisualizerDrawOverride::partioVisualizerDrawOverride(const MObject& obj) : MPxDrawOverride(obj, DrawCallback), m_object(obj) + { + MStatus status; + MFnDependencyNode dnode(m_object, &status); + if (status) + p_visualizer = dynamic_cast(dnode.userNode()); + } + + partioVisualizerDrawOverride::~partioVisualizerDrawOverride() + { + + } + + void partioVisualizerDrawOverride::DrawCallback(const MDrawContext& context, const MUserData* data) + { + const DrawData* draw_data = reinterpret_cast(data); + + if (draw_data == 0 || shader_program == INVALID_GL_OBJECT) + return; + + const bool draw_bounding_box = context.getDisplayStyle() & MHWRender::MFrameContext::kBoundingBox; + + bool draw_cache = true; + bool draw_logo = true; + MStatus status; + MBoundingBox frustrum_box = context.getFrustumBox(&status); + if (status) + { + if (!frustrum_box.intersects(draw_data->m_cache_bbox)) + draw_cache = false; + if (draw_bounding_box || !frustrum_box.intersects(draw_data->m_logo_bbox)) + draw_logo = false; + } + + if (!(draw_logo || draw_cache)) + return; + + glPushAttrib(GL_ALL_ATTRIB_BITS); + glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS); + float world_view[4][4]; + MMatrix world_view_matrix = context.getMatrix(MHWRender::MDrawContext::kWorldViewMtx); + world_view_matrix.get(world_view); + float proj[4][4]; + context.getMatrix(MHWRender::MDrawContext::kProjectionMtx).get(proj); + + GLint current_program = 0; + glGetIntegerv(GL_CURRENT_PROGRAM, ¤t_program); + + glUseProgram(shader_program); + + glUniformMatrix4fv(world_view_location, 1, false, &world_view[0][0]); + glUniformMatrix4fv(proj_location, 1, false, &proj[0][0]); + + draw_data->draw(draw_bounding_box, world_view_matrix); + + if (draw_logo) + { + if (draw_data->m_draw_error == 0) + glColor3fv(draw_data->m_wireframe_color); + if (draw_data->m_draw_error == 1) + glColor3f(.75f, 0.0f, 0.0f); + else if (draw_data->m_draw_error == 2) + glColor3f(0.0f, 0.0f, 0.0f); + + draw_data->draw_icon(); + } + + glUseProgram(current_program); + + glPopClientAttrib(); + glPopAttrib(); + } + + MBoundingBox partioVisualizerDrawOverride::boundingBox(const MDagPath& objPath, const MDagPath& cameraPath) const + { + return MBoundingBox(); + } + + bool partioVisualizerDrawOverride::isBounded(const MDagPath& objPath, const MDagPath& cameraPath) const + { + // the cache and the bounding box can change at any time + // plus calling the prepareForDraw also updates the data, so we always have to draw + // then manually do the frustum culling in the draw function + return false; + } + + MUserData* partioVisualizerDrawOverride::prepareForDraw(const MDagPath& objPath, const MDagPath& cameraPath, + const MFrameContext& frameContext, MUserData* oldData) + { + DrawData* draw_data = oldData == 0 ? new DrawData() : reinterpret_cast(oldData); + if (p_visualizer != 0) + { + // TODO: debate if the the bbox queries should be moved to the bounding box function + partioVizReaderCache* p_cache = p_visualizer->updateParticleCache(); + draw_data->update_data(m_object, p_cache); + MColor color = MHWRender::MGeometryUtilities::wireframeColor(objPath); + draw_data->m_wireframe_color[0] = color.r; + draw_data->m_wireframe_color[1] = color.g; + draw_data->m_wireframe_color[2] = color.b; + draw_data->m_wireframe_color[3] = color.a; + draw_data->m_draw_error = p_visualizer->drawError; + } + return draw_data; + } + + DrawAPI partioVisualizerDrawOverride::supportedDrawAPIs() const + { +#if MAYA_API_VERSION >= 201600 + return kOpenGL | kOpenGLCoreProfile; +#else + return kOpenGL; +#endif + } + + void partioVisualizerDrawOverride::init_shaders() + { + + if (!create_shader(vertex_shader, vertex_shader_code)) + return; + if (!create_shader(pixel_shader, pixel_shader_code)) + { + glDeleteShader(vertex_shader); vertex_shader = INVALID_GL_OBJECT; + return; + } + + shader_program = glCreateProgram(); + + glAttachShader(shader_program, vertex_shader); + glAttachShader(shader_program, pixel_shader); + glLinkProgram(shader_program); + + GLint success = 0; + glGetProgramiv(shader_program, GL_LINK_STATUS, &success); + if (success == GL_FALSE) + { + std::cout << "[partioVisualizer] Error linking shader." << std::endl; + + GLint max_length = 0; + glGetProgramiv(shader_program, GL_INFO_LOG_LENGTH, &max_length); + std::vector info_log(max_length); + glGetProgramInfoLog(shader_program, max_length, &max_length, &info_log[0]); + + std::cout << &info_log[0] << std::endl; + + glDeleteShader(vertex_shader); vertex_shader = INVALID_GL_OBJECT; + glDeleteShader(pixel_shader); pixel_shader = INVALID_GL_OBJECT; + glDeleteProgram(shader_program); shader_program = INVALID_GL_OBJECT; + return; + } + + glDetachShader(shader_program, vertex_shader); + glDetachShader(shader_program, pixel_shader); + + world_view_location = glGetUniformLocation(shader_program, "world_view"); + proj_location = glGetUniformLocation(shader_program, "proj"); + } + + void partioVisualizerDrawOverride::free_shaders() + { + if (vertex_shader != INVALID_GL_OBJECT) + glDeleteShader(vertex_shader); + if (pixel_shader != INVALID_GL_OBJECT) + glDeleteShader(pixel_shader); + if (shader_program != INVALID_GL_OBJECT) + glDeleteProgram(shader_program); + } +} diff --git a/contrib/partio4Maya/partioVisualizerDrawOverride.h b/contrib/partio4Maya/partioVisualizerDrawOverride.h new file mode 100644 index 00000000..b0875525 --- /dev/null +++ b/contrib/partio4Maya/partioVisualizerDrawOverride.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +#include "partioVisualizer.h" + +namespace MHWRender{ + class partioVisualizerDrawOverride : public MPxDrawOverride { + public: + static MPxDrawOverride* creator(const MObject& obj); + + static MString registrantId; + + static void init_shaders(); + static void free_shaders(); + private: + partioVisualizerDrawOverride(const MObject& obj); + ~partioVisualizerDrawOverride(); + + static void DrawCallback(const MDrawContext& context, const MUserData* data); + + // this is pure virtual in Maya 2015 + virtual MBoundingBox boundingBox( + const MDagPath& objPath, + const MDagPath& cameraPath) const; + + virtual MUserData* prepareForDraw( + const MDagPath& objPath, + const MDagPath& cameraPath, + const MFrameContext& frameContext, + MUserData* oldData); + + virtual bool isBounded( + const MDagPath& objPath, + const MDagPath& cameraPath) const; + + virtual MHWRender::DrawAPI supportedDrawAPIs() const; + + const MObject m_object; + partioVisualizer* p_visualizer; + }; +} diff --git a/contrib/partio4Maya/plugin.cpp b/contrib/partio4Maya/plugin.cpp index 95381a17..852dd5fb 100644 --- a/contrib/partio4Maya/plugin.cpp +++ b/contrib/partio4Maya/plugin.cpp @@ -27,18 +27,29 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. */ +#include + #include "partioVisualizer.h" #include "partioInstancer.h" #include "partioEmitter.h" #include "partioExport.h" #include "partioImport.h" -#include "partio4MayaShared.h" +#include "partioVisualizerDrawOverride.h" #include - - +#include +#include MStatus initializePlugin ( MObject obj ) { + if (MGlobal::mayaState() == MGlobal::kInteractive) + { + MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(); + if (renderer != 0 && renderer->drawAPIIsOpenGL()) + { + glewInit(); + MHWRender::partioVisualizerDrawOverride::init_shaders(); + } + } // source mel scripts this way if they're missing from the script path it will alert the user... MGlobal::executeCommand("source AEpartioEmitterTemplate.mel"); @@ -46,7 +57,6 @@ MStatus initializePlugin ( MObject obj ) MGlobal::executeCommand("source AEpartioInstancerTemplate.mel"); MGlobal::executeCommand("source partioExportGui.mel"); MGlobal::executeCommand("source partioUtils.mel"); - MGlobal::executeCommand("source shelf_Partio4Maya.mel"); MStatus status; MFnPlugin plugin ( obj, "RedpawFX,Luma Pictures,WDAS", "0.9.8", "Any" ); @@ -54,33 +64,43 @@ MStatus initializePlugin ( MObject obj ) status = plugin.registerShape( "partioVisualizer", partioVisualizer::id, &partioVisualizer::creator, &partioVisualizer::initialize, - &partioVisualizerUI::creator); + &partioVisualizerUI::creator, + &partioVisualizer::drawDbClassification); + if (!status) + { + status.perror("registerNode partioVisualizer failed"); + return status; + } - if ( !status ) + status = MHWRender::MDrawRegistry::registerDrawOverrideCreator( + partioVisualizer::drawDbClassification, + MHWRender::partioVisualizerDrawOverride::registrantId, + MHWRender::partioVisualizerDrawOverride::creator); + + if (!status) { - status.perror ( "registerNode partioVisualizer failed" ); + status.perror("registerGeometryOverride partioVisualizerOverride failed"); return status; } + status = plugin.registerShape( "partioInstancer", partioInstancer::id, &partioInstancer::creator, &partioInstancer::initialize, &partioInstancerUI::creator); - - if ( !status ) + if (!status) { - status.perror ( "registerNode partioInstancer failed" ); + status.perror("registerNode partioInstancer failed"); return status; } - - status = plugin.registerNode ( "partioEmitter", partioEmitter::id, - &partioEmitter::creator, &partioEmitter::initialize, - MPxNode::kEmitterNode ); - if ( !status ) + status = plugin.registerNode("partioEmitter", partioEmitter::id, + &partioEmitter::creator, &partioEmitter::initialize, + MPxNode::kEmitterNode); + if (!status) { - status.perror ( "registerNode partioEmitter failed" ); + status.perror("registerNode partioEmitter failed"); return status; } @@ -102,19 +122,22 @@ MStatus initializePlugin ( MObject obj ) MStatus uninitializePlugin ( MObject obj ) { + if (MGlobal::mayaState() == MGlobal::kInteractive) + MHWRender::partioVisualizerDrawOverride::free_shaders(); + MStatus status; MFnPlugin plugin ( obj ); - status = plugin.deregisterNode ( partioVisualizer::id ); - if ( !status ) + status = plugin.deregisterCommand("partioImport"); + if (!status) { - status.perror ( "deregisterNode partioVisualizer failed" ); - return status; + status.perror("deregisterCommand partioImport failed"); } - status = plugin.deregisterNode ( partioInstancer::id ); - if ( !status ) + + status = plugin.deregisterCommand("partioExport"); + if (!status) { - status.perror ( "deregisterNode partioInstancer failed" ); + status.perror("deregisterCommand partioExport failed"); return status; } @@ -125,17 +148,30 @@ MStatus uninitializePlugin ( MObject obj ) return status; } - status = plugin.deregisterCommand("partioExport"); + status = plugin.deregisterNode(partioInstancer::id); if (!status) { - status.perror("deregisterCommand partioExport failed"); + status.perror("deregisterNode partioInstancer failed"); return status; } - status = plugin.deregisterCommand("partioImport"); + + status = MHWRender::MDrawRegistry::deregisterDrawOverrideCreator( + partioVisualizer::drawDbClassification, + MHWRender::partioVisualizerDrawOverride::registrantId); + if (!status) { - status.perror("deregisterCommand partioImport failed"); + status.perror("deregisterDrawOverride partioVisualizerDrawOverride failed"); + return status; + } + + status = plugin.deregisterNode(partioVisualizer::id); + if (!status) + { + status.perror("deregisterNode partioVisualizer failed"); + return status; } + return status; } diff --git a/contrib/partio4Maya/scripts/AEpartioInstancerTemplate.mel b/contrib/partio4Maya/scripts/AEpartioInstancerTemplate.mel old mode 100755 new mode 100644 index 4c89e74d..9673739c --- a/contrib/partio4Maya/scripts/AEpartioInstancerTemplate.mel +++ b/contrib/partio4Maya/scripts/AEpartioInstancerTemplate.mel @@ -30,72 +30,88 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. global proc AEpartioInstancerTemplate( string $nodeName ) { - editorTemplate -callCustom pioInstLogoHeader pioInstLogoHeader $nodeName; - editorTemplate -beginLayout "Global" -collapse 0; - editorTemplate -addControl "cacheActive"; - editorTemplate -addControl "staticCache"; - //editorTemplate -addControl "flipYZ"; - editorTemplate -addControl "computeVeloPos"; - editorTemplate -addControl -l "Velocity Mult" "veloMult"; - editorTemplate -callCustom pioAEoutpathNew pioAEoutpathReplace cacheDir; - editorTemplate -addControl "cachePrefix"; - editorTemplate -addControl "cacheOffset"; - editorTemplate -addControl "byFrame"; - editorTemplate -addControl "cacheFormat"; - editorTemplate -addControl "iconSize"; - editorTemplate -callCustom pioInstForceUpdate pioInstForceUpdate $nodeName; - - - editorTemplate -endLayout; - - editorTemplate -beginScrollLayout; - - editorTemplate -beginLayout "General Parameters" -collapse 0; - editorTemplate -addControl "pointSize"; - editorTemplate -addControl "drawStyle"; - //editorTemplate -addControl "useEmitterTransform"; - //editorTemplate -addControl -l "Jitter Position Magnitude" "jitterPos" ; - //editorTemplate -addControl -l "Jitter Position Frequency" "jitterFreq"; - editorTemplate -endLayout; - editorTemplate -beginLayout "Instancer Channels" -collapse 0; - editorTemplate -callCustom "pioInstCustomAttrsManage" "pioInstCustomAttrsManage" $nodeName; - editorTemplate -endLayout; - - // include/call base class/node attributes - //AEdependNodeTemplate $nodeName; - editorTemplate -beginLayout ("Render Stats"); - editorTemplate -beginNoOptimize; - editorTemplate -addControl "castsShadows"; - editorTemplate -addControl "receiveShadows"; - editorTemplate -addControl "motionBlur"; - editorTemplate -addControl "primaryVisibility"; - editorTemplate -addControl "smoothShading"; - editorTemplate -addControl "visibleInReflections"; - editorTemplate -addControl "visibleInRefractions"; - editorTemplate -endLayout; - - AEshapeTemplate $nodeName; // adds place for renderer specific controls - - editorTemplate -suppress "compInstObjGroups"; - editorTemplate -suppress "ignoreSelfShadowing"; - editorTemplate -suppress "geometryAntialiasingOverride"; - editorTemplate -suppress "antialiasingLevel"; - editorTemplate -suppress "shadingSamplesOverride"; - editorTemplate -suppress "shadingSamples"; - editorTemplate -suppress "maxShadingSamples"; - editorTemplate -suppress "volumeSamplesOverride"; - editorTemplate -suppress "volumeSamples"; - editorTemplate -suppress "depthJitter"; - editorTemplate -suppress "maxVisibilitySamplesOverride"; - editorTemplate -suppress "maxVisibilitySamples"; - editorTemplate -suppress "localPosition"; - editorTemplate -suppress "localScale"; - - - editorTemplate -addExtraControls; - editorTemplate -endScrollLayout; + editorTemplate -callCustom pioInstLogoHeader pioInstLogoHeader $nodeName; + + editorTemplate -beginScrollLayout; + + editorTemplate -beginLayout "Global" -collapse 0; + editorTemplate -addControl "cacheActive"; + editorTemplate -addControl "staticCache"; + //editorTemplate -addControl "flipYZ"; + editorTemplate -addControl "computeVeloPos"; + editorTemplate -addControl "velocitySource"; + editorTemplate -addControl "angularVelocitySource"; + editorTemplate -addControl -l "Velocity Mult" "veloMult"; + editorTemplate -addControl -l "Angular Velocity Mult" "angVeloMult"; + editorTemplate -callCustom pioAEoutpathNew pioAEoutpathReplace cacheDir; + editorTemplate -addControl "cachePrefix"; + editorTemplate -addControl "cacheOffset"; + editorTemplate -addControl "byFrame"; + editorTemplate -addControl "cacheFormat"; + editorTemplate -addControl "iconSize"; + editorTemplate -callCustom pioInstForceUpdate pioInstForceUpdate $nodeName; + + editorTemplate -endLayout; + + editorTemplate -beginLayout "General Parameters" -collapse 0; + editorTemplate -addControl "pointSize"; + editorTemplate -addControl "drawStyle"; + //editorTemplate -addControl "useEmitterTransform"; + //editorTemplate -addControl -l "Jitter Position Magnitude" "jitterPos" ; + //editorTemplate -addControl -l "Jitter Position Frequency" "jitterFreq"; + editorTemplate -endLayout; + editorTemplate -beginLayout "Instancer Channels" -collapse 0; + editorTemplate -callCustom "pioInstCustomAttrsManage" "pioInstCustomAttrsManage" $nodeName; + editorTemplate -endLayout; + + // include/call base class/node attributes + //AEdependNodeTemplate $nodeName; + editorTemplate -beginLayout ("Render Stats"); + editorTemplate -beginNoOptimize; + editorTemplate -addControl "castsShadows"; + editorTemplate -addControl "receiveShadows"; + editorTemplate -addControl "motionBlur"; + editorTemplate -addControl "primaryVisibility"; + editorTemplate -addControl "smoothShading"; + editorTemplate -addControl "visibleInReflections"; + editorTemplate -addControl "visibleInRefractions"; + editorTemplate -endLayout; + + AEshapeTemplate $nodeName; // adds place for renderer specific controls + + editorTemplate -suppress "compInstObjGroups"; + editorTemplate -suppress "ignoreSelfShadowing"; + editorTemplate -suppress "geometryAntialiasingOverride"; + editorTemplate -suppress "antialiasingLevel"; + editorTemplate -suppress "shadingSamplesOverride"; + editorTemplate -suppress "shadingSamples"; + editorTemplate -suppress "maxShadingSamples"; + editorTemplate -suppress "volumeSamplesOverride"; + editorTemplate -suppress "volumeSamples"; + editorTemplate -suppress "depthJitter"; + editorTemplate -suppress "maxVisibilitySamplesOverride"; + editorTemplate -suppress "maxVisibilitySamples"; + editorTemplate -suppress "localPosition"; + editorTemplate -suppress "localScale"; + + + editorTemplate -addExtraControls; + editorTemplate -endScrollLayout; } +proc generateAttributesMenu(string $nodeName, string $attrNameList[], string $labels[], string $attributes[]) +{ + int $i = 0; + for ($i = 0; $i < size($attributes); ++$i) + { + attrControlGrp -annotation $labels[$i] -attribute ($nodeName + "." + $attributes[$i]); + popupMenu; + for ($attr in $attrNameList) + { + menuItem -label $attr -c ("setAttr -type \"string\" " + $nodeName + "." + $attributes[$i] + " " + $attr); + } + } +} global proc pioInstCustomAttrsManage (string $nodeName) { @@ -107,318 +123,90 @@ global proc pioInstCustomAttrsManage (string $nodeName) string $multiList[] = `listAttr -multi ($nodeName+".partioCacheAttributes")`; - int $scaleFrom = `getAttr ($nodeName+".scaleFrom")` + 2; - int $lastScaleFrom = `getAttr ($nodeName+".lastScaleFrom")` + 2; - int $rotationType = `getAttr ($nodeName+".rotationType")` + 2; - int $rotationFrom = `getAttr ($nodeName+".rotationFrom")` + 2; - int $lastRotationFrom = `getAttr ($nodeName+".lastRotationFrom")` + 2; - int $aimDirectionFrom = `getAttr ($nodeName+".aimDirectionFrom")` + 2; - int $lastAimDirectionFrom = `getAttr ($nodeName+".lastAimDirectionFrom")` + 2; - int $aimPositionFrom = `getAttr ($nodeName+".aimPositionFrom")` + 2; - int $lastAimPositionFrom = `getAttr ($nodeName+".lastAimPositionFrom")` + 2; - int $aimAxisFrom = `getAttr ($nodeName+".aimAxisFrom")` + 2; - int $aimUpAxisFrom = `getAttr ($nodeName+".aimUpAxisFrom")` + 2; - int $aimWorldUpFrom = `getAttr ($nodeName+".aimWorldUpFrom")` + 2; - int $indexFrom = `getAttr ($nodeName+".indexFrom")` + 2; - -/// General attrs -frameLayout -collapse 0 -collapsable 0 -borderVisible 0 -w 450 -l "General Channels" ; -/// SCALE - columnLayout; - string $scaleMenu = `optionMenuGrp -label "Scale"`; - menuItem -l "None"; + string $attrNameList[] = {}; + int $id = 0; for ($multi in $multiList) { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; + $attrNameList[$id] = `getAttr ($nodeName + "." + $multi)`; + $id = $id + 1; } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 0 + " " + $scaleMenu) $scaleMenu; - -setParent ..; -setParent ..; -/// ROTATION stuff -frameLayout -collapse 0 -collapsable 0 -borderVisible 0 -w 450 -l "Rotation Channels" ; -columnLayout; -/// ROT TYPE - string $rotationTypeMenu = `optionMenuGrp -label "RotationType"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 1 + " " + $rotationTypeMenu) $rotationTypeMenu; - -/// ROT - string $rotationMenu = `optionMenuGrp -label "Rotation"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 2 + " " + $rotationMenu) $rotationMenu; - -/// AimDirection - string $aimDirMenu = `optionMenuGrp -label "Aim Direction"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 3 + " " + $aimDirMenu) $aimDirMenu; - -/// Aim Position - - string $aimPosMenu = `optionMenuGrp -label "Aim Position"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 4 + " " + $aimPosMenu) $aimPosMenu; - -/// Aim Axis - - string $aimAxisMenu = `optionMenuGrp -label "Aim Axis"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 5 + " " + $aimAxisMenu) $aimAxisMenu; - -/// Aim UP Axis - - string $aimUpAxisMenu = `optionMenuGrp -label "Aim UpAxis"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 6 + " " + $aimUpAxisMenu) $aimUpAxisMenu; - -/// Aim world Up - - string $aimWorldUpMenu = `optionMenuGrp -label "Aim WorldUp"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 7 + " " + $aimWorldUpMenu) $aimWorldUpMenu; - -setParent ..; -setParent ..; - -/// INDEX -frameLayout -collapse 0 -collapsable 0 -borderVisible 0 -w 450 -l "Index Channels" ; - - columnLayout; - string $indexMenu = `optionMenuGrp -label "index"`; - menuItem -l "None"; - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 8 + " " + $indexMenu) $indexMenu; - -setParent ..; -setParent ..; - -/// LAST ATTRIBUTES -frameLayout -collapse 1 -collapsable 1 -borderVisible 0 -w 450 -l "Motion blur Channels (if left blank they will inherit above channels)" ; -columnLayout; -/// LAST SCALE - string $lastScaleMenu = `optionMenuGrp -label "Last Scale"`; - menuItem -l "None"; - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 9 + " " + $lastScaleMenu) $lastScaleMenu; - -/// LAST ROT - string $lastRotationMenu = `optionMenuGrp -label "Last Rotation"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 10 + " " + $lastRotationMenu) $lastRotationMenu; - -/// LAST Aim Direction - string $lastAimDirMenu = `optionMenuGrp -label "Last Aim Direction"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 11 + " " + $lastAimDirMenu) $lastAimDirMenu; - -/// LAST Aim Position - string $lastAimPosMenu = `optionMenuGrp -label "Last Aim Position"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioInstSwitchAttributeFrom " + $nodeName + " " + 12 + " " + $lastAimPosMenu) $lastAimPosMenu; - - setParent ..; - setParent ..; - - if (`size($multiList)`) - { - optionMenuGrp -e -sl $scaleFrom $scaleMenu; - optionMenuGrp -e -sl $rotationType $rotationTypeMenu; - optionMenuGrp -e -sl $rotationFrom $rotationMenu; - optionMenuGrp -e -sl $aimDirectionFrom $aimDirMenu; - optionMenuGrp -e -sl $aimPositionFrom $aimPosMenu; - optionMenuGrp -e -sl $aimAxisFrom $aimAxisMenu; - optionMenuGrp -e -sl $aimUpAxisFrom $aimUpAxisMenu; - optionMenuGrp -e -sl $aimWorldUpFrom $aimWorldUpMenu; - optionMenuGrp -e -sl $indexFrom $indexMenu; - optionMenuGrp -e -sl $lastScaleFrom $lastScaleMenu; - optionMenuGrp -e -sl $lastRotationFrom $lastRotationMenu; - optionMenuGrp -e -sl $lastAimDirectionFrom $lastAimDirMenu; - optionMenuGrp -e -sl $lastAimPositionFrom $lastAimPosMenu; - - } - -} - -global proc pioInstSwitchAttributeFrom(string $nodeName, int $attr, string $menu) -{ - string $attrList[] = { "scaleFrom", - "rotationType", - "rotationFrom", - "aimDirectionFrom", - "aimPositionFrom", - "aimAxisFrom", - "aimUpAxisFrom", - "aimWorldUpFrom", - "indexFrom", - "lastScaleFrom", - "lastRotationFrom", - "lastAimDirectionFrom", - "lastAimPositionFrom" - }; - int $sel = `optionMenuGrp -q -sl $menu`; - - setAttr ($nodeName+"."+$attrList[$attr]) ($sel-2); + /// General attrs + frameLayout -collapse 0 -collapsable 0 -borderVisible 0 -w 450 -l "General Channels" ; + /// SCALE + columnLayout; + string $scaleAttributes[] = {"scaleFrom"}; + string $scaleLabels[] = {"Scale"}; + generateAttributesMenu($nodeName, $attrNameList, $scaleLabels, $scaleAttributes); + setParent ..; + setParent ..; + /// ROTATION stuff + frameLayout -collapse 0 -collapsable 0 -borderVisible 0 -w 450 -l "Rotation Channels" ; + columnLayout; + /// ROT TYPE + string $rotationAttributes[] = {"rotationType", "rotationFrom", "aimDirectionFrom", "aimPositionFrom", "aimAxisFrom", "aimUpAxisFrom", "aimWorldUpFrom"}; + string $rotationLabels[] = {"Rotation Type", "Rotation", "Aim Direction", "Aim Position", "Aim Axis", "Aim Up Axis", "Aim World Up"}; + generateAttributesMenu($nodeName, $attrNameList, $rotationLabels, $rotationAttributes); + + setParent ..; + setParent ..; + + /// INDEX + frameLayout -collapse 0 -collapsable 0 -borderVisible 0 -w 450 -l "Index Channels" ; + columnLayout; + string $indexAttributes[] = {"indexFrom"}; + string $indexLabels[] = {"Index"}; + generateAttributesMenu($nodeName, $attrNameList, $indexLabels, $indexAttributes); + setParent ..; + setParent ..; + + /// LAST ATTRIBUTES + frameLayout -collapse 1 -collapsable 1 -borderVisible 0 -w 450 -l "Motion blur Channels (if left blank they will inherit above channels)" ; + columnLayout; + string $lastAttributes[] = {"velocityFrom", "lastPositionFrom", "angularVelocityFrom", "lastRotationFrom", "lastAimDirectionFrom", "lastAimPositionFrom"}; + string $lastLabels[] = {"Velocity", "Last Position", "Angular Velocity", "Last Rotation", "Last Aim Direction", "Last Aim Position"}; + generateAttributesMenu($nodeName, $attrNameList, $lastLabels, $lastAttributes); + setParent ..; + setParent ..; + + frameLayout -collapse 1 -borderVisible 0 -w 450 -l "Custom Attributes Export"; + + attrControlGrp -attribute ($nodeName+".exportAttributes") "ExportAttributesCtrlGrp"; + + setParent ..; + setParent ..; } global proc pioInstForceUpdate(string $nodeName) { - $nodeName = pioStripNodeName ($nodeName); - if (!`button -q -exists pioInstReloadButton`) - { rowLayout -nc 1 ; - button -ebg true -bgc 1 0.678 0.125 -w 100 -l "------" -c ("setAttr "+$nodeName+".forceReload true") pioInstReloadButton; - } + $nodeName = pioStripNodeName ($nodeName); + if (!`button -q -exists pioInstReloadButton`) + { rowLayout -nc 1 ; + button -ebg true -bgc 1 0.678 0.125 -w 100 -l "------" -c ("setAttr "+$nodeName+".forceReload true") pioInstReloadButton; + } } global proc pioInstLogoHeader(string $nodeName) { - if (!`symbolButton -q -exists pioInstHeaderIcon`) - { rowLayout -nc 2 ; - symbolButton -h 45 -w 235 -c "pioInstSwapAboutText()" -image "partioInstancer_logo.png" pioInstHeaderIcon; - text -fn "smallBoldLabelFont" -l "Partio Instancer!!" pioInstAboutText; - } + if (!`symbolButton -q -exists pioInstHeaderIcon`) + { rowLayout -nc 2 ; + symbolButton -h 45 -w 235 -c "pioInstSwapAboutText()" -image "partioInstancer_logo.png" pioInstHeaderIcon; + text -fn "smallBoldLabelFont" -l "Partio Instancer!!" pioInstAboutText; + } } - global proc pioInstSwapAboutText() { + string $text1 = "Partio Instancer!!"; + string $text2 = "Partio Instancer by: \n John Cassella (redpawfx)\n with Luma-Pictures 2012"; - string $text1 = "Partio Instancer!!"; - string $text2 = "Partio Instancer by: \n John Cassella (redpawfx)\n with Luma-Pictures 2012"; - - string $text = `text -q -l pioInstAboutText`; - if (`gmatch $text "Partio Instancer!!"`) - { - text -e -l $text2 pioInstAboutText; - } - else - { - text -e -l $text1 pioInstAboutText; - } - + string $text = `text -q -l pioInstAboutText`; + if (`gmatch $text "Partio Instancer!!"`) + { + text -e -l $text2 pioInstAboutText; + } + else + { + text -e -l $text1 pioInstAboutText; + } } - - - - diff --git a/contrib/partio4Maya/scripts/AEpartioVisualizerTemplate.mel b/contrib/partio4Maya/scripts/AEpartioVisualizerTemplate.mel old mode 100755 new mode 100644 index 9232cdac..16bc68d9 --- a/contrib/partio4Maya/scripts/AEpartioVisualizerTemplate.mel +++ b/contrib/partio4Maya/scripts/AEpartioVisualizerTemplate.mel @@ -29,77 +29,81 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. global proc AEpartioVisualizerTemplate( string $nodeName ) { - editorTemplate -callCustom pioVizLogoHeader pioVizLogoHeader $nodeName; - editorTemplate -beginLayout "Global" -collapse 0; - editorTemplate -addControl "cacheActive"; - editorTemplate -addControl "staticCache"; - //editorTemplate -addControl "flipYZ"; - editorTemplate -callCustom pioAEoutpathNew pioAEoutpathReplace cacheDir; - editorTemplate -addControl "cachePrefix"; - editorTemplate -addControl "cacheOffset"; - editorTemplate -addControl "byFrame"; - editorTemplate -addControl "cacheFormat"; - editorTemplate -addControl "iconSize"; - editorTemplate -callCustom pioVizForceUpdate pioVizForceUpdate $nodeName; - - - editorTemplate -endLayout; - - editorTemplate -beginScrollLayout; - - editorTemplate -beginLayout "General Parameters" -collapse 0; - editorTemplate -addControl "pointSize"; - editorTemplate -addControl "drawStyle"; - editorTemplate -addControl "drawSkip"; - editorTemplate -addControl "defaultPointColor"; - editorTemplate -addControl "defaultAlpha"; - editorTemplate -addControl "invertAlpha"; - editorTemplate -addControl "defaultRadius"; - //editorTemplate -addControl "useEmitterTransform"; - //editorTemplate -addControl -l "Jitter Position Magnitude" "jitterPos" ; - //editorTemplate -addControl -l "Jitter Position Frequency" "jitterFreq"; - editorTemplate -endLayout; - editorTemplate -beginLayout "Channel Control" -collapse 0; - editorTemplate -callCustom "pioVizCustomAttrsManage" "pioVizCustomAttrsManage" $nodeName; - editorTemplate -endLayout; - - // include/call base class/node attributes - //AEdependNodeTemplate $nodeName; - editorTemplate -beginLayout ("Render Stats"); - editorTemplate -beginNoOptimize; - editorTemplate -addControl "castsShadows"; - editorTemplate -addControl "receiveShadows"; - editorTemplate -addControl "motionBlur"; - editorTemplate -addControl "primaryVisibility"; - editorTemplate -addControl "smoothShading"; - editorTemplate -addControl "visibleInReflections"; - editorTemplate -addControl "visibleInRefractions"; - editorTemplate -endLayout; - - AEshapeTemplate $nodeName; // adds place for renderer specific controls - - editorTemplate -suppress "compInstObjGroups"; - editorTemplate -suppress "ignoreSelfShadowing"; - editorTemplate -suppress "geometryAntialiasingOverride"; - editorTemplate -suppress "antialiasingLevel"; - editorTemplate -suppress "shadingSamplesOverride"; - editorTemplate -suppress "shadingSamples"; - editorTemplate -suppress "maxShadingSamples"; - editorTemplate -suppress "volumeSamplesOverride"; - editorTemplate -suppress "volumeSamples"; - editorTemplate -suppress "depthJitter"; - editorTemplate -suppress "maxVisibilitySamplesOverride"; - editorTemplate -suppress "maxVisibilitySamples"; - editorTemplate -suppress "localPosition"; - editorTemplate -suppress "localScale"; - - - editorTemplate -addExtraControls; - editorTemplate -endScrollLayout; + editorTemplate -callCustom pioVizLogoHeader pioVizLogoHeader $nodeName; + + editorTemplate -beginScrollLayout; + + editorTemplate -beginLayout "Global" -collapse 0; + editorTemplate -addControl "cacheActive"; + editorTemplate -addControl "staticCache"; + //editorTemplate -addControl "flipYZ"; + editorTemplate -callCustom pioAEoutpathNew pioAEoutpathReplace cacheDir; + editorTemplate -addControl "cachePrefix"; + editorTemplate -addControl "cacheOffset"; + editorTemplate -addControl "byFrame"; + editorTemplate -addControl "cacheFormat"; + editorTemplate -addControl "iconSize"; + editorTemplate -callCustom pioVizForceUpdate pioVizForceUpdate $nodeName; + + + editorTemplate -endLayout; + + editorTemplate -beginLayout "General Parameters" -collapse 0; + editorTemplate -addControl "pointSize"; + editorTemplate -addControl "drawStyle"; + editorTemplate -addControl "drawSkip"; + editorTemplate -addControl "defaultPointColor"; + editorTemplate -addControl "defaultAlpha"; + editorTemplate -addControl "invertAlpha"; + editorTemplate -addControl "defaultRadius"; + //editorTemplate -addControl "useEmitterTransform"; + //editorTemplate -addControl -l "Jitter Position Magnitude" "jitterPos" ; + //editorTemplate -addControl -l "Jitter Position Frequency" "jitterFreq"; + editorTemplate -endLayout; + editorTemplate -beginLayout "Channel Control" -collapse 0; + editorTemplate -callCustom "pioVizCustomAttrsManage" "pioVizCustomAttrsManage" $nodeName; + //editorTemplate -addControl "velocityFrom"; + //editorTemplate -addControl "colorFrom"; + //editorTemplate -addControl "incandescenceFrom"; + //editorTemplate -addControl "opacityFrom"; + //editorTemplate -addControl "radiusFrom"; + editorTemplate -endLayout; + + // include/call base class/node attributes + //AEdependNodeTemplate $nodeName; + editorTemplate -beginLayout ("Render Stats"); + editorTemplate -beginNoOptimize; + editorTemplate -addControl "castsShadows"; + editorTemplate -addControl "receiveShadows"; + editorTemplate -addControl "motionBlur"; + editorTemplate -addControl "primaryVisibility"; + editorTemplate -addControl "smoothShading"; + editorTemplate -addControl "visibleInReflections"; + editorTemplate -addControl "visibleInRefractions"; + editorTemplate -endLayout; + + AEshapeTemplate $nodeName; // adds place for renderer specific controls + + editorTemplate -suppress "compInstObjGroups"; + editorTemplate -suppress "ignoreSelfShadowing"; + editorTemplate -suppress "geometryAntialiasingOverride"; + editorTemplate -suppress "antialiasingLevel"; + editorTemplate -suppress "shadingSamplesOverride"; + editorTemplate -suppress "shadingSamples"; + editorTemplate -suppress "maxShadingSamples"; + editorTemplate -suppress "volumeSamplesOverride"; + editorTemplate -suppress "volumeSamples"; + editorTemplate -suppress "depthJitter"; + editorTemplate -suppress "maxVisibilitySamplesOverride"; + editorTemplate -suppress "maxVisibilitySamples"; + editorTemplate -suppress "localPosition"; + editorTemplate -suppress "localScale"; + + + editorTemplate -addExtraControls; + editorTemplate -endScrollLayout; } - - global proc pioVizCustomAttrsManage (string $nodeName) { $nodeName = pioStripNodeName ($nodeName); @@ -109,123 +113,72 @@ global proc pioVizCustomAttrsManage (string $nodeName) columnLayout foobar; string $multiList[] = `listAttr -multi ($nodeName+".partioCacheAttributes")`; - - int $colorFrom = `getAttr ($nodeName+".colorFrom")` + 2; - int $opacityFrom = `getAttr ($nodeName+".opacityFrom")` + 2; - int $radiusFrom = `getAttr ($nodeName+".radiusFrom")` + 2; - int $incandFrom = `getAttr ($nodeName+".incandescenceFrom")` + 2; - - - string $colorMenu = `optionMenuGrp -label "Color from->"`; - menuItem -l "None"; - - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioVizSwitchAttributeFrom " + $nodeName + " " + 0 + " " + $colorMenu) $colorMenu; - - string $incandMenu = `optionMenuGrp -label "Incandescence from->"`; - menuItem -l "None"; - + string $attrNameList[] = {}; + int $id = 0; for ($multi in $multiList) { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; + $attrNameList[$id] = `getAttr ($nodeName + "." + $multi)`; + $id = $id + 1; } - optionMenuGrp -e -cc ("pioVizSwitchAttributeFrom " + $nodeName + " " + 1 + " " + $incandMenu) $incandMenu; + string $attributes[] = {"velocityFrom", "accelerationFrom", "colorFrom", "opacityFrom", "radiusFrom", "incandescenceFrom"}; + string $labels[] = {"Velocity from ->", "Acceleration from ->", "Color from ->", "Opacity from ->", "Radius from ->", "Incandescence from ->"}; - string $opacMenu = `optionMenuGrp -label "Opacity from->"`; - menuItem -l "None"; - for ($multi in $multiList) + int $i = 0; + for ($i = 0; $i < size($attributes); ++$i) { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; + attrControlGrp -annotation $labels[$i] -attribute ($nodeName + "." + $attributes[$i]); + popupMenu; + for ($attr in $attrNameList) + { + menuItem -label $attr -c ("setAttr -type \"string\" " + $nodeName + "." + $attributes[$i] + " " + $attr); + } } - optionMenuGrp -e -cc ("pioVizSwitchAttributeFrom " + $nodeName + " " + 2 + " " + $opacMenu) $opacMenu; - - - string $radiusMenu = `optionMenuGrp -label "Radius from->"`; - menuItem -l "None"; - for ($multi in $multiList) - { - string $tok[]; - tokenize $multi "[" $tok; - string $index = $tok[1]; - $index = substituteAllString($index, "]", ""); - string $attr = `getAttr ($nodeName+"."+$multi)`; - menuItem -label $attr; - } - optionMenuGrp -e -cc ("pioVizSwitchAttributeFrom " + $nodeName + " " + 3 + " " + $radiusMenu) $radiusMenu; - - - if (`size($multiList)`) - { - optionMenuGrp -e -sl $colorFrom $colorMenu; - optionMenuGrp -e -sl $incandFrom $incandMenu; - optionMenuGrp -e -sl $opacityFrom $opacMenu; - optionMenuGrp -e -sl $radiusFrom $radiusMenu; - } - } global proc pioVizSwitchAttributeFrom(string $nodeName, int $attr, string $menu) { - string $attrList[] = {"colorFrom", "incandescenceFrom", "opacityFrom", "radiusFrom"}; - int $sel = `optionMenuGrp -q -sl $menu`; + string $attrList[] = {"colorFrom", "incandescenceFrom", "opacityFrom", "radiusFrom"}; + int $sel = `optionMenuGrp -q -sl $menu`; - setAttr ($nodeName+"."+$attrList[$attr]) ($sel-2); + setAttr ($nodeName+"."+$attrList[$attr]) ($sel-2); } global proc pioVizForceUpdate(string $nodeName) { - $nodeName = pioStripNodeName ($nodeName); - if (!`button -q -exists pioVizReloadButton`) - { rowLayout -nc 1 ; - button -ebg true -bgc 1 0.678 0.125 -w 100 -l "------" -c ("setAttr "+$nodeName+".forceReload true") pioVizReloadButton; - } + $nodeName = pioStripNodeName ($nodeName); + if (!`button -q -exists pioVizReloadButton`) + { rowLayout -nc 1 ; + button -ebg true -bgc 1 0.678 0.125 -w 100 -l "------" -c ("setAttr "+$nodeName+".forceReload true") pioVizReloadButton; + } } global proc pioVizLogoHeader(string $nodeName) { - if (!`symbolButton -q -exists pioVizHeaderIcon`) - { rowLayout -nc 2 ; - symbolButton -h 45 -w 235 -c "pioVizSwapAboutText()" -image "partioVisualizer_logo.png" pioVizHeaderIcon; - text -fn "smallBoldLabelFont" -l "Partio Visualizer!!" pioVizAboutText; - } + if (!`symbolButton -q -exists pioVizHeaderIcon`) + { rowLayout -nc 2 ; + symbolButton -h 45 -w 235 -c "pioVizSwapAboutText()" -image "partioVisualizer_logo.png" pioVizHeaderIcon; + text -fn "smallBoldLabelFont" -l "Partio Visualizer!!" pioVizAboutText; + } } global proc pioVizSwapAboutText() { - string $text1 = "Partio Visualizer!!"; - string $text2 = "Partio Visualizer by: \n John Cassella (redpawfx)\n with Luma-Pictures 2015"; - - string $text = `text -q -l pioVizAboutText`; - if (`gmatch $text "Partio Visualizer!!"`) - { - text -e -l $text2 pioVizAboutText; - } - else - { - text -e -l $text1 pioVizAboutText; - } + string $text1 = "Partio Visualizer!!"; + string $text2 = "Partio Visualizer by: \n John Cassella (redpawfx)\n with Luma-Pictures 2015"; + + string $text = `text -q -l pioVizAboutText`; + if (`gmatch $text "Partio Visualizer!!"`) + { + text -e -l $text2 pioVizAboutText; + } + else + { + text -e -l $text1 pioVizAboutText; + } } diff --git a/contrib/partio4Maya/scripts/partioExportGui.mel b/contrib/partio4Maya/scripts/partioExportGui.mel index fb9cc07e..420ae22c 100644 --- a/contrib/partio4Maya/scripts/partioExportGui.mel +++ b/contrib/partio4Maya/scripts/partioExportGui.mel @@ -84,7 +84,7 @@ global proc partioExportGui () optionMenuGrp -e -sl 5 $partioExportFormatOptionMenu; - string $exportPerFrameCheckbox = `checkBoxGrp -numberOfCheckBoxes 1 -label1 "Per/Frame" -v1 0`; + string $exportPerFrameCheckbox = `checkBoxGrp -numberOfCheckBoxes 1 -label1 "Per/Frame" -v1 1`; string $startFrame = `intFieldGrp -l "StartFrame" -cw 1 90 -cw 2 80 -nf 1 -v $start 0 0 0 `; string $endFrame = `intFieldGrp -l "EndFrame" -cw 1 90 -cw 2 80 -nf 1 -v $end 0 0 0 `; diff --git a/contrib/partio4Maya/scripts/partioUtils.mel b/contrib/partio4Maya/scripts/partioUtils.mel index e2f33cec..fdf1f521 100644 --- a/contrib/partio4Maya/scripts/partioUtils.mel +++ b/contrib/partio4Maya/scripts/partioUtils.mel @@ -110,7 +110,7 @@ global proc string[] partioGetBaseFileName(string $inFileName) $l = `size $breakdownFileName`; - string $last = `substring $breakdownFileName $l $l`; + $last = `substring $breakdownFileName $l $l`; if ( $last == "_" || $last == ".") { diff --git a/src/houdini/CMakeLists.txt b/src/houdini/CMakeLists.txt index a146291d..72b9ca7d 100644 --- a/src/houdini/CMakeLists.txt +++ b/src/houdini/CMakeLists.txt @@ -36,20 +36,27 @@ find_package(Houdini) if(HOUDINI_FOUND) - SET (HOUDINI_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/build-${CMAKE_INSTALL_PREFIX}/houdini/$ENV{HOUDINI_VERSION}) - SET (HOUDINI_INCS ${HOUDINI_INCLUDE_DIRS}) - SET (HOUDINI_LIBDIR ${HOUDINI_LIBRARY_DIRS}) - SET (HOUDINI_LIBS HoudiniUI HoudiniOPZ HoudiniOP3 HoudiniOP2 HoudiniOP1 HoudiniSIM HoudiniGEO HoudiniPRM HoudiniUT) - ADD_DEFINITIONS (${HOUDINI_DEFINITIONS} -DHOUDINI_DEFINES -DHOUDINI_API_VERSION=$ENV{HOUDINI_VERSION} -D_REENTRANT -D_FILE_OFFSET_BITS=64 -DMAKING_DSO) - - - LINK_DIRECTORIES( ${HOUDINI_LIBDIR} ) - INCLUDE_DIRECTORIES( ${CMAKE_SOURCE_DIR}/src/lib ${HOUDINI_INCS} ) + SET (HOUDINI_LIBS + HoudiniUI + HoudiniOPZ + HoudiniOP3 + HoudiniOP2 + HoudiniOP1 + HoudiniSIM + HoudiniGEO + HoudiniPRM + HoudiniUT) + + ADD_DEFINITIONS (${HOUDINI_DEFINITIONS} -DHOUDINI_DEFINES -DHOUDINI_API_VERSION=${HOUDINI_VERSION} -D_REENTRANT -D_FILE_OFFSET_BITS=64 -DMAKING_DSO) + + LINK_DIRECTORIES( ${HOUDINI_LIBRARY_DIRS} ) + INCLUDE_DIRECTORIES( ${CMAKE_SOURCE_DIR}/src/lib ${HOUDINI_INCLUDE_DIRS} ) ADD_LIBRARY(partio4Houdini SHARED SOP_FromPartio.cpp ROP_ToPartio.cpp initialize.cpp) - target_link_libraries(partio4Houdini ${PARTIO_LIBRARIES} ${HOUDINI_LIBS}) + TARGET_LINK_LIBRARIES(partio4Houdini ${PARTIO_LIBRARIES} ${HOUDINI_LIBS}) - INSTALL(TARGETS partio4Houdini DESTINATION ${HOUDINI_OUTPUT_PATH} ) + INSTALL(TARGETS partio4Houdini + DESTINATION houdini ) endif (HOUDINI_FOUND) diff --git a/src/lib/CMakeLists.txt b/src/lib/CMakeLists.txt index 6048798e..4e0ef4c1 100644 --- a/src/lib/CMakeLists.txt +++ b/src/lib/CMakeLists.txt @@ -38,5 +38,17 @@ ADD_LIBRARY (partio ${3rdParty_io_cpp} ${io_cpp} ${core_cpp}) FILE(GLOB public_includes "*.h") -INSTALL (TARGETS partio DESTINATION ${LIBRARY_INSTALL_PATH}) -INSTALL( FILES ${public_includes} DESTINATION ${INCLUDE_INSTALL_PATH}) +IF (${LOCAL_INSTALL}) +INSTALL(TARGETS partio + LIBRARY DESTINATION lib/${PARTIO_BUILD_PLATFORM} + ARCHIVE DESTINATION lib/${PARTIO_BUILD_PLATFORM}) +ELSE(${LOCAL_INSTALL}) +INSTALL(TARGETS partio + LIBRARY DESTINATION lib + ARCHIVE DESTINATION lib) +ENDIF(${LOCAL_INSTALL}) + + +INSTALL(FILES ${public_includes} + DESTINATION include) + diff --git a/src/lib/Partio.h b/src/lib/Partio.h index 55eb92de..d4b30c45 100644 --- a/src/lib/Partio.h +++ b/src/lib/Partio.h @@ -47,10 +47,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include #include +#include "PartioConfig.h" #include "PartioAttribute.h" #include "PartioIterator.h" -namespace Partio{ +ENTER_PARTIO_NAMESPACE //! Opaque random access method to a single particle. No number is implied or guaranteed. typedef uint64_t ParticleIndex; @@ -288,5 +289,6 @@ void print(const ParticlesData* particles); //! TODO: this is a temporary hack to develop binary json support Partio::ParticlesDataMutable* testRead(const char* filename); -} +EXIT_PARTIO_NAMESPACE + #endif diff --git a/src/lib/PartioAttribute.h b/src/lib/PartioAttribute.h index fc8a9706..113e0f19 100644 --- a/src/lib/PartioAttribute.h +++ b/src/lib/PartioAttribute.h @@ -41,7 +41,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #ifndef _PartioParticleAttribute_h_ #define _PartioParticleAttribute_h_ -namespace Partio{ + +#include "PartioConfig.h" + +ENTER_PARTIO_NAMESPACE // Particle Types enum ParticleAttributeType {NONE=0,VECTOR=1,FLOAT=2,INT=3,INDEXEDSTR=4}; @@ -112,5 +115,7 @@ class ParticleAttribute //! for example for a PTC file to read and write this could be "color" or "point" // std::string comment; }; -} + +EXIT_PARTIO_NAMESPACE + #endif diff --git a/src/lib/PartioConfig.h b/src/lib/PartioConfig.h new file mode 100644 index 00000000..75065a6a --- /dev/null +++ b/src/lib/PartioConfig.h @@ -0,0 +1,49 @@ +/* +PARTIO SOFTWARE +Copyright 2013 Disney Enterprises, Inc. All rights reserved + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in +the documentation and/or other materials provided with the +distribution. + +* The names "Disney", "Walt Disney Pictures", "Walt Disney Animation +Studios" or the names of its contributors may NOT be used to +endorse or promote products derived from this software without +specific prior written permission from Walt Disney Pictures. + +Disclaimer: THIS SOFTWARE IS PROVIDED BY WALT DISNEY PICTURES AND +CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, +BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, NONINFRINGEMENT AND TITLE ARE DISCLAIMED. +IN NO EVENT SHALL WALT DISNEY PICTURES, THE COPYRIGHT HOLDER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND BASED ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +*/ + +#ifndef _PartioConfig_h_ +#define _PartioConfig_h_ + +#ifdef PARTIO_NAMESPACE +#define PARTIO PARTIO_NAMESPACE::Partio +#define ENTER_PARTIO_NAMESPACE namespace PARTIO_NAMESPACE { namespace Partio { +#define EXIT_PARTIO_NAMESPACE } } +#else +#define PARTIO Partio +#define ENTER_PARTIO_NAMESPACE namespace Partio { +#define EXIT_PARTIO_NAMESPACE } +#endif + +#endif diff --git a/src/lib/PartioIterator.h b/src/lib/PartioIterator.h index 7d063cc8..babfa805 100644 --- a/src/lib/PartioIterator.h +++ b/src/lib/PartioIterator.h @@ -38,9 +38,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include #include +#include "PartioConfig.h" #include "PartioAttribute.h" -namespace Partio{ +ENTER_PARTIO_NAMESPACE class ParticlesData; struct ParticleAccessor; @@ -216,7 +217,6 @@ std::ostream& operator<<(std::ostream& output,const Data& v) return output; } - -} +EXIT_PARTIO_NAMESPACE #endif diff --git a/src/lib/core/KdTree.h b/src/lib/core/KdTree.h index 061c4d19..608d8c92 100644 --- a/src/lib/core/KdTree.h +++ b/src/lib/core/KdTree.h @@ -40,8 +40,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #endif -namespace Partio -{ +ENTER_PARTIO_NAMESPACE /* balanced kdtree Brent Burley, Mar 2006 @@ -443,5 +442,6 @@ void KdTree::findPoints(std::vector& result, const BBox& bbox, findPoints(result, bbox, n+left+1, right, nextj); } -} +EXIT_PARTIO_NAMESPACE + #endif diff --git a/src/lib/core/Mutex.h b/src/lib/core/Mutex.h index 33e4ad30..7e99492b 100644 --- a/src/lib/core/Mutex.h +++ b/src/lib/core/Mutex.h @@ -39,9 +39,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #ifndef PARTIO_WIN32 #include +#include "../PartioConfig.h" -namespace Partio -{ +ENTER_PARTIO_NAMESPACE #ifndef PARTIO_USE_SPINLOCK @@ -100,7 +100,7 @@ namespace Partio }; #endif // USE_PTHREAD_SPINLOCK -} +EXIT_PARTIO_NAMESPACE #else #include diff --git a/src/lib/core/Particle.cpp b/src/lib/core/Particle.cpp index 464c33ff..7496bd8d 100644 --- a/src/lib/core/Particle.cpp +++ b/src/lib/core/Particle.cpp @@ -40,7 +40,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include #include -namespace Partio{ +ENTER_PARTIO_NAMESPACE //ParticlesDataMutable::~ParticlesDataMutable() //{} @@ -124,5 +124,4 @@ print(const ParticlesData* particles) } } - -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/core/ParticleCaching.cpp b/src/lib/core/ParticleCaching.cpp index 6c5a8d56..6c450c5e 100644 --- a/src/lib/core/ParticleCaching.cpp +++ b/src/lib/core/ParticleCaching.cpp @@ -38,7 +38,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "../Partio.h" //##################################################################### -namespace Partio{ +ENTER_PARTIO_NAMESPACE namespace { @@ -118,4 +118,4 @@ void endCachedAccess(ParticlesData* particles) // TODO: for future use } -} // namespace Partio +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/core/ParticleCaching.h b/src/lib/core/ParticleCaching.h index ccfbdd98..c3e36b07 100644 --- a/src/lib/core/ParticleCaching.h +++ b/src/lib/core/ParticleCaching.h @@ -36,9 +36,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #ifndef _ParticleCaching_h_ #define _ParticleCaching_h_ -namespace Partio{ +ENTER_PARTIO_NAMESPACE + class Particles; void freeCached(ParticlesInfo* particles); -} + +EXIT_PARTIO_NAMESPACE #endif diff --git a/src/lib/core/ParticleHeaders.cpp b/src/lib/core/ParticleHeaders.cpp index 0fba4c99..47b747a2 100644 --- a/src/lib/core/ParticleHeaders.cpp +++ b/src/lib/core/ParticleHeaders.cpp @@ -38,7 +38,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include -using namespace Partio; +ENTER_PARTIO_NAMESPACE ParticleHeaders:: ParticleHeaders() @@ -201,3 +201,4 @@ dataAsFloat(const ParticleAttribute& attribute,const int indexCount, assert(false); } +EXIT_PARTIO_NAMESPACE \ No newline at end of file diff --git a/src/lib/core/ParticleHeaders.h b/src/lib/core/ParticleHeaders.h index ac6418d8..90a553d9 100644 --- a/src/lib/core/ParticleHeaders.h +++ b/src/lib/core/ParticleHeaders.h @@ -36,9 +36,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #define _ParticlesHeaders_h_ #include "../Partio.h" -namespace Partio{ +ENTER_PARTIO_NAMESPACE -class ParticleHeaders:public ParticlesDataMutable +class ParticleHeaders : public ParticlesDataMutable { public: ParticleHeaders(); @@ -88,5 +88,7 @@ class ParticleHeaders:public ParticlesDataMutable std::map nameToAttribute; }; -} + +EXIT_PARTIO_NAMESPACE + #endif diff --git a/src/lib/core/ParticleSimple.cpp b/src/lib/core/ParticleSimple.cpp index 8d152ee8..77eba197 100644 --- a/src/lib/core/ParticleSimple.cpp +++ b/src/lib/core/ParticleSimple.cpp @@ -46,8 +46,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "KdTree.h" - -using namespace Partio; +ENTER_PARTIO_NAMESPACE ParticlesSimple:: ParticlesSimple() @@ -353,3 +352,4 @@ indexedStrs(const ParticleAttribute& attr) const return table.strings; } +EXIT_PARTIO_NAMESPACE \ No newline at end of file diff --git a/src/lib/core/ParticleSimple.h b/src/lib/core/ParticleSimple.h index 289c81a3..bb1a4e9b 100644 --- a/src/lib/core/ParticleSimple.h +++ b/src/lib/core/ParticleSimple.h @@ -39,7 +39,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "Mutex.h" #include "../Partio.h" -namespace Partio{ +ENTER_PARTIO_NAMESPACE template class KdTree; @@ -108,4 +108,4 @@ class ParticlesSimple:public ParticlesDataMutable, KdTree<3>* kdtree; }; -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/core/ParticleSimpleInterleave.cpp b/src/lib/core/ParticleSimpleInterleave.cpp index 905b19f3..ce4778c0 100644 --- a/src/lib/core/ParticleSimpleInterleave.cpp +++ b/src/lib/core/ParticleSimpleInterleave.cpp @@ -46,7 +46,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "KdTree.h" -using namespace Partio; +ENTER_PARTIO_NAMESPACE ParticlesSimpleInterleave:: ParticlesSimpleInterleave() @@ -353,3 +353,4 @@ indexedStrs(const ParticleAttribute& attr) const return table.strings; } +EXIT_PARTIO_NAMESPACE \ No newline at end of file diff --git a/src/lib/core/ParticleSimpleInterleave.h b/src/lib/core/ParticleSimpleInterleave.h index 5f4814cc..2cb441dc 100644 --- a/src/lib/core/ParticleSimpleInterleave.h +++ b/src/lib/core/ParticleSimpleInterleave.h @@ -41,7 +41,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "Mutex.h" #include "../Partio.h" -namespace Partio{ +ENTER_PARTIO_NAMESPACE template class KdTree; @@ -112,5 +112,6 @@ class ParticlesSimpleInterleave:public ParticlesDataMutable, KdTree<3>* kdtree; }; -} +EXIT_PARTIO_NAMESPACE + #endif diff --git a/src/lib/io/3rdParty/nextLimit/FileReader.cpp b/src/lib/io/3rdParty/nextLimit/FileReader.cpp index e7a009ff..5397664c 100644 --- a/src/lib/io/3rdParty/nextLimit/FileReader.cpp +++ b/src/lib/io/3rdParty/nextLimit/FileReader.cpp @@ -15,6 +15,8 @@ static int64_t PGetFilePointer(FILE* fp) { return ftello64(fp); } #define FILE_READER_CACHE_SIZE (1024*1024) +ENTER_PARTIO_NAMESPACE + FileReader::FileReader() { m_fp = NULL; @@ -139,3 +141,5 @@ const void* FileReader::GetBuffer(uint32_t* availableBytes) *availableBytes = m_cacheLen - (int)cacheOffset; return m_cache + cacheOffset; } + +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/3rdParty/nextLimit/FileReader.h b/src/lib/io/3rdParty/nextLimit/FileReader.h index 635a74d5..688c5ac8 100644 --- a/src/lib/io/3rdParty/nextLimit/FileReader.h +++ b/src/lib/io/3rdParty/nextLimit/FileReader.h @@ -11,10 +11,14 @@ #define ZLIB_CONST #include "zlib.h" +#include "../../../PartioConfig.h" + #define HandleBufferEndianness16(buf, num) #define HandleBufferEndianness32(buf, num) #define HandleBufferEndianness64(buf, num) +ENTER_PARTIO_NAMESPACE + class FileReader { public: @@ -124,4 +128,6 @@ class FileReader int64_t m_fileSize; }; +EXIT_PARTIO_NAMESPACE + #endif diff --git a/src/lib/io/3rdParty/nextLimit/RPCReader.cpp b/src/lib/io/3rdParty/nextLimit/RPCReader.cpp index 99129561..9263c0a7 100644 --- a/src/lib/io/3rdParty/nextLimit/RPCReader.cpp +++ b/src/lib/io/3rdParty/nextLimit/RPCReader.cpp @@ -5,6 +5,8 @@ #define RPC_MIN_SUPPORTED_VERSION 3 #define RPC_MAX_SUPPORTED_VERSION 3 +ENTER_PARTIO_NAMESPACE + RPCFile::ChannelInfo::ChannelInfo() { m_name = NULL; @@ -346,3 +348,5 @@ void* RPCFile::ReadWholeChannel(const char* name) const int idx = FindChannelIndex(name); return (idx >= 0) ? ReadWholeChannel(idx) : NULL; } + +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/3rdParty/nextLimit/RPCReader.h b/src/lib/io/3rdParty/nextLimit/RPCReader.h index 8090b8e2..48d21a4f 100644 --- a/src/lib/io/3rdParty/nextLimit/RPCReader.h +++ b/src/lib/io/3rdParty/nextLimit/RPCReader.h @@ -9,6 +9,10 @@ #include #include +#include "../../../PartioConfig.h" + +ENTER_PARTIO_NAMESPACE + #define ZLIB_CONST #include "zlib.h" @@ -124,4 +128,6 @@ class RPCFile ChannelInfo* m_channels; }; +EXIT_PARTIO_NAMESPACE + #endif diff --git a/src/lib/io/BGEO.cpp b/src/lib/io/BGEO.cpp index 26022015..0643806a 100644 --- a/src/lib/io/BGEO.cpp +++ b/src/lib/io/BGEO.cpp @@ -43,8 +43,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include -namespace Partio -{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -316,4 +315,4 @@ bool writeBGEO(const char* filename,const ParticlesData& p,const bool compressed return true; } -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/BIN.cpp b/src/lib/io/BIN.cpp index a5c6ef05..e5d6d4bf 100644 --- a/src/lib/io/BIN.cpp +++ b/src/lib/io/BIN.cpp @@ -49,7 +49,7 @@ Modifications from: github user: redpawfx (redpawFX@gmail.com) and Luma Picture #include -namespace Partio{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -488,4 +488,4 @@ bool writeBIN(const char* filename,const ParticlesData& p,const bool /*compresse return true; } -}// end of namespace Partio +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/GEO.cpp b/src/lib/io/GEO.cpp index c1868283..a9fd63ab 100644 --- a/src/lib/io/GEO.cpp +++ b/src/lib/io/GEO.cpp @@ -44,8 +44,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include -namespace Partio -{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -326,4 +325,4 @@ bool writeGEO(const char* filename,const ParticlesData& p,const bool compressed) return true; } -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/MC.cpp b/src/lib/io/MC.cpp index b56416d3..ddd598fe 100644 --- a/src/lib/io/MC.cpp +++ b/src/lib/io/MC.cpp @@ -48,8 +48,7 @@ Modifications from: github user: redpawfx (redpawFX@gmail.com) and Luma Picture #include #include -namespace Partio -{ +ENTER_PARTIO_NAMESPACE //#define PartioBIG_ENDIAN using namespace std; @@ -363,4 +362,4 @@ int main(){ */ -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/NEW_BGEO.cpp b/src/lib/io/NEW_BGEO.cpp index 958709ba..4278611b 100644 --- a/src/lib/io/NEW_BGEO.cpp +++ b/src/lib/io/NEW_BGEO.cpp @@ -48,7 +48,7 @@ infringement. #include #include -namespace Partio{ +ENTER_PARTIO_NAMESPACE struct BGEOAttributeType:public JSONParser { @@ -329,7 +329,7 @@ struct BGEOMainParser:public JSONParser int64 pointcount,vertexcount,primitivecount; Partio::ParticlesDataMutable* particles; - BGEOMainParser(JSONParserState& state,::Partio::ParticlesDataMutable* particles) + BGEOMainParser(JSONParserState& state, ParticlesDataMutable* particles) :JSONParser(state),particles(particles) {} @@ -439,4 +439,4 @@ ParticlesDataMutable* testRead(const char* filename) return particles; } -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/PCD.cpp b/src/lib/io/PCD.cpp index 5d0efd22..8ccff66e 100644 --- a/src/lib/io/PCD.cpp +++ b/src/lib/io/PCD.cpp @@ -63,8 +63,7 @@ DATA ascii */ -namespace Partio -{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -430,4 +429,4 @@ bool writePCD(const char* filename,const ParticlesData& p,const bool compressed) } -} // namespace +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/PDA.cpp b/src/lib/io/PDA.cpp index 997901a5..e9105532 100644 --- a/src/lib/io/PDA.cpp +++ b/src/lib/io/PDA.cpp @@ -42,8 +42,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include -namespace Partio -{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -192,4 +191,4 @@ bool writePDA(const char* filename,const ParticlesData& p,const bool compressed) } -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/PDB.cpp b/src/lib/io/PDB.cpp index f8a7c804..332d031c 100644 --- a/src/lib/io/PDB.cpp +++ b/src/lib/io/PDB.cpp @@ -37,9 +37,7 @@ This code is partially based on the Gifts/readpdb directory of Autodesk Maya #include "../Partio.h" #include "../core/ParticleHeaders.h" -namespace PDB{ -#include "pdb.h" -} + #include "PartioEndian.h" #include "ZIP.h" #include @@ -48,8 +46,11 @@ namespace PDB{ #include #include #include -namespace Partio -{ +ENTER_PARTIO_NAMESPACE + +namespace PDB{ +#include "pdb.h" +} using namespace std; @@ -292,4 +293,4 @@ ParticlesDataMutable* readPDB(const char* filename,const bool headersOnly) bool writePDB(const char* filename,const ParticlesData& p,const bool compressed) {return writePDBHelper<32>(filename,p,compressed);} -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/PDC.cpp b/src/lib/io/PDC.cpp index 0f847d5c..19a9d526 100644 --- a/src/lib/io/PDC.cpp +++ b/src/lib/io/PDC.cpp @@ -47,7 +47,7 @@ Modifications from: github user: redpawfx (redpawFX@gmail.com) and Luma Picture #include #include -namespace Partio{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -185,4 +185,4 @@ bool writePDC(const char* filename,const ParticlesData& p,const bool compressed) return true; } -}// end of namespace Partio +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/PRT.cpp b/src/lib/io/PRT.cpp index 63bd03b3..8bdbcbbc 100644 --- a/src/lib/io/PRT.cpp +++ b/src/lib/io/PRT.cpp @@ -57,7 +57,7 @@ Modifications from: github user: redpawfx (redpawFX@gmail.com) and Luma Picture #include #include -namespace Partio{ +ENTER_PARTIO_NAMESPACE #define OUT_BUFSIZE (4096) @@ -418,5 +418,5 @@ bool writePRT(const char* filename,const ParticlesData& p,const bool /*compresse return true; } -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/PTC.cpp b/src/lib/io/PTC.cpp index d3ff5c63..85b378fb 100644 --- a/src/lib/io/PTC.cpp +++ b/src/lib/io/PTC.cpp @@ -47,8 +47,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include -namespace Partio -{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -371,4 +370,4 @@ bool writePTC(const char* filename,const ParticlesData& p,const bool compressed) return true; } -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/PTS.cpp b/src/lib/io/PTS.cpp index 29a635b3..34c23c9b 100644 --- a/src/lib/io/PTS.cpp +++ b/src/lib/io/PTS.cpp @@ -47,8 +47,7 @@ Some code for this format was helped along by referring to an implementation b #include #include -namespace Partio -{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -298,5 +297,5 @@ bool writePTS(const char* filename,const ParticlesData& p,const bool compressed) } */ -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/ParticleIO.cpp b/src/lib/io/ParticleIO.cpp index 229b2e67..d1d76d15 100644 --- a/src/lib/io/ParticleIO.cpp +++ b/src/lib/io/ParticleIO.cpp @@ -39,7 +39,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include "../Partio.h" #include "readers.h" -namespace Partio{ +ENTER_PARTIO_NAMESPACE using namespace std; // reader and writer code @@ -182,4 +182,4 @@ write(const char* c_filename,const ParticlesData& particles,const bool forceComp (*i->second)(c_filename,particles,forceCompressed || endsWithGz); } -} // namespace Partio +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/PartioBinaryJson.h b/src/lib/io/PartioBinaryJson.h index b139188d..301432a9 100644 --- a/src/lib/io/PartioBinaryJson.h +++ b/src/lib/io/PartioBinaryJson.h @@ -50,7 +50,7 @@ infringement. #include #include #include -namespace Partio{ +ENTER_PARTIO_NAMESPACE /// TODO: figure out what this isfor template @@ -491,4 +491,4 @@ struct PrintParser:public JSONParser } }; -} // namespace Partio +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/PartioEndian.h b/src/lib/io/PartioEndian.h index 693c2d39..37969d87 100644 --- a/src/lib/io/PartioEndian.h +++ b/src/lib/io/PartioEndian.h @@ -39,7 +39,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include -namespace Partio{ +#include "../PartioConfig.h" + +ENTER_PARTIO_NAMESPACE #ifdef PartioBIG_ENDIAN static const bool big_endian=true; @@ -125,5 +127,6 @@ template void write(std::ostream& output,const T1& d1,const T2& d2,const T3& d3,const T4& d4,const T5& d5,const T6& d6) {write(output,d1);write(output,d2,d3,d4,d5,d6);} -} +EXIT_PARTIO_NAMESPACE + #endif diff --git a/src/lib/io/RIB.cpp b/src/lib/io/RIB.cpp index a646e44d..3b2bc903 100644 --- a/src/lib/io/RIB.cpp +++ b/src/lib/io/RIB.cpp @@ -31,8 +31,7 @@ #include #include -namespace Partio -{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -149,4 +148,5 @@ bool writeRIB(const char* filename, const ParticlesData& p, const bool compresse return true; } -} + +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/RPC.cpp b/src/lib/io/RPC.cpp index 74f78a57..55660515 100644 --- a/src/lib/io/RPC.cpp +++ b/src/lib/io/RPC.cpp @@ -48,7 +48,7 @@ Some code for this format was helped along by referring to the official nextli #include -namespace Partio{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -288,5 +288,4 @@ bool writeRPC(const char* filename,const ParticlesData& p,const bool /*compresse return true; } - -}// end of namespace Partio +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/XYZ.cpp b/src/lib/io/XYZ.cpp index c7a3cd56..1b43a0c7 100644 --- a/src/lib/io/XYZ.cpp +++ b/src/lib/io/XYZ.cpp @@ -47,8 +47,7 @@ Some code for this format was helped along by referring to an implementation b #include #include -namespace Partio -{ +ENTER_PARTIO_NAMESPACE using namespace std; @@ -271,4 +270,4 @@ bool writePTS(const char* filename,const ParticlesData& p,const bool compressed) } */ -} +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/ZIP.cpp b/src/lib/io/ZIP.cpp index eb877086..bc4e4956 100644 --- a/src/lib/io/ZIP.cpp +++ b/src/lib/io/ZIP.cpp @@ -49,7 +49,7 @@ extern "C"{ #include "ZIP.h" -namespace Partio{ +ENTER_PARTIO_NAMESPACE @@ -616,4 +616,5 @@ Gzip_Out(const std::string& filename,std::ios::openmode mode) //##################################################################### #endif -} // namespace Partio + +EXIT_PARTIO_NAMESPACE diff --git a/src/lib/io/ZIP.h b/src/lib/io/ZIP.h index b4a68526..c3367850 100644 --- a/src/lib/io/ZIP.h +++ b/src/lib/io/ZIP.h @@ -41,8 +41,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include #include +#include "../PartioConfig.h" + +ENTER_PARTIO_NAMESPACE -namespace Partio{ struct ZipFileHeader; //##################################################################### // Functions Gzip_Out/Gzip_In - Create streams that read/write .gz @@ -83,5 +85,7 @@ class ZipFileReader bool Find_And_Read_Central_Header(); //##################################################################### }; -} + +EXIT_PARTIO_NAMESPACE + #endif diff --git a/src/lib/io/pdb.h b/src/lib/io/pdb.h index f7c01248..abd6ab46 100644 --- a/src/lib/io/pdb.h +++ b/src/lib/io/pdb.h @@ -45,7 +45,6 @@ difficult/error prone to detect what type the PDB file is. */ - #define PDB_VECTOR 1 #define PDB_REAL 2 #define PDB_LONG 3 @@ -159,4 +158,3 @@ typedef struct { unsigned int data; } PDB_Header32; - diff --git a/src/lib/io/readers.h b/src/lib/io/readers.h index 9a027eeb..1bb09883 100644 --- a/src/lib/io/readers.h +++ b/src/lib/io/readers.h @@ -35,7 +35,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #ifndef _READERS_h_ #define _READERS_h_ -namespace Partio{ +ENTER_PARTIO_NAMESPACE + ParticlesDataMutable* readBGEO (const char* filename,const bool headersOnly); ParticlesDataMutable* readGEO (const char* filename,const bool headersOnly); ParticlesDataMutable* readPDB (const char* filename,const bool headersOnly); @@ -65,6 +66,7 @@ bool writePRT (const char* filename,const ParticlesData& p,const bool compresse bool writeBIN (const char* filename,const ParticlesData& p,const bool compressed); bool writePCD (const char* filename,const ParticlesData& p,const bool compressed); //bool writeRPC (const char* filename,const ParticlesData& p,const bool compressed); -} + +EXIT_PARTIO_NAMESPACE #endif diff --git a/src/py/CMakeLists.txt b/src/py/CMakeLists.txt index bebd702d..840bc0c9 100644 --- a/src/py/CMakeLists.txt +++ b/src/py/CMakeLists.txt @@ -37,42 +37,48 @@ FIND_PACKAGE(NumPy) FIND_PACKAGE(SWIG) IF(SWIG_FOUND) -FIND_PACKAGE(PythonLibs) -IF(PYTHONLIBS_FOUND) + FIND_PACKAGE(PythonLibs) + IF(PYTHONLIBS_FOUND) + INCLUDE(${SWIG_USE_FILE}) -INCLUDE(${SWIG_USE_FILE}) + INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) -EXECUTE_PROCESS( COMMAND python -c "import sys;print" %s.%s "%sys.version_info[0:2]" OUTPUT_VARIABLE PYTHON_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE) + INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + IF(PARTIO_NAMESPACE) + SET(CMAKE_SWIG_FLAGS "-DPARTIO_NAMESPACE=${PARTIO_NAMESPACE}") + ELSE() + SET(CMAKE_SWIG_FLAGS "") + ENDIF() -INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) + SET_SOURCE_FILES_PROPERTIES(partio.i PROPERTIES CPLUSPLUS ON) -INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) + # This fails. not sure when it worked, but it gets overridden if numpy is found (CHAD) + #SET_SOURCE_FILES_PROPERTIES(partio.i + # PROPERTIES SWIG_FLAGS "-includeall -module _partio") -SET(CMAKE_SWIG_FLAGS "") + IF(NUMPY_FOUND) + INCLUDE_DIRECTORIES(${NUMPY_INCLUDE_DIRS}) + ADD_DEFINITIONS (-DPARTIO_USE_NUMPY) + SET_SOURCE_FILES_PROPERTIES(partio.i PROPERTIES SWIG_FLAGS "-DPARTIO_USE_NUMPY") + ENDIF(NUMPY_FOUND) -# setup output path -SET(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/py) -SET(CMAKE_SWIG_OUTDIR ${PROJECT_BINARY_DIR}/py) + SWIG_ADD_MODULE(partio python partio.i) + SWIG_LINK_LIBRARIES(partio ${PYTHON_LIBRARIES} ${ZLIB_LIBRARY} partio) -SET_SOURCE_FILES_PROPERTIES(partio.i PROPERTIES CPLUSPLUS ON) -SET_SOURCE_FILES_PROPERTIES(partio.i PROPERTIES SWIG_FLAGS "-includeall") + #EXECUTE_PROCESS( COMMAND python -c "import sys;print"%s.%s"%sys.version_info[0:2]" + # OUTPUT_VARIABLE PYTHON_VERSION + # OUTPUT_STRIP_TRAILING_WHITESPACE ) -IF(NUMPY_FOUND) - INCLUDE_DIRECTORIES(${NUMPY_INCLUDE_DIRS}) - ADD_DEFINITIONS (-DPARTIO_USE_NUMPY) - SET_SOURCE_FILES_PROPERTIES(partio.i PROPERTIES SWIG_FLAGS "-DPARTIO_USE_NUMPY") -ENDIF(NUMPY_FOUND) + #SET(PYTHON_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/py) + #SET(PYTHON_DEST ${PYTHON_OUTPUT_PATH}/${PARTIO_BUILD_PLATFORM}/python${PYTHON_VERSION}/site-packages ) -SWIG_ADD_MODULE(partio python partio.i) -SWIG_LINK_LIBRARIES(partio ${PYTHON_LIBRARIES} ${ZLIB_LIBRARY} partio) + INSTALL(TARGETS _partio + DESTINATION python) + FILE(GLOB PARTIO_PYTHON_MODULES "py/*.py") + INSTALL(FILES ${PARTIO_PYTHON_MODULES} + DESTINATION python) -SET(PYTHON_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/build-${PARTIO_BUILD_PLATFORM}/py) -SET(PYTHON_DEST ${PYTHON_OUTPUT_PATH}/${PARTIO_BUILD_PLATFORM}/python${PYTHON_VERSION}/site-packages ) - -INSTALL(TARGETS _partio DESTINATION ${PYTHON_DEST}) -INSTALL(FILES ${CMAKE_BINARY_DIR}/${outdir}/py/partio.py DESTINATION ${PYTHON_DEST}) - -ENDIF(PYTHONLIBS_FOUND) + ENDIF(PYTHONLIBS_FOUND) ENDIF(SWIG_FOUND) diff --git a/src/py/cmake/FindNumPy.cmake b/src/py/cmake/FindNumPy.cmake index 74ecb1a1..2180333c 100644 --- a/src/py/cmake/FindNumPy.cmake +++ b/src/py/cmake/FindNumPy.cmake @@ -62,30 +62,29 @@ if(NOT _NUMPY_SEARCH_SUCCESS MATCHES 0) "NumPy import failure:\n${_NUMPY_ERROR_VALUE}") endif() set(NUMPY_FOUND FALSE) -endif() - -# Convert the process output into a list -string(REGEX REPLACE ";" "\\\\;" _NUMPY_VALUES ${_NUMPY_VALUES}) -string(REGEX REPLACE "\n" ";" _NUMPY_VALUES ${_NUMPY_VALUES}) -list(GET _NUMPY_VALUES 0 NUMPY_VERSION) -list(GET _NUMPY_VALUES 1 NUMPY_INCLUDE_DIRS) - -# Make sure all directory separators are '/' -string(REGEX REPLACE "\\\\" "/" NUMPY_INCLUDE_DIRS ${NUMPY_INCLUDE_DIRS}) +else() + # Convert the process output into a list + string(REGEX REPLACE ";" "\\\\;" _NUMPY_VALUES ${_NUMPY_VALUES}) + string(REGEX REPLACE "\n" ";" _NUMPY_VALUES ${_NUMPY_VALUES}) + list(GET _NUMPY_VALUES 0 NUMPY_VERSION) + list(GET _NUMPY_VALUES 1 NUMPY_INCLUDE_DIRS) -# Get the major and minor version numbers -string(REGEX REPLACE "\\." ";" _NUMPY_VERSION_LIST ${NUMPY_VERSION}) -list(GET _NUMPY_VERSION_LIST 0 NUMPY_VERSION_MAJOR) -list(GET _NUMPY_VERSION_LIST 1 NUMPY_VERSION_MINOR) -list(GET _NUMPY_VERSION_LIST 2 NUMPY_VERSION_PATCH) -string(REGEX MATCH "[0-9]*" NUMPY_VERSION_PATCH ${NUMPY_VERSION_PATCH}) -math(EXPR NUMPY_VERSION_DECIMAL - "(${NUMPY_VERSION_MAJOR} * 10000) + (${NUMPY_VERSION_MINOR} * 100) + ${NUMPY_VERSION_PATCH}") + # Make sure all directory separators are '/' + string(REGEX REPLACE "\\\\" "/" NUMPY_INCLUDE_DIRS ${NUMPY_INCLUDE_DIRS}) -find_package_message(NUMPY - "Found NumPy: version \"${NUMPY_VERSION}\" ${NUMPY_INCLUDE_DIRS}" - "${NUMPY_INCLUDE_DIRS}${NUMPY_VERSION}") + # Get the major and minor version numbers + string(REGEX REPLACE "\\." ";" _NUMPY_VERSION_LIST ${NUMPY_VERSION}) + list(GET _NUMPY_VERSION_LIST 0 NUMPY_VERSION_MAJOR) + list(GET _NUMPY_VERSION_LIST 1 NUMPY_VERSION_MINOR) + list(GET _NUMPY_VERSION_LIST 2 NUMPY_VERSION_PATCH) + string(REGEX MATCH "[0-9]*" NUMPY_VERSION_PATCH ${NUMPY_VERSION_PATCH}) + math(EXPR NUMPY_VERSION_DECIMAL + "(${NUMPY_VERSION_MAJOR} * 10000) + (${NUMPY_VERSION_MINOR} * 100) + ${NUMPY_VERSION_PATCH}") -set(NUMPY_FOUND TRUE) -set(NUMPY_INCLUDE_DIR ${NUMPY_INCLUDE_DIRS} CACHE STRING "Numpy include path") + find_package_message(NUMPY + "Found NumPy: version \"${NUMPY_VERSION}\" ${NUMPY_INCLUDE_DIRS}" + "${NUMPY_INCLUDE_DIRS}${NUMPY_VERSION}") + set(NUMPY_FOUND TRUE) + set(NUMPY_INCLUDE_DIR ${NUMPY_INCLUDE_DIRS} CACHE STRING "Numpy include path") +endif() diff --git a/src/py/partio.i b/src/py/partio.i index 06d8e483..5155d9d0 100644 --- a/src/py/partio.i +++ b/src/py/partio.i @@ -42,20 +42,21 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #endif +#include #include #include -namespace Partio{ +ENTER_PARTIO_NAMESPACE typedef uint64_t ParticleIndex; -} +EXIT_PARTIO_NAMESPACE -using namespace Partio; +using namespace PARTIO; // This is for passing fixed sized arrays struct fixedFloatArray { int count; - Partio::ParticleAttributeType type; // should be float or VECTOR + ParticleAttributeType type; // should be float or VECTOR union{ float f[16]; int i[16]; @@ -63,8 +64,10 @@ struct fixedFloatArray }; %} -%init %{ +%init %{ +#ifdef PARTIO_USE_NUMPY import_array(); +#endif %} // Particle Types @@ -310,7 +313,6 @@ public: return PyArray_Return((PyArrayObject *)array); } -#endif %feature("autodoc"); %feature("docstring","Get"); @@ -344,6 +346,7 @@ public: return PyArray_Return((PyArrayObject *)array); } +#endif %feature("autodoc"); %feature("docstring","Gets a single flattened tuple, containing attribute data for all particles"); diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index a536e597..8a9ac0b4 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -34,5 +34,9 @@ foreach(item makecircle makeline jsontest) ADD_EXECUTABLE(${item} "${item}.cpp") TARGET_LINK_LIBRARIES(${item} ${PARTIO_LIBRARIES}) - INSTALL(TARGETS ${item} DESTINATION ${EXECUTABLE_INSTALL_PATH}) + IF (${LOCAL_INSTALL}) + INSTALL(TARGETS ${item} RUNTIME DESTINATION bin/${PARTIO_BUILD_PLATFORM}) + ELSE(${LOCAL_INSTALL}) + INSTALL(TARGETS ${item} RUNTIME DESTINATION bin) + ENDIF(${LOCAL_INSTALL}) endforeach(item) diff --git a/src/tests/jsontest.cpp b/src/tests/jsontest.cpp index ab4b5e2c..2f45766a 100644 --- a/src/tests/jsontest.cpp +++ b/src/tests/jsontest.cpp @@ -50,10 +50,10 @@ int main(int argc,char *argv[]){ std::cerr<<"Usage: "<"< -using namespace Partio; - int main(int argc,char *argv[]) { - ParticlesDataMutable* p=create(); - ParticleAttribute positionAttr=p->addAttribute("position",VECTOR,3); - ParticleAttribute normalAttr=p->addAttribute("normal",VECTOR,3); + PARTIO::ParticlesDataMutable* p=PARTIO::create(); + PARTIO::ParticleAttribute positionAttr=p->addAttribute("position",PARTIO::VECTOR,3); + PARTIO::ParticleAttribute normalAttr=p->addAttribute("normal",PARTIO::VECTOR,3); int n=30; for(int i=0;iaddParticle(); diff --git a/src/tests/makeline.cpp b/src/tests/makeline.cpp index 2af12e38..c9bb0b3e 100644 --- a/src/tests/makeline.cpp +++ b/src/tests/makeline.cpp @@ -40,35 +40,35 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. int main(int argc,char *argv[]) { - Partio::ParticlesDataMutable* particles=Partio::createInterleave(); + PARTIO::ParticlesDataMutable* particles=PARTIO::createInterleave(); particles->addParticles(10); - Partio::ParticleAttribute position=particles->addAttribute("position",Partio::VECTOR,3); - Partio::ParticleAttribute id=particles->addAttribute("id",Partio::INT,1); + PARTIO::ParticleAttribute position=particles->addAttribute("position",PARTIO::VECTOR,3); + PARTIO::ParticleAttribute id=particles->addAttribute("id",PARTIO::INT,1); // before adding additional attrs. you must ->begin() the iterator - Partio::ParticlesDataMutable::iterator it=particles->begin(); - Partio::ParticleAccessor positionAccess(position); + PARTIO::ParticlesDataMutable::iterator it=particles->begin(); + PARTIO::ParticleAccessor positionAccess(position); it.addAccessor(positionAccess); - Partio::ParticleAccessor idAccess(id); + PARTIO::ParticleAccessor idAccess(id); it.addAccessor(idAccess); float x=0; int idCounter=0; for(;it!=particles->end();++it){ - Partio::Data& P=positionAccess.data >(it); - Partio::Data& id=idAccess.data >(it); + PARTIO::Data& P=positionAccess.data >(it); + PARTIO::Data& id=idAccess.data >(it); P[0]=x;P[1]=-x;P[2]=0; id[0]=idCounter; x+=1.; idCounter++; } - Partio::write("test.bgeo",*particles); - Partio::write("test.geo",*particles); + PARTIO::write("test.bgeo",*particles); + PARTIO::write("test.geo",*particles); } diff --git a/src/tools/CMakeLists.txt b/src/tools/CMakeLists.txt index 7ed09b18..c0ba7fe8 100644 --- a/src/tools/CMakeLists.txt +++ b/src/tools/CMakeLists.txt @@ -34,14 +34,32 @@ include_directories( ${CMAKE_SOURCE_DIR}/src/lib ${GLUT_INCLUDE_PATH} + ${GLEW_INCLUDE_PATH} ) -IF(GLUT_FOUND AND OPENGL_FOUND) - INCLUDE_DIRECTORIES(${GLUT_INCLUDE_DIR} ${OPENGL_INCLUDE_DIR}) - ADD_EXECUTABLE(partview partview.cpp) - target_link_libraries(partview ${PARTIO_LIBRARIES} ${OPENGL_LIBRARY}) - install(TARGETS partview DESTINATION ${EXECUTABLE_INSTALL_PATH}) -ENDIF(GLUT_FOUND AND OPENGL_FOUND) +########################################################################## HDA +INCLUDE_DIRECTORIES(${GLEW_INCLUDE_DIR}) +########################################################################## HDA + +MESSAGE( STATUS "HDA #### GLUT_INCLUDE_PATH: " ${GLUT_INCLUDE_PATH} ) +MESSAGE( STATUS "HDA #### GLEW_INCLUDE_PATH: " ${GLEW_INCLUDE_PATH} ) +MESSAGE( STATUS "HDA #### GLUT_FOUND: " ${GLUT_FOUND} ) +MESSAGE( STATUS "HDA #### GLUT_INCLUDE_DIR: " ${GLUT_INCLUDE_DIR} ) +MESSAGE( STATUS "HDA #### GLUT_LIBRARY: " ${GLUT_LIBRARY} ) + +MESSAGE( STATUS "HDA BLA BLA BLA ....") + + +#IF(GLUT_FOUND AND OPENGL_FOUND) +# INCLUDE_DIRECTORIES(${GLUT_INCLUDE_DIR} ${OPENGL_INCLUDE_DIR}) +# ADD_EXECUTABLE(partview partview.cpp) +# target_link_libraries(partview ${PARTIO_LIBRARIES} ${GLUT_LIBRARY} ${OPENGL_LIBRARY}) +# IF (${LOCAL_INSTALL}) +# INSTALL(TARGETS partview RUNTIME DESTINATION bin/${PARTIO_BUILD_PLATFORM}) +# ELSE(${LOCAL_INSTALL}) +# INSTALL(TARGETS partview RUNTIME DESTINATION bin) +# ENDIF(${LOCAL_INSTALL}) +#ENDIF(GLUT_FOUND AND OPENGL_FOUND) ADD_EXECUTABLE(partinfo partinfo.cpp) target_link_libraries(partinfo ${PARTIO_LIBRARIES}) @@ -52,5 +70,10 @@ target_link_libraries(partconv ${PARTIO_LIBRARIES}) ADD_EXECUTABLE(partattr partattr.cpp) target_link_libraries(partattr ${PARTIO_LIBRARIES}) -INSTALL(TARGETS partattr partconv partinfo DESTINATION ${EXECUTABLE_INSTALL_PATH}) +IF (${LOCAL_INSTALL}) + INSTALL(TARGETS partattr partconv partinfo RUNTIME DESTINATION bin/${PARTIO_BUILD_PLATFORM}) +ELSE(${LOCAL_INSTALL}) + INSTALL(TARGETS partattr partconv partinfo RUNTIME DESTINATION bin) +ENDIF(${LOCAL_INSTALL}) + diff --git a/src/tools/partattr.cpp b/src/tools/partattr.cpp index c128b8e6..e5161f87 100644 --- a/src/tools/partattr.cpp +++ b/src/tools/partattr.cpp @@ -45,9 +45,9 @@ int main(int argc,char *argv[]) std::cerr<<"Usage is: "< { particle attribute to print info } "<attributeInfo(argv[2], attrhandle); for(int i = 0; i < std::min(10, p->numParticles()); i++){ diff --git a/src/tools/partconv.cpp b/src/tools/partconv.cpp index 0c7d364c..e5ac62c1 100644 --- a/src/tools/partconv.cpp +++ b/src/tools/partconv.cpp @@ -41,10 +41,10 @@ int main(int argc,char *argv[]) std::cerr<<"Usage is: "< "<release(); } diff --git a/src/tools/partinfo.cpp b/src/tools/partinfo.cpp index 13df70bb..16c41879 100644 --- a/src/tools/partinfo.cpp +++ b/src/tools/partinfo.cpp @@ -43,21 +43,21 @@ int main(int argc,char *argv[]) std::cerr<<"Usage is: "< { particle indices to print full info } "<numParticles()<numAttributes(); std::cout<attributeInfo(i,attr); - std::cout<attributeInfo("position",positionhandle); if(argc==2){ for(int i=0;inumParticles());i++){ @@ -73,14 +73,14 @@ int main(int argc,char *argv[]) std::cout<<"OUT OF RANGE"<attributeInfo(i,attr); - std::cout<data(attr,particleIndex)[ii]; std::cout<<" "<indexedStrs(attr)[val]<<"'"; - }else if(attr.type==Partio::INT) std::cout<<" "<data(attr,particleIndex)[ii]; + }else if(attr.type==PARTIO::INT) std::cout<<" "<data(attr,particleIndex)[ii]; else std::cout<<" "<data(attr,particleIndex)[ii]; } std::cout<=0) { - ParticlesData* newParticles; + PARTIO::ParticlesData* newParticles; newParticles = particles; particles = NULL; if (newParticles != NULL) @@ -524,7 +524,7 @@ void reloadParticleFile(int direction) //particles = particles->reset(); newParticles->release(); } - particles = read(particleFile.c_str()); + particles = PARTIO::read(particleFile.c_str()); if (!glutGetWindow()) { return; @@ -757,7 +757,7 @@ int buildPopupMenu() glutAddMenuEntry("None", -1); for (int i = 0; i < numAttr; i++) { - Partio::ParticleAttribute attr; + PARTIO::ParticleAttribute attr; particles->attributeInfo(i,attr); glutAddMenuEntry(attr.name.c_str(), i); } @@ -766,7 +766,7 @@ int buildPopupMenu() glutAddMenuEntry("None", -1); for (int i = 0; i < numAttr; i++) { - Partio::ParticleAttribute attr; + PARTIO::ParticleAttribute attr; particles->attributeInfo(i,attr); glutAddMenuEntry(attr.name.c_str(), i); } diff --git a/src/tools/partview.h b/src/tools/partview.h index ba48b6b7..fad0c179 100644 --- a/src/tools/partview.h +++ b/src/tools/partview.h @@ -51,16 +51,15 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. #include #include "Camera.h" -using namespace Partio; using namespace std; // global vars -ParticlesData* particles; +PARTIO::ParticlesData* particles; Camera camera; -ParticleAttribute positionAttr; -ParticleAttribute colorAttr; -ParticleAttribute alphaAttr; +PARTIO::ParticleAttribute positionAttr; +PARTIO::ParticleAttribute colorAttr; +PARTIO::ParticleAttribute alphaAttr; int numPoints; int frameNumberOGL; From 5f8af13b4518dacc3326a651503cc549ade4bff9 Mon Sep 17 00:00:00 2001 From: hda Date: Tue, 21 Mar 2017 15:10:13 +0100 Subject: [PATCH 8/9] rm partioGenerator.h (to be sync to the origin depot) --- .../procedurals/partioGenerator.h | 49 ------------------- 1 file changed, 49 deletions(-) delete mode 100644 contrib/partio4Arnold/procedurals/partioGenerator.h diff --git a/contrib/partio4Arnold/procedurals/partioGenerator.h b/contrib/partio4Arnold/procedurals/partioGenerator.h deleted file mode 100644 index 701da386..00000000 --- a/contrib/partio4Arnold/procedurals/partioGenerator.h +++ /dev/null @@ -1,49 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////////// -/// PARTIO GENERATOR an arnold procedural cache reader that uses the partio Library -/// by John Cassella (redpawfx) for Luma Pictures (c) 2012 - - -#include "ai.h" -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - - -// global variables for procedural -float arg_radius; -float arg_maxParticleRadius; -float arg_radiusMult; -const char* arg_file; -int arg_renderType; -bool arg_overrideRadiusPP; -const char* arg_rgbFrom; -const char* arg_incandFrom; -const char* arg_opacFrom; -const char* arg_radFrom; -AtRGB arg_defaultColor; -float arg_defaultOpac; -float arg_stepSize; - -float arg_motionBlurMult; -const char* arg_extraPPAttrs; -float global_motionByFrame; -float global_fps; -int global_motionBlurSteps; -Partio::ParticlesDataMutable* points; -Partio::ParticleAttribute positionAttr; -Partio::ParticleAttribute velocityAttr; -Partio::ParticleAttribute rgbAttr; -Partio::ParticleAttribute opacityAttr; -Partio::ParticleAttribute radiusAttr; -Partio::ParticleAttribute incandAttr; -int pointCount; -bool cacheExists; -bool canMotionBlur, hasRadiusPP, hasRgbPP,hasOpacPP, hasIncandPP; From f1d2c08677a02fa459d975b4202ecf35fb8a9af1 Mon Sep 17 00:00:00 2001 From: hda Date: Wed, 22 Mar 2017 10:59:25 +0100 Subject: [PATCH 9/9] miscs on the translator --- build.sh | 4 ++-- .../plugin/PartioVizTranslator.cpp | 21 ++++++++----------- contrib/partio4Arnold/plugin/plugin.cpp | 7 +++++-- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/build.sh b/build.sh index fa2272aa..b1eebf8d 100755 --- a/build.sh +++ b/build.sh @@ -8,8 +8,8 @@ build_type=Release #mayaVersions=(2015.sp6) #2014.sp4 do not build #mayaVersions=(2016.sp6) #2014.sp4 do not build -mayaVersions=(ext2.2016.sp1) -#mayaVersions=(2017.0.0) +#mayaVersions=(ext2.2016.sp1) +mayaVersions=(2017.0.0) ##################################################################### diff --git a/contrib/partio4Arnold/plugin/PartioVizTranslator.cpp b/contrib/partio4Arnold/plugin/PartioVizTranslator.cpp index 1ce3f8fe..e5f2f3a0 100644 --- a/contrib/partio4Arnold/plugin/PartioVizTranslator.cpp +++ b/contrib/partio4Arnold/plugin/PartioVizTranslator.cpp @@ -22,9 +22,7 @@ void* CPartioVizTranslator::creator() void CPartioVizTranslator::NodeInitializer(CAbTranslator context) { - MGlobal::displayInfo("@@@@@@@@@@  CPartioVizTranslator::NodeInitializer"); - - + MGlobal::displayInfo("CPartioVizTranslator::NodeInitializer"); CExtensionAttrHelper helper(context.maya, "procedural"); CShapeTranslator::MakeCommonAttributes(helper); @@ -113,13 +111,13 @@ void CPartioVizTranslator::NodeInitializer(CAbTranslator context) AtNode* CPartioVizTranslator::CreateArnoldNodes() { - cout << "CreateArnoldNodes" << endl; + cout << "CPartioVizTranslator::CreateArnoldNodes" << endl; return IsMasterInstance() ? AddArnoldNode("procedural") : AddArnoldNode("ginstance"); } void CPartioVizTranslator::Export(AtNode* anode) { - cout << "Export" << endl; + cout << "CPartioVizTranslator::Export" << endl; if (AiNodeIs(anode, "ginstance")) ExportInstance(anode, GetMasterInstance()); else @@ -128,7 +126,7 @@ void CPartioVizTranslator::Export(AtNode* anode) void CPartioVizTranslator::ExportMotion(AtNode* anode) { - cout << "ExportMotion" << endl; + cout << "CPartioVizTranslator::ExportMotion" << endl; ExportMatrix(anode); } @@ -141,7 +139,7 @@ void CPartioVizTranslator::Update(AtNode* anode) // AtNode* CPartioVizTranslator::ExportInstance(AtNode* instance, const MDagPath& masterInstance) { - cout << "ExportInstance" << endl; + cout << "CPartioVizTranslator::ExportInstance" << endl; AtNode* masterNode = AiNodeLookUpByName(masterInstance.partialPathName().asChar()); AiNodeSetStr(instance, "name", m_dagPath.partialPathName().asChar()); @@ -164,7 +162,7 @@ AtNode* CPartioVizTranslator::ExportInstance(AtNode* instance, const MDagPath& m void CPartioVizTranslator::ExportShaders() { - cout << "ExportShaders" << endl; + cout << "CPartioVizTranslator::ExportShaders" << endl; AiMsgWarning("[mtoa] Shaders untested with new multitranslator and standin code."); /// TODO: Test shaders with standins. //ExportPartioVizShaders(GetArnoldRootNode()); @@ -173,7 +171,7 @@ void CPartioVizTranslator::ExportShaders() void CPartioVizTranslator::ExportPartioVizShaders(AtNode* procedural) { - cout << "ExportPartioVizShaders" << endl; + cout << "CPartioVizTranslator::ExportPartioVizShaders" << endl; int instanceNum = m_dagPath.isInstanced() ? m_dagPath.instanceNumber() : 0; std::vector meshShaders; @@ -202,7 +200,7 @@ void CPartioVizTranslator::ExportPartioVizShaders(AtNode* procedural) // THIS MAY NOT REALLY BE NEEDED ANYMORE BUT LEAVING IT FOR NOW void CPartioVizTranslator::ExportBoundingBox(AtNode* procedural) { - cout << "ExportBoundingBox" << endl; + cout << "CPartioVizTranslator::ExportBoundingBox" << endl; MBoundingBox boundingBox = m_DagNode.boundingBox(); MPoint bbMin = boundingBox.min(); MPoint bbMax = boundingBox.max(); @@ -221,7 +219,7 @@ void CPartioVizTranslator::ExportBoundingBox(AtNode* procedural) AtNode* CPartioVizTranslator::ExportProcedural(AtNode* procedural, bool update) { - cout << "ExportProcedural" << endl; + cout << "CPartioVizTranslator::ExportProcedural" << endl; m_DagNode.setObject(m_dagPath.node()); AiNodeSetStr(procedural, "name", m_dagPath.partialPathName().asChar()); @@ -418,4 +416,3 @@ bool CPartioVizTranslator::fileCacheExists(const char* fileName) return (statReturn); } - diff --git a/contrib/partio4Arnold/plugin/plugin.cpp b/contrib/partio4Arnold/plugin/plugin.cpp index 3ac9b280..8673d893 100644 --- a/contrib/partio4Arnold/plugin/plugin.cpp +++ b/contrib/partio4Arnold/plugin/plugin.cpp @@ -25,9 +25,12 @@ extern "C" { -DLLEXPORT void initializeExtension(CExtension &plugin) +DLLEXPORT void initializeExtension(CExtension& extension) { - plugin.RegisterTranslator("partioVisualizer", + MStatus status; + extension.Requires("partio4Maya"); + + status = extension.RegisterTranslator("partioVisualizer", "", CPartioVizTranslator::creator, CPartioVizTranslator::NodeInitializer);