Merge pull request #12 from assimp/master

Update Fork
pull/1350/head
Madrich 2017-06-18 23:16:00 +02:00 committed by GitHub
commit 1eca19b400
874 changed files with 152758 additions and 30849 deletions

2
.coveralls.yml 100644
View File

@ -0,0 +1,2 @@
service_name: travis-pro
repo_token: GZXuNlublKFy7HAewHAZLk5ZwgipTFAOA

7
.gitattributes vendored
View File

@ -2,7 +2,14 @@
*.cpp text eol=lf *.cpp text eol=lf
*.h text eol=lf *.h text eol=lf
*.c text eol=lf *.c text eol=lf
*.cc text eol=lf
*.cpp text eol=lf
*.rc text eol=lf
*.hpp text eol=lf *.hpp text eol=lf
*.txt text eol=lf *.txt text eol=lf
*.cmake text eol=lf *.cmake text eol=lf
*.sh text eol=lf *.sh text eol=lf
CHANGES text eol=lf
CREDITS text eol=lf
LICENSE text eol=lf
Readme.md text eol=lf

7
.gitignore vendored
View File

@ -29,6 +29,13 @@ cmake_uninstall.cmake
assimp-config.cmake assimp-config.cmake
assimp-config-version.cmake assimp-config-version.cmake
# MakeFile
Makefile
code/Makefile
test/Makefile
test/headercheck/Makefile
tools/assimp_cmd/Makefile
# Tests # Tests
test/results test/results

View File

@ -1,13 +1,14 @@
function generate() function generate()
{ {
cmake -G "Unix Makefiles" -DASSIMP_ENABLE_BOOST_WORKAROUND=YES -DASSIMP_NO_EXPORT=$TRAVIS_NO_EXPORT -DBUILD_SHARED_LIBS=$SHARED_BUILD cmake -G "Unix Makefiles" -DASSIMP_NO_EXPORT=$TRAVIS_NO_EXPORT -DBUILD_SHARED_LIBS=$SHARED_BUILD -DASSIMP_COVERALLS=$ENABLE_COVERALLS
} }
if [ $ANDROID ]; then if [ $ANDROID ]; then
ant -v -Dmy.dir=${TRAVIS_BUILD_DIR} -f ${TRAVIS_BUILD_DIR}/port/jassimp/build.xml ndk-jni ant -v -Dmy.dir=${TRAVIS_BUILD_DIR} -f ${TRAVIS_BUILD_DIR}/port/jassimp/build.xml ndk-jni
else fi
if [ "$TRAVIS_OS_NAME" = "linux" ]; then
generate \ generate \
&& make \ && make -j4 \
&& sudo make install \ && sudo make install \
&& sudo ldconfig \ && sudo ldconfig \
&& (cd test/unit; ../../bin/unit) \ && (cd test/unit; ../../bin/unit) \

View File

@ -1,25 +1,33 @@
sudo: required
language: cpp
before_install: before_install:
- sudo apt-get update -qq - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo apt-get update -qq && sudo apt-get install cmake && sudo apt-get install cmake python3 && sudo apt-get install -qq freeglut3-dev libxmu-dev libxi-dev ; fi
- sudo apt-get install cmake python3 - if [ "$TRAVIS_OS_NAME" = "osx" ]; then brew install cmake python3 homebrew/x11/freeglut; fi
- if [ $LINUX ]; then sudo apt-get install -qq freeglut3-dev libxmu-dev libxi-dev ; fi
- echo -e "#ifndef A_R_H_INC\n#define A_R_H_INC\n#define GitVersion ${TRAVIS_JOB_ID}\n#define GitBranch \"${TRAVIS_BRANCH}\"\n#endif // A_R_H_INC" > revision.h - echo -e "#ifndef A_R_H_INC\n#define A_R_H_INC\n#define GitVersion ${TRAVIS_JOB_ID}\n#define GitBranch \"${TRAVIS_BRANCH}\"\n#endif // A_R_H_INC" > revision.h
# install latest LCOV (1.9 was failing)
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then cd ${TRAVIS_BUILD_DIR} && wget http://ftp.de.debian.org/debian/pool/main/l/lcov/lcov_1.11.orig.tar.gz && tar xf lcov_1.11.orig.tar.gz && sudo make -C lcov-1.11/ install && gem install coveralls-lcov && lcov --version && g++ --version ; fi
branches: branches:
only: only:
- master - master
osx_image: xcode8.3
env: env:
global: global:
- secure: "lZ7pHQvl5dpZWzBQAaIMf0wqrvtcZ4wiZKeIZjf83TEsflW8+z0uTpIuN30ZV6Glth/Sq1OhLnTP5+N57fZU/1ebA5twHdvP4bS5CIUUg71/CXQZNl36xeaqvxsG/xRrdpKOsPdjAOsQ9KPTQulsX43XDLS7CasMiLvYOpqKcPc="
- PV=r8e PLATF=linux-x86_64 NDK_HOME=${TRAVIS_BUILD_DIR}/android-ndk-${PV} PATH=${PATH}:${NDK_HOME} - PV=r8e PLATF=linux-x86_64 NDK_HOME=${TRAVIS_BUILD_DIR}/android-ndk-${PV} PATH=${PATH}:${NDK_HOME}
matrix: matrix:
- LINUX=1 TRAVIS_NO_EXPORT=YES - LINUX=1 TRAVIS_NO_EXPORT=YES ENABLE_COVERALLS=ON
- LINUX=1 TRAVIS_NO_EXPORT=NO - LINUX=1 TRAVIS_NO_EXPORT=NO ENABLE_COVERALLS=OFF
- LINUX=1 SHARED_BUILD=ON - LINUX=1 SHARED_BUILD=ON ENABLE_COVERALLS=OFF
- LINUX=1 SHARED_BUILD=OFF - LINUX=1 SHARED_BUILD=OFF ENABLE_COVERALLS=OFF
- ANDROID=1 #exclude:
# - os: linux
language: cpp # compiler: clang
# - os: osx
# compiler: gcc
compiler: compiler:
- gcc - gcc
- clang - clang
@ -27,5 +35,26 @@ compiler:
install: install:
- if [ $ANDROID ]; then wget -c http://dl.google.com/android/ndk/android-ndk-${PV}-${PLATF}.tar.bz2 && tar xf android-ndk-${PV}-${PLATF}.tar.bz2 ; fi - if [ $ANDROID ]; then wget -c http://dl.google.com/android/ndk/android-ndk-${PV}-${PLATF}.tar.bz2 && tar xf android-ndk-${PV}-${PLATF}.tar.bz2 ; fi
before_script:
# init coverage to 0 (optional)
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then cd ${TRAVIS_BUILD_DIR} && lcov --directory . --zerocounters ; fi
script: script:
- export COVERALLS_SERVICE_NAME=travis-ci
- export COVERALLS_REPO_TOKEN=abc12345
- . ./.travis.sh - . ./.travis.sh
os:
- linux
- osx
after_success:
- if [ "$TRAVIS_OS_NAME" = "linux" ]; then cd ${TRAVIS_BUILD_DIR} && lcov --directory . --capture --output-file coverage.info && lcov --remove coverage.info '/usr/*' 'contrib/*' 'test/*' --output-file coverage.info && lcov --list coverage.info && coveralls-lcov --source-encoding=ISO-8859-1 --repo-token=${COVERALLS_TOKEN} coverage.info ; fi
addons:
coverity_scan:
project:
name: "assimp/assimp"
notification_email: kim.kulling@googlemail.com
build_command_prepend: "cmake"
build_command: "make"
branch_pattern: coverity_scan

362
CHANGES
View File

@ -1,157 +1,205 @@
---------------------------------------------------------------------- ----------------------------------------------------------------------
CHANGELOG CHANGELOG
---------------------------------------------------------------------- ----------------------------------------------------------------------
3.2.0 (2015-11-03) 3.3.1 (2016-07-08)
FEATURES: FIXES/HOUSEKEEPING:
- OpenDDL-Parser is part of contrib-source. - Setup of default precision for 17 exporters
- Experimental OpenGEX-support - Fix xcode project files
- CI-check for linux and windows - Fix BlenderTesselator: offsetof operator
- Coverity check added - Invalid version in cmake file
- New regression testsuite. - Update pstdint.h to latest greatest
FIXES/HOUSEKEEPING:
- Hundreds of bugfixes in all parts of the library 3.3.0 (2016-07-05)
- Unified line endings
FEATURES:
- C++11 support enabled
API COMPATIBILITY: - New regression-test-UI
- Removed precompiled header to increase build speed for linux - Experimental glTF-importer support
- OpenGEX: add support for cameras and lights
- C4D: update to latest Melange-SDK
3.1.1 (2014-06-15) - Add a gitter channel
- Coverity check enabled
FEATURES: - Switch to <...> include brackets for public headers
- Support for FBX 2013 and newer, binary and ASCII (this is partly - Enable export by pyAssimp
work from Google Summer of Code 2012) - CI: check windows build
- Support for OGRE binary mesh and skeleton format - Add functionality to perform a singlepost-processing step
- Updated BLEND support for newer Blender versions - many more, just check the history
- Support for arbitrary meta data, used to hold FBX and DAE metadata
- OBJ Export now produces smaller files FIXES/HOUSEKEEPING:
- Meshes can now have names, this is supported by the major importers - Fix of many resource leaks in unittests and main lib
- Improved IFC geometry generation - Fix iOS-buildfor X64
- M3 support has been removed - Choosing zlib manually for cmake
- many more, just check the history
FIXES/HOUSEKEEPING:
- Hundreds of bugfixes in all parts of the library
- CMake is now the primary build system 3.2.1 (2016-010-10)
API COMPATIBILITY: FEATURES:
- 3.1.1 is not binary compatible to 3.0 due to aiNode::mMetaData - Updated glTF exporter to meet 1.0 specification.
and aiMesh::mName
- Export interface has been cleaned up and unified FIXES/HOUSEKEEPING:
- Other than that no relevant changes - Fixed glTF Validator errors for exported glTF format.
ISSUES:
3.0 (2012-07-07) - Hard coded sampler setting for
- magFilter
FEATURES: - minFilter
- new export interface similar to the import API. - void* in ExportData for accessor max and min.
- Supported export formats: Collada, OBJ, PLY and STL
- added new import formats: XGL/ZGL, M3 (experimental)
- new postprocessing steps: Debone 3.2.0 (2015-11-03)
- vastly improved IFC (Industry Foundation Classes) support
- introduced API to query importer meta information (such as supported FEATURES:
format versions, full name, maintainer info). - OpenDDL-Parser is part of contrib-source.
- reworked Ogre XML import - Experimental OpenGEX-support
- C-API now supports per-import properties - CI-check for linux and windows
- Coverity check added
FIXES/HOUSEKEEPING: - New regression testsuite.
- hundreds of bugfixes in all parts of the library FIXES/HOUSEKEEPING:
- unified naming and cleanup of public headers - Hundreds of bugfixes in all parts of the library
- improved CMake build system - Unified line endings
- templatized math library
- reduce dependency on boost.thread, only remaining spot
is synchronization for the C logging API API COMPATIBILITY:
- Removed precompiled header to increase build speed for linux
API COMPATIBILITY:
- renamed headers, export interface, C API properties and meta data
prevent compatibility with code written for 2.0, but in 3.1.1 (2014-06-15)
most cases these can be easily resolved
- Note: 3.0 is not binary compatible with 2.0 FEATURES:
- Support for FBX 2013 and newer, binary and ASCII (this is partly
work from Google Summer of Code 2012)
- Support for OGRE binary mesh and skeleton format
- Updated BLEND support for newer Blender versions
2.0 (2010-11-21) - Support for arbitrary meta data, used to hold FBX and DAE metadata
- OBJ Export now produces smaller files
FEATURES: - Meshes can now have names, this is supported by the major importers
- Add support for static Blender (*.blend) scenes - Improved IFC geometry generation
- Add support for Q3BSP scenes - M3 support has been removed
- Add a windows-based OpenGL sample featuring texturing & basic materials
- Add an experimental progress feedback interface. FIXES/HOUSEKEEPING:
- Vastly improved performance (up to 500%, depending on mesh size and - Hundreds of bugfixes in all parts of the library
spatial structure) in some expensive postprocessing steps - CMake is now the primary build system
- AssimpView now uses a reworked layout which leaves more space
to the scene hierarchy window API COMPATIBILITY:
- 3.1.1 is not binary compatible to 3.0 due to aiNode::mMetaData
- Add C# bindings ('Assimp.NET') and aiMesh::mName
- Keep BSD-licensed and otherwise free test files in separate - Export interface has been cleaned up and unified
folders (./test/models and ./test/models-nonbsd). - Other than that no relevant changes
FIXES:
- Many Collada bugfixes, improve fault tolerance 3.0 (2012-07-07)
- Fix possible crashes in the Obj loader
- Improve the Ogre XML loader FEATURES:
- OpenGL-sample now works with MinGW - new export interface similar to the import API.
- Fix Importer::FindLoader failing on uppercase file extensions - Supported export formats: Collada, OBJ, PLY and STL
- Fix flawed path handling when locating external files - added new import formats: XGL/ZGL, M3 (experimental)
- Limit the maximum number of vertices, faces, face indices and - new postprocessing steps: Debone
weights that Assimp is able to handle. This is to avoid - vastly improved IFC (Industry Foundation Classes) support
crashes due to overflowing counters. - introduced API to query importer meta information (such as supported
format versions, full name, maintainer info).
- Updated XCode project files - reworked Ogre XML import
- Further CMAKE build improvements - C-API now supports per-import properties
FIXES/HOUSEKEEPING:
API CHANGES:
- Add data structures for vertex-based animations (These are not - hundreds of bugfixes in all parts of the library
currently used, however ...) - unified naming and cleanup of public headers
- Some Assimp::Importer methods are const now. - improved CMake build system
- templatized math library
- reduce dependency on boost.thread, only remaining spot
is synchronization for the C logging API
API COMPATIBILITY:
1.1 (2010-04-17) - renamed headers, export interface, C API properties and meta data
This is the list of relevant changes from the 1.0 (r412) release to 1.1 (r700). prevent compatibility with code written for 2.0, but in
most cases these can be easily resolved
FEATURES: - Note: 3.0 is not binary compatible with 2.0
- Vastly improved Collada support
- Add MS3D (Milkshape 3D) support
- Add support for Ogre XML static meshes
- Add experimental COB (TrueSpace) support
- Automatic test suite to quickly locate regressions 2.0 (2010-11-21)
- D bindings (`dAssimp`)
- Python 2.n bindings (`PyAssimp`) FEATURES:
- Add basic support for Unicode input files (utf8, utf16 and utf32) - Add support for static Blender (*.blend) scenes
- Add further utilities to the `assimp` tool (xml/binary dumps, quick file stats) - Add support for Q3BSP scenes
- Switch to a CMAKE-based build system including an install target for unix'es - Add a windows-based OpenGL sample featuring texturing & basic materials
- Automatic evaluation of subdivision surfaces for some formats. - Add an experimental progress feedback interface.
- Add `Importer::ReadFileFromMemory` and the corresponding C-API `aiReadFileFromMemory` - Vastly improved performance (up to 500%, depending on mesh size and
- Expose further math utilities via the C-API (i.e. `aiMultiplyMatrix4`) spatial structure) in some expensive postprocessing steps
- AssimpView now uses a reworked layout which leaves more space
- Move noboost files away from the public include directory to the scene hierarchy window
- Many, many bugfixes and improvements in existing loaders and postprocessing steps
- Documentation improved and clarified in many places. - Add C# bindings ('Assimp.NET')
- Add a sample on using Assimp in conjunction with OpenGL - Keep BSD-licensed and otherwise free test files in separate
folders (./test/models and ./test/models-nonbsd).
- Distribution/packaging: comfortable SDK installer for Windows
- Distribution/packaging: improved release packages for other architectures FIXES:
- Many Collada bugfixes, improve fault tolerance
CRITICAL FIXES: - Fix possible crashes in the Obj loader
- Resolve problems with clashing heap managers, STL ABIs and runtime libraries (win32) - Improve the Ogre XML loader
- Fix automatic detection of file type if no file extension is given - OpenGL-sample now works with MinGW
- Improved exception safety and robustness, prevent leaking of exceptions through the C interface - Fix Importer::FindLoader failing on uppercase file extensions
- Fix possible heap corruption due to material properties pulled in incorrectly - Fix flawed path handling when locating external files
- Avoid leaking in certain error scenarios - Limit the maximum number of vertices, faces, face indices and
- Fix 64 bit compatibility problems in some loaders (i.e. MDL) weights that Assimp is able to handle. This is to avoid
crashes due to overflowing counters.
BREAKING API CHANGES:
- None - - Updated XCode project files
- Further CMAKE build improvements
MINOR API BEHAVIOUR CHANGES:
- Change quaternion orientation to suit to the more common convention (-w).
- aiString is utf8 now. Not yet consistent, however. API CHANGES:
- Add data structures for vertex-based animations (These are not
currently used, however ...)
- Some Assimp::Importer methods are const now.
1.1 (2010-04-17)
This is the list of relevant changes from the 1.0 (r412) release to 1.1 (r700).
FEATURES:
- Vastly improved Collada support
- Add MS3D (Milkshape 3D) support
- Add support for Ogre XML static meshes
- Add experimental COB (TrueSpace) support
- Automatic test suite to quickly locate regressions
- D bindings (`dAssimp`)
- Python 2.n bindings (`PyAssimp`)
- Add basic support for Unicode input files (utf8, utf16 and utf32)
- Add further utilities to the `assimp` tool (xml/binary dumps, quick file stats)
- Switch to a CMAKE-based build system including an install target for unix'es
- Automatic evaluation of subdivision surfaces for some formats.
- Add `Importer::ReadFileFromMemory` and the corresponding C-API `aiReadFileFromMemory`
- Expose further math utilities via the C-API (i.e. `aiMultiplyMatrix4`)
- Move noboost files away from the public include directory
- Many, many bugfixes and improvements in existing loaders and postprocessing steps
- Documentation improved and clarified in many places.
- Add a sample on using Assimp in conjunction with OpenGL
- Distribution/packaging: comfortable SDK installer for Windows
- Distribution/packaging: improved release packages for other architectures
CRITICAL FIXES:
- Resolve problems with clashing heap managers, STL ABIs and runtime libraries (win32)
- Fix automatic detection of file type if no file extension is given
- Improved exception safety and robustness, prevent leaking of exceptions through the C interface
- Fix possible heap corruption due to material properties pulled in incorrectly
- Avoid leaking in certain error scenarios
- Fix 64 bit compatibility problems in some loaders (i.e. MDL)
BREAKING API CHANGES:
- None -
MINOR API BEHAVIOUR CHANGES:
- Change quaternion orientation to suit to the more common convention (-w).
- aiString is utf8 now. Not yet consistent, however.

View File

@ -1,7 +1,6 @@
# Open Asset Import Library (assimp) # Open Asset Import Library (assimp)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# # Copyright (c) 2006-2017, assimp team
# Copyright (c) 2006-2016, assimp team
# All rights reserved. # All rights reserved.
# #
# Redistribution and use of this software in source and binary forms, # Redistribution and use of this software in source and binary forms,
@ -33,13 +32,75 @@
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#---------------------------------------------------------------------- #----------------------------------------------------------------------
SET(CMAKE_LEGACY_CYGWIN_WIN32 0) # Remove when CMake >= 2.8.4 is required SET(CMAKE_LEGACY_CYGWIN_WIN32 0) # Remove when CMake >= 2.8.4 is required
cmake_minimum_required( VERSION 2.8 ) cmake_minimum_required( VERSION 2.8 )
PROJECT( Assimp ) PROJECT( Assimp )
OPTION(BUILD_SHARED_LIBS "Build package with shared libraries." ON) # All supported options ###############################################
OPTION( BUILD_SHARED_LIBS
"Build package with shared libraries."
ON
)
OPTION( ASSIMP_DOUBLE_PRECISION
"Set to ON to enable double precision processing"
OFF
)
OPTION( ASSIMP_OPT_BUILD_PACKAGES
"Set to ON to generate CPack configuration files and packaging targets"
OFF
)
OPTION( ASSIMP_ANDROID_JNIIOSYSTEM
"Android JNI IOSystem support is active"
OFF
)
OPTION( ASSIMP_NO_EXPORT
"Disable Assimp's export functionality."
OFF
)
OPTION( ASSIMP_BUILD_ZLIB
"Build your own zlib"
OFF
)
option( ASSIMP_BUILD_ASSIMP_TOOLS
"If the supplementary tools for Assimp are built in addition to the library."
ON
)
option ( ASSIMP_BUILD_SAMPLES
"If the official samples are built as well (needs Glut)."
OFF
)
OPTION ( ASSIMP_BUILD_TESTS
"If the test suite for Assimp is built in addition to the library."
ON
)
OPTION ( ASSIMP_COVERALLS
"Eańable this to measure test coverage."
OFF
)
option ( SYSTEM_IRRXML
"Use system installed Irrlicht/IrrXML library."
OFF
)
OPTION ( BUILD_DOCS
"Build documentation using Doxygen."
OFF
)
if (WIN32)
add_definitions( -DWIN32_LEAN_AND_MEAN )
endif()
IF(MSVC)
set (CMAKE_PREFIX_PATH "D:\\libs\\devil")
OPTION( ASSIMP_INSTALL_PDB
"Install MSVC debug files."
ON
)
ENDIF(MSVC)
IF(NOT BUILD_SHARED_LIBS) IF(NOT BUILD_SHARED_LIBS)
SET(LINK_SEARCH_START_STATIC TRUE) SET(LINK_SEARCH_START_STATIC TRUE)
ENDIF(NOT BUILD_SHARED_LIBS) ENDIF(NOT BUILD_SHARED_LIBS)
@ -80,15 +141,17 @@ IF(NOT GIT_COMMIT_HASH)
SET(GIT_COMMIT_HASH 0) SET(GIT_COMMIT_HASH 0)
ENDIF(NOT GIT_COMMIT_HASH) ENDIF(NOT GIT_COMMIT_HASH)
OPTION(ASSIMP_DOUBLE_PRECISION
"Set to ON to enable double precision processing"
OFF
)
IF(ASSIMP_DOUBLE_PRECISION) IF(ASSIMP_DOUBLE_PRECISION)
ADD_DEFINITIONS(-DAI_DOUBLE_PRECISION) ADD_DEFINITIONS(-DASSIMP_DOUBLE_PRECISION)
ENDIF(ASSIMP_DOUBLE_PRECISION) ENDIF(ASSIMP_DOUBLE_PRECISION)
# Check for OpenMP support
find_package(OpenMP)
if (OPENMP_FOUND)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
endif()
configure_file( configure_file(
${CMAKE_CURRENT_LIST_DIR}/revision.h.in ${CMAKE_CURRENT_LIST_DIR}/revision.h.in
${CMAKE_CURRENT_BINARY_DIR}/revision.h ${CMAKE_CURRENT_BINARY_DIR}/revision.h
@ -96,7 +159,7 @@ configure_file(
configure_file( configure_file(
${CMAKE_CURRENT_LIST_DIR}/include/assimp/config.h.in ${CMAKE_CURRENT_LIST_DIR}/include/assimp/config.h.in
${CMAKE_CURRENT_LIST_DIR}/include/assimp/config.h ${CMAKE_CURRENT_BINARY_DIR}/include/assimp/config.h
) )
include_directories( include_directories(
@ -105,38 +168,48 @@ include_directories(
${CMAKE_CURRENT_BINARY_DIR}/include ${CMAKE_CURRENT_BINARY_DIR}/include
) )
OPTION(ASSIMP_OPT_BUILD_PACKAGES "Set to ON to generate CPack configuration files and packaging targets" OFF) LIST(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake-modules" )
SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake-modules" )
SET(LIBASSIMP_COMPONENT "libassimp${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH}" ) SET(LIBASSIMP_COMPONENT "libassimp${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH}" )
SET(LIBASSIMP-DEV_COMPONENT "libassimp${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH}-dev" ) SET(LIBASSIMP-DEV_COMPONENT "libassimp${ASSIMP_VERSION_MAJOR}.${ASSIMP_VERSION_MINOR}.${ASSIMP_VERSION_PATCH}-dev" )
SET(CPACK_COMPONENTS_ALL assimp-bin ${LIBASSIMP_COMPONENT} ${LIBASSIMP-DEV_COMPONENT} assimp-dev) SET(CPACK_COMPONENTS_ALL assimp-bin ${LIBASSIMP_COMPONENT} ${LIBASSIMP-DEV_COMPONENT} assimp-dev)
SET(ASSIMP_LIBRARY_SUFFIX "" CACHE STRING "Suffix to append to library names") SET(ASSIMP_LIBRARY_SUFFIX "" CACHE STRING "Suffix to append to library names")
OPTION(ASSIMP_ANDROID_JNIIOSYSTEM "Android JNI IOSystem support is active" OFF) IF( UNIX )
# Ensure that we do not run into issues like http://www.tcm.phy.cam.ac.uk/sw/inodes64.html on 32 bit linux
# Workaround to be able to deal with compiler bug "Too many sections" with mingw. IF ( CMAKE_SIZEOF_VOID_P EQUAL 4) # only necessary for 32-bit linux
IF( CMAKE_COMPILER_IS_MINGW ) ADD_DEFINITIONS(-D_FILE_OFFSET_BITS=64 )
ADD_DEFINITIONS(-DASSIMP_BUILD_NO_IFC_IMPORTER )
ENDIF()
IF((CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) AND NOT CMAKE_COMPILER_IS_MINGW)
IF (BUILD_SHARED_LIBS AND CMAKE_SIZEOF_VOID_P EQUAL 8) # -fPIC is only required for shared libs on 64 bit
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
ENDIF() ENDIF()
# Use GNUInstallDirs for Unix predefined directories
include(GNUInstallDirs)
ENDIF( UNIX )
# Grouped compiler settings
IF ((CMAKE_C_COMPILER_ID MATCHES "GNU") AND NOT CMAKE_COMPILER_IS_MINGW)
# hide all not-exported symbols # hide all not-exported symbols
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -Wall -std=c++0x" ) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fvisibility=hidden -fPIC -Wall -std=c++0x")
SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
SET(LIBSTDC++_LIBRARIES -lstdc++)
ELSEIF(MSVC) ELSEIF(MSVC)
# enable multi-core compilation with MSVC # enable multi-core compilation with MSVC
add_compile_options(/MP) add_compile_options(/MP)
ELSEIF ( "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" ) ELSEIF ( "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -Wall -Wno-long-long -pedantic -std=c++11" ) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -fvisibility=hidden -fPIC -Wall -Wno-long-long -pedantic -std=c++11" )
ELSEIF( CMAKE_COMPILER_IS_MINGW ) ELSEIF( CMAKE_COMPILER_IS_MINGW )
SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -Wall -Wno-long-long -pedantic -std=c++11" ) SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -Wall -Wno-long-long -pedantic -std=c++11" )
add_definitions( -U__STRICT_ANSI__ )
ENDIF() ENDIF()
INCLUDE (FindPkgConfig) if (ASSIMP_COVERALLS)
include(Coveralls)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage")
endif()
INCLUDE_DIRECTORIES( include ) INCLUDE_DIRECTORIES( include )
INCLUDE (FindPkgMacros)
INCLUDE (PrecompiledHeader) INCLUDE (PrecompiledHeader)
# If this is an in-source build (CMAKE_SOURCE_DIR == CMAKE_BINARY_DIR), # If this is an in-source build (CMAKE_SOURCE_DIR == CMAKE_BINARY_DIR),
@ -170,8 +243,6 @@ IF (NOT TARGET uninstall)
add_custom_target(uninstall "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake") add_custom_target(uninstall "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake")
ENDIF() ENDIF()
# cmake configuration files # cmake configuration files
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/assimp-config.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimp-config.cmake" @ONLY IMMEDIATE) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/assimp-config.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimp-config.cmake" @ONLY IMMEDIATE)
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/assimp-config-version.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimp-config-version.cmake" @ONLY IMMEDIATE) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/assimp-config-version.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/assimp-config-version.cmake" @ONLY IMMEDIATE)
@ -179,22 +250,17 @@ install(FILES "${CMAKE_CURRENT_BINARY_DIR}/assimp-config.cmake" "${C
FIND_PACKAGE( DirectX ) FIND_PACKAGE( DirectX )
OPTION ( ASSIMP_NO_EXPORT IF( BUILD_DOCS )
"Disable Assimp's export functionality." add_subdirectory(doc)
OFF ENDIF( BUILD_DOCS )
)
IF( CMAKE_COMPILER_IS_GNUCXX ) # Look for system installed irrXML
SET(LIBSTDC++_LIBRARIES -lstdc++) IF ( SYSTEM_IRRXML )
ENDIF( CMAKE_COMPILER_IS_GNUCXX ) find_package( IrrXML REQUIRED )
ENDIF( SYSTEM_IRRXML )
# Search for external dependencies, and build them from source if not found # Search for external dependencies, and build them from source if not found
# Search for zlib # Search for zlib
OPTION(ASSIMP_BUILD_ZLIB
"Build your own zlib"
OFF
)
IF ( NOT ASSIMP_BUILD_ZLIB ) IF ( NOT ASSIMP_BUILD_ZLIB )
find_package(ZLIB) find_package(ZLIB)
ENDIF( NOT ASSIMP_BUILD_ZLIB ) ENDIF( NOT ASSIMP_BUILD_ZLIB )
@ -216,9 +282,7 @@ ENDIF(NOT ZLIB_FOUND)
INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIR}) INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIR})
# Search for unzip # Search for unzip
IF (PKG_CONFIG_FOUND) use_pkgconfig(UNZIP minizip)
PKG_CHECK_MODULES(UNZIP minizip)
ENDIF (PKG_CONFIG_FOUND)
IF ( ASSIMP_NO_EXPORT ) IF ( ASSIMP_NO_EXPORT )
ADD_DEFINITIONS( -DASSIMP_BUILD_NO_EXPORT) ADD_DEFINITIONS( -DASSIMP_BUILD_NO_EXPORT)
@ -244,7 +308,6 @@ ENDIF ( ASSIMP_BUILD_COMPILER STREQUAL "")
MARK_AS_ADVANCED ( ASSIMP_BUILD_ARCHITECTURE ASSIMP_BUILD_COMPILER ) MARK_AS_ADVANCED ( ASSIMP_BUILD_ARCHITECTURE ASSIMP_BUILD_COMPILER )
SET ( ASSIMP_BUILD_NONFREE_C4D_IMPORTER OFF CACHE BOOL SET ( ASSIMP_BUILD_NONFREE_C4D_IMPORTER OFF CACHE BOOL
"Build the C4D importer, which relies on the non-free Melange SDK." "Build the C4D importer, which relies on the non-free Melange SDK."
) )
@ -290,19 +353,16 @@ ELSE (ASSIMP_BUILD_NONFREE_C4D_IMPORTER)
ADD_DEFINITIONS( -DASSIMP_BUILD_NO_C4D_IMPORTER ) ADD_DEFINITIONS( -DASSIMP_BUILD_NO_C4D_IMPORTER )
ENDIF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) ENDIF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER)
ADD_SUBDIRECTORY(contrib)
ADD_SUBDIRECTORY( code/ ) ADD_SUBDIRECTORY( code/ )
option ( ASSIMP_BUILD_ASSIMP_TOOLS
"If the supplementary tools for Assimp are built in addition to the library."
ON
)
IF ( ASSIMP_BUILD_ASSIMP_TOOLS ) IF ( ASSIMP_BUILD_ASSIMP_TOOLS )
IF ( WIN32 ) IF ( WIN32 AND DirectX_D3DX9_LIBRARY )
option ( ASSIMP_BUILD_ASSIMP_VIEW "If the Assimp view tool is built. (requires DirectX)" ${DirectX_FOUND} ) option ( ASSIMP_BUILD_ASSIMP_VIEW "If the Assimp view tool is built. (requires DirectX)" ${DirectX_FOUND} )
IF ( ASSIMP_BUILD_ASSIMP_VIEW ) IF ( ASSIMP_BUILD_ASSIMP_VIEW )
ADD_SUBDIRECTORY( tools/assimp_view/ ) ADD_SUBDIRECTORY( tools/assimp_view/ )
ENDIF ( ASSIMP_BUILD_ASSIMP_VIEW ) ENDIF ( ASSIMP_BUILD_ASSIMP_VIEW )
ENDIF ( WIN32 ) ENDIF ( WIN32 AND DirectX_D3DX9_LIBRARY )
ADD_SUBDIRECTORY( tools/assimp_cmd/ ) ADD_SUBDIRECTORY( tools/assimp_cmd/ )
@ -310,16 +370,16 @@ IF ( ASSIMP_BUILD_ASSIMP_TOOLS )
# Why here? Maybe user do not want Qt viewer and have no Qt. # Why here? Maybe user do not want Qt viewer and have no Qt.
# Why assimp_qt_viewer/CMakeLists.txt still contain similar check? # Why assimp_qt_viewer/CMakeLists.txt still contain similar check?
# Because viewer can be build independently of Assimp. # Because viewer can be build independently of Assimp.
FIND_PACKAGE(Qt4 QUIET) FIND_PACKAGE(Qt5Widgets QUIET)
FIND_PACKAGE(DevIL QUIET) FIND_PACKAGE(DevIL QUIET)
FIND_PACKAGE(OpenGL QUIET) FIND_PACKAGE(OpenGL QUIET)
IF ( Qt4_FOUND AND IL_FOUND AND OPENGL_FOUND) IF ( Qt5Widgets_FOUND AND IL_FOUND AND OPENGL_FOUND)
ADD_SUBDIRECTORY( tools/assimp_qt_viewer/ ) ADD_SUBDIRECTORY( tools/assimp_qt_viewer/ )
ELSE() ELSE()
SET ( ASSIMP_QT_VIEWER_DEPENDENCIES "") SET ( ASSIMP_QT_VIEWER_DEPENDENCIES "")
IF (NOT Qt4_FOUND) IF (NOT Qt5_FOUND)
SET ( ASSIMP_QT_VIEWER_DEPENDENCIES "${ASSIMP_QT_VIEWER_DEPENDENCIES} Qt4") SET ( ASSIMP_QT_VIEWER_DEPENDENCIES "${ASSIMP_QT_VIEWER_DEPENDENCIES} Qt5")
ENDIF (NOT Qt4_FOUND) ENDIF (NOT Qt5_FOUND)
IF (NOT IL_FOUND) IF (NOT IL_FOUND)
SET ( ASSIMP_QT_VIEWER_DEPENDENCIES "${ASSIMP_QT_VIEWER_DEPENDENCIES} DevIL") SET ( ASSIMP_QT_VIEWER_DEPENDENCIES "${ASSIMP_QT_VIEWER_DEPENDENCIES} DevIL")
@ -330,14 +390,9 @@ IF ( ASSIMP_BUILD_ASSIMP_TOOLS )
ENDIF (NOT OPENGL_FOUND) ENDIF (NOT OPENGL_FOUND)
MESSAGE (WARNING "Build of assimp_qt_viewer is disabled. Unsatisfied dendencies: ${ASSIMP_QT_VIEWER_DEPENDENCIES}") MESSAGE (WARNING "Build of assimp_qt_viewer is disabled. Unsatisfied dendencies: ${ASSIMP_QT_VIEWER_DEPENDENCIES}")
ENDIF ( Qt4_FOUND AND IL_FOUND AND OPENGL_FOUND) ENDIF ( Qt5Widgets_FOUND AND IL_FOUND AND OPENGL_FOUND)
ENDIF ( ASSIMP_BUILD_ASSIMP_TOOLS ) ENDIF ( ASSIMP_BUILD_ASSIMP_TOOLS )
option ( ASSIMP_BUILD_SAMPLES
"If the official samples are built as well (needs Glut)."
OFF
)
IF ( ASSIMP_BUILD_SAMPLES) IF ( ASSIMP_BUILD_SAMPLES)
IF ( WIN32 ) IF ( WIN32 )
ADD_SUBDIRECTORY( samples/SimpleTexturedOpenGL/ ) ADD_SUBDIRECTORY( samples/SimpleTexturedOpenGL/ )
@ -345,22 +400,10 @@ IF ( ASSIMP_BUILD_SAMPLES)
ADD_SUBDIRECTORY( samples/SimpleOpenGL/ ) ADD_SUBDIRECTORY( samples/SimpleOpenGL/ )
ENDIF ( ASSIMP_BUILD_SAMPLES ) ENDIF ( ASSIMP_BUILD_SAMPLES )
OPTION ( ASSIMP_BUILD_TESTS
"If the test suite for Assimp is built in addition to the library."
ON
)
IF ( ASSIMP_BUILD_TESTS ) IF ( ASSIMP_BUILD_TESTS )
ADD_SUBDIRECTORY( test/ ) ADD_SUBDIRECTORY( test/ )
ENDIF ( ASSIMP_BUILD_TESTS ) ENDIF ( ASSIMP_BUILD_TESTS )
IF(MSVC)
OPTION ( ASSIMP_INSTALL_PDB
"Install MSVC debug files."
ON
)
ENDIF(MSVC)
# Generate a pkg-config .pc for the Assimp library. # Generate a pkg-config .pc for the Assimp library.
CONFIGURE_FILE( "${PROJECT_SOURCE_DIR}/assimp.pc.in" "${PROJECT_BINARY_DIR}/assimp.pc" @ONLY ) CONFIGURE_FILE( "${PROJECT_SOURCE_DIR}/assimp.pc.in" "${PROJECT_BINARY_DIR}/assimp.pc" @ONLY )
INSTALL( FILES "${PROJECT_BINARY_DIR}/assimp.pc" DESTINATION ${ASSIMP_LIB_INSTALL_DIR}/pkgconfig/ COMPONENT ${LIBASSIMP-DEV_COMPONENT}) INSTALL( FILES "${PROJECT_BINARY_DIR}/assimp.pc" DESTINATION ${ASSIMP_LIB_INSTALL_DIR}/pkgconfig/ COMPONENT ${LIBASSIMP-DEV_COMPONENT})
@ -415,29 +458,29 @@ IF(CMAKE_CPACK_COMMAND AND UNIX AND ASSIMP_OPT_BUILD_PACKAGES)
ENDIF() ENDIF()
if(WIN32) if(WIN32)
if (CMAKE_SIZEOF_VOID_P EQUAL 8) if (CMAKE_SIZEOF_VOID_P EQUAL 8)
SET(BIN_DIR "${PROJECT_SOURCE_DIR}/bin64/") SET(BIN_DIR "${PROJECT_SOURCE_DIR}/bin64/")
SET(LIB_DIR "${PROJECT_SOURCE_DIR}/lib64/") SET(LIB_DIR "${PROJECT_SOURCE_DIR}/lib64/")
elseif() elseif()
SET(BIN_DIR "${PROJECT_SOURCE_DIR}/bin32/") SET(BIN_DIR "${PROJECT_SOURCE_DIR}/bin32/")
SET(LIB_DIR "${PROJECT_SOURCE_DIR}/lib32/") SET(LIB_DIR "${PROJECT_SOURCE_DIR}/lib32/")
ENDIF() ENDIF()
if(MSVC12) if(MSVC12)
SET(ASSIMP_MSVC_VERSION "vc120") SET(ASSIMP_MSVC_VERSION "vc120")
elseif(MSVC14) elseif(MSVC14)
SET(ASSIMP_MSVC_VERSION "vc140") SET(ASSIMP_MSVC_VERSION "vc140")
ENDIF(MSVC12) ENDIF(MSVC12)
if(MSVC12 OR MSVC14) if(MSVC12 OR MSVC14)
add_custom_target(UpdateAssimpLibsDebugSymbolsAndDLLs COMMENT "Copying Assimp Libraries ..." VERBATIM) add_custom_target(UpdateAssimpLibsDebugSymbolsAndDLLs COMMENT "Copying Assimp Libraries ..." VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.dll VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.dll VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.exp VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.exp VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.lib VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Release/assimp-${ASSIMP_MSVC_VERSION}-mt.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mt.lib VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.dll VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.dll ${BIN_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.dll VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.exp VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.exp ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.exp VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.ilk VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.lib VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.lib ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.lib VERBATIM)
add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb VERBATIM) add_custom_command(TARGET UpdateAssimpLibsDebugSymbolsAndDLLs COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/code/Debug/assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb ${LIB_DIR}assimp-${ASSIMP_MSVC_VERSION}-mtd.pdb VERBATIM)
ENDIF(MSVC12 OR MSVC14) ENDIF(MSVC12 OR MSVC14)
ENDIF (WIN32) ENDIF (WIN32)

320
CREDITS
View File

@ -1,160 +1,160 @@
=============================================================== ===============================================================
Open Asset Import Library (Assimp) Open Asset Import Library (Assimp)
Developers and Contributors Developers and Contributors
=============================================================== ===============================================================
The following is a non-exhaustive list of all constributors over the years. The following is a non-exhaustive list of all constributors over the years.
If you think your name should be listed here, drop us a line and we'll add you. If you think your name should be listed here, drop us a line and we'll add you.
- Alexander Gessler, - Alexander Gessler,
3DS-, BLEND-, ASE-, DXF-, HMP-, MDL-, MD2-, MD3-, MD5-, MDC-, NFF-, PLY-, STL-, RAW-, OFF-, MS3D-, Q3D- and LWO-Loader, Assimp-Viewer, assimp-cmd, -noboost, Website (Admin and Design). 3DS-, BLEND-, ASE-, DXF-, HMP-, MDL-, MD2-, MD3-, MD5-, MDC-, NFF-, PLY-, STL-, RAW-, OFF-, MS3D-, Q3D- and LWO-Loader, Assimp-Viewer, assimp-cmd, -noboost, Website (Design).
- Thomas Schulze, - Thomas Schulze,
X-, Collada-, BVH-Loader, Postprocessing framework. Data structure & Interface design, documentation. X-, Collada-, BVH-Loader, Postprocessing framework. Data structure & Interface design, documentation.
- Kim Kulling, - Kim Kulling,
Obj-Loader, Logging system, Scons-build environment, CMake build environment, Linux build. Obj-, Q3BSD-, OpenGEX-Loader, Logging system, CMake-build-environment, Linux-build, Website ( Admin ), Coverity ( Admin ), Glitter ( Admin ).
- R.Schmidt, - R.Schmidt,
Linux build, eclipse support. Linux build, eclipse support.
- Matthias Gubisch, - Matthias Gubisch,
Assimp.net Assimp.net
Visual Studio 9 support, bugfixes. Visual Studio 9 support, bugfixes.
- Mark Sibly - Mark Sibly
B3D-Loader, Assimp testing B3D-Loader, Assimp testing
- Jonathan Klein - Jonathan Klein
Ogre Loader, VC2010 fixes and CMake fixes. Ogre Loader, VC2010 fixes and CMake fixes.
- Sebastian Hempel, - Sebastian Hempel,
PyAssimp (first version) PyAssimp (first version)
Compile-Bugfixes for mingw, add environment for static library support in make. Compile-Bugfixes for mingw, add environment for static library support in make.
- Jonathan Pokrass - Jonathan Pokrass
Supplied a bugfix concerning the scaling in the md3 loader. Supplied a bugfix concerning the scaling in the md3 loader.
- Andrew Galante, - Andrew Galante,
Submitted patches to make Assimp compile with GCC-4, a makefile and the xcode3 workspace. Submitted patches to make Assimp compile with GCC-4, a makefile and the xcode3 workspace.
- Andreas Nagel - Andreas Nagel
First Assimp testing & verification under Windows Vista 64 Bit. First Assimp testing & verification under Windows Vista 64 Bit.
- Marius Schr<68>der - Marius Schr<68>der
Allowed us to use many of his models for screenshots and testing. Allowed us to use many of his models for screenshots and testing.
- Christian Schubert - Christian Schubert
Supplied various XFiles for testing purposes. Supplied various XFiles for testing purposes.
- Tizian Wieland - Tizian Wieland
Searched the web for hundreds of test models for internal use Searched the web for hundreds of test models for internal use
- John Connors - John Connors
Supplied patches for linux and SCons. Supplied patches for linux and SCons.
- T. R. - T. R.
The GUY who performed some of the CSM mocaps. The GUY who performed some of the CSM mocaps.
- Andy Maloney - Andy Maloney
Contributed fixes for the documentation and the doxygen markup Contributed fixes for the documentation and the doxygen markup
- Zhao Lei - Zhao Lei
Contributed several bugfixes fixing memory leaks and improving float parsing Contributed several bugfixes fixing memory leaks and improving float parsing
- sueastside - sueastside
Updated PyAssimp to the latest Assimp data structures and provided a script to keep the Python binding up-to-date. Updated PyAssimp to the latest Assimp data structures and provided a script to keep the Python binding up-to-date.
- Tobias Rittig - Tobias Rittig
Collada testing with Cinema 4D Collada testing with Cinema 4D
- Brad Grantham - Brad Grantham
Improvements in OpenGL-Sample. Improvements in OpenGL-Sample.
- Robert Ramirez - Robert Ramirez
Add group loading feature to Obj-Loader. Add group loading feature to Obj-Loader.
- Chris Maiwald - Chris Maiwald
Many bugreports, improving Assimp's portability, regular testing & feedback. Many bugreports, improving Assimp's portability, regular testing & feedback.
- Stepan Hrbek - Stepan Hrbek
Bugreport and fix for a obj-materialloader crash. Bugreport and fix for a obj-materialloader crash.
- David Nadlinger - David Nadlinger
D bindings, CMake install support. D bindings, CMake install support.
- Dario Accornero - Dario Accornero
Contributed several patches regarding Mac OS/XCode targets, bug reports. Contributed several patches regarding Mac OS/XCode targets, bug reports.
- Martin Walser (Samhayne) - Martin Walser (Samhayne)
Contributed the 'SimpleTexturedOpenGl' sample. Contributed the 'SimpleTexturedOpenGl' sample.
- Matthias Fauconneau - Matthias Fauconneau
Contributed a fix for the Q3-BSP loader. Contributed a fix for the Q3-BSP loader.
- J<EFBFBD>rgen P. Tjern<72> - Jørgen P. Tjernø
Contributed updated and improved xcode workspaces Contributed updated and improved xcode workspaces
- drparallax - drparallax
Contributed the /samples/SimpleAssimpViewX sample Contributed the /samples/SimpleAssimpViewX sample
- Carsten Fuchs - Carsten Fuchs
Contributed a fix for the Normalize method in aiQuaternion. Contributed a fix for the Normalize method in aiQuaternion.
- dbburgess - dbburgess
Contributes a Android-specific build issue: log the hardware architecture for ARM. Contributes a Android-specific build issue: log the hardware architecture for ARM.
- alfiereinre7 - alfiereinre7
Contributes a obj-fileparser fix: missing tokens in the obj-token list. Contributes a obj-fileparser fix: missing tokens in the obj-token list.
- Roman Kharitonov - Roman Kharitonov
Contributes a fix for the configure script environment. Contributes a fix for the configure script environment.
- Ed Diana - Ed Diana
Contributed AssimpDelphi (/port/AssimpDelphi). Contributed AssimpDelphi (/port/AssimpDelphi).
- rdb - rdb
Contributes a bundle of fixes and improvements for the bsp-importer. Contributes a bundle of fixes and improvements for the bsp-importer.
- Mick P - Mick P
For contributing the De-bone postprocessing step and filing various bug reports. For contributing the De-bone postprocessing step and filing various bug reports.
- Rosen Diankov - Rosen Diankov
Contributed patches to build assimp debian packages using cmake. Contributed patches to build assimp debian packages using cmake.
- Mark Page - Mark Page
Contributed a patch to fix the VertexTriangleAdjacency postprocessing step. Contributed a patch to fix the VertexTriangleAdjacency postprocessing step.
- IOhannes - IOhannes
Contributed the Debian build fixes ( architecture macro ). Contributed the Debian build fixes ( architecture macro ).
- gellule - gellule
Several LWO and LWS fixes (pivoting). Several LWO and LWS fixes (pivoting).
- Marcel Metz - Marcel Metz
GCC/Linux fixes for the SimpleOpenGL sample. GCC/Linux fixes for the SimpleOpenGL sample.
- Brian Miller - Brian Miller
Bugfix for a compiler fix for iOS on arm. Bugfix for a compiler fix for iOS on arm.
- S<EFBFBD>verin Lemaignan - SĂ©verin Lemaignan
Rewrite of PyAssimp, distutils and Python3 support Rewrite of PyAssimp, distutils and Python3 support
- albert-wang - albert-wang
Bugfixes for the collada parser Bugfixes for the collada parser
- Ya ping Jin - Ya ping Jin
Bugfixes for uv-tanget calculation. Bugfixes for uv-tanget calculation.
- Jonne Nauha - Jonne Nauha
Ogre Binary format support Ogre Binary format support
- Filip Wasil, Tieto Poland Sp. z o.o. - Filip Wasil, Tieto Poland Sp. z o.o.
Android JNI asset extraction support Android JNI asset extraction support
- Richard Steffen - Richard Steffen
Contributed ExportProperties interface Contributed ExportProperties interface
Contributed X File exporter Contributed X File exporter
Contributed Step (stp) exporter Contributed Step (stp) exporter

156
LICENSE
View File

@ -1,78 +1,78 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2016, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the with or without modification, are permitted provided that the
following conditions are met: following conditions are met:
* Redistributions of source code must retain the above * Redistributions of source code must retain the above
copyright notice, this list of conditions and the copyright notice, this list of conditions and the
following disclaimer. following disclaimer.
* Redistributions in binary form must reproduce the above * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other following disclaimer in the documentation and/or other
materials provided with the distribution. materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its * Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products contributors may be used to endorse or promote products
derived from this software without specific prior derived from this software without specific prior
written permission of the assimp team. written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
****************************************************************************** ******************************************************************************
AN EXCEPTION applies to all files in the ./test/models-nonbsd folder. AN EXCEPTION applies to all files in the ./test/models-nonbsd folder.
These are 3d models for testing purposes, from various free sources These are 3d models for testing purposes, from various free sources
on the internet. They are - unless otherwise stated - copyright of on the internet. They are - unless otherwise stated - copyright of
their respective creators, which may impose additional requirements their respective creators, which may impose additional requirements
on the use of their work. For any of these models, see on the use of their work. For any of these models, see
<model-name>.source.txt for more legal information. Contact us if you <model-name>.source.txt for more legal information. Contact us if you
are a copyright holder and believe that we credited you inproperly or are a copyright holder and believe that we credited you inproperly or
if you don't want your files to appear in the repository. if you don't want your files to appear in the repository.
****************************************************************************** ******************************************************************************
Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors
http://code.google.com/p/poly2tri/ http://code.google.com/p/poly2tri/
All rights reserved. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met: are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, * Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution. and/or other materials provided with the distribution.
* Neither the name of Poly2Tri nor the names of its contributors may be * Neither the name of Poly2Tri nor the names of its contributors may be
used to endorse or promote products derived from this software without specific used to endorse or promote products derived from this software without specific
prior written permission. prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

284
Readme.md
View File

@ -1,139 +1,145 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
================================== ==================================
APIs are provided for C and C++. There are various bindings to other languages (C#, Java, Python, Delphi, D). Assimp also runs on Android and iOS. [![Linux Build Status](https://travis-ci.org/assimp/assimp.svg)](https://travis-ci.org/assimp/assimp)
[![Windows Build Status](https://ci.appveyor.com/api/projects/status/tmo433wax6u6cjp4?svg=true)](https://ci.appveyor.com/project/kimkulling/assimp)
Additionally, assimp features various __mesh post processing tools__: normals and tangent space generation, triangulation, vertex cache locality optimization, removal of degenerate primitives and duplicate vertices, sorting by primitive type, merging of redundant materials and many more. <a href="https://scan.coverity.com/projects/5607">
<img alt="Coverity Scan Build Status"
This is the development trunk containing the latest features and bugfixes. For productive use though, we recommend one of the stable releases available from [assimp.sf.net](http://assimp.sf.net) or from *nix package repositories. src="https://scan.coverity.com/projects/5607/badge.svg"/>
The current build status is: </a>
<span class="badge-patreon"><a href="https://www.patreon.com/assimp" title="Donate to this project using Patreon"><img src="https://img.shields.io/badge/patreon-donate-yellow.svg" alt="Patreon donate button" /></a></span>
Linux [![Linux Build Status](https://travis-ci.org/assimp/assimp.png)](https://travis-ci.org/assimp/assimp) [![Coverage Status](https://coveralls.io/repos/github/assimp/assimp/badge.svg?branch=master)](https://coveralls.io/github/assimp/assimp?branch=master)
Windows [![Windows Build Status](https://ci.appveyor.com/api/projects/status/tmo433wax6u6cjp4?svg=true)](https://ci.appveyor.com/project/kimkulling/assimp) <br>
Coverity<a href="https://scan.coverity.com/projects/5607">
<img alt="Coverity Scan Build Status" APIs are provided for C and C++. There are various bindings to other languages (C#, Java, Python, Delphi, D). Assimp also runs on Android and iOS.
src="https://scan.coverity.com/projects/5607/badge.svg"/>
</a> Additionally, assimp features various __mesh post processing tools__: normals and tangent space generation, triangulation, vertex cache locality optimization, removal of degenerate primitives and duplicate vertices, sorting by primitive type, merging of redundant materials and many more.
Gitter [![Join the chat at https://gitter.im/assimp/assimp](https://badges.gitter.im/assimp/assimp.svg)](https://gitter.im/assimp/assimp?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<br> This is the development trunk containing the latest features and bugfixes. For productive use though, we recommend one of the stable releases available from [assimp.sf.net](http://assimp.sf.net) or from *nix package repositories.
__[open3mod](https://github.com/acgessler/open3mod) is a powerful 3D model viewer based on Assimp's import and export abilities.__ The current build status is:
#### Supported file formats #### Gitter chat: [![Join the chat at https://gitter.im/assimp/assimp](https://badges.gitter.im/assimp/assimp.svg)](https://gitter.im/assimp/assimp?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)<br>
A full list [is here](http://assimp.sourceforge.net/main_features_formats.html). And we also have an IRC-channel at freenode: #assetimporterlib . You can easily join us via: [KiwiIRC/freenote](https://kiwiirc.com/client/irc.freenode.net), choose your nickname and type
__Importers__: > /join #assetimporterlib
- 3DS <br>
- BLEND (Blender) __[open3mod](https://github.com/acgessler/open3mod) is a powerful 3D model viewer based on Assimp's import and export abilities.__
- DAE/Collada
- FBX Please check our Wiki as well: https://github.com/assimp/assimp/wiki
- IFC-STEP
- ASE #### Supported file formats ####
- DXF
- HMP A full list [is here](http://assimp.org/main_features_formats.html).
- MD2 __Importers__:
- MD3
- MD5 - 3DS
- MDC - BLEND (Blender)
- MDL - DAE/Collada
- NFF - FBX
- PLY - IFC-STEP
- STL - ASE
- X - DXF
- OBJ - HMP
- OpenGEX - MD2
- SMD - MD3
- LWO - MD5
- LXO - MDC
- LWS - MDL
- TER - NFF
- AC3D - PLY
- MS3D - STL
- COB - X
- Q3BSP - OBJ
- XGL - OpenGEX
- CSM - SMD
- BVH - LWO
- B3D - LXO
- NDO - LWS
- Ogre Binary - TER
- Ogre XML - AC3D
- Q3D - MS3D
- ASSBIN (Assimp custom format) - COB
- glTF (partial) - Q3BSP
- 3MF - XGL
- CSM
Additionally, some formats are supported by dependency on non-free code or external SDKs (not built by default): - BVH
- B3D
- C4D (https://github.com/acgessler/assimp-cinema4d) - NDO
- Ogre Binary
__Exporters__: - Ogre XML
- Q3D
- DAE (Collada) - ASSBIN (Assimp custom format)
- STL - glTF (partial)
- OBJ - 3MF
- PLY
- X Additionally, some formats are supported by dependency on non-free code or external SDKs (not built by default):
- 3DS
- JSON (for WebGl, via https://github.com/acgessler/assimp2json) - C4D (https://github.com/acgessler/assimp-cinema4d)
- ASSBIN
- STEP __Exporters__:
- glTF (partial)
- DAE (Collada)
### Building ### - STL
Take a look into the `INSTALL` file. Our build system is CMake, if you used CMake before there is a good chance you know what to do. - OBJ
- PLY
### Ports ### - X
* [Android](port/AndroidJNI/README.md) - 3DS
* [Python](port/PyAssimp/README.md) - JSON (for WebGl, via https://github.com/acgessler/assimp2json)
* [.NET](port/AssimpNET/Readme.md) - ASSBIN
* [Pascal](port/AssimpPascal/Readme.md) - STEP
- glTF (partial)
#### Repository structure ####
Open Asset Import Library is implemented in C++. The directory structure is: ### Building ###
Take a look into the `INSTALL` file. Our build system is CMake, if you used CMake before there is a good chance you know what to do.
/code Source code
/contrib Third-party libraries ### Ports ###
/doc Documentation (doxysource and pre-compiled docs) * [Android](port/AndroidJNI/README.md)
/include Public header C and C++ header files * [Python](port/PyAssimp/README.md)
/scripts Scripts used to generate the loading code for some formats * [.NET](port/AssimpNET/Readme.md)
/port Ports to other languages and scripts to maintain those. * [Pascal](port/AssimpPascal/Readme.md)
/test Unit- and regression tests, test suite of models * [Javascript (Alpha)](https://github.com/makc/assimp2json)
/tools Tools (old assimp viewer, command line `assimp`)
/samples A small number of samples to illustrate possible #### Repository structure ####
use cases for Assimp Open Asset Import Library is implemented in C++. The directory structure is:
/workspaces Build environments for vc,xcode,... (deprecated,
CMake has superseeded all legacy build options!) /code Source code
/contrib Third-party libraries
/doc Documentation (doxysource and pre-compiled docs)
### Where to get help ### /include Public header C and C++ header files
For more information, visit [our website](http://assimp.sourceforge.net/). Or check out the `./doc`- folder, which contains the official documentation in HTML format. /scripts Scripts used to generate the loading code for some formats
(CHMs for Windows are included in some release packages and should be located right here in the root folder). /port Ports to other languages and scripts to maintain those.
/test Unit- and regression tests, test suite of models
If the docs don't solve your problem, ask on [StackOverflow](http://stackoverflow.com/questions/tagged/assimp?sort=newest). If you think you found a bug, please open an issue on Github. /tools Tools (old assimp viewer, command line `assimp`)
/samples A small number of samples to illustrate possible
For development discussions, there is also a (very low-volume) mailing list, _assimp-discussions_ use cases for Assimp
[(subscribe here)]( https://lists.sourceforge.net/lists/listinfo/assimp-discussions) /workspaces Build environments for vc,xcode,... (deprecated,
CMake has superseeded all legacy build options!)
Open Asset Import Library is a library to load various 3d file formats into a shared, in-memory format. It supports more than __40 file formats__ for import and a growing selection of file formats for export.
And we also have an IRC-channel at freenode: #assetimporterlib . You can easily join us via: [KiwiIRC/freenote](https://kiwiirc.com/client/irc.freenode.net), choose your nickname and type ### Where to get help ###
> /join #assetimporterlib For more information, visit [our website](http://assimp.org/). Or check out the `./doc`- folder, which contains the official documentation in HTML format.
(CHMs for Windows are included in some release packages and should be located right here in the root folder).
### Contributing ###
Contributions to assimp are highly appreciated. The easiest way to get involved is to submit If the docs don't solve your problem, ask on [StackOverflow](http://stackoverflow.com/questions/tagged/assimp?sort=newest). If you think you found a bug, please open an issue on Github.
a pull request with your changes against the main repository's `master` branch.
For development discussions, there is also a (very low-volume) mailing list, _assimp-discussions_
### Donate ### [(subscribe here)]( https://lists.sourceforge.net/lists/listinfo/assimp-discussions)
If you like assimp, consider buying us a beer (or two):
[Donate](http://sourceforge.net/donate/index.php?group_id=226462) Open Asset Import Library is a library to load various 3d file formats into a shared, in-memory format. It supports more than __40 file formats__ for import and a growing selection of file formats for export.
### License ### And we also have a Gitter-channel:Gitter [![Join the chat at https://gitter.im/assimp/assimp](https://badges.gitter.im/assimp/assimp.svg)](https://gitter.im/assimp/assimp?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)<br>
Our license is based on the modified, __3-clause BSD__-License.
### Contributing ###
An _informal_ summary is: do whatever you want, but include Assimp's license text with your product - Contributions to assimp are highly appreciated. The easiest way to get involved is to submit
and don't sue us if our code doesn't work. Note that, unlike LGPLed code, you may link statically to Assimp. a pull request with your changes against the main repository's `master` branch.
For the legal details, see the `LICENSE` file.
### License ###
### Why this name ### Our license is based on the modified, __3-clause BSD__-License.
Sorry, we're germans :-), no english native speakers ...
An _informal_ summary is: do whatever you want, but include Assimp's license text with your product -
and don't sue us if our code doesn't work. Note that, unlike LGPLed code, you may link statically to Assimp.
For the legal details, see the `LICENSE` file.
### Why this name ###
Sorry, we're germans :-), no english native speakers ...

View File

@ -28,9 +28,11 @@ install:
- call c:\projects\assimp\scripts\appveyor\compiler_setup.bat - call c:\projects\assimp\scripts\appveyor\compiler_setup.bat
build_script: build_script:
- cd c:\projects\assimp - cd c:\projects\assimp
- cmake CMakeLists.txt -G "Visual Studio %Configuration%" - if "%platform%" equ "x64" (cmake CMakeLists.txt -G "Visual Studio %Configuration% Win64")
- msbuild /m /p:Configuration=Release /p:Platform="Win32" Assimp.sln - if "%platform%" equ "x86" (cmake CMakeLists.txt -G "Visual Studio %Configuration%")
- if "%platform%" equ "x64" (msbuild /m /p:Configuration=Release /p:Platform="x64" Assimp.sln)
- if "%platform%" equ "x86" (msbuild /m /p:Configuration=Release /p:Platform="Win32" Assimp.sln)
after_build: after_build:
- 7z a assimp.7z c:\projects\assimp\bin\release\* c:\projects\assimp\lib\release\* - 7z a assimp.7z c:\projects\assimp\bin\release\* c:\projects\assimp\lib\release\*

View File

@ -1,8 +1,43 @@
# Open Asset Import Library (assimp)
# ----------------------------------------------------------------------
# Copyright (c) 2006-2017, assimp team
# All rights reserved.
#
# Redistribution and use of this software 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.
#
# * Neither the name of the assimp team, nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior
# written permission of the assimp team.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER 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 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 DAMAGE.
#----------------------------------------------------------------------
set( PACKAGE_VERSION "@ASSIMP_VERSION@" ) set( PACKAGE_VERSION "@ASSIMP_VERSION@" )
if( "${PACKAGE_FIND_VERSION}" VERSION_EQUAL "@ASSIMP_VERSION@") if( "${PACKAGE_FIND_VERSION}" VERSION_EQUAL "@ASSIMP_VERSION@")
set(PACKAGE_VERSION_EXACT 1) set(PACKAGE_VERSION_EXACT 1)
endif() endif()
if( "${PACKAGE_FIND_VERSION_MAJOR}.${PACKAGE_FIND_VERSION_MINOR}" EQUAL "@ASSIMP_SOVERSION@" ) if( "${PACKAGE_FIND_VERSION_MAJOR}.${PACKAGE_FIND_VERSION_MINOR}" EQUAL "@ASSIMP_VERSION@" )
set(PACKAGE_VERSION_COMPATIBLE 1) set(PACKAGE_VERSION_COMPATIBLE 1)
elseif( "${PACKAGE_FIND_VERSION_MAJOR}" EQUAL "@ASSIMP_VERSION_MAJOR@" ) elseif( "${PACKAGE_FIND_VERSION_MAJOR}" EQUAL "@ASSIMP_VERSION_MAJOR@" )
# for now backward compatible if minor version is less # for now backward compatible if minor version is less

View File

@ -1,78 +0,0 @@
find_package(Threads REQUIRED)
include(ExternalProject)
if(MSYS OR MINGW)
set(DISABLE_PTHREADS ON)
else()
set(DISABLE_PTHREADS OFF)
endif()
if (MSVC)
set(RELEASE_LIB_DIR ReleaseLibs)
set(DEBUG_LIB_DIR DebugLibs)
elseif(XCODE_VERSION)
set(RELEASE_LIB_DIR Release)
set(DEBUG_LIB_DIR Debug)
else()
set(RELEASE_LIB_DIR "")
set(DEBUG_LIB_DIR "")
endif()
set(GTEST_CMAKE_ARGS
"-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}"
"-Dgtest_force_shared_crt=ON"
"-Dgtest_disable_pthreads:BOOL=${DISABLE_PTHREADS}"
"-DBUILD_GTEST=ON")
set(GTEST_RELEASE_LIB_DIR "")
set(GTEST_DEBUGLIB_DIR "")
if (MSVC)
set(GTEST_CMAKE_ARGS ${GTEST_CMAKE_ARGS}
"-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG:PATH=${DEBUG_LIB_DIR}"
"-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE:PATH=${RELEASE_LIB_DIR}")
set(GTEST_LIB_DIR)
endif()
set(GTEST_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/gtest")
# try to find git - if found, setup gtest
find_package(Git)
if(NOT GIT_FOUND)
set(AddGTest_FOUND false CACHE BOOL "Was gtest setup correctly?")
else(NOT GIT_FOUND)
set(AddGTest_FOUND true CACHE BOOL "Was gtest setup correctly?")
ExternalProject_Add(gtest
GIT_REPOSITORY https://github.com/google/googletest.git
TIMEOUT 10
PREFIX "${GTEST_PREFIX}"
CMAKE_ARGS "${GTEST_CMAKE_ARGS}"
LOG_DOWNLOAD ON
LOG_CONFIGURE ON
LOG_BUILD ON
# Disable install
INSTALL_COMMAND ""
)
set(LIB_PREFIX "${CMAKE_STATIC_LIBRARY_PREFIX}")
set(LIB_SUFFIX "${CMAKE_STATIC_LIBRARY_SUFFIX}")
set(GTEST_LOCATION "${GTEST_PREFIX}/src/gtest-build")
set(GTEST_DEBUG_LIBRARIES
"${LIB_PREFIX}gtest${LIB_SUFFIX}"
"${CMAKE_THREAD_LIBS_INIT}")
SET(GTEST_RELEASE_LIBRARIES
"${LIB_PREFIX}gtest${LIB_SUFFIX}"
"${CMAKE_THREAD_LIBS_INIT}")
if(MSVC_VERSION EQUAL 1700)
add_definitions(-D_VARIADIC_MAX=10)
endif()
ExternalProject_Get_Property(gtest source_dir)
include_directories(${source_dir}/googletest/include)
include_directories(${source_dir}/gtest/include)
ExternalProject_Get_Property(gtest binary_dir)
link_directories(${binary_dir}/googlemock/gtest)
link_directories(${binary_dir}/googlemock/gtest/${RELEASE_LIB_DIR})
link_directories(${binary_dir}/googlemock/gtest/${DEBUG_LIB_DIR})
endif(NOT GIT_FOUND)

View File

@ -0,0 +1,126 @@
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Copyright (C) 2014 Joakim Söderberg <joakim.soderberg@gmail.com>
#
set(_CMAKE_SCRIPT_PATH ${CMAKE_CURRENT_LIST_DIR}) # must be outside coveralls_setup() to get correct path
#
# Param _COVERAGE_SRCS A list of source files that coverage should be collected for.
# Param _COVERALLS_UPLOAD Upload the result to coveralls?
#
function(coveralls_setup _COVERAGE_SRCS _COVERALLS_UPLOAD)
if (ARGC GREATER 2)
set(_CMAKE_SCRIPT_PATH ${ARGN})
message(STATUS "Coveralls: Using alternate CMake script dir: ${_CMAKE_SCRIPT_PATH}")
endif()
if (NOT EXISTS "${_CMAKE_SCRIPT_PATH}/CoverallsClear.cmake")
message(FATAL_ERROR "Coveralls: Missing ${_CMAKE_SCRIPT_PATH}/CoverallsClear.cmake")
endif()
if (NOT EXISTS "${_CMAKE_SCRIPT_PATH}/CoverallsGenerateGcov.cmake")
message(FATAL_ERROR "Coveralls: Missing ${_CMAKE_SCRIPT_PATH}/CoverallsGenerateGcov.cmake")
endif()
# When passing a CMake list to an external process, the list
# will be converted from the format "1;2;3" to "1 2 3".
# This means the script we're calling won't see it as a list
# of sources, but rather just one long path. We remedy this
# by replacing ";" with "*" and then reversing that in the script
# that we're calling.
# http://cmake.3232098.n2.nabble.com/Passing-a-CMake-list-quot-as-is-quot-to-a-custom-target-td6505681.html
set(COVERAGE_SRCS_TMP ${_COVERAGE_SRCS})
set(COVERAGE_SRCS "")
foreach (COVERAGE_SRC ${COVERAGE_SRCS_TMP})
set(COVERAGE_SRCS "${COVERAGE_SRCS}*${COVERAGE_SRC}")
endforeach()
#message("Coverage sources: ${COVERAGE_SRCS}")
set(COVERALLS_FILE ${PROJECT_BINARY_DIR}/coveralls.json)
add_custom_target(coveralls_generate
# Zero the coverage counters.
COMMAND ${CMAKE_COMMAND} -DPROJECT_BINARY_DIR="${PROJECT_BINARY_DIR}" -P "${_CMAKE_SCRIPT_PATH}/CoverallsClear.cmake"
# Run regress tests.
COMMAND ${CMAKE_CTEST_COMMAND} --output-on-failure
# Generate Gcov and translate it into coveralls JSON.
# We do this by executing an external CMake script.
# (We don't want this to run at CMake generation time, but after compilation and everything has run).
COMMAND ${CMAKE_COMMAND}
-DCOVERAGE_SRCS="${COVERAGE_SRCS}" # TODO: This is passed like: "a b c", not "a;b;c"
-DCOVERALLS_OUTPUT_FILE="${COVERALLS_FILE}"
-DCOV_PATH="${PROJECT_BINARY_DIR}"
-DPROJECT_ROOT="${PROJECT_SOURCE_DIR}"
-P "${_CMAKE_SCRIPT_PATH}/CoverallsGenerateGcov.cmake"
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
COMMENT "Generating coveralls output..."
)
if (_COVERALLS_UPLOAD)
message("COVERALLS UPLOAD: ON")
find_program(CURL_EXECUTABLE curl)
if (NOT CURL_EXECUTABLE)
message(FATAL_ERROR "Coveralls: curl not found! Aborting")
endif()
add_custom_target(coveralls_upload
# Upload the JSON to coveralls.
COMMAND ${CURL_EXECUTABLE}
-S -F json_file=@${COVERALLS_FILE}
https://coveralls.io/api/v1/jobs
DEPENDS coveralls_generate
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
COMMENT "Uploading coveralls output...")
add_custom_target(coveralls DEPENDS coveralls_upload)
else()
message("COVERALLS UPLOAD: OFF")
add_custom_target(coveralls DEPENDS coveralls_generate)
endif()
endfunction()
macro(coveralls_turn_on_coverage)
if(NOT (CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)
AND (NOT "${CMAKE_C_COMPILER_ID}" STREQUAL "Clang"))
message(FATAL_ERROR "Coveralls: Compiler ${CMAKE_C_COMPILER_ID} is not GNU gcc! Aborting... You can set this on the command line using CC=/usr/bin/gcc CXX=/usr/bin/g++ cmake <options> ..")
endif()
if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
message(FATAL_ERROR "Coveralls: Code coverage results with an optimised (non-Debug) build may be misleading! Add -DCMAKE_BUILD_TYPE=Debug")
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage")
endmacro()

View File

@ -0,0 +1,31 @@
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Copyright (C) 2014 Joakim Söderberg <joakim.soderberg@gmail.com>
#
# do not follow symlinks in file(GLOB_RECURSE ...)
cmake_policy(SET CMP0009 NEW)
file(GLOB_RECURSE GCDA_FILES "${PROJECT_BINARY_DIR}/*.gcda")
if(NOT GCDA_FILES STREQUAL "")
file(REMOVE ${GCDA_FILES})
endif()

View File

@ -0,0 +1,482 @@
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Copyright (C) 2014 Joakim Söderberg <joakim.soderberg@gmail.com>
#
# This is intended to be run by a custom target in a CMake project like this.
# 0. Compile program with coverage support.
# 1. Clear coverage data. (Recursively delete *.gcda in build dir)
# 2. Run the unit tests.
# 3. Run this script specifying which source files the coverage should be performed on.
#
# This script will then use gcov to generate .gcov files in the directory specified
# via the COV_PATH var. This should probably be the same as your cmake build dir.
#
# It then parses the .gcov files to convert them into the Coveralls JSON format:
# https://coveralls.io/docs/api
#
# Example for running as standalone CMake script from the command line:
# (Note it is important the -P is at the end...)
# $ cmake -DCOV_PATH=$(pwd)
# -DCOVERAGE_SRCS="catcierge_rfid.c;catcierge_timer.c"
# -P ../cmake/CoverallsGcovUpload.cmake
#
CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
#
# Make sure we have the needed arguments.
#
if (NOT COVERALLS_OUTPUT_FILE)
message(FATAL_ERROR "Coveralls: No coveralls output file specified. Please set COVERALLS_OUTPUT_FILE")
endif()
if (NOT COV_PATH)
message(FATAL_ERROR "Coveralls: Missing coverage directory path where gcov files will be generated. Please set COV_PATH")
endif()
if (NOT COVERAGE_SRCS)
message(FATAL_ERROR "Coveralls: Missing the list of source files that we should get the coverage data for COVERAGE_SRCS")
endif()
if (NOT PROJECT_ROOT)
message(FATAL_ERROR "Coveralls: Missing PROJECT_ROOT.")
endif()
# Since it's not possible to pass a CMake list properly in the
# "1;2;3" format to an external process, we have replaced the
# ";" with "*", so reverse that here so we get it back into the
# CMake list format.
string(REGEX REPLACE "\\*" ";" COVERAGE_SRCS ${COVERAGE_SRCS})
if (NOT DEFINED ENV{GCOV})
find_program(GCOV_EXECUTABLE gcov)
else()
find_program(GCOV_EXECUTABLE $ENV{GCOV})
endif()
# convert all paths in COVERAGE_SRCS to absolute paths
set(COVERAGE_SRCS_TMP "")
foreach (COVERAGE_SRC ${COVERAGE_SRCS})
if (NOT "${COVERAGE_SRC}" MATCHES "^/")
set(COVERAGE_SRC ${PROJECT_ROOT}/${COVERAGE_SRC})
endif()
list(APPEND COVERAGE_SRCS_TMP ${COVERAGE_SRC})
endforeach()
set(COVERAGE_SRCS ${COVERAGE_SRCS_TMP})
unset(COVERAGE_SRCS_TMP)
if (NOT GCOV_EXECUTABLE)
message(FATAL_ERROR "gcov not found! Aborting...")
endif()
find_package(Git)
set(JSON_REPO_TEMPLATE
"{
\"head\": {
\"id\": \"\@GIT_COMMIT_HASH\@\",
\"author_name\": \"\@GIT_AUTHOR_NAME\@\",
\"author_email\": \"\@GIT_AUTHOR_EMAIL\@\",
\"committer_name\": \"\@GIT_COMMITTER_NAME\@\",
\"committer_email\": \"\@GIT_COMMITTER_EMAIL\@\",
\"message\": \"\@GIT_COMMIT_MESSAGE\@\"
},
\"branch\": \"@GIT_BRANCH@\",
\"remotes\": []
}"
)
# TODO: Fill in git remote data
if (GIT_FOUND)
# Branch.
execute_process(
COMMAND ${GIT_EXECUTABLE} rev-parse --abbrev-ref HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_BRANCH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
macro (git_log_format FORMAT_CHARS VAR_NAME)
execute_process(
COMMAND ${GIT_EXECUTABLE} log -1 --pretty=format:%${FORMAT_CHARS}
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE ${VAR_NAME}
OUTPUT_STRIP_TRAILING_WHITESPACE
)
endmacro()
git_log_format(an GIT_AUTHOR_NAME)
git_log_format(ae GIT_AUTHOR_EMAIL)
git_log_format(cn GIT_COMMITTER_NAME)
git_log_format(ce GIT_COMMITTER_EMAIL)
git_log_format(B GIT_COMMIT_MESSAGE)
git_log_format(H GIT_COMMIT_HASH)
if(GIT_COMMIT_MESSAGE)
string(REPLACE "\n" "\\n" GIT_COMMIT_MESSAGE ${GIT_COMMIT_MESSAGE})
endif()
message("Git exe: ${GIT_EXECUTABLE}")
message("Git branch: ${GIT_BRANCH}")
message("Git author: ${GIT_AUTHOR_NAME}")
message("Git e-mail: ${GIT_AUTHOR_EMAIL}")
message("Git commiter name: ${GIT_COMMITTER_NAME}")
message("Git commiter e-mail: ${GIT_COMMITTER_EMAIL}")
message("Git commit hash: ${GIT_COMMIT_HASH}")
message("Git commit message: ${GIT_COMMIT_MESSAGE}")
string(CONFIGURE ${JSON_REPO_TEMPLATE} JSON_REPO_DATA)
else()
set(JSON_REPO_DATA "{}")
endif()
############################# Macros #########################################
#
# This macro converts from the full path format gcov outputs:
#
# /path/to/project/root/build/#path#to#project#root#subdir#the_file.c.gcov
#
# to the original source file path the .gcov is for:
#
# /path/to/project/root/subdir/the_file.c
#
macro(get_source_path_from_gcov_filename _SRC_FILENAME _GCOV_FILENAME)
# /path/to/project/root/build/#path#to#project#root#subdir#the_file.c.gcov
# ->
# #path#to#project#root#subdir#the_file.c.gcov
get_filename_component(_GCOV_FILENAME_WEXT ${_GCOV_FILENAME} NAME)
# #path#to#project#root#subdir#the_file.c.gcov -> /path/to/project/root/subdir/the_file.c
string(REGEX REPLACE "\\.gcov$" "" SRC_FILENAME_TMP ${_GCOV_FILENAME_WEXT})
string(REGEX REPLACE "\#" "/" SRC_FILENAME_TMP ${SRC_FILENAME_TMP})
set(${_SRC_FILENAME} "${SRC_FILENAME_TMP}")
endmacro()
##############################################################################
# Get the coverage data.
file(GLOB_RECURSE GCDA_FILES "${COV_PATH}/*.gcda")
message("GCDA files:")
# Get a list of all the object directories needed by gcov
# (The directories the .gcda files and .o files are found in)
# and run gcov on those.
foreach(GCDA ${GCDA_FILES})
message("Process: ${GCDA}")
message("------------------------------------------------------------------------------")
get_filename_component(GCDA_DIR ${GCDA} PATH)
#
# The -p below refers to "Preserve path components",
# This means that the generated gcov filename of a source file will
# keep the original files entire filepath, but / is replaced with #.
# Example:
#
# /path/to/project/root/build/CMakeFiles/the_file.dir/subdir/the_file.c.gcda
# ------------------------------------------------------------------------------
# File '/path/to/project/root/subdir/the_file.c'
# Lines executed:68.34% of 199
# /path/to/project/root/subdir/the_file.c:creating '#path#to#project#root#subdir#the_file.c.gcov'
#
# If -p is not specified then the file is named only "the_file.c.gcov"
#
execute_process(
COMMAND ${GCOV_EXECUTABLE} -p -o ${GCDA_DIR} ${GCDA}
WORKING_DIRECTORY ${COV_PATH}
)
endforeach()
# TODO: Make these be absolute path
file(GLOB ALL_GCOV_FILES ${COV_PATH}/*.gcov)
# Get only the filenames to use for filtering.
#set(COVERAGE_SRCS_NAMES "")
#foreach (COVSRC ${COVERAGE_SRCS})
# get_filename_component(COVSRC_NAME ${COVSRC} NAME)
# message("${COVSRC} -> ${COVSRC_NAME}")
# list(APPEND COVERAGE_SRCS_NAMES "${COVSRC_NAME}")
#endforeach()
#
# Filter out all but the gcov files we want.
#
# We do this by comparing the list of COVERAGE_SRCS filepaths that the
# user wants the coverage data for with the paths of the generated .gcov files,
# so that we only keep the relevant gcov files.
#
# Example:
# COVERAGE_SRCS =
# /path/to/project/root/subdir/the_file.c
#
# ALL_GCOV_FILES =
# /path/to/project/root/build/#path#to#project#root#subdir#the_file.c.gcov
# /path/to/project/root/build/#path#to#project#root#subdir#other_file.c.gcov
#
# Result should be:
# GCOV_FILES =
# /path/to/project/root/build/#path#to#project#root#subdir#the_file.c.gcov
#
set(GCOV_FILES "")
#message("Look in coverage sources: ${COVERAGE_SRCS}")
message("\nFilter out unwanted GCOV files:")
message("===============================")
set(COVERAGE_SRCS_REMAINING ${COVERAGE_SRCS})
foreach (GCOV_FILE ${ALL_GCOV_FILES})
#
# /path/to/project/root/build/#path#to#project#root#subdir#the_file.c.gcov
# ->
# /path/to/project/root/subdir/the_file.c
get_source_path_from_gcov_filename(GCOV_SRC_PATH ${GCOV_FILE})
file(RELATIVE_PATH GCOV_SRC_REL_PATH "${PROJECT_ROOT}" "${GCOV_SRC_PATH}")
# Is this in the list of source files?
# TODO: We want to match against relative path filenames from the source file root...
list(FIND COVERAGE_SRCS ${GCOV_SRC_PATH} WAS_FOUND)
if (NOT WAS_FOUND EQUAL -1)
message("YES: ${GCOV_FILE}")
list(APPEND GCOV_FILES ${GCOV_FILE})
# We remove it from the list, so we don't bother searching for it again.
# Also files left in COVERAGE_SRCS_REMAINING after this loop ends should
# have coverage data generated from them (no lines are covered).
list(REMOVE_ITEM COVERAGE_SRCS_REMAINING ${GCOV_SRC_PATH})
else()
message("NO: ${GCOV_FILE}")
endif()
endforeach()
# TODO: Enable setting these
set(JSON_SERVICE_NAME "travis-ci")
set(JSON_SERVICE_JOB_ID $ENV{TRAVIS_JOB_ID})
set(JSON_REPO_TOKEN $ENV{COVERALLS_REPO_TOKEN})
set(JSON_TEMPLATE
"{
\"repo_token\": \"\@JSON_REPO_TOKEN\@\",
\"service_name\": \"\@JSON_SERVICE_NAME\@\",
\"service_job_id\": \"\@JSON_SERVICE_JOB_ID\@\",
\"source_files\": \@JSON_GCOV_FILES\@,
\"git\": \@JSON_REPO_DATA\@
}"
)
set(SRC_FILE_TEMPLATE
"{
\"name\": \"\@GCOV_SRC_REL_PATH\@\",
\"source_digest\": \"\@GCOV_CONTENTS_MD5\@\",
\"coverage\": \@GCOV_FILE_COVERAGE\@
}"
)
message("\nGenerate JSON for files:")
message("=========================")
set(JSON_GCOV_FILES "[")
# Read the GCOV files line by line and get the coverage data.
foreach (GCOV_FILE ${GCOV_FILES})
get_source_path_from_gcov_filename(GCOV_SRC_PATH ${GCOV_FILE})
file(RELATIVE_PATH GCOV_SRC_REL_PATH "${PROJECT_ROOT}" "${GCOV_SRC_PATH}")
# The new coveralls API doesn't need the entire source (Yay!)
# However, still keeping that part for now. Will cleanup in the future.
file(MD5 "${GCOV_SRC_PATH}" GCOV_CONTENTS_MD5)
message("MD5: ${GCOV_SRC_PATH} = ${GCOV_CONTENTS_MD5}")
# Loads the gcov file as a list of lines.
# (We first open the file and replace all occurences of [] with _
# because CMake will fail to parse a line containing unmatched brackets...
# also the \ to escaped \n in macros screws up things.)
# https://public.kitware.com/Bug/view.php?id=15369
file(READ ${GCOV_FILE} GCOV_CONTENTS)
string(REPLACE "[" "_" GCOV_CONTENTS "${GCOV_CONTENTS}")
string(REPLACE "]" "_" GCOV_CONTENTS "${GCOV_CONTENTS}")
string(REPLACE "\\" "_" GCOV_CONTENTS "${GCOV_CONTENTS}")
# Remove file contents to avoid encoding issues (cmake 2.8 has no ENCODING option)
string(REGEX REPLACE "([^:]*):([^:]*):([^\n]*)\n" "\\1:\\2: \n" GCOV_CONTENTS "${GCOV_CONTENTS}")
file(WRITE ${GCOV_FILE}_tmp "${GCOV_CONTENTS}")
file(STRINGS ${GCOV_FILE}_tmp GCOV_LINES)
list(LENGTH GCOV_LINES LINE_COUNT)
# Instead of trying to parse the source from the
# gcov file, simply read the file contents from the source file.
# (Parsing it from the gcov is hard because C-code uses ; in many places
# which also happens to be the same as the CMake list delimeter).
file(READ ${GCOV_SRC_PATH} GCOV_FILE_SOURCE)
string(REPLACE "\\" "\\\\" GCOV_FILE_SOURCE "${GCOV_FILE_SOURCE}")
string(REGEX REPLACE "\"" "\\\\\"" GCOV_FILE_SOURCE "${GCOV_FILE_SOURCE}")
string(REPLACE "\t" "\\\\t" GCOV_FILE_SOURCE "${GCOV_FILE_SOURCE}")
string(REPLACE "\r" "\\\\r" GCOV_FILE_SOURCE "${GCOV_FILE_SOURCE}")
string(REPLACE "\n" "\\\\n" GCOV_FILE_SOURCE "${GCOV_FILE_SOURCE}")
# According to http://json.org/ these should be escaped as well.
# Don't know how to do that in CMake however...
#string(REPLACE "\b" "\\\\b" GCOV_FILE_SOURCE "${GCOV_FILE_SOURCE}")
#string(REPLACE "\f" "\\\\f" GCOV_FILE_SOURCE "${GCOV_FILE_SOURCE}")
#string(REGEX REPLACE "\u([a-fA-F0-9]{4})" "\\\\u\\1" GCOV_FILE_SOURCE "${GCOV_FILE_SOURCE}")
# We want a json array of coverage data as a single string
# start building them from the contents of the .gcov
set(GCOV_FILE_COVERAGE "[")
set(GCOV_LINE_COUNT 1) # Line number for the .gcov.
set(DO_SKIP 0)
foreach (GCOV_LINE ${GCOV_LINES})
#message("${GCOV_LINE}")
# Example of what we're parsing:
# Hitcount |Line | Source
# " 8: 26: if (!allowed || (strlen(allowed) == 0))"
string(REGEX REPLACE
"^([^:]*):([^:]*):(.*)$"
"\\1;\\2;\\3"
RES
"${GCOV_LINE}")
# Check if we should exclude lines using the Lcov syntax.
string(REGEX MATCH "LCOV_EXCL_START" START_SKIP "${GCOV_LINE}")
string(REGEX MATCH "LCOV_EXCL_END" END_SKIP "${GCOV_LINE}")
string(REGEX MATCH "LCOV_EXCL_LINE" LINE_SKIP "${GCOV_LINE}")
set(RESET_SKIP 0)
if (LINE_SKIP AND NOT DO_SKIP)
set(DO_SKIP 1)
set(RESET_SKIP 1)
endif()
if (START_SKIP)
set(DO_SKIP 1)
message("${GCOV_LINE_COUNT}: Start skip")
endif()
if (END_SKIP)
set(DO_SKIP 0)
endif()
list(LENGTH RES RES_COUNT)
if (RES_COUNT GREATER 2)
list(GET RES 0 HITCOUNT)
list(GET RES 1 LINE)
list(GET RES 2 SOURCE)
string(STRIP ${HITCOUNT} HITCOUNT)
string(STRIP ${LINE} LINE)
# Lines with 0 line numbers are metadata and can be ignored.
if (NOT ${LINE} EQUAL 0)
if (DO_SKIP)
set(GCOV_FILE_COVERAGE "${GCOV_FILE_COVERAGE}null, ")
else()
# Translate the hitcount into valid JSON values.
if (${HITCOUNT} STREQUAL "#####" OR ${HITCOUNT} STREQUAL "=====")
set(GCOV_FILE_COVERAGE "${GCOV_FILE_COVERAGE}0, ")
elseif (${HITCOUNT} STREQUAL "-")
set(GCOV_FILE_COVERAGE "${GCOV_FILE_COVERAGE}null, ")
else()
set(GCOV_FILE_COVERAGE "${GCOV_FILE_COVERAGE}${HITCOUNT}, ")
endif()
endif()
endif()
else()
message(WARNING "Failed to properly parse line (RES_COUNT = ${RES_COUNT}) ${GCOV_FILE}:${GCOV_LINE_COUNT}\n-->${GCOV_LINE}")
endif()
if (RESET_SKIP)
set(DO_SKIP 0)
endif()
math(EXPR GCOV_LINE_COUNT "${GCOV_LINE_COUNT}+1")
endforeach()
message("${GCOV_LINE_COUNT} of ${LINE_COUNT} lines read!")
# Advanced way of removing the trailing comma in the JSON array.
# "[1, 2, 3, " -> "[1, 2, 3"
string(REGEX REPLACE ",[ ]*$" "" GCOV_FILE_COVERAGE ${GCOV_FILE_COVERAGE})
# Append the trailing ] to complete the JSON array.
set(GCOV_FILE_COVERAGE "${GCOV_FILE_COVERAGE}]")
# Generate the final JSON for this file.
message("Generate JSON for file: ${GCOV_SRC_REL_PATH}...")
string(CONFIGURE ${SRC_FILE_TEMPLATE} FILE_JSON)
set(JSON_GCOV_FILES "${JSON_GCOV_FILES}${FILE_JSON}, ")
endforeach()
# Loop through all files we couldn't find any coverage for
# as well, and generate JSON for those as well with 0% coverage.
foreach(NOT_COVERED_SRC ${COVERAGE_SRCS_REMAINING})
# Set variables for json replacement
set(GCOV_SRC_PATH ${NOT_COVERED_SRC})
file(MD5 "${GCOV_SRC_PATH}" GCOV_CONTENTS_MD5)
file(RELATIVE_PATH GCOV_SRC_REL_PATH "${PROJECT_ROOT}" "${GCOV_SRC_PATH}")
# Loads the source file as a list of lines.
file(STRINGS ${NOT_COVERED_SRC} SRC_LINES)
set(GCOV_FILE_COVERAGE "[")
set(GCOV_FILE_SOURCE "")
foreach (SOURCE ${SRC_LINES})
set(GCOV_FILE_COVERAGE "${GCOV_FILE_COVERAGE}null, ")
string(REPLACE "\\" "\\\\" SOURCE "${SOURCE}")
string(REGEX REPLACE "\"" "\\\\\"" SOURCE "${SOURCE}")
string(REPLACE "\t" "\\\\t" SOURCE "${SOURCE}")
string(REPLACE "\r" "\\\\r" SOURCE "${SOURCE}")
set(GCOV_FILE_SOURCE "${GCOV_FILE_SOURCE}${SOURCE}\\n")
endforeach()
# Remove trailing comma, and complete JSON array with ]
string(REGEX REPLACE ",[ ]*$" "" GCOV_FILE_COVERAGE ${GCOV_FILE_COVERAGE})
set(GCOV_FILE_COVERAGE "${GCOV_FILE_COVERAGE}]")
# Generate the final JSON for this file.
message("Generate JSON for non-gcov file: ${NOT_COVERED_SRC}...")
string(CONFIGURE ${SRC_FILE_TEMPLATE} FILE_JSON)
set(JSON_GCOV_FILES "${JSON_GCOV_FILES}${FILE_JSON}, ")
endforeach()
# Get rid of trailing comma.
string(REGEX REPLACE ",[ ]*$" "" JSON_GCOV_FILES ${JSON_GCOV_FILES})
set(JSON_GCOV_FILES "${JSON_GCOV_FILES}]")
# Generate the final complete JSON!
message("Generate final JSON...")
string(CONFIGURE ${JSON_TEMPLATE} JSON)
file(WRITE "${COVERALLS_OUTPUT_FILE}" "${JSON}")
message("###########################################################################")
message("Generated coveralls JSON containing coverage data:")
message("${COVERALLS_OUTPUT_FILE}")
message("###########################################################################")

View File

@ -0,0 +1,72 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#.rst:
# FindDevIL
# ---------
#
#
#
# This module locates the developer's image library.
# http://openil.sourceforge.net/
#
# This module sets:
#
# ::
#
# IL_LIBRARIES - the name of the IL library. These include the full path to
# the core DevIL library. This one has to be linked into the
# application.
# ILU_LIBRARIES - the name of the ILU library. Again, the full path. This
# library is for filters and effects, not actual loading. It
# doesn't have to be linked if the functionality it provides
# is not used.
# ILUT_LIBRARIES - the name of the ILUT library. Full path. This part of the
# library interfaces with OpenGL. It is not strictly needed
# in applications.
# IL_INCLUDE_DIR - where to find the il.h, ilu.h and ilut.h files.
# IL_FOUND - this is set to TRUE if all the above variables were set.
# This will be set to false if ILU or ILUT are not found,
# even if they are not needed. In most systems, if one
# library is found all the others are as well. That's the
# way the DevIL developers release it.
# TODO: Add version support.
# Tested under Linux and Windows (MSVC)
#include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
include(FindPackageHandleStandardArgs)
find_path(IL_INCLUDE_DIR il.h
PATH_SUFFIXES include IL
DOC "The path to the directory that contains il.h"
)
#message("IL_INCLUDE_DIR is ${IL_INCLUDE_DIR}")
find_library(IL_LIBRARIES
NAMES IL DEVIL
PATH_SUFFIXES lib64 lib lib32
DOC "The file that corresponds to the base il library."
)
#message("IL_LIBRARIES is ${IL_LIBRARIES}")
find_library(ILUT_LIBRARIES
NAMES ILUT
PATH_SUFFIXES lib64 lib lib32
DOC "The file that corresponds to the il (system?) utility library."
)
#message("ILUT_LIBRARIES is ${ILUT_LIBRARIES}")
find_library(ILU_LIBRARIES
NAMES ILU
PATH_SUFFIXES lib64 lib lib32
DOC "The file that corresponds to the il utility library."
)
#message("ILU_LIBRARIES is ${ILU_LIBRARIES}")
FIND_PACKAGE_HANDLE_STANDARD_ARGS(IL DEFAULT_MSG
IL_LIBRARIES IL_INCLUDE_DIR)

View File

@ -0,0 +1,17 @@
# Find IrrXMl from irrlicht project
#
# Find LibIrrXML headers and library
#
# IRRXML_FOUND - IrrXML found
# IRRXML_INCLUDE_DIR - Headers location
# IRRXML_LIBRARY - IrrXML main library
find_path(IRRXML_INCLUDE_DIR irrXML.h
PATH_SUFFIXES include/irrlicht include/irrxml)
find_library(IRRXML_LIBRARY IrrXML)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(IrrXML REQUIRED_VARS IRRXML_INCLUDE_DIR IRRXML_LIBRARY)
mark_as_advanced(IRRXML_INCLUDE_DIR IRRXML_LIBRARY)

View File

@ -59,10 +59,13 @@ endmacro(clear_if_changed)
# Try to get some hints from pkg-config, if available # Try to get some hints from pkg-config, if available
macro(use_pkgconfig PREFIX PKGNAME) macro(use_pkgconfig PREFIX PKGNAME)
find_package(PkgConfig) # Android does not support PKG_CONFIG so we disable it
if (PKG_CONFIG_FOUND) IF ( NOT ANDROID )
pkg_check_modules(${PREFIX} ${PKGNAME}) find_package(PkgConfig)
endif () if (PKG_CONFIG_FOUND)
pkg_check_modules(${PREFIX} ${PKGNAME})
endif ()
ENDIF ( NOT ANDROID )
endmacro (use_pkgconfig) endmacro (use_pkgconfig)
# Couple a set of release AND debug libraries (or frameworks) # Couple a set of release AND debug libraries (or frameworks)

View File

@ -0,0 +1,20 @@
# Try to find real time libraries
# Once done, this will define
#
# RT_FOUND - system has rt library
# RT_LIBRARIES - rt libraries directory
#
# Source: https://gitlab.cern.ch/dss/eos/commit/44070e575faaa46bd998708ef03eedb381506ff0
#
if(RT_LIBRARIES)
set(RT_FIND_QUIETLY TRUE)
endif(RT_LIBRARIES)
find_library(RT_LIBRARY rt)
set(RT_LIBRARIES ${RT_LIBRARY})
# handle the QUIETLY and REQUIRED arguments and set
# RT_FOUND to TRUE if all listed variables are TRUE
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(rt DEFAULT_MSG RT_LIBRARY)
mark_as_advanced(RT_LIBRARY)

View File

@ -11,7 +11,7 @@
# Once done, this will define # Once done, this will define
# #
# ZLIB_FOUND - system has ZLIB # ZLIB_FOUND - system has ZLIB
# ZLIB_INCLUDE_DIRS - the ZLIB include directories # ZLIB_INCLUDE_DIRS - the ZLIB include directories
# ZLIB_LIBRARIES - link these to use ZLIB # ZLIB_LIBRARIES - link these to use ZLIB
include(FindPkgMacros) include(FindPkgMacros)

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -690,7 +691,7 @@ void Discreet3DSImporter::AddNodeToGraph(aiScene* pcSOut,aiNode* pcOut,
pcOut->mChildren = new aiNode*[pcIn->mChildren.size()]; pcOut->mChildren = new aiNode*[pcIn->mChildren.size()];
// Recursively process all children // Recursively process all children
const unsigned int size = pcIn->mChildren.size(); const unsigned int size = static_cast<unsigned int>(pcIn->mChildren.size());
for (unsigned int i = 0; i < size;++i) for (unsigned int i = 0; i < size;++i)
{ {
pcOut->mChildren[i] = new aiNode(); pcOut->mChildren[i] = new aiNode();
@ -742,7 +743,7 @@ void Discreet3DSImporter::GenerateNodeGraph(aiScene* pcOut)
DefaultLogger::get()->warn("No hierarchy information has been found in the file. "); DefaultLogger::get()->warn("No hierarchy information has been found in the file. ");
pcOut->mRootNode->mNumChildren = pcOut->mNumMeshes + pcOut->mRootNode->mNumChildren = pcOut->mNumMeshes +
mScene->mCameras.size() + mScene->mLights.size(); static_cast<unsigned int>(mScene->mCameras.size() + mScene->mLights.size());
pcOut->mRootNode->mChildren = new aiNode* [ pcOut->mRootNode->mNumChildren ]; pcOut->mRootNode->mChildren = new aiNode* [ pcOut->mRootNode->mNumChildren ];
pcOut->mRootNode->mName.Set("<3DSDummyRoot>"); pcOut->mRootNode->mName.Set("<3DSDummyRoot>");

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -44,6 +45,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "3DSExporter.h" #include "3DSExporter.h"
#include "3DSLoader.h" #include "3DSLoader.h"
#include "3DSHelper.h"
#include "SceneCombiner.h" #include "SceneCombiner.h"
#include "SplitLargeMeshes.h" #include "SplitLargeMeshes.h"
#include "StringComparison.h" #include "StringComparison.h"
@ -54,6 +56,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using namespace Assimp; using namespace Assimp;
namespace Assimp { namespace Assimp {
using namespace D3DS;
namespace { namespace {
@ -85,7 +88,7 @@ namespace {
const std::size_t chunk_size = head_pos - chunk_start_pos; const std::size_t chunk_size = head_pos - chunk_start_pos;
writer.SetCurrentPos(chunk_start_pos + SIZE_OFFSET); writer.SetCurrentPos(chunk_start_pos + SIZE_OFFSET);
writer.PutU4(chunk_size); writer.PutU4(static_cast<uint32_t>(chunk_size));
writer.SetCurrentPos(head_pos); writer.SetCurrentPos(head_pos);
} }
@ -365,7 +368,7 @@ void Discreet3DSExporter::WriteTexture(const aiMaterial& mat, aiTextureType type
aiTextureMapMode map_mode[2] = { aiTextureMapMode map_mode[2] = {
aiTextureMapMode_Wrap, aiTextureMapMode_Wrap aiTextureMapMode_Wrap, aiTextureMapMode_Wrap
}; };
float blend = 1.0f; ai_real blend = 1.0;
if (mat.GetTexture(type, 0, &path, NULL, NULL, &blend, NULL, map_mode) != AI_SUCCESS || !path.length) { if (mat.GetTexture(type, 0, &path, NULL, NULL, &blend, NULL, map_mode) != AI_SUCCESS || !path.length) {
return; return;
} }
@ -560,6 +563,12 @@ void Discreet3DSExporter::WritePercentChunk(float f) {
writer.PutF4(f); writer.PutF4(f);
} }
// ------------------------------------------------------------------------------------------------
void Discreet3DSExporter::WritePercentChunk(double f) {
ChunkWriter chunk(writer, Discreet3DS::CHUNK_PERCENTD);
writer.PutF8(f);
}
#endif // ASSIMP_BUILD_NO_3DS_EXPORTER #endif // ASSIMP_BUILD_NO_3DS_EXPORTER
#endif // ASSIMP_BUILD_NO_EXPORT #endif // ASSIMP_BUILD_NO_EXPORT

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -48,7 +49,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <memory> #include <memory>
#include "StreamWriter.h" #include "StreamWriter.h"
#include "./../include/assimp/material.h" #include <assimp/material.h>
struct aiScene; struct aiScene;
struct aiNode; struct aiNode;
@ -80,6 +81,7 @@ private:
void WriteString(const aiString& s); void WriteString(const aiString& s);
void WriteColor(const aiColor3D& color); void WriteColor(const aiColor3D& color);
void WritePercentChunk(float f); void WritePercentChunk(float f);
void WritePercentChunk(double f);
private: private:

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -48,10 +49,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "SmoothingGroups.h" #include "SmoothingGroups.h"
#include "StringUtils.h" #include "StringUtils.h"
#include "qnan.h" #include "qnan.h"
#include "./../include/assimp/material.h" #include <assimp/material.h>
#include "./../include/assimp/camera.h" #include <assimp/camera.h>
#include "./../include/assimp/light.h" #include <assimp/light.h>
#include "./../include/assimp/anim.h" #include <assimp/anim.h>
#include <stdio.h> //sprintf #include <stdio.h> //sprintf
namespace Assimp { namespace Assimp {
@ -129,6 +130,7 @@ public:
CHUNK_PERCENTW = 0x0030, // int2 percentage CHUNK_PERCENTW = 0x0030, // int2 percentage
CHUNK_PERCENTF = 0x0031, // float4 percentage CHUNK_PERCENTF = 0x0031, // float4 percentage
CHUNK_PERCENTD = 0x0032, // float8 percentage
// ******************************************************************** // ********************************************************************
// Prj master chunk // Prj master chunk
@ -368,14 +370,13 @@ struct Material
{ {
//! Default constructor. Builds a default name for the material //! Default constructor. Builds a default name for the material
Material() Material()
: : mDiffuse ( ai_real( 0.6 ), ai_real( 0.6 ), ai_real( 0.6 ) ) // FIX ... we won't want object to be black
mDiffuse (0.6,0.6,0.6), // FIX ... we won't want object to be black , mSpecularExponent ( ai_real( 0.0 ) )
mSpecularExponent (0.0), , mShininessStrength ( ai_real( 1.0 ) )
mShininessStrength (1.0), , mShading(Discreet3DS::Gouraud)
mShading(Discreet3DS::Gouraud), , mTransparency ( ai_real( 1.0 ) )
mTransparency (1.0), , mBumpHeight ( ai_real( 1.0 ) )
mBumpHeight (1.0), , mTwoSided (false)
mTwoSided (false)
{ {
static int iCnt = 0; static int iCnt = 0;

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -54,6 +55,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/IOSystem.hpp> #include <assimp/IOSystem.hpp>
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp> #include <assimp/DefaultLogger.hpp>
#include <assimp/importerdesc.h>
#include "StringComparison.h" #include "StringComparison.h"
using namespace Assimp; using namespace Assimp;
@ -182,7 +184,7 @@ void Discreet3DSImporter::InternReadFile( const std::string& pFile,
ParseMainChunk(); ParseMainChunk();
// Process all meshes in the file. First check whether all // Process all meshes in the file. First check whether all
// face indices haev valid values. The generate our // face indices have valid values. The generate our
// internal verbose representation. Finally compute normal // internal verbose representation. Finally compute normal
// vectors from the smoothing groups we read from the // vectors from the smoothing groups we read from the
// file. // file.
@ -679,7 +681,7 @@ void Discreet3DSImporter::ParseHierarchyChunk(uint16_t parent)
if ( pcNode) if ( pcNode)
{ {
// if the source is not a CHUNK_TRACKINFO block it wont be an object instance // if the source is not a CHUNK_TRACKINFO block it won't be an object instance
if (parent != Discreet3DS::CHUNK_TRACKINFO) if (parent != Discreet3DS::CHUNK_TRACKINFO)
{ {
mCurrentNode = pcNode; mCurrentNode = pcNode;
@ -1166,14 +1168,15 @@ void Discreet3DSImporter::ParseMaterialChunk()
case Discreet3DS::CHUNK_MAT_TRANSPARENCY: case Discreet3DS::CHUNK_MAT_TRANSPARENCY:
{ {
// This is the material's transparency // This is the material's transparency
ai_real* pcf = &mScene->mMaterials.back().mTransparency; ai_real* pcf = &mScene->mMaterials.back().mTransparency;
*pcf = ParsePercentageChunk(); *pcf = ParsePercentageChunk();
// NOTE: transparency, not opacity // NOTE: transparency, not opacity
if (is_qnan(*pcf)) if (is_qnan(*pcf))
*pcf = 1.0; *pcf = ai_real( 1.0 );
else *pcf = 1.0 - *pcf * (ai_real)0xFFFF / 100.0; else
*pcf = ai_real( 1.0 ) - *pcf * (ai_real)0xFFFF / ai_real( 100.0 );
} }
break; break;
@ -1199,21 +1202,23 @@ void Discreet3DSImporter::ParseMaterialChunk()
case Discreet3DS::CHUNK_MAT_SHININESS_PERCENT: case Discreet3DS::CHUNK_MAT_SHININESS_PERCENT:
{ // This is the shininess strength of the material { // This is the shininess strength of the material
ai_real* pcf = &mScene->mMaterials.back().mShininessStrength; ai_real* pcf = &mScene->mMaterials.back().mShininessStrength;
*pcf = ParsePercentageChunk(); *pcf = ParsePercentageChunk();
if (is_qnan(*pcf)) if (is_qnan(*pcf))
*pcf = 0.0; *pcf = ai_real( 0.0 );
else *pcf *= (ai_real)0xffff / 100.0; else
*pcf *= (ai_real)0xffff / ai_real( 100.0 );
} }
break; break;
case Discreet3DS::CHUNK_MAT_SELF_ILPCT: case Discreet3DS::CHUNK_MAT_SELF_ILPCT:
{ // This is the self illumination strength of the material { // This is the self illumination strength of the material
ai_real f = ParsePercentageChunk(); ai_real f = ParsePercentageChunk();
if (is_qnan(f)) if (is_qnan(f))
f = 0.0; f = ai_real( 0.0 );
else f *= (ai_real)0xFFFF / 100.0; else
mScene->mMaterials.back().mEmissive = aiColor3D(f,f,f); f *= (ai_real)0xFFFF / ai_real( 100.0 );
mScene->mMaterials.back().mEmissive = aiColor3D(f,f,f);
} }
break; break;
@ -1270,6 +1275,11 @@ void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture* pcOut)
break; break;
case Discreet3DS::CHUNK_PERCENTD:
// Manually parse the blend factor
pcOut->mTextureBlend = ai_real( stream->GetF8() );
break;
case Discreet3DS::CHUNK_PERCENTF: case Discreet3DS::CHUNK_PERCENTF:
// Manually parse the blend factor // Manually parse the blend factor
pcOut->mTextureBlend = stream->GetF4(); pcOut->mTextureBlend = stream->GetF4();
@ -1277,7 +1287,7 @@ void Discreet3DSImporter::ParseTextureChunk(D3DS::Texture* pcOut)
case Discreet3DS::CHUNK_PERCENTW: case Discreet3DS::CHUNK_PERCENTW:
// Manually parse the blend factor // Manually parse the blend factor
pcOut->mTextureBlend = (ai_real)((uint16_t)stream->GetI2()) / 100.0; pcOut->mTextureBlend = (ai_real)((uint16_t)stream->GetI2()) / ai_real( 100.0 );
break; break;
case Discreet3DS::CHUNK_MAT_MAP_USCALE: case Discreet3DS::CHUNK_MAT_MAP_USCALE:
@ -1350,8 +1360,7 @@ ai_real Discreet3DSImporter::ParsePercentageChunk()
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Read a color chunk. If a percentage chunk is found instead it is read as a grayscale color // Read a color chunk. If a percentage chunk is found instead it is read as a grayscale color
void Discreet3DSImporter::ParseColorChunk(aiColor3D* out, void Discreet3DSImporter::ParseColorChunk( aiColor3D* out, bool acceptPercent )
bool acceptPercent)
{ {
ai_assert(out != NULL); ai_assert(out != NULL);
@ -1384,13 +1393,16 @@ void Discreet3DSImporter::ParseColorChunk(aiColor3D* out,
case Discreet3DS::CHUNK_LINRGBB: case Discreet3DS::CHUNK_LINRGBB:
bGamma = true; bGamma = true;
case Discreet3DS::CHUNK_RGBB: case Discreet3DS::CHUNK_RGBB:
if (sizeof(char) * 3 > diff) { {
*out = clrError; if ( sizeof( char ) * 3 > diff ) {
return; *out = clrError;
return;
}
const ai_real invVal = ai_real( 1.0 ) / ai_real( 255.0 );
out->r = ( ai_real ) ( uint8_t ) stream->GetI1() * invVal;
out->g = ( ai_real ) ( uint8_t ) stream->GetI1() * invVal;
out->b = ( ai_real ) ( uint8_t ) stream->GetI1() * invVal;
} }
out->r = (ai_real)(uint8_t)stream->GetI1() / 255.0;
out->g = (ai_real)(uint8_t)stream->GetI1() / 255.0;
out->b = (ai_real)(uint8_t)stream->GetI1() / 255.0;
break; break;
// Percentage chunks are accepted, too. // Percentage chunks are accepted, too.
@ -1404,7 +1416,7 @@ void Discreet3DSImporter::ParseColorChunk(aiColor3D* out,
case Discreet3DS::CHUNK_PERCENTW: case Discreet3DS::CHUNK_PERCENTW:
if (acceptPercent && 1 <= diff) { if (acceptPercent && 1 <= diff) {
out->g = out->b = out->r = (ai_real)(uint8_t)stream->GetI1() / 255.0; out->g = out->b = out->r = (ai_real)(uint8_t)stream->GetI1() / ai_real( 255.0 );
break; break;
} }
*out = clrError; *out = clrError;

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -4,7 +4,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -60,6 +61,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/config.h> #include <assimp/config.h>
#include <assimp/IOSystem.hpp> #include <assimp/IOSystem.hpp>
#include <assimp/importerdesc.h>
#include <memory> #include <memory>
using namespace Assimp; using namespace Assimp;

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -0,0 +1,704 @@
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 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 DAMAGE.
---------------------------------------------------------------------------
*/
/// \file AMFImporter.cpp
/// \brief AMF-format files importer for Assimp: main algorithm implementation.
/// \date 2016
/// \author smal.root@gmail.com
#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
// Header files, Assimp.
#include "AMFImporter.hpp"
#include "AMFImporter_Macro.hpp"
#include "fast_atof.h"
#include <assimp/DefaultIOSystem.h>
// Header files, stdlib.
#include <memory>
namespace Assimp
{
/// \var aiImporterDesc AMFImporter::Description
/// Conastant which hold importer description
const aiImporterDesc AMFImporter::Description = {
"Additive manufacturing file format(AMF) Importer",
"smalcom",
"",
"See documentation in source code. Chapter: Limitations.",
aiImporterFlags_SupportTextFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
0,
0,
0,
0,
"amf"
};
void AMFImporter::Clear()
{
mNodeElement_Cur = nullptr;
mUnit.clear();
mMaterial_Converted.clear();
mTexture_Converted.clear();
// Delete all elements
if(mNodeElement_List.size())
{
for(CAMFImporter_NodeElement* ne: mNodeElement_List) { delete ne; }
mNodeElement_List.clear();
}
}
AMFImporter::~AMFImporter()
{
if(mReader != nullptr) delete mReader;
// Clear() is accounting if data already is deleted. So, just check again if all data is deleted.
Clear();
}
/*********************************************************************************************************************************************/
/************************************************************ Functions: find set ************************************************************/
/*********************************************************************************************************************************************/
bool AMFImporter::Find_NodeElement(const std::string& pID, const CAMFImporter_NodeElement::EType pType, CAMFImporter_NodeElement** pNodeElement) const
{
for(CAMFImporter_NodeElement* ne: mNodeElement_List)
{
if((ne->ID == pID) && (ne->Type == pType))
{
if(pNodeElement != nullptr) *pNodeElement = ne;
return true;
}
}// for(CAMFImporter_NodeElement* ne: mNodeElement_List)
return false;
}
bool AMFImporter::Find_ConvertedNode(const std::string& pID, std::list<aiNode*>& pNodeList, aiNode** pNode) const
{
aiString node_name(pID.c_str());
for(aiNode* node: pNodeList)
{
if(node->mName == node_name)
{
if(pNode != nullptr) *pNode = node;
return true;
}
}// for(aiNode* node: pNodeList)
return false;
}
bool AMFImporter::Find_ConvertedMaterial(const std::string& pID, const SPP_Material** pConvertedMaterial) const
{
for(const SPP_Material& mat: mMaterial_Converted)
{
if(mat.ID == pID)
{
if(pConvertedMaterial != nullptr) *pConvertedMaterial = &mat;
return true;
}
}// for(const SPP_Material& mat: mMaterial_Converted)
return false;
}
/*********************************************************************************************************************************************/
/************************************************************ Functions: throw set ***********************************************************/
/*********************************************************************************************************************************************/
void AMFImporter::Throw_CloseNotFound(const std::string& pNode)
{
throw DeadlyImportError("Close tag for node <" + pNode + "> not found. Seems file is corrupt.");
}
void AMFImporter::Throw_IncorrectAttr(const std::string& pAttrName)
{
throw DeadlyImportError("Node <" + std::string(mReader->getNodeName()) + "> has incorrect attribute \"" + pAttrName + "\".");
}
void AMFImporter::Throw_IncorrectAttrValue(const std::string& pAttrName)
{
throw DeadlyImportError("Attribute \"" + pAttrName + "\" in node <" + std::string(mReader->getNodeName()) + "> has incorrect value.");
}
void AMFImporter::Throw_MoreThanOnceDefined(const std::string& pNodeType, const std::string& pDescription)
{
throw DeadlyImportError("\"" + pNodeType + "\" node can be used only once in " + mReader->getNodeName() + ". Description: " + pDescription);
}
void AMFImporter::Throw_ID_NotFound(const std::string& pID) const
{
throw DeadlyImportError("Not found node with name \"" + pID + "\".");
}
/*********************************************************************************************************************************************/
/************************************************************* Functions: XML set ************************************************************/
/*********************************************************************************************************************************************/
void AMFImporter::XML_CheckNode_MustHaveChildren()
{
if(mReader->isEmptyElement()) throw DeadlyImportError(std::string("Node <") + mReader->getNodeName() + "> must have children.");
}
void AMFImporter::XML_CheckNode_SkipUnsupported(const std::string& pParentNodeName)
{
static const size_t Uns_Skip_Len = 3;
const char* Uns_Skip[Uns_Skip_Len] = { "composite", "edge", "normal" };
static bool skipped_before[Uns_Skip_Len] = { false, false, false };
std::string nn(mReader->getNodeName());
bool found = false;
bool close_found = false;
size_t sk_idx;
for(sk_idx = 0; sk_idx < Uns_Skip_Len; sk_idx++)
{
if(nn != Uns_Skip[sk_idx]) continue;
found = true;
if(mReader->isEmptyElement())
{
close_found = true;
goto casu_cres;
}
while(mReader->read())
{
if((mReader->getNodeType() == irr::io::EXN_ELEMENT_END) && (nn == mReader->getNodeName()))
{
close_found = true;
goto casu_cres;
}
}
}// for(sk_idx = 0; sk_idx < Uns_Skip_Len; sk_idx++)
casu_cres:
if(!found) throw DeadlyImportError("Unknown node \"" + nn + "\" in " + pParentNodeName + ".");
if(!close_found) Throw_CloseNotFound(nn);
if(!skipped_before[sk_idx])
{
skipped_before[sk_idx] = true;
LogWarning("Skipping node \"" + nn + "\" in " + pParentNodeName + ".");
}
}
bool AMFImporter::XML_SearchNode(const std::string& pNodeName)
{
while(mReader->read())
{
if((mReader->getNodeType() == irr::io::EXN_ELEMENT) && XML_CheckNode_NameEqual(pNodeName)) return true;
}
return false;
}
bool AMFImporter::XML_ReadNode_GetAttrVal_AsBool(const int pAttrIdx)
{
std::string val(mReader->getAttributeValue(pAttrIdx));
if((val == "false") || (val == "0"))
return false;
else if((val == "true") || (val == "1"))
return true;
else
throw DeadlyImportError("Bool attribute value can contain \"false\"/\"0\" or \"true\"/\"1\" not the \"" + val + "\"");
}
float AMFImporter::XML_ReadNode_GetAttrVal_AsFloat(const int pAttrIdx)
{
std::string val;
float tvalf;
ParseHelper_FixTruncatedFloatString(mReader->getAttributeValue(pAttrIdx), val);
fast_atoreal_move(val.c_str(), tvalf, false);
return tvalf;
}
uint32_t AMFImporter::XML_ReadNode_GetAttrVal_AsU32(const int pAttrIdx)
{
return strtoul10(mReader->getAttributeValue(pAttrIdx));
}
float AMFImporter::XML_ReadNode_GetVal_AsFloat()
{
std::string val;
float tvalf;
if(!mReader->read()) throw DeadlyImportError("XML_ReadNode_GetVal_AsFloat. No data, seems file is corrupt.");
if(mReader->getNodeType() != irr::io::EXN_TEXT) throw DeadlyImportError("XML_ReadNode_GetVal_AsFloat. Invalid type of XML element, seems file is corrupt.");
ParseHelper_FixTruncatedFloatString(mReader->getNodeData(), val);
fast_atoreal_move(val.c_str(), tvalf, false);
return tvalf;
}
uint32_t AMFImporter::XML_ReadNode_GetVal_AsU32()
{
if(!mReader->read()) throw DeadlyImportError("XML_ReadNode_GetVal_AsU32. No data, seems file is corrupt.");
if(mReader->getNodeType() != irr::io::EXN_TEXT) throw DeadlyImportError("XML_ReadNode_GetVal_AsU32. Invalid type of XML element, seems file is corrupt.");
return strtoul10(mReader->getNodeData());
}
void AMFImporter::XML_ReadNode_GetVal_AsString(std::string& pValue)
{
if(!mReader->read()) throw DeadlyImportError("XML_ReadNode_GetVal_AsString. No data, seems file is corrupt.");
if(mReader->getNodeType() != irr::io::EXN_TEXT)
throw DeadlyImportError("XML_ReadNode_GetVal_AsString. Invalid type of XML element, seems file is corrupt.");
pValue = mReader->getNodeData();
}
/*********************************************************************************************************************************************/
/************************************************************ Functions: parse set ***********************************************************/
/*********************************************************************************************************************************************/
void AMFImporter::ParseHelper_Node_Enter(CAMFImporter_NodeElement* pNode)
{
mNodeElement_Cur->Child.push_back(pNode);// add new element to current element child list.
mNodeElement_Cur = pNode;// switch current element to new one.
}
void AMFImporter::ParseHelper_Node_Exit()
{
// check if we can walk up.
if(mNodeElement_Cur != nullptr) mNodeElement_Cur = mNodeElement_Cur->Parent;
}
void AMFImporter::ParseHelper_FixTruncatedFloatString(const char* pInStr, std::string& pOutString)
{
size_t instr_len;
pOutString.clear();
instr_len = strlen(pInStr);
if(!instr_len) return;
pOutString.reserve(instr_len * 3 / 2);
// check and correct floats in format ".x". Must be "x.y".
if(pInStr[0] == '.') pOutString.push_back('0');
pOutString.push_back(pInStr[0]);
for(size_t ci = 1; ci < instr_len; ci++)
{
if((pInStr[ci] == '.') && ((pInStr[ci - 1] == ' ') || (pInStr[ci - 1] == '-') || (pInStr[ci - 1] == '+') || (pInStr[ci - 1] == '\t')))
{
pOutString.push_back('0');
pOutString.push_back('.');
}
else
{
pOutString.push_back(pInStr[ci]);
}
}
}
static bool ParseHelper_Decode_Base64_IsBase64(const char pChar)
{
return (isalnum(pChar) || (pChar == '+') || (pChar == '/'));
}
void AMFImporter::ParseHelper_Decode_Base64(const std::string& pInputBase64, std::vector<uint8_t>& pOutputData) const
{
// With help from
// René Nyffenegger http://www.adp-gmbh.ch/cpp/common/base64.html
const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint8_t tidx = 0;
uint8_t arr4[4], arr3[3];
// check input data
if(pInputBase64.size() % 4) throw DeadlyImportError("Base64-encoded data must have size multiply of four.");
// prepare output place
pOutputData.clear();
pOutputData.reserve(pInputBase64.size() / 4 * 3);
for(size_t in_len = pInputBase64.size(), in_idx = 0; (in_len > 0) && (pInputBase64[in_idx] != '='); in_len--)
{
if(ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx]))
{
arr4[tidx++] = pInputBase64[in_idx++];
if(tidx == 4)
{
for(tidx = 0; tidx < 4; tidx++) arr4[tidx] = (uint8_t)base64_chars.find(arr4[tidx]);
arr3[0] = (arr4[0] << 2) + ((arr4[1] & 0x30) >> 4);
arr3[1] = ((arr4[1] & 0x0F) << 4) + ((arr4[2] & 0x3C) >> 2);
arr3[2] = ((arr4[2] & 0x03) << 6) + arr4[3];
for(tidx = 0; tidx < 3; tidx++) pOutputData.push_back(arr3[tidx]);
tidx = 0;
}// if(tidx == 4)
}// if(ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx]))
else
{
in_idx++;
}// if(ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx])) else
}
if(tidx)
{
for(uint8_t i = tidx; i < 4; i++) arr4[i] = 0;
for(uint8_t i = 0; i < 4; i++) arr4[i] = (uint8_t)(base64_chars.find(arr4[i]));
arr3[0] = (arr4[0] << 2) + ((arr4[1] & 0x30) >> 4);
arr3[1] = ((arr4[1] & 0x0F) << 4) + ((arr4[2] & 0x3C) >> 2);
arr3[2] = ((arr4[2] & 0x03) << 6) + arr4[3];
for(uint8_t i = 0; i < (tidx - 1); i++) pOutputData.push_back(arr3[i]);
}
}
void AMFImporter::ParseFile(const std::string& pFile, IOSystem* pIOHandler)
{
irr::io::IrrXMLReader* OldReader = mReader;// store current XMLreader.
std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
// Check whether we can read from the file
if(file.get() == NULL) throw DeadlyImportError("Failed to open AMF file " + pFile + ".");
// generate a XML reader for it
std::unique_ptr<CIrrXML_IOStreamReader> mIOWrapper(new CIrrXML_IOStreamReader(file.get()));
mReader = irr::io::createIrrXMLReader(mIOWrapper.get());
if(!mReader) throw DeadlyImportError("Failed to create XML reader for file" + pFile + ".");
//
// start reading
// search for root tag <amf>
if(XML_SearchNode("amf"))
ParseNode_Root();
else
throw DeadlyImportError("Root node \"amf\" not found.");
delete mReader;
// restore old XMLreader
mReader = OldReader;
}
// <amf
// unit="" - The units to be used. May be "inch", "millimeter", "meter", "feet", or "micron".
// version="" - Version of file format.
// >
// </amf>
// Root XML element.
// Multi elements - No.
void AMFImporter::ParseNode_Root()
{
std::string unit, version;
CAMFImporter_NodeElement *ne( nullptr );
// Read attributes for node <amf>.
MACRO_ATTRREAD_LOOPBEG;
MACRO_ATTRREAD_CHECK_RET("unit", unit, mReader->getAttributeValue);
MACRO_ATTRREAD_CHECK_RET("version", version, mReader->getAttributeValue);
MACRO_ATTRREAD_LOOPEND_WSKIP;
// Check attributes
if(!mUnit.empty())
{
if((mUnit != "inch") && (mUnit != "millimeter") && (mUnit != "meter") && (mUnit != "feet") && (mUnit != "micron")) Throw_IncorrectAttrValue("unit");
}
// create root node element.
ne = new CAMFImporter_NodeElement_Root(nullptr);
mNodeElement_Cur = ne;// set first "current" element
// and assign attribute's values
((CAMFImporter_NodeElement_Root*)ne)->Unit = unit;
((CAMFImporter_NodeElement_Root*)ne)->Version = version;
// Check for child nodes
if(!mReader->isEmptyElement())
{
MACRO_NODECHECK_LOOPBEGIN("amf");
if(XML_CheckNode_NameEqual("object")) { ParseNode_Object(); continue; }
if(XML_CheckNode_NameEqual("material")) { ParseNode_Material(); continue; }
if(XML_CheckNode_NameEqual("texture")) { ParseNode_Texture(); continue; }
if(XML_CheckNode_NameEqual("constellation")) { ParseNode_Constellation(); continue; }
if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
MACRO_NODECHECK_LOOPEND("amf");
mNodeElement_Cur = ne;// force restore "current" element
}// if(!mReader->isEmptyElement())
mNodeElement_List.push_back(ne);// add to node element list because its a new object in graph.
}
// <constellation
// id="" - The Object ID of the new constellation being defined.
// >
// </constellation>
// A collection of objects or constellations with specific relative locations.
// Multi elements - Yes.
// Parent element - <amf>.
void AMFImporter::ParseNode_Constellation()
{
std::string id;
CAMFImporter_NodeElement* ne( nullptr );
// Read attributes for node <constellation>.
MACRO_ATTRREAD_LOOPBEG;
MACRO_ATTRREAD_CHECK_RET("id", id, mReader->getAttributeValue);
MACRO_ATTRREAD_LOOPEND;
// create and if needed - define new grouping object.
ne = new CAMFImporter_NodeElement_Constellation(mNodeElement_Cur);
CAMFImporter_NodeElement_Constellation& als = *((CAMFImporter_NodeElement_Constellation*)ne);// alias for convenience
if(!id.empty()) als.ID = id;
// Check for child nodes
if(!mReader->isEmptyElement())
{
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("constellation");
if(XML_CheckNode_NameEqual("instance")) { ParseNode_Instance(); continue; }
if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
MACRO_NODECHECK_LOOPEND("constellation");
ParseHelper_Node_Exit();
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <instance
// objectid="" - The Object ID of the new constellation being defined.
// >
// </instance>
// A collection of objects or constellations with specific relative locations.
// Multi elements - Yes.
// Parent element - <amf>.
void AMFImporter::ParseNode_Instance()
{
std::string objectid;
CAMFImporter_NodeElement* ne( nullptr );
// Read attributes for node <constellation>.
MACRO_ATTRREAD_LOOPBEG;
MACRO_ATTRREAD_CHECK_RET("objectid", objectid, mReader->getAttributeValue);
MACRO_ATTRREAD_LOOPEND;
// used object id must be defined, check that.
if(objectid.empty()) throw DeadlyImportError("\"objectid\" in <instance> must be defined.");
// create and define new grouping object.
ne = new CAMFImporter_NodeElement_Instance(mNodeElement_Cur);
CAMFImporter_NodeElement_Instance& als = *((CAMFImporter_NodeElement_Instance*)ne);// alias for convenience
als.ObjectID = objectid;
// Check for child nodes
if(!mReader->isEmptyElement())
{
bool read_flag[6] = { false, false, false, false, false, false };
als.Delta.Set(0, 0, 0);
als.Rotation.Set(0, 0, 0);
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("instance");
MACRO_NODECHECK_READCOMP_F("deltax", read_flag[0], als.Delta.x);
MACRO_NODECHECK_READCOMP_F("deltay", read_flag[1], als.Delta.y);
MACRO_NODECHECK_READCOMP_F("deltaz", read_flag[2], als.Delta.z);
MACRO_NODECHECK_READCOMP_F("rx", read_flag[3], als.Rotation.x);
MACRO_NODECHECK_READCOMP_F("ry", read_flag[4], als.Rotation.y);
MACRO_NODECHECK_READCOMP_F("rz", read_flag[5], als.Rotation.z);
MACRO_NODECHECK_LOOPEND("instance");
ParseHelper_Node_Exit();
// also convert degrees to radians.
als.Rotation.x = AI_MATH_PI_F * als.Rotation.x / 180.0f;
als.Rotation.y = AI_MATH_PI_F * als.Rotation.y / 180.0f;
als.Rotation.z = AI_MATH_PI_F * als.Rotation.z / 180.0f;
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <object
// id="" - A unique ObjectID for the new object being defined.
// >
// </object>
// An object definition.
// Multi elements - Yes.
// Parent element - <amf>.
void AMFImporter::ParseNode_Object()
{
std::string id;
CAMFImporter_NodeElement* ne( nullptr );
// Read attributes for node <object>.
MACRO_ATTRREAD_LOOPBEG;
MACRO_ATTRREAD_CHECK_RET("id", id, mReader->getAttributeValue);
MACRO_ATTRREAD_LOOPEND;
// create and if needed - define new geometry object.
ne = new CAMFImporter_NodeElement_Object(mNodeElement_Cur);
CAMFImporter_NodeElement_Object& als = *((CAMFImporter_NodeElement_Object*)ne);// alias for convenience
if(!id.empty()) als.ID = id;
// Check for child nodes
if(!mReader->isEmptyElement())
{
bool col_read = false;
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("object");
if(XML_CheckNode_NameEqual("color"))
{
// Check if color already defined for object.
if(col_read) Throw_MoreThanOnceDefined("color", "Only one color can be defined for <object>.");
// read data and set flag about it
ParseNode_Color();
col_read = true;
continue;
}
if(XML_CheckNode_NameEqual("mesh")) { ParseNode_Mesh(); continue; }
if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
MACRO_NODECHECK_LOOPEND("object");
ParseHelper_Node_Exit();
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <metadata
// type="" - The type of the attribute.
// >
// </metadata>
// Specify additional information about an entity.
// Multi elements - Yes.
// Parent element - <amf>, <object>, <volume>, <material>, <vertex>.
//
// Reserved types are:
// "Name" - The alphanumeric label of the entity, to be used by the interpreter if interacting with the user.
// "Description" - A description of the content of the entity
// "URL" - A link to an external resource relating to the entity
// "Author" - Specifies the name(s) of the author(s) of the entity
// "Company" - Specifying the company generating the entity
// "CAD" - specifies the name of the originating CAD software and version
// "Revision" - specifies the revision of the entity
// "Tolerance" - specifies the desired manufacturing tolerance of the entity in entity's unit system
// "Volume" - specifies the total volume of the entity, in the entity's unit system, to be used for verification (object and volume only)
void AMFImporter::ParseNode_Metadata()
{
std::string type, value;
CAMFImporter_NodeElement* ne( nullptr );
// read attribute
MACRO_ATTRREAD_LOOPBEG;
MACRO_ATTRREAD_CHECK_RET("type", type, mReader->getAttributeValue);
MACRO_ATTRREAD_LOOPEND;
// and value of node.
value = mReader->getNodeData();
// Create node element and assign read data.
ne = new CAMFImporter_NodeElement_Metadata(mNodeElement_Cur);
((CAMFImporter_NodeElement_Metadata*)ne)->Type = type;
((CAMFImporter_NodeElement_Metadata*)ne)->Value = value;
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
/*********************************************************************************************************************************************/
/******************************************************** Functions: BaseImporter set ********************************************************/
/*********************************************************************************************************************************************/
bool AMFImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool pCheckSig) const
{
const std::string extension = GetExtension(pFile);
if ( extension == "amf" ) {
return true;
}
if(!extension.length() || pCheckSig)
{
const char* tokens[] = { "<amf" };
return SearchFileHeaderForToken( pIOHandler, pFile, tokens, 1 );
}
return false;
}
void AMFImporter::GetExtensionList(std::set<std::string>& pExtensionList)
{
pExtensionList.insert("amf");
}
const aiImporterDesc* AMFImporter::GetInfo () const
{
return &Description;
}
void AMFImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
{
Clear();// delete old graph.
ParseFile(pFile, pIOHandler);
Postprocess_BuildScene(pScene);
// scene graph is ready, exit.
}
}// namespace Assimp
#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER

View File

@ -0,0 +1,563 @@
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 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 DAMAGE.
---------------------------------------------------------------------------
*/
/// \file AMFImporter.hpp
/// \brief AMF-format files importer for Assimp.
/// \date 2016
/// \author smal.root@gmail.com
// Thanks to acorn89 for support.
#pragma once
#ifndef INCLUDED_AI_AMF_IMPORTER_H
#define INCLUDED_AI_AMF_IMPORTER_H
#include "AMFImporter_Node.hpp"
// Header files, Assimp.
#include <assimp/DefaultLogger.hpp>
#include <assimp/importerdesc.h>
#include "assimp/types.h"
#include "BaseImporter.h"
#include "irrXMLWrapper.h"
// Header files, stdlib.
#include <set>
namespace Assimp
{
/// \class AMFImporter
/// Class that holding scene graph which include: geometry, metadata, materials etc.
///
/// Implementing features.
///
/// Limitations.
///
/// 1. When for texture mapping used set of source textures (r, g, b, a) not only one then attribute "tiled" for all set will be true if it true in any of
/// source textures.
/// Example. Triangle use for texture mapping three textures. Two of them has "tiled" set to false and one - set to true. In scene all three textures
/// will be tiled.
///
/// Unsupported features:
/// 1. Node <composite>, formulas in <composite> and <color>. For implementing this feature can be used expression parser "muParser" like in project
/// "amf_tools".
/// 2. Attribute "profile" in node <color>.
/// 3. Curved geometry: <edge>, <normal> and children nodes of them.
/// 4. Attributes: "unit" and "version" in <amf> read but do nothing.
/// 5. <metadata> stored only for root node <amf>.
/// 6. Color averaging of vertices for which <triangle>'s set different colors.
///
/// Supported nodes:
/// General:
/// <amf>; <constellation>; <instance> and children <deltax>, <deltay>, <deltaz>, <rx>, <ry>, <rz>; <metadata>;
///
/// Geometry:
/// <object>; <mesh>; <vertices>; <vertex>; <coordinates> and children <x>, <y>, <z>; <volume>; <triangle> and children <v1>, <v2>, <v3>;
///
/// Material:
/// <color> and children <r>, <g>, <b>, <a>; <texture>; <material>;
/// two variants of texture coordinates:
/// new - <texmap> and children <utex1>, <utex2>, <utex3>, <vtex1>, <vtex2>, <vtex3>
/// old - <map> and children <u1>, <u2>, <u3>, <v1>, <v2>, <v3>
///
class AMFImporter : public BaseImporter
{
/***********************************************/
/******************** Types ********************/
/***********************************************/
private:
struct SPP_Material;// forward declaration
/// \struct SPP_Composite
/// Data type for postprocessing step. More suitable container for part of material's composition.
struct SPP_Composite
{
SPP_Material* Material;///< Pointer to material - part of composition.
std::string Formula;///< Formula for calculating ratio of \ref Material.
};
/// \struct SPP_Material
/// Data type for postprocessing step. More suitable container for material.
struct SPP_Material
{
std::string ID;///< Material ID.
std::list<CAMFImporter_NodeElement_Metadata*> Metadata;///< Metadata of material.
CAMFImporter_NodeElement_Color* Color;///< Color of material.
std::list<SPP_Composite> Composition;///< List of child materials if current material is composition of few another.
/// \fn aiColor4D GetColor(const float pX, const float pY, const float pZ) const
/// Return color calculated for specified coordinate.
/// \param [in] pX - "x" coordinate.
/// \param [in] pY - "y" coordinate.
/// \param [in] pZ - "z" coordinate.
/// \return calculated color.
aiColor4D GetColor(const float pX, const float pY, const float pZ) const;
};
/// \struct SPP_Texture
/// Data type for post-processing step. More suitable container for texture.
struct SPP_Texture
{
std::string ID;
size_t Width, Height, Depth;
bool Tiled;
char FormatHint[ 9 ];// 8 for string + 1 for terminator.
uint8_t *Data;
};
/// \struct SComplexFace
/// Data type for post-processing step. Contain face data.
struct SComplexFace
{
aiFace Face;///< Face vertices.
const CAMFImporter_NodeElement_Color* Color;///< Face color. Equal to nullptr if color is not set for the face.
const CAMFImporter_NodeElement_TexMap* TexMap;///< Face texture mapping data. Equal to nullptr if texture mapping is not set for the face.
};
/***********************************************/
/****************** Constants ******************/
/***********************************************/
private:
static const aiImporterDesc Description;
/***********************************************/
/****************** Variables ******************/
/***********************************************/
private:
CAMFImporter_NodeElement* mNodeElement_Cur;///< Current element.
std::list<CAMFImporter_NodeElement*> mNodeElement_List;///< All elements of scene graph.
irr::io::IrrXMLReader* mReader;///< Pointer to XML-reader object
std::string mUnit;
std::list<SPP_Material> mMaterial_Converted;///< List of converted materials for postprocessing step.
std::list<SPP_Texture> mTexture_Converted;///< List of converted textures for postprocessing step.
/***********************************************/
/****************** Functions ******************/
/***********************************************/
private:
/// \fn AMFImporter(const AMFImporter& pScene)
/// Disabled copy constructor.
AMFImporter(const AMFImporter& pScene);
/// \fn AMFImporter& operator=(const AMFImporter& pScene)
/// Disabled assign operator.
AMFImporter& operator=(const AMFImporter& pScene);
/// \fn void Clear()
/// Clear all temporary data.
void Clear();
/***********************************************/
/************* Functions: find set *************/
/***********************************************/
/// \fn bool Find_NodeElement(const std::string& pID, const CAMFImporter_NodeElement::EType pType, aiNode** pNode) const
/// Find specified node element in node elements list ( \ref mNodeElement_List).
/// \param [in] pID - ID(name) of requested node element.
/// \param [in] pType - type of node element.
/// \param [out] pNode - pointer to pointer to item found.
/// \return true - if the node element is found, else - false.
bool Find_NodeElement(const std::string& pID, const CAMFImporter_NodeElement::EType pType, CAMFImporter_NodeElement** pNodeElement) const;
/// \fn bool Find_ConvertedNode(const std::string& pID, std::list<aiNode*>& pNodeList, aiNode** pNode) const
/// Find requested aiNode in node list.
/// \param [in] pID - ID(name) of requested node.
/// \param [in] pNodeList - list of nodes where to find the node.
/// \param [out] pNode - pointer to pointer to item found.
/// \return true - if the node is found, else - false.
bool Find_ConvertedNode(const std::string& pID, std::list<aiNode*>& pNodeList, aiNode** pNode) const;
/// \fn bool Find_ConvertedMaterial(const std::string& pID, const SPP_Material** pConvertedMaterial) const
/// Find material in list for converted materials. Use at postprocessing step.
/// \param [in] pID - material ID.
/// \param [out] pConvertedMaterial - pointer to found converted material (\ref SPP_Material).
/// \return true - if the material is found, else - false.
bool Find_ConvertedMaterial(const std::string& pID, const SPP_Material** pConvertedMaterial) const;
/// \fn bool Find_ConvertedTexture(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B, const std::string& pID_A, uint32_t* pConvertedTextureIndex = nullptr) const
/// Find texture in list of converted textures. Use at postprocessing step,
/// \param [in] pID_R - ID of source "red" texture.
/// \param [in] pID_G - ID of source "green" texture.
/// \param [in] pID_B - ID of source "blue" texture.
/// \param [in] pID_A - ID of source "alpha" texture. Use empty string to find RGB-texture.
/// \param [out] pConvertedTextureIndex - pointer where index in list of found texture will be written. If equivalent to nullptr then nothing will be
/// written.
/// \return true - if the texture is found, else - false.
bool Find_ConvertedTexture(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B, const std::string& pID_A,
uint32_t* pConvertedTextureIndex = nullptr) const;
/***********************************************/
/********* Functions: postprocess set **********/
/***********************************************/
/// \fn void PostprocessHelper_CreateMeshDataArray(const CAMFImporter_NodeElement_Mesh& pNodeElement, std::vector<aiVector3D>& pVertexCoordinateArray, std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray) const
/// Get data stored in <vertices> and place it to arrays.
/// \param [in] pNodeElement - reference to node element which kept <object> data.
/// \param [in] pVertexCoordinateArray - reference to vertices coordinates kept in <vertices>.
/// \param [in] pVertexColorArray - reference to vertices colors for all <vertex's. If color for vertex is not set then corresponding member of array
/// contain nullptr.
void PostprocessHelper_CreateMeshDataArray(const CAMFImporter_NodeElement_Mesh& pNodeElement, std::vector<aiVector3D>& pVertexCoordinateArray,
std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray) const;
/// \fn size_t PostprocessHelper_GetTextureID_Or_Create(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B, const std::string& pID_A)
/// Return converted texture ID which related to specified source textures ID's. If converted texture does not exist then it will be created and ID on new
/// converted texture will be returned. Convertion: set of textures from \ref CAMFImporter_NodeElement_Texture to one \ref SPP_Texture and place it
/// to converted textures list.
/// Any of source ID's can be absent(empty string) or even one ID only specified. But at least one ID must be specified.
/// \param [in] pID_R - ID of source "red" texture.
/// \param [in] pID_G - ID of source "green" texture.
/// \param [in] pID_B - ID of source "blue" texture.
/// \param [in] pID_A - ID of source "alpha" texture.
/// \return index of the texture in array of the converted textures.
size_t PostprocessHelper_GetTextureID_Or_Create(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B, const std::string& pID_A);
/// \fn void PostprocessHelper_SplitFacesByTextureID(std::list<SComplexFace>& pInputList, std::list<std::list<SComplexFace> > pOutputList_Separated)
/// Separate input list by texture IDs. This step is needed because aiMesh can contain mesh which is use only one texture (or set: diffuse, bump etc).
/// \param [in] pInputList - input list with faces. Some of them can contain color or texture mapping, or both of them, or nothing. Will be cleared after
/// processing.
/// \param [out] pOutputList_Separated - output list of the faces lists. Separated faces list by used texture IDs. Will be cleared before processing.
void PostprocessHelper_SplitFacesByTextureID(std::list<SComplexFace>& pInputList, std::list<std::list<SComplexFace> >& pOutputList_Separated);
/// \fn void Postprocess_AddMetadata(const std::list<CAMFImporter_NodeElement_Metadata*>& pMetadataList, aiNode& pSceneNode) const
/// Check if child elements of node element is metadata and add it to scene node.
/// \param [in] pMetadataList - reference to list with collected metadata.
/// \param [out] pSceneNode - scene node in which metadata will be added.
void Postprocess_AddMetadata(const std::list<CAMFImporter_NodeElement_Metadata*>& pMetadataList, aiNode& pSceneNode) const;
/// \fn void Postprocess_BuildNodeAndObject(const CAMFImporter_NodeElement_Object& pNodeElement, std::list<aiMesh*>& pMeshList, aiNode** pSceneNode)
/// To create aiMesh and aiNode for it from <object>.
/// \param [in] pNodeElement - reference to node element which kept <object> data.
/// \param [out] pMeshList - reference to a list with all aiMesh of the scene.
/// \param [out] pSceneNode - pointer to place where new aiNode will be created.
void Postprocess_BuildNodeAndObject(const CAMFImporter_NodeElement_Object& pNodeElement, std::list<aiMesh*>& pMeshList, aiNode** pSceneNode);
/// \fn void Postprocess_BuildMeshSet(const CAMFImporter_NodeElement_Mesh& pNodeElement, const std::vector<aiVector3D>& pVertexCoordinateArray, const std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray, const CAMFImporter_NodeElement_Color* pObjectColor, std::list<aiMesh*>& pMeshList, aiNode& pSceneNode)
/// Create mesh for every <volume> in <mesh>.
/// \param [in] pNodeElement - reference to node element which kept <mesh> data.
/// \param [in] pVertexCoordinateArray - reference to vertices coordinates for all <volume>'s.
/// \param [in] pVertexColorArray - reference to vertices colors for all <volume>'s. If color for vertex is not set then corresponding member of array
/// contain nullptr.
/// \param [in] pObjectColor - pointer to colors for <object>. If color is not set then argument contain nullptr.
/// \param [in] pMaterialList - reference to a list with defined materials.
/// \param [out] pMeshList - reference to a list with all aiMesh of the scene.
/// \param [out] pSceneNode - reference to aiNode which will own new aiMesh's.
void Postprocess_BuildMeshSet(const CAMFImporter_NodeElement_Mesh& pNodeElement, const std::vector<aiVector3D>& pVertexCoordinateArray,
const std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray, const CAMFImporter_NodeElement_Color* pObjectColor,
std::list<aiMesh*>& pMeshList, aiNode& pSceneNode);
/// \fn void Postprocess_BuildMaterial(const CAMFImporter_NodeElement_Material& pMaterial)
/// Convert material from \ref CAMFImporter_NodeElement_Material to \ref SPP_Material.
/// \param [in] pMaterial - source CAMFImporter_NodeElement_Material.
void Postprocess_BuildMaterial(const CAMFImporter_NodeElement_Material& pMaterial);
/// \fn void Postprocess_BuildConstellation(CAMFImporter_NodeElement_Constellation& pConstellation, std::list<aiNode*>& pNodeList) const
/// Create and add to aiNode's list new part of scene graph defined by <constellation>.
/// \param [in] pConstellation - reference to <constellation> node.
/// \param [out] pNodeList - reference to aiNode's list.
void Postprocess_BuildConstellation(CAMFImporter_NodeElement_Constellation& pConstellation, std::list<aiNode*>& pNodeList) const;
/// \fn void Postprocess_BuildScene()
/// Build Assimp scene graph in aiScene from collected data.
/// \param [out] pScene - pointer to aiScene where tree will be built.
void Postprocess_BuildScene(aiScene* pScene);
/***********************************************/
/************* Functions: throw set ************/
/***********************************************/
/// \fn void Throw_CloseNotFound(const std::string& pNode)
/// Call that function when close tag of node not found and exception must be raised.
/// E.g.:
/// <amf>
/// <object>
/// </amf> <!--- object not closed --->
/// \throw DeadlyImportError.
/// \param [in] pNode - node name in which exception happened.
void Throw_CloseNotFound(const std::string& pNode);
/// \fn void Throw_IncorrectAttr(const std::string& pAttrName)
/// Call that function when attribute name is incorrect and exception must be raised.
/// \param [in] pAttrName - attribute name.
/// \throw DeadlyImportError.
void Throw_IncorrectAttr(const std::string& pAttrName);
/// \fn void Throw_IncorrectAttrValue(const std::string& pAttrName)
/// Call that function when attribute value is incorrect and exception must be raised.
/// \param [in] pAttrName - attribute name.
/// \throw DeadlyImportError.
void Throw_IncorrectAttrValue(const std::string& pAttrName);
/// \fn void Throw_MoreThanOnceDefined(const std::string& pNode, const std::string& pDescription)
/// Call that function when some type of nodes are defined twice or more when must be used only once and exception must be raised.
/// E.g.:
/// <object>
/// <color>... <!--- color defined --->
/// <color>... <!--- color defined again --->
/// </object>
/// \throw DeadlyImportError.
/// \param [in] pNodeType - type of node which defined one more time.
/// \param [in] pDescription - message about error. E.g. what the node defined while exception raised.
void Throw_MoreThanOnceDefined(const std::string& pNodeType, const std::string& pDescription);
/// \fn void Throw_ID_NotFound(const std::string& pID) const
/// Call that function when referenced element ID are not found in graph and exception must be raised.
/// \param [in] pID - ID of of element which not found.
/// \throw DeadlyImportError.
void Throw_ID_NotFound(const std::string& pID) const;
/***********************************************/
/************** Functions: LOG set *************/
/***********************************************/
/// \fn void LogInfo(const std::string& pMessage)
/// Short variant for calling \ref DefaultLogger::get()->info()
void LogInfo(const std::string& pMessage) { DefaultLogger::get()->info(pMessage); }
/// \fn void LogWarning(const std::string& pMessage)
/// Short variant for calling \ref DefaultLogger::get()->warn()
void LogWarning(const std::string& pMessage) { DefaultLogger::get()->warn(pMessage); }
/// \fn void LogError(const std::string& pMessage)
/// Short variant for calling \ref DefaultLogger::get()->error()
void LogError(const std::string& pMessage) { DefaultLogger::get()->error(pMessage); }
/***********************************************/
/************** Functions: XML set *************/
/***********************************************/
/// \fn void XML_CheckNode_MustHaveChildren()
/// Check if current node have children: <node>...</node>. If not then exception will throwed.
void XML_CheckNode_MustHaveChildren();
/// \fn bool XML_CheckNode_NameEqual(const std::string& pNodeName)
/// Chek if current node name is equal to pNodeName.
/// \param [in] pNodeName - name for checking.
/// return true if current node name is equal to pNodeName, else - false.
bool XML_CheckNode_NameEqual(const std::string& pNodeName) { return mReader->getNodeName() == pNodeName; }
/// \fn void XML_CheckNode_SkipUnsupported(const std::string& pParentNodeName)
/// Skip unsupported node and report about that. Depend on node name can be skipped begin tag of node all whole node.
/// \param [in] pParentNodeName - parent node name. Used for reporting.
void XML_CheckNode_SkipUnsupported(const std::string& pParentNodeName);
/// \fn bool XML_SearchNode(const std::string& pNodeName)
/// Search for specified node in file. XML file read pointer(mReader) will point to found node or file end after search is end.
/// \param [in] pNodeName - requested node name.
/// return true - if node is found, else - false.
bool XML_SearchNode(const std::string& pNodeName);
/// \fn bool XML_ReadNode_GetAttrVal_AsBool(const int pAttrIdx)
/// Read attribute value.
/// \param [in] pAttrIdx - attribute index (\ref mReader->getAttribute* set).
/// \return read data.
bool XML_ReadNode_GetAttrVal_AsBool(const int pAttrIdx);
/// \fn float XML_ReadNode_GetAttrVal_AsFloat(const int pAttrIdx)
/// Read attribute value.
/// \param [in] pAttrIdx - attribute index (\ref mReader->getAttribute* set).
/// \return read data.
float XML_ReadNode_GetAttrVal_AsFloat(const int pAttrIdx);
/// \fn uint32_t XML_ReadNode_GetAttrVal_AsU32(const int pAttrIdx)
/// Read attribute value.
/// \param [in] pAttrIdx - attribute index (\ref mReader->getAttribute* set).
/// \return read data.
uint32_t XML_ReadNode_GetAttrVal_AsU32(const int pAttrIdx);
/// \fn float XML_ReadNode_GetVal_AsFloat()
/// Read node value.
/// \return read data.
float XML_ReadNode_GetVal_AsFloat();
/// \fn uint32_t XML_ReadNode_GetVal_AsU32()
/// Read node value.
/// \return read data.
uint32_t XML_ReadNode_GetVal_AsU32();
/// \fn void XML_ReadNode_GetVal_AsString(std::string& pValue)
/// Read node value.
/// \return read data.
void XML_ReadNode_GetVal_AsString(std::string& pValue);
/***********************************************/
/******** Functions: parse set private *********/
/***********************************************/
/// \fn void ParseHelper_Node_Enter(CAMFImporter_NodeElement* pNode)
/// Make pNode as current and enter deeper for parsing child nodes. At end \ref ParseHelper_Node_Exit must be called.
/// \param [in] pNode - new current node.
void ParseHelper_Node_Enter(CAMFImporter_NodeElement* pNode);
/// \fn void ParseHelper_Group_End()
/// This function must be called when exiting from grouping node. \ref ParseHelper_Group_Begin.
void ParseHelper_Node_Exit();
/// \fn void ParseHelper_FixTruncatedFloatString(const char* pInStr, std::string& pOutString)
/// Attribute values of floating point types can take form ".x"(without leading zero). irrXMLReader can not read this form of values and it
/// must be converted to right form - "0.xxx".
/// \param [in] pInStr - pointer to input string which can contain incorrect form of values.
/// \param [out[ pOutString - output string with right form of values.
void ParseHelper_FixTruncatedFloatString(const char* pInStr, std::string& pOutString);
/// \fn void ParseHelper_Decode_Base64(const std::string& pInputBase64, std::vector<uint8_t>& pOutputData) const
/// Decode Base64-encoded data.
/// \param [in] pInputBase64 - reference to input Base64-encoded string.
/// \param [out] pOutputData - reference to output array for decoded data.
void ParseHelper_Decode_Base64(const std::string& pInputBase64, std::vector<uint8_t>& pOutputData) const;
/// \fn void ParseNode_Root()
/// Parse <AMF> node of the file.
void ParseNode_Root();
/******** Functions: top nodes *********/
/// \fn void ParseNode_Constellation()
/// Parse <constellation> node of the file.
void ParseNode_Constellation();
/// \fn void ParseNode_Constellation()
/// Parse <instance> node of the file.
void ParseNode_Instance();
/// \fn void ParseNode_Material()
/// Parse <material> node of the file.
void ParseNode_Material();
/// \fn void ParseNode_Metadata()
/// Parse <metadata> node.
void ParseNode_Metadata();
/// \fn void ParseNode_Object()
/// Parse <object> node of the file.
void ParseNode_Object();
/// \fn void ParseNode_Texture()
/// Parse <texture> node of the file.
void ParseNode_Texture();
/******** Functions: geometry nodes *********/
/// \fn void ParseNode_Coordinates()
/// Parse <coordinates> node of the file.
void ParseNode_Coordinates();
/// \fn void ParseNode_Edge()
/// Parse <edge> node of the file.
void ParseNode_Edge();
/// \fn void ParseNode_Mesh()
/// Parse <mesh> node of the file.
void ParseNode_Mesh();
/// \fn void ParseNode_Triangle()
/// Parse <triangle> node of the file.
void ParseNode_Triangle();
/// \fn void ParseNode_Vertex()
/// Parse <vertex> node of the file.
void ParseNode_Vertex();
/// \fn void ParseNode_Vertices()
/// Parse <vertices> node of the file.
void ParseNode_Vertices();
/// \fn void ParseNode_Volume()
/// Parse <volume> node of the file.
void ParseNode_Volume();
/******** Functions: material nodes *********/
/// \fn void ParseNode_Color()
/// Parse <color> node of the file.
void ParseNode_Color();
/// \fn void ParseNode_TexMap(const bool pUseOldName = false)
/// Parse <texmap> of <map> node of the file.
/// \param [in] pUseOldName - if true then use old name of node(and children) - <map>, instead of new name - <texmap>.
void ParseNode_TexMap(const bool pUseOldName = false);
public:
/// \fn AMFImporter()
/// Default constructor.
AMFImporter()
: mNodeElement_Cur(nullptr), mReader(nullptr)
{}
/// \fn ~AMFImporter()
/// Default destructor.
~AMFImporter();
/***********************************************/
/******** Functions: parse set, public *********/
/***********************************************/
/// \fn void ParseFile(const std::string& pFile, IOSystem* pIOHandler)
/// Parse AMF file and fill scene graph. The function has no return value. Result can be found by analyzing the generated graph.
/// Also exception can be throwed if trouble will found.
/// \param [in] pFile - name of file to be parsed.
/// \param [in] pIOHandler - pointer to IO helper object.
void ParseFile(const std::string& pFile, IOSystem* pIOHandler);
/***********************************************/
/********* Functions: BaseImporter set *********/
/***********************************************/
bool CanRead(const std::string& pFile, IOSystem* pIOHandler, bool pCheckSig) const;
void GetExtensionList(std::set<std::string>& pExtensionList);
void InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler);
const aiImporterDesc* GetInfo ()const;
};// class AMFImporter
}// namespace Assimp
#endif // INCLUDED_AI_AMF_IMPORTER_H

View File

@ -0,0 +1,356 @@
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 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 DAMAGE.
---------------------------------------------------------------------------
*/
/// \file AMFImporter_Geometry.cpp
/// \brief Parsing data from geometry nodes.
/// \date 2016
/// \author smal.root@gmail.com
#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
#include "AMFImporter.hpp"
#include "AMFImporter_Macro.hpp"
namespace Assimp
{
// <mesh>
// </mesh>
// A 3D mesh hull.
// Multi elements - Yes.
// Parent element - <object>.
void AMFImporter::ParseNode_Mesh()
{
CAMFImporter_NodeElement* ne;
// create new mesh object.
ne = new CAMFImporter_NodeElement_Mesh(mNodeElement_Cur);
// Check for child nodes
if(!mReader->isEmptyElement())
{
bool vert_read = false;
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("mesh");
if(XML_CheckNode_NameEqual("vertices"))
{
// Check if data already defined.
if(vert_read) Throw_MoreThanOnceDefined("vertices", "Only one vertices set can be defined for <mesh>.");
// read data and set flag about it
ParseNode_Vertices();
vert_read = true;
continue;
}
if(XML_CheckNode_NameEqual("volume")) { ParseNode_Volume(); continue; }
MACRO_NODECHECK_LOOPEND("mesh");
ParseHelper_Node_Exit();
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <vertices>
// </vertices>
// The list of vertices to be used in defining triangles.
// Multi elements - No.
// Parent element - <mesh>.
void AMFImporter::ParseNode_Vertices()
{
CAMFImporter_NodeElement* ne;
// create new mesh object.
ne = new CAMFImporter_NodeElement_Vertices(mNodeElement_Cur);
// Check for child nodes
if(!mReader->isEmptyElement())
{
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("vertices");
if(XML_CheckNode_NameEqual("vertex")) { ParseNode_Vertex(); continue; }
MACRO_NODECHECK_LOOPEND("vertices");
ParseHelper_Node_Exit();
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <vertex>
// </vertex>
// A vertex to be referenced in triangles.
// Multi elements - Yes.
// Parent element - <vertices>.
void AMFImporter::ParseNode_Vertex()
{
CAMFImporter_NodeElement* ne;
// create new mesh object.
ne = new CAMFImporter_NodeElement_Vertex(mNodeElement_Cur);
// Check for child nodes
if(!mReader->isEmptyElement())
{
bool col_read = false;
bool coord_read = false;
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("vertex");
if(XML_CheckNode_NameEqual("color"))
{
// Check if data already defined.
if(col_read) Throw_MoreThanOnceDefined("color", "Only one color can be defined for <vertex>.");
// read data and set flag about it
ParseNode_Color();
col_read = true;
continue;
}
if(XML_CheckNode_NameEqual("coordinates"))
{
// Check if data already defined.
if(coord_read) Throw_MoreThanOnceDefined("coordinates", "Only one coordinates set can be defined for <vertex>.");
// read data and set flag about it
ParseNode_Coordinates();
coord_read = true;
continue;
}
if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
MACRO_NODECHECK_LOOPEND("vertex");
ParseHelper_Node_Exit();
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <coordinates>
// </coordinates>
// Specifies the 3D location of this vertex.
// Multi elements - No.
// Parent element - <vertex>.
//
// Children elements:
// <x>, <y>, <z>
// Multi elements - No.
// X, Y, or Z coordinate, respectively, of a vertex position in space.
void AMFImporter::ParseNode_Coordinates()
{
CAMFImporter_NodeElement* ne;
// create new color object.
ne = new CAMFImporter_NodeElement_Coordinates(mNodeElement_Cur);
CAMFImporter_NodeElement_Coordinates& als = *((CAMFImporter_NodeElement_Coordinates*)ne);// alias for convenience
// Check for child nodes
if(!mReader->isEmptyElement())
{
bool read_flag[3] = { false, false, false };
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("coordinates");
MACRO_NODECHECK_READCOMP_F("x", read_flag[0], als.Coordinate.x);
MACRO_NODECHECK_READCOMP_F("y", read_flag[1], als.Coordinate.y);
MACRO_NODECHECK_READCOMP_F("z", read_flag[2], als.Coordinate.z);
MACRO_NODECHECK_LOOPEND("coordinates");
ParseHelper_Node_Exit();
// check that all components was defined
if((read_flag[0] && read_flag[1] && read_flag[2]) == 0) throw DeadlyImportError("Not all coordinate's components are defined.");
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <volume
// materialid="" - Which material to use.
// type="" - What this volume describes can be “region” or “support”. If none specified, “object” is assumed. If support, then the geometric
// requirements 1-8 listed in section 5 do not need to be maintained.
// >
// </volume>
// Defines a volume from the established vertex list.
// Multi elements - Yes.
// Parent element - <mesh>.
void AMFImporter::ParseNode_Volume()
{
std::string materialid;
std::string type;
CAMFImporter_NodeElement* ne;
// Read attributes for node <color>.
MACRO_ATTRREAD_LOOPBEG;
MACRO_ATTRREAD_CHECK_RET("materialid", materialid, mReader->getAttributeValue);
MACRO_ATTRREAD_CHECK_RET("type", type, mReader->getAttributeValue);
MACRO_ATTRREAD_LOOPEND;
// create new object.
ne = new CAMFImporter_NodeElement_Volume(mNodeElement_Cur);
// and assign read data
((CAMFImporter_NodeElement_Volume*)ne)->MaterialID = materialid;
((CAMFImporter_NodeElement_Volume*)ne)->Type = type;
// Check for child nodes
if(!mReader->isEmptyElement())
{
bool col_read = false;
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("volume");
if(XML_CheckNode_NameEqual("color"))
{
// Check if data already defined.
if(col_read) Throw_MoreThanOnceDefined("color", "Only one color can be defined for <volume>.");
// read data and set flag about it
ParseNode_Color();
col_read = true;
continue;
}
if(XML_CheckNode_NameEqual("triangle")) { ParseNode_Triangle(); continue; }
if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
MACRO_NODECHECK_LOOPEND("volume");
ParseHelper_Node_Exit();
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <triangle>
// </triangle>
// Defines a 3D triangle from three vertices, according to the right-hand rule (counter-clockwise when looking from the outside).
// Multi elements - Yes.
// Parent element - <volume>.
//
// Children elements:
// <v1>, <v2>, <v3>
// Multi elements - No.
// Index of the desired vertices in a triangle or edge.
void AMFImporter::ParseNode_Triangle()
{
CAMFImporter_NodeElement* ne;
// create new color object.
ne = new CAMFImporter_NodeElement_Triangle(mNodeElement_Cur);
CAMFImporter_NodeElement_Triangle& als = *((CAMFImporter_NodeElement_Triangle*)ne);// alias for convenience
// Check for child nodes
if(!mReader->isEmptyElement())
{
bool col_read = false, tex_read = false;
bool read_flag[3] = { false, false, false };
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("triangle");
if(XML_CheckNode_NameEqual("color"))
{
// Check if data already defined.
if(col_read) Throw_MoreThanOnceDefined("color", "Only one color can be defined for <triangle>.");
// read data and set flag about it
ParseNode_Color();
col_read = true;
continue;
}
if(XML_CheckNode_NameEqual("texmap"))// new name of node: "texmap".
{
// Check if data already defined.
if(tex_read) Throw_MoreThanOnceDefined("texmap", "Only one texture coordinate can be defined for <triangle>.");
// read data and set flag about it
ParseNode_TexMap();
tex_read = true;
continue;
}
else if(XML_CheckNode_NameEqual("map"))// old name of node: "map".
{
// Check if data already defined.
if(tex_read) Throw_MoreThanOnceDefined("map", "Only one texture coordinate can be defined for <triangle>.");
// read data and set flag about it
ParseNode_TexMap(true);
tex_read = true;
continue;
}
MACRO_NODECHECK_READCOMP_U32("v1", read_flag[0], als.V[0]);
MACRO_NODECHECK_READCOMP_U32("v2", read_flag[1], als.V[1]);
MACRO_NODECHECK_READCOMP_U32("v3", read_flag[2], als.V[2]);
MACRO_NODECHECK_LOOPEND("triangle");
ParseHelper_Node_Exit();
// check that all components was defined
if((read_flag[0] && read_flag[1] && read_flag[2]) == 0) throw DeadlyImportError("Not all vertices of the triangle are defined.");
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
}// namespace Assimp
#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER

View File

@ -0,0 +1,165 @@
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 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 DAMAGE.
---------------------------------------------------------------------------
*/
/// \file AMFImporter_Macro.hpp
/// \brief Useful macrodefines.
/// \date 2016
/// \author smal.root@gmail.com
#pragma once
#ifndef AMFIMPORTER_MACRO_HPP_INCLUDED
#define AMFIMPORTER_MACRO_HPP_INCLUDED
/// \def MACRO_ATTRREAD_LOOPBEG
/// Begin of loop that read attributes values.
#define MACRO_ATTRREAD_LOOPBEG \
for(int idx = 0, idx_end = mReader->getAttributeCount(); idx < idx_end; idx++) \
{ \
std::string an(mReader->getAttributeName(idx));
/// \def MACRO_ATTRREAD_LOOPEND
/// End of loop that read attributes values.
#define MACRO_ATTRREAD_LOOPEND \
Throw_IncorrectAttr(an); \
}
/// \def MACRO_ATTRREAD_LOOPEND_WSKIP
/// End of loop that read attributes values. Difference from \ref MACRO_ATTRREAD_LOOPEND in that: current macro skip unknown attributes, but
/// \ref MACRO_ATTRREAD_LOOPEND throw an exception.
#define MACRO_ATTRREAD_LOOPEND_WSKIP \
continue; \
}
/// \def MACRO_ATTRREAD_CHECK_REF
/// Check curent attribute name and if it equal to requested then read value. Result write to output variable by reference. If result was read then
/// "continue" will called.
/// \param [in] pAttrName - attribute name.
/// \param [out] pVarName - output variable name.
/// \param [in] pFunction - function which read attribute value and write it to pVarName.
#define MACRO_ATTRREAD_CHECK_REF(pAttrName, pVarName, pFunction) \
if(an == pAttrName) \
{ \
pFunction(idx, pVarName); \
continue; \
}
/// \def MACRO_ATTRREAD_CHECK_RET
/// Check curent attribute name and if it equal to requested then read value. Result write to output variable using return value of \ref pFunction.
/// If result was read then "continue" will called.
/// \param [in] pAttrName - attribute name.
/// \param [out] pVarName - output variable name.
/// \param [in] pFunction - function which read attribute value and write it to pVarName.
#define MACRO_ATTRREAD_CHECK_RET(pAttrName, pVarName, pFunction) \
if(an == pAttrName) \
{ \
pVarName = pFunction(idx); \
continue; \
}
/// \def MACRO_NODECHECK_LOOPBEGIN(pNodeName)
/// Begin of loop of parsing child nodes. Do not add ';' at end.
/// \param [in] pNodeName - current node name.
#define MACRO_NODECHECK_LOOPBEGIN(pNodeName) \
do { \
bool close_found = false; \
\
while(mReader->read()) \
{ \
if(mReader->getNodeType() == irr::io::EXN_ELEMENT) \
{
/// \def MACRO_NODECHECK_LOOPEND(pNodeName)
/// End of loop of parsing child nodes.
/// \param [in] pNodeName - current node name.
#define MACRO_NODECHECK_LOOPEND(pNodeName) \
XML_CheckNode_SkipUnsupported(pNodeName); \
}/* if(mReader->getNodeType() == irr::io::EXN_ELEMENT) */ \
else if(mReader->getNodeType() == irr::io::EXN_ELEMENT_END) \
{ \
if(XML_CheckNode_NameEqual(pNodeName)) \
{ \
close_found = true; \
\
break; \
} \
}/* else if(mReader->getNodeType() == irr::io::EXN_ELEMENT_END) */ \
}/* while(mReader->read()) */ \
\
if(!close_found) Throw_CloseNotFound(pNodeName); \
\
} while(false)
/// \def MACRO_NODECHECK_READCOMP_F
/// Check curent node name and if it equal to requested then read value. Result write to output variable of type "float".
/// If result was read then "continue" will called. Also check if node data already read then raise exception.
/// \param [in] pNodeName - node name.
/// \param [in, out] pReadFlag - read flag.
/// \param [out] pVarName - output variable name.
#define MACRO_NODECHECK_READCOMP_F(pNodeName, pReadFlag, pVarName) \
if(XML_CheckNode_NameEqual(pNodeName)) \
{ \
/* Check if field already read before. */ \
if(pReadFlag) Throw_MoreThanOnceDefined(pNodeName, "Only one component can be defined."); \
/* Read color component and assign it to object. */ \
pVarName = XML_ReadNode_GetVal_AsFloat(); \
pReadFlag = true; \
continue; \
}
/// \def MACRO_NODECHECK_READCOMP_U32
/// Check curent node name and if it equal to requested then read value. Result write to output variable of type "uint32_t".
/// If result was read then "continue" will called. Also check if node data already read then raise exception.
/// \param [in] pNodeName - node name.
/// \param [in, out] pReadFlag - read flag.
/// \param [out] pVarName - output variable name.
#define MACRO_NODECHECK_READCOMP_U32(pNodeName, pReadFlag, pVarName) \
if(XML_CheckNode_NameEqual(pNodeName)) \
{ \
/* Check if field already read before. */ \
if(pReadFlag) Throw_MoreThanOnceDefined(pNodeName, "Only one component can be defined."); \
/* Read color component and assign it to object. */ \
pVarName = XML_ReadNode_GetVal_AsU32(); \
pReadFlag = true; \
continue; \
}
#endif // AMFIMPORTER_MACRO_HPP_INCLUDED

View File

@ -0,0 +1,310 @@
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 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 DAMAGE.
---------------------------------------------------------------------------
*/
/// \file AMFImporter_Material.cpp
/// \brief Parsing data from material nodes.
/// \date 2016
/// \author smal.root@gmail.com
#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
#include "AMFImporter.hpp"
#include "AMFImporter_Macro.hpp"
namespace Assimp
{
// <color
// profile="" - The ICC color space used to interpret the three color channels <r>, <g> and <b>.
// >
// </color>
// A color definition.
// Multi elements - No.
// Parent element - <material>, <object>, <volume>, <vertex>, <triangle>.
//
// "profile" can be one of "sRGB", "AdobeRGB", "Wide-Gamut-RGB", "CIERGB", "CIELAB", or "CIEXYZ".
// Children elements:
// <r>, <g>, <b>, <a>
// Multi elements - No.
// Red, Greed, Blue and Alpha (transparency) component of a color in sRGB space, values ranging from 0 to 1. The
// values can be specified as constants, or as a formula depending on the coordinates.
void AMFImporter::ParseNode_Color()
{
std::string profile;
CAMFImporter_NodeElement* ne;
// Read attributes for node <color>.
MACRO_ATTRREAD_LOOPBEG;
MACRO_ATTRREAD_CHECK_RET("profile", profile, mReader->getAttributeValue);
MACRO_ATTRREAD_LOOPEND;
// create new color object.
ne = new CAMFImporter_NodeElement_Color(mNodeElement_Cur);
CAMFImporter_NodeElement_Color& als = *((CAMFImporter_NodeElement_Color*)ne);// alias for convenience
als.Profile = profile;
// Check for child nodes
if(!mReader->isEmptyElement())
{
bool read_flag[4] = { false, false, false, false };
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("color");
MACRO_NODECHECK_READCOMP_F("r", read_flag[0], als.Color.r);
MACRO_NODECHECK_READCOMP_F("g", read_flag[1], als.Color.g);
MACRO_NODECHECK_READCOMP_F("b", read_flag[2], als.Color.b);
MACRO_NODECHECK_READCOMP_F("a", read_flag[3], als.Color.a);
MACRO_NODECHECK_LOOPEND("color");
ParseHelper_Node_Exit();
// check that all components was defined
if(!(read_flag[0] && read_flag[1] && read_flag[2])) throw DeadlyImportError("Not all color components are defined.");
// check if <a> is absent. Then manualy add "a == 1".
if(!read_flag[3]) als.Color.a = 1;
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
als.Composed = false;
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <material
// id="" - A unique material id. material ID "0" is reserved to denote no material (void) or sacrificial material.
// >
// </material>
// An available material.
// Multi elements - Yes.
// Parent element - <amf>.
void AMFImporter::ParseNode_Material()
{
std::string id;
CAMFImporter_NodeElement* ne;
// Read attributes for node <color>.
MACRO_ATTRREAD_LOOPBEG;
MACRO_ATTRREAD_CHECK_RET("id", id, mReader->getAttributeValue);
MACRO_ATTRREAD_LOOPEND;
// create new object.
ne = new CAMFImporter_NodeElement_Material(mNodeElement_Cur);
// and assign read data
((CAMFImporter_NodeElement_Material*)ne)->ID = id;
// Check for child nodes
if(!mReader->isEmptyElement())
{
bool col_read = false;
ParseHelper_Node_Enter(ne);
MACRO_NODECHECK_LOOPBEGIN("material");
if(XML_CheckNode_NameEqual("color"))
{
// Check if data already defined.
if(col_read) Throw_MoreThanOnceDefined("color", "Only one color can be defined for <material>.");
// read data and set flag about it
ParseNode_Color();
col_read = true;
continue;
}
if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
MACRO_NODECHECK_LOOPEND("material");
ParseHelper_Node_Exit();
}// if(!mReader->isEmptyElement())
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}// if(!mReader->isEmptyElement()) else
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <texture
// id="" - Assigns a unique texture id for the new texture.
// width="" - Width (horizontal size, x) of the texture, in pixels.
// height="" - Height (lateral size, y) of the texture, in pixels.
// depth="" - Depth (vertical size, z) of the texture, in pixels.
// type="" - Encoding of the data in the texture. Currently allowed values are "grayscale" only. In grayscale mode, each pixel is represented by one byte
// in the range of 0-255. When the texture is referenced using the tex function, these values are converted into a single floating point number in the
// range of 0-1 (see Annex 2). A full color graphics will typically require three textures, one for each of the color channels. A graphic involving
// transparency may require a fourth channel.
// tiled="" - If true then texture repeated when UV-coordinates is greater than 1.
// >
// </triangle>
// Specifies an texture data to be used as a map. Lists a sequence of Base64 values specifying values for pixels from left to right then top to bottom,
// then layer by layer.
// Multi elements - Yes.
// Parent element - <amf>.
void AMFImporter::ParseNode_Texture()
{
std::string id;
uint32_t width = 0;
uint32_t height = 0;
uint32_t depth = 1;
std::string type;
bool tiled = false;
std::string enc64_data;
CAMFImporter_NodeElement* ne;
// Read attributes for node <color>.
MACRO_ATTRREAD_LOOPBEG;
MACRO_ATTRREAD_CHECK_RET("id", id, mReader->getAttributeValue);
MACRO_ATTRREAD_CHECK_RET("width", width, XML_ReadNode_GetAttrVal_AsU32);
MACRO_ATTRREAD_CHECK_RET("height", height, XML_ReadNode_GetAttrVal_AsU32);
MACRO_ATTRREAD_CHECK_RET("depth", depth, XML_ReadNode_GetAttrVal_AsU32);
MACRO_ATTRREAD_CHECK_RET("type", type, mReader->getAttributeValue);
MACRO_ATTRREAD_CHECK_RET("tiled", tiled, XML_ReadNode_GetAttrVal_AsBool);
MACRO_ATTRREAD_LOOPEND;
// create new texture object.
ne = new CAMFImporter_NodeElement_Texture(mNodeElement_Cur);
CAMFImporter_NodeElement_Texture& als = *((CAMFImporter_NodeElement_Texture*)ne);// alias for convenience
// Check for child nodes
if(!mReader->isEmptyElement()) XML_ReadNode_GetVal_AsString(enc64_data);
// check that all components was defined
if(id.empty()) throw DeadlyImportError("ID for texture must be defined.");
if(width < 1) Throw_IncorrectAttrValue("width");
if(height < 1) Throw_IncorrectAttrValue("height");
if(depth < 1) Throw_IncorrectAttrValue("depth");
if(type != "grayscale") Throw_IncorrectAttrValue("type");
if(enc64_data.empty()) throw DeadlyImportError("Texture data not defined.");
// copy data
als.ID = id;
als.Width = width;
als.Height = height;
als.Depth = depth;
als.Tiled = tiled;
ParseHelper_Decode_Base64(enc64_data, als.Data);
// check data size
if((width * height * depth) != als.Data.size()) throw DeadlyImportError("Texture has incorrect data size.");
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
}
// <texmap
// rtexid="" - Texture ID for red color component.
// gtexid="" - Texture ID for green color component.
// btexid="" - Texture ID for blue color component.
// atexid="" - Texture ID for alpha color component. Optional.
// >
// </texmap>, old name: <map>
// Specifies texture coordinates for triangle.
// Multi elements - No.
// Parent element - <triangle>.
// Children elements:
// <utex1>, <utex2>, <utex3>, <vtex1>, <vtex2>, <vtex3>. Old name: <u1>, <u2>, <u3>, <v1>, <v2>, <v3>.
// Multi elements - No.
// Texture coordinates for every vertex of triangle.
void AMFImporter::ParseNode_TexMap(const bool pUseOldName)
{
std::string rtexid, gtexid, btexid, atexid;
CAMFImporter_NodeElement* ne;
// Read attributes for node <color>.
MACRO_ATTRREAD_LOOPBEG;
MACRO_ATTRREAD_CHECK_RET("rtexid", rtexid, mReader->getAttributeValue);
MACRO_ATTRREAD_CHECK_RET("gtexid", gtexid, mReader->getAttributeValue);
MACRO_ATTRREAD_CHECK_RET("btexid", btexid, mReader->getAttributeValue);
MACRO_ATTRREAD_CHECK_RET("atexid", atexid, mReader->getAttributeValue);
MACRO_ATTRREAD_LOOPEND;
// create new texture coordinates object.
ne = new CAMFImporter_NodeElement_TexMap(mNodeElement_Cur);
CAMFImporter_NodeElement_TexMap& als = *((CAMFImporter_NodeElement_TexMap*)ne);// alias for convenience
// check data
if(rtexid.empty() && gtexid.empty() && btexid.empty()) throw DeadlyImportError("ParseNode_TexMap. At least one texture ID must be defined.");
// Check for children nodes
XML_CheckNode_MustHaveChildren();
// read children nodes
bool read_flag[6] = { false, false, false, false, false, false };
ParseHelper_Node_Enter(ne);
if(!pUseOldName)
{
MACRO_NODECHECK_LOOPBEGIN("texmap");
MACRO_NODECHECK_READCOMP_F("utex1", read_flag[0], als.TextureCoordinate[0].x);
MACRO_NODECHECK_READCOMP_F("utex2", read_flag[1], als.TextureCoordinate[1].x);
MACRO_NODECHECK_READCOMP_F("utex3", read_flag[2], als.TextureCoordinate[2].x);
MACRO_NODECHECK_READCOMP_F("vtex1", read_flag[3], als.TextureCoordinate[0].y);
MACRO_NODECHECK_READCOMP_F("vtex2", read_flag[4], als.TextureCoordinate[1].y);
MACRO_NODECHECK_READCOMP_F("vtex3", read_flag[5], als.TextureCoordinate[2].y);
MACRO_NODECHECK_LOOPEND("texmap");
}
else
{
MACRO_NODECHECK_LOOPBEGIN("map");
MACRO_NODECHECK_READCOMP_F("u1", read_flag[0], als.TextureCoordinate[0].x);
MACRO_NODECHECK_READCOMP_F("u2", read_flag[1], als.TextureCoordinate[1].x);
MACRO_NODECHECK_READCOMP_F("u3", read_flag[2], als.TextureCoordinate[2].x);
MACRO_NODECHECK_READCOMP_F("v1", read_flag[3], als.TextureCoordinate[0].y);
MACRO_NODECHECK_READCOMP_F("v2", read_flag[4], als.TextureCoordinate[1].y);
MACRO_NODECHECK_READCOMP_F("v3", read_flag[5], als.TextureCoordinate[2].y);
MACRO_NODECHECK_LOOPEND("map");
}// if(!pUseOldName) else
ParseHelper_Node_Exit();
// check that all components was defined
if(!(read_flag[0] && read_flag[1] && read_flag[2] && read_flag[3] && read_flag[4] && read_flag[5]))
throw DeadlyImportError("Not all texture coordinates are defined.");
// copy attributes data
als.TextureID_R = rtexid;
als.TextureID_G = gtexid;
als.TextureID_B = btexid;
als.TextureID_A = atexid;
mNodeElement_List.push_back(ne);// add to node element list because its a new object in graph.
}
}// namespace Assimp
#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER

View File

@ -0,0 +1,400 @@
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 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 DAMAGE.
---------------------------------------------------------------------------
*/
/// \file AMFImporter_Node.hpp
/// \brief Elements of scene graph.
/// \date 2016
/// \author smal.root@gmail.com
#pragma once
#ifndef INCLUDED_AI_AMF_IMPORTER_NODE_H
#define INCLUDED_AI_AMF_IMPORTER_NODE_H
// Header files, stdlib.
#include <list>
#include <string>
#include <vector>
// Header files, Assimp.
#include "assimp/types.h"
#include "assimp/scene.h"
/// \class CAMFImporter_NodeElement
/// Base class for elements of nodes.
class CAMFImporter_NodeElement {
public:
/// Define what data type contain node element.
enum EType {
ENET_Color, ///< Color element: <color>.
ENET_Constellation,///< Grouping element: <constellation>.
ENET_Coordinates, ///< Coordinates element: <coordinates>.
ENET_Edge, ///< Edge element: <edge>.
ENET_Instance, ///< Grouping element: <constellation>.
ENET_Material, ///< Material element: <material>.
ENET_Metadata, ///< Metadata element: <metadata>.
ENET_Mesh, ///< Metadata element: <mesh>.
ENET_Object, ///< Element which hold object: <object>.
ENET_Root, ///< Root element: <amf>.
ENET_Triangle, ///< Triangle element: <triangle>.
ENET_TexMap, ///< Texture coordinates element: <texmap> or <map>.
ENET_Texture, ///< Texture element: <texture>.
ENET_Vertex, ///< Vertex element: <vertex>.
ENET_Vertices, ///< Vertex element: <vertices>.
ENET_Volume, ///< Volume element: <volume>.
ENET_Invalid ///< Element has invalid type and possible contain invalid data.
};
const EType Type;///< Type of element.
std::string ID;///< ID of element.
CAMFImporter_NodeElement* Parent;///< Parent element. If nullptr then this node is root.
std::list<CAMFImporter_NodeElement*> Child;///< Child elements.
public: /// Destructor, virtual..
virtual ~CAMFImporter_NodeElement() {
// empty
}
private:
/// Disabled copy constructor.
CAMFImporter_NodeElement(const CAMFImporter_NodeElement& pNodeElement);
/// Disabled assign operator.
CAMFImporter_NodeElement& operator=(const CAMFImporter_NodeElement& pNodeElement);
/// Disabled default constructor.
CAMFImporter_NodeElement();
protected:
/// In constructor inheritor must set element type.
/// \param [in] pType - element type.
/// \param [in] pParent - parent element.
CAMFImporter_NodeElement(const EType pType, CAMFImporter_NodeElement* pParent)
: Type(pType)
, ID()
, Parent(pParent)
, Child() {
// empty
}
};// class IAMFImporter_NodeElement
/// \struct CAMFImporter_NodeElement_Constellation
/// A collection of objects or constellations with specific relative locations.
struct CAMFImporter_NodeElement_Constellation : public CAMFImporter_NodeElement
{
/// \fn CAMFImporter_NodeElement_Constellation(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Constellation(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Constellation, pParent)
{}
};// struct CAMFImporter_NodeElement_Constellation
/// \struct CAMFImporter_NodeElement_Instance
/// Part of constellation.
struct CAMFImporter_NodeElement_Instance : public CAMFImporter_NodeElement
{
/****************** Variables ******************/
std::string ObjectID;///< ID of object for instanciation.
/// \var Delta - The distance of translation in the x, y, or z direction, respectively, in the referenced object's coordinate system, to
/// create an instance of the object in the current constellation.
aiVector3D Delta;
/// \var Rotation - The rotation, in degrees, to rotate the referenced object about its x, y, and z axes, respectively, to create an
/// instance of the object in the current constellation. Rotations shall be executed in order of x first, then y, then z.
aiVector3D Rotation;
/****************** Functions ******************/
/// \fn CAMFImporter_NodeElement_Instance(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Instance(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Instance, pParent)
{}
};// struct CAMFImporter_NodeElement_Instance
/// \struct CAMFImporter_NodeElement_Metadata
/// Structure that define metadata node.
struct CAMFImporter_NodeElement_Metadata : public CAMFImporter_NodeElement
{
/****************** Variables ******************/
std::string Type;///< Type of "Value".
std::string Value;///< Value.
/****************** Functions ******************/
/// \fn CAMFImporter_NodeElement_Metadata(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Metadata(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Metadata, pParent)
{}
};// struct CAMFImporter_NodeElement_Metadata
/// \struct CAMFImporter_NodeElement_Root
/// Structure that define root node.
struct CAMFImporter_NodeElement_Root : public CAMFImporter_NodeElement
{
/****************** Variables ******************/
std::string Unit;///< The units to be used. May be "inch", "millimeter", "meter", "feet", or "micron".
std::string Version;///< Version of format.
/****************** Functions ******************/
/// \fn CAMFImporter_NodeElement_Root(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Root(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Root, pParent)
{}
};// struct CAMFImporter_NodeElement_Root
/// \struct CAMFImporter_NodeElement_Color
/// Structure that define object node.
struct CAMFImporter_NodeElement_Color : public CAMFImporter_NodeElement
{
/****************** Variables ******************/
bool Composed;///< Type of color stored: if true then look for formula in \ref Color_Composed[4], else - in \ref Color.
std::string Color_Composed[4];///< By components formulas of composed color. [0..3] => RGBA.
aiColor4D Color;///< Constant color.
std::string Profile;///< The ICC color space used to interpret the three color channels <r>, <g> and <b>..
/****************** Functions ******************/
/// \fn CAMFImporter_NodeElement_Color(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Color(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Color, pParent)
{}
};// struct CAMFImporter_NodeElement_Color
/// \struct CAMFImporter_NodeElement_Material
/// Structure that define material node.
struct CAMFImporter_NodeElement_Material : public CAMFImporter_NodeElement
{
/// \fn CAMFImporter_NodeElement_Material(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Material(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Material, pParent)
{}
};// struct CAMFImporter_NodeElement_Material
/// \struct CAMFImporter_NodeElement_Object
/// Structure that define object node.
struct CAMFImporter_NodeElement_Object : public CAMFImporter_NodeElement
{
/// \fn CAMFImporter_NodeElement_Object(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Object(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Object, pParent)
{}
};// struct CAMFImporter_NodeElement_Object
/// \struct CAMFImporter_NodeElement_Mesh
/// Structure that define mesh node.
struct CAMFImporter_NodeElement_Mesh : public CAMFImporter_NodeElement
{
/// \fn CAMFImporter_NodeElement_Mesh(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Mesh(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Mesh, pParent)
{}
};// struct CAMFImporter_NodeElement_Mesh
/// \struct CAMFImporter_NodeElement_Vertex
/// Structure that define vertex node.
struct CAMFImporter_NodeElement_Vertex : public CAMFImporter_NodeElement
{
/// \fn CAMFImporter_NodeElement_Vertex(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Vertex(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Vertex, pParent)
{}
};// struct CAMFImporter_NodeElement_Vertex
/// \struct CAMFImporter_NodeElement_Edge
/// Structure that define edge node.
struct CAMFImporter_NodeElement_Edge : public CAMFImporter_NodeElement
{
/// \fn CAMFImporter_NodeElement_Edge(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Edge(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Edge, pParent)
{}
};// struct CAMFImporter_NodeElement_Vertex
/// \struct CAMFImporter_NodeElement_Vertices
/// Structure that define vertices node.
struct CAMFImporter_NodeElement_Vertices : public CAMFImporter_NodeElement
{
/// \fn CAMFImporter_NodeElement_Vertices(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Vertices(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Vertices, pParent)
{}
};// struct CAMFImporter_NodeElement_Vertices
/// \struct CAMFImporter_NodeElement_Volume
/// Structure that define volume node.
struct CAMFImporter_NodeElement_Volume : public CAMFImporter_NodeElement
{
/****************** Variables ******************/
std::string MaterialID;///< Which material to use.
std::string Type;///< What this volume describes can be “region” or “support”. If none specified, “object” is assumed.
/****************** Functions ******************/
/// \fn CAMFImporter_NodeElement_Volume(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Volume(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Volume, pParent)
{}
};// struct CAMFImporter_NodeElement_Volume
/// \struct CAMFImporter_NodeElement_Coordinates
/// Structure that define coordinates node.
struct CAMFImporter_NodeElement_Coordinates : public CAMFImporter_NodeElement
{
/****************** Variables ******************/
aiVector3D Coordinate;///< Coordinate.
/****************** Functions ******************/
/// \fn CAMFImporter_NodeElement_Coordinates(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Coordinates(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Coordinates, pParent)
{}
};// struct CAMFImporter_NodeElement_Coordinates
/// \struct CAMFImporter_NodeElement_TexMap
/// Structure that define texture coordinates node.
struct CAMFImporter_NodeElement_TexMap : public CAMFImporter_NodeElement
{
/****************** Variables ******************/
aiVector3D TextureCoordinate[3];///< Texture coordinates.
std::string TextureID_R;///< Texture ID for red color component.
std::string TextureID_G;///< Texture ID for green color component.
std::string TextureID_B;///< Texture ID for blue color component.
std::string TextureID_A;///< Texture ID for alpha color component.
/****************** Functions ******************/
/// \fn CAMFImporter_NodeElement_TexMap(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_TexMap(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_TexMap, pParent)
{}
};// struct CAMFImporter_NodeElement_TexMap
/// \struct CAMFImporter_NodeElement_Triangle
/// Structure that define triangle node.
struct CAMFImporter_NodeElement_Triangle : public CAMFImporter_NodeElement
{
/****************** Variables ******************/
size_t V[3];///< Triangle vertices.
/****************** Functions ******************/
/// \fn CAMFImporter_NodeElement_Triangle(CAMFImporter_NodeElement* pParent)
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Triangle(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Triangle, pParent)
{}
};// struct CAMFImporter_NodeElement_Triangle
/// Structure that define texture node.
struct CAMFImporter_NodeElement_Texture : public CAMFImporter_NodeElement {
size_t Width, Height, Depth;///< Size of the texture.
std::vector<uint8_t> Data;///< Data of the texture.
bool Tiled;
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Texture(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Texture, pParent)
, Width( 0 )
, Height( 0 )
, Depth( 0 )
, Data()
, Tiled( false ){
// empty
}
};// struct CAMFImporter_NodeElement_Texture
#endif // INCLUDED_AI_AMF_IMPORTER_NODE_H

View File

@ -0,0 +1,974 @@
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 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 DAMAGE.
---------------------------------------------------------------------------
*/
/// \file AMFImporter_Postprocess.cpp
/// \brief Convert built scenegraph and objects to Assimp scenegraph.
/// \date 2016
/// \author smal.root@gmail.com
#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
#include "AMFImporter.hpp"
// Header files, Assimp.
#include "SceneCombiner.h"
#include "StandardShapes.h"
#include "StringUtils.h"
// Header files, stdlib.
#include <iterator>
namespace Assimp
{
aiColor4D AMFImporter::SPP_Material::GetColor(const float pX, const float pY, const float pZ) const
{
aiColor4D tcol;
// Check if stored data are supported.
if(Composition.size() != 0)
{
throw DeadlyImportError("IME. GetColor for composition");
}
else if(Color->Composed)
{
throw DeadlyImportError("IME. GetColor, composed color");
}
else
{
tcol = Color->Color;
}
// Check if default color must be used
if((tcol.r == 0) && (tcol.g == 0) && (tcol.b == 0) && (tcol.a == 0))
{
tcol.r = 0.5f;
tcol.g = 0.5f;
tcol.b = 0.5f;
tcol.a = 1;
}
return tcol;
}
void AMFImporter::PostprocessHelper_CreateMeshDataArray(const CAMFImporter_NodeElement_Mesh& pNodeElement, std::vector<aiVector3D>& pVertexCoordinateArray,
std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray) const
{
CAMFImporter_NodeElement_Vertices* vn = nullptr;
size_t col_idx;
// All data stored in "vertices", search for it.
for(CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
{
if(ne_child->Type == CAMFImporter_NodeElement::ENET_Vertices) vn = (CAMFImporter_NodeElement_Vertices*)ne_child;
}
// If "vertices" not found then no work for us.
if(vn == nullptr) return;
pVertexCoordinateArray.reserve(vn->Child.size());// all coordinates stored as child and we need to reserve space for future push_back's.
pVertexColorArray.resize(vn->Child.size());// colors count equal vertices count.
col_idx = 0;
// Inside vertices collect all data and place to arrays
for(CAMFImporter_NodeElement* vn_child: vn->Child)
{
// vertices, colors
if(vn_child->Type == CAMFImporter_NodeElement::ENET_Vertex)
{
// by default clear color for current vertex
pVertexColorArray[col_idx] = nullptr;
for(CAMFImporter_NodeElement* vtx: vn_child->Child)
{
if(vtx->Type == CAMFImporter_NodeElement::ENET_Coordinates)
{
pVertexCoordinateArray.push_back(((CAMFImporter_NodeElement_Coordinates*)vtx)->Coordinate);
continue;
}
if(vtx->Type == CAMFImporter_NodeElement::ENET_Color)
{
pVertexColorArray[col_idx] = (CAMFImporter_NodeElement_Color*)vtx;
continue;
}
}// for(CAMFImporter_NodeElement* vtx: vn_child->Child)
col_idx++;
}// if(vn_child->Type == CAMFImporter_NodeElement::ENET_Vertex)
}// for(CAMFImporter_NodeElement* vn_child: vn->Child)
}
size_t AMFImporter::PostprocessHelper_GetTextureID_Or_Create(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B,
const std::string& pID_A)
{
size_t TextureConverted_Index;
std::string TextureConverted_ID;
// check input data
if(pID_R.empty() && pID_G.empty() && pID_B.empty() && pID_A.empty())
throw DeadlyImportError("PostprocessHelper_GetTextureID_Or_Create. At least one texture ID must be defined.");
// Create ID
TextureConverted_ID = pID_R + "_" + pID_G + "_" + pID_B + "_" + pID_A;
// Check if texture specified by set of IDs is converted already.
TextureConverted_Index = 0;
for(const SPP_Texture& tex_convd: mTexture_Converted)
{
if(tex_convd.ID == TextureConverted_ID)
return TextureConverted_Index;
else
TextureConverted_Index++;
}
//
// Converted texture not found, create it.
//
CAMFImporter_NodeElement_Texture* src_texture[4]{nullptr};
std::vector<CAMFImporter_NodeElement_Texture*> src_texture_4check;
SPP_Texture converted_texture;
{// find all specified source textures
CAMFImporter_NodeElement* t_tex;
// R
if(!pID_R.empty())
{
if(!Find_NodeElement(pID_R, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_R);
src_texture[0] = (CAMFImporter_NodeElement_Texture*)t_tex;
src_texture_4check.push_back((CAMFImporter_NodeElement_Texture*)t_tex);
}
else
{
src_texture[0] = nullptr;
}
// G
if(!pID_G.empty())
{
if(!Find_NodeElement(pID_G, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_G);
src_texture[1] = (CAMFImporter_NodeElement_Texture*)t_tex;
src_texture_4check.push_back((CAMFImporter_NodeElement_Texture*)t_tex);
}
else
{
src_texture[1] = nullptr;
}
// B
if(!pID_B.empty())
{
if(!Find_NodeElement(pID_B, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_B);
src_texture[2] = (CAMFImporter_NodeElement_Texture*)t_tex;
src_texture_4check.push_back((CAMFImporter_NodeElement_Texture*)t_tex);
}
else
{
src_texture[2] = nullptr;
}
// A
if(!pID_A.empty())
{
if(!Find_NodeElement(pID_A, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_A);
src_texture[3] = (CAMFImporter_NodeElement_Texture*)t_tex;
src_texture_4check.push_back((CAMFImporter_NodeElement_Texture*)t_tex);
}
else
{
src_texture[3] = nullptr;
}
}// END: find all specified source textures
// check that all textures has same size
if(src_texture_4check.size() > 1)
{
for (size_t i = 0, i_e = (src_texture_4check.size() - 1); i < i_e; i++)
{
if((src_texture_4check[i]->Width != src_texture_4check[i + 1]->Width) || (src_texture_4check[i]->Height != src_texture_4check[i + 1]->Height) ||
(src_texture_4check[i]->Depth != src_texture_4check[i + 1]->Depth))
{
throw DeadlyImportError("PostprocessHelper_GetTextureID_Or_Create. Source texture must has the same size.");
}
}
}// if(src_texture_4check.size() > 1)
// set texture attributes
converted_texture.Width = src_texture_4check[0]->Width;
converted_texture.Height = src_texture_4check[0]->Height;
converted_texture.Depth = src_texture_4check[0]->Depth;
// if one of source texture is tiled then converted texture is tiled too.
converted_texture.Tiled = false;
for(uint8_t i = 0; i < src_texture_4check.size(); i++) converted_texture.Tiled |= src_texture_4check[i]->Tiled;
// Create format hint.
strcpy(converted_texture.FormatHint, "rgba0000");// copy initial string.
if(!pID_R.empty()) converted_texture.FormatHint[4] = '8';
if(!pID_G.empty()) converted_texture.FormatHint[5] = '8';
if(!pID_B.empty()) converted_texture.FormatHint[6] = '8';
if(!pID_A.empty()) converted_texture.FormatHint[7] = '8';
//
// Сopy data of textures.
//
size_t tex_size = 0;
size_t step = 0;
size_t off_g = 0;
size_t off_b = 0;
// Calculate size of the target array and rule how data will be copied.
if(!pID_R.empty() && nullptr != src_texture[ 0 ] ) {
tex_size += src_texture[0]->Data.size(); step++, off_g++, off_b++;
}
if(!pID_G.empty() && nullptr != src_texture[ 1 ] ) {
tex_size += src_texture[1]->Data.size(); step++, off_b++;
}
if(!pID_B.empty() && nullptr != src_texture[ 2 ] ) {
tex_size += src_texture[2]->Data.size(); step++;
}
if(!pID_A.empty() && nullptr != src_texture[ 3 ] ) {
tex_size += src_texture[3]->Data.size(); step++;
}
// Create target array.
converted_texture.Data = new uint8_t[tex_size];
// And copy data
auto CopyTextureData = [&](const std::string& pID, const size_t pOffset, const size_t pStep, const uint8_t pSrcTexNum) -> void
{
if(!pID.empty())
{
for(size_t idx_target = pOffset, idx_src = 0; idx_target < tex_size; idx_target += pStep, idx_src++)
converted_texture.Data[idx_target] = src_texture[pSrcTexNum]->Data.at(idx_src);
}
};// auto CopyTextureData = [&](const size_t pOffset, const size_t pStep, const uint8_t pSrcTexNum) -> void
CopyTextureData(pID_R, 0, step, 0);
CopyTextureData(pID_G, off_g, step, 1);
CopyTextureData(pID_B, off_b, step, 2);
CopyTextureData(pID_A, step - 1, step, 3);
// Store new converted texture ID
converted_texture.ID = TextureConverted_ID;
// Store new converted texture
mTexture_Converted.push_back(converted_texture);
return TextureConverted_Index;
}
void AMFImporter::PostprocessHelper_SplitFacesByTextureID(std::list<SComplexFace>& pInputList, std::list<std::list<SComplexFace> >& pOutputList_Separated)
{
auto texmap_is_equal = [](const CAMFImporter_NodeElement_TexMap* pTexMap1, const CAMFImporter_NodeElement_TexMap* pTexMap2) -> bool
{
if((pTexMap1 == nullptr) && (pTexMap2 == nullptr)) return true;
if(pTexMap1 == nullptr) return false;
if(pTexMap2 == nullptr) return false;
if(pTexMap1->TextureID_R != pTexMap2->TextureID_R) return false;
if(pTexMap1->TextureID_G != pTexMap2->TextureID_G) return false;
if(pTexMap1->TextureID_B != pTexMap2->TextureID_B) return false;
if(pTexMap1->TextureID_A != pTexMap2->TextureID_A) return false;
return true;
};
pOutputList_Separated.clear();
if(pInputList.size() == 0) return;
do
{
SComplexFace face_start = pInputList.front();
std::list<SComplexFace> face_list_cur;
for(std::list<SComplexFace>::iterator it = pInputList.begin(), it_end = pInputList.end(); it != it_end;)
{
if(texmap_is_equal(face_start.TexMap, it->TexMap))
{
auto it_old = it;
it++;
face_list_cur.push_back(*it_old);
pInputList.erase(it_old);
}
else
{
it++;
}
}
if(face_list_cur.size() > 0) pOutputList_Separated.push_back(face_list_cur);
} while(pInputList.size() > 0);
}
void AMFImporter::Postprocess_AddMetadata(const std::list<CAMFImporter_NodeElement_Metadata*>& metadataList, aiNode& sceneNode) const
{
if ( !metadataList.empty() )
{
if(sceneNode.mMetaData != nullptr) throw DeadlyImportError("Postprocess. MetaData member in node are not nullptr. Something went wrong.");
// copy collected metadata to output node.
sceneNode.mMetaData = aiMetadata::Alloc( static_cast<unsigned int>(metadataList.size()) );
size_t meta_idx( 0 );
for(const CAMFImporter_NodeElement_Metadata& metadata: metadataList)
{
sceneNode.mMetaData->Set(static_cast<unsigned int>(meta_idx++), metadata.Type, aiString(metadata.Value));
}
}// if(!metadataList.empty())
}
void AMFImporter::Postprocess_BuildNodeAndObject(const CAMFImporter_NodeElement_Object& pNodeElement, std::list<aiMesh*>& pMeshList, aiNode** pSceneNode)
{
CAMFImporter_NodeElement_Color* object_color = nullptr;
// create new aiNode and set name as <object> has.
*pSceneNode = new aiNode;
(*pSceneNode)->mName = pNodeElement.ID;
// read mesh and color
for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
{
std::vector<aiVector3D> vertex_arr;
std::vector<CAMFImporter_NodeElement_Color*> color_arr;
// color for object
if(ne_child->Type == CAMFImporter_NodeElement::ENET_Color) object_color = (CAMFImporter_NodeElement_Color*)ne_child;
if(ne_child->Type == CAMFImporter_NodeElement::ENET_Mesh)
{
// Create arrays from children of mesh: vertices.
PostprocessHelper_CreateMeshDataArray(*((CAMFImporter_NodeElement_Mesh*)ne_child), vertex_arr, color_arr);
// Use this arrays as a source when creating every aiMesh
Postprocess_BuildMeshSet(*((CAMFImporter_NodeElement_Mesh*)ne_child), vertex_arr, color_arr, object_color, pMeshList, **pSceneNode);
}
}// for(const CAMFImporter_NodeElement* ne_child: pNodeElement)
}
void AMFImporter::Postprocess_BuildMeshSet(const CAMFImporter_NodeElement_Mesh& pNodeElement, const std::vector<aiVector3D>& pVertexCoordinateArray,
const std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray,
const CAMFImporter_NodeElement_Color* pObjectColor, std::list<aiMesh*>& pMeshList, aiNode& pSceneNode)
{
std::list<unsigned int> mesh_idx;
// all data stored in "volume", search for it.
for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
{
const CAMFImporter_NodeElement_Color* ne_volume_color = nullptr;
const SPP_Material* cur_mat = nullptr;
if(ne_child->Type == CAMFImporter_NodeElement::ENET_Volume)
{
/******************* Get faces *******************/
const CAMFImporter_NodeElement_Volume* ne_volume = reinterpret_cast<const CAMFImporter_NodeElement_Volume*>(ne_child);
std::list<SComplexFace> complex_faces_list;// List of the faces of the volume.
std::list<std::list<SComplexFace> > complex_faces_toplist;// List of the face list for every mesh.
// check if volume use material
if(!ne_volume->MaterialID.empty())
{
if(!Find_ConvertedMaterial(ne_volume->MaterialID, &cur_mat)) Throw_ID_NotFound(ne_volume->MaterialID);
}
// inside "volume" collect all data and place to arrays or create new objects
for(const CAMFImporter_NodeElement* ne_volume_child: ne_volume->Child)
{
// color for volume
if(ne_volume_child->Type == CAMFImporter_NodeElement::ENET_Color)
{
ne_volume_color = reinterpret_cast<const CAMFImporter_NodeElement_Color*>(ne_volume_child);
}
else if(ne_volume_child->Type == CAMFImporter_NodeElement::ENET_Triangle)// triangles, triangles colors
{
const CAMFImporter_NodeElement_Triangle& tri_al = *reinterpret_cast<const CAMFImporter_NodeElement_Triangle*>(ne_volume_child);
SComplexFace complex_face;
// initialize pointers
complex_face.Color = nullptr;
complex_face.TexMap = nullptr;
// get data from triangle children: color, texture coordinates.
if(tri_al.Child.size())
{
for(const CAMFImporter_NodeElement* ne_triangle_child: tri_al.Child)
{
if(ne_triangle_child->Type == CAMFImporter_NodeElement::ENET_Color)
complex_face.Color = reinterpret_cast<const CAMFImporter_NodeElement_Color*>(ne_triangle_child);
else if(ne_triangle_child->Type == CAMFImporter_NodeElement::ENET_TexMap)
complex_face.TexMap = reinterpret_cast<const CAMFImporter_NodeElement_TexMap*>(ne_triangle_child);
}
}// if(tri_al.Child.size())
// create new face and store it.
complex_face.Face.mNumIndices = 3;
complex_face.Face.mIndices = new unsigned int[3];
complex_face.Face.mIndices[0] = static_cast<unsigned int>(tri_al.V[0]);
complex_face.Face.mIndices[1] = static_cast<unsigned int>(tri_al.V[1]);
complex_face.Face.mIndices[2] = static_cast<unsigned int>(tri_al.V[2]);
complex_faces_list.push_back(complex_face);
}
}// for(const CAMFImporter_NodeElement* ne_volume_child: ne_volume->Child)
/**** Split faces list: one list per mesh ****/
PostprocessHelper_SplitFacesByTextureID(complex_faces_list, complex_faces_toplist);
/***** Create mesh for every faces list ******/
for(std::list<SComplexFace>& face_list_cur: complex_faces_toplist)
{
auto VertexIndex_GetMinimal = [](const std::list<SComplexFace>& pFaceList, const size_t* pBiggerThan) -> size_t
{
size_t rv;
if(pBiggerThan != nullptr)
{
bool found = false;
for(const SComplexFace& face: pFaceList)
{
for(size_t idx_vert = 0; idx_vert < face.Face.mNumIndices; idx_vert++)
{
if(face.Face.mIndices[idx_vert] > *pBiggerThan)
{
rv = face.Face.mIndices[idx_vert];
found = true;
break;
}
}
if(found) break;
}
if(!found) return *pBiggerThan;
}
else
{
rv = pFaceList.front().Face.mIndices[0];
}// if(pBiggerThan != nullptr) else
for(const SComplexFace& face: pFaceList)
{
for(size_t vi = 0; vi < face.Face.mNumIndices; vi++)
{
if(face.Face.mIndices[vi] < rv)
{
if(pBiggerThan != nullptr)
{
if(face.Face.mIndices[vi] > *pBiggerThan) rv = face.Face.mIndices[vi];
}
else
{
rv = face.Face.mIndices[vi];
}
}
}
}// for(const SComplexFace& face: pFaceList)
return rv;
};// auto VertexIndex_GetMinimal = [](const std::list<SComplexFace>& pFaceList, const size_t* pBiggerThan) -> size_t
auto VertexIndex_Replace = [](std::list<SComplexFace>& pFaceList, const size_t pIdx_From, const size_t pIdx_To) -> void
{
for(const SComplexFace& face: pFaceList)
{
for(size_t vi = 0; vi < face.Face.mNumIndices; vi++)
{
if(face.Face.mIndices[vi] == pIdx_From) face.Face.mIndices[vi] = static_cast<unsigned int>(pIdx_To);
}
}
};// auto VertexIndex_Replace = [](std::list<SComplexFace>& pFaceList, const size_t pIdx_From, const size_t pIdx_To) -> void
auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D
{
// Color priorities(In descending order):
// 1. triangle color;
// 2. vertex color;
// 3. volume color;
// 4. object color;
// 5. material;
// 6. default - invisible coat.
//
// Fill vertices colors in color priority list above that's points from 1 to 6.
if((pIdx < pVertexColorArray.size()) && (pVertexColorArray[pIdx] != nullptr))// check for vertex color
{
if(pVertexColorArray[pIdx]->Composed)
throw DeadlyImportError("IME: vertex color composed");
else
return pVertexColorArray[pIdx]->Color;
}
else if(ne_volume_color != nullptr)// check for volume color
{
if(ne_volume_color->Composed)
throw DeadlyImportError("IME: volume color composed");
else
return ne_volume_color->Color;
}
else if(pObjectColor != nullptr)// check for object color
{
if(pObjectColor->Composed)
throw DeadlyImportError("IME: object color composed");
else
return pObjectColor->Color;
}
else if(cur_mat != nullptr)// check for material
{
return cur_mat->GetColor(pVertexCoordinateArray.at(pIdx).x, pVertexCoordinateArray.at(pIdx).y, pVertexCoordinateArray.at(pIdx).z);
}
else// set default color.
{
return {0, 0, 0, 0};
}// if((vi < pVertexColorArray.size()) && (pVertexColorArray[vi] != nullptr)) else
};// auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D
aiMesh* tmesh = new aiMesh;
tmesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;// Only triangles is supported by AMF.
//
// set geometry and colors (vertices)
//
// copy faces/triangles
tmesh->mNumFaces = static_cast<unsigned int>(face_list_cur.size());
tmesh->mFaces = new aiFace[tmesh->mNumFaces];
// Create vertices list and optimize indices. Optimisation mean following.In AMF all volumes use one big list of vertices. And one volume
// can use only part of vertices list, for example: vertices list contain few thousands of vertices and volume use vertices 1, 3, 10.
// Do you need all this thousands of garbage? Of course no. So, optimisation step transformate sparse indices set to continuous.
size_t VertexCount_Max = tmesh->mNumFaces * 3;// 3 - triangles.
std::vector<aiVector3D> vert_arr, texcoord_arr;
std::vector<aiColor4D> col_arr;
vert_arr.reserve(VertexCount_Max * 2);// "* 2" - see below TODO.
col_arr.reserve(VertexCount_Max * 2);
{// fill arrays
size_t vert_idx_from, vert_idx_to;
// first iteration.
vert_idx_to = 0;
vert_idx_from = VertexIndex_GetMinimal(face_list_cur, nullptr);
vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from));
col_arr.push_back(Vertex_CalculateColor(vert_idx_from));
if(vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to);
// rest iterations
do
{
vert_idx_from = VertexIndex_GetMinimal(face_list_cur, &vert_idx_to);
if(vert_idx_from == vert_idx_to) break;// all indices are transferred,
vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from));
col_arr.push_back(Vertex_CalculateColor(vert_idx_from));
vert_idx_to++;
if(vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to);
} while(true);
}// fill arrays. END.
//
// check if triangle colors are used and create additional faces if needed.
//
for(const SComplexFace& face_cur: face_list_cur)
{
if(face_cur.Color != nullptr)
{
aiColor4D face_color;
size_t vert_idx_new = vert_arr.size();
if(face_cur.Color->Composed)
throw DeadlyImportError("IME: face color composed");
else
face_color = face_cur.Color->Color;
for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++)
{
vert_arr.push_back(vert_arr.at(face_cur.Face.mIndices[idx_ind]));
col_arr.push_back(face_color);
face_cur.Face.mIndices[idx_ind] = static_cast<unsigned int>(vert_idx_new++);
}
}// if(face_cur.Color != nullptr)
}// for(const SComplexFace& face_cur: face_list_cur)
//
// if texture is used then copy texture coordinates too.
//
if(face_list_cur.front().TexMap != nullptr)
{
size_t idx_vert_new = vert_arr.size();
///TODO: clean unused vertices. "* 2": in certain cases - mesh full of triangle colors - vert_arr will contain duplicated vertices for
/// colored triangles and initial vertices (for colored vertices) which in real became unused. This part need more thinking about
/// optimisation.
bool* idx_vert_used;
idx_vert_used = new bool[VertexCount_Max * 2];
for(size_t i = 0, i_e = VertexCount_Max * 2; i < i_e; i++) idx_vert_used[i] = false;
// This ID's will be used when set materials ID in scene.
tmesh->mMaterialIndex = static_cast<unsigned int>(PostprocessHelper_GetTextureID_Or_Create(face_list_cur.front().TexMap->TextureID_R,
face_list_cur.front().TexMap->TextureID_G,
face_list_cur.front().TexMap->TextureID_B,
face_list_cur.front().TexMap->TextureID_A));
texcoord_arr.resize(VertexCount_Max * 2);
for(const SComplexFace& face_cur: face_list_cur)
{
for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++)
{
const size_t idx_vert = face_cur.Face.mIndices[idx_ind];
if(!idx_vert_used[idx_vert])
{
texcoord_arr.at(idx_vert) = face_cur.TexMap->TextureCoordinate[idx_ind];
idx_vert_used[idx_vert] = true;
}
else if(texcoord_arr.at(idx_vert) != face_cur.TexMap->TextureCoordinate[idx_ind])
{
// in that case one vertex is shared with many texture coordinates. We need to duplicate vertex with another texture
// coordinates.
vert_arr.push_back(vert_arr.at(idx_vert));
col_arr.push_back(col_arr.at(idx_vert));
texcoord_arr.at(idx_vert_new) = face_cur.TexMap->TextureCoordinate[idx_ind];
face_cur.Face.mIndices[idx_ind] = static_cast<unsigned int>(idx_vert_new++);
}
}// for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++)
}// for(const SComplexFace& face_cur: face_list_cur)
delete [] idx_vert_used;
// shrink array
texcoord_arr.resize(idx_vert_new);
}// if(face_list_cur.front().TexMap != nullptr)
//
// copy collected data to mesh
//
tmesh->mNumVertices = static_cast<unsigned int>(vert_arr.size());
tmesh->mVertices = new aiVector3D[tmesh->mNumVertices];
tmesh->mColors[0] = new aiColor4D[tmesh->mNumVertices];
tmesh->mFaces = new aiFace[face_list_cur.size()];
memcpy(tmesh->mVertices, vert_arr.data(), tmesh->mNumVertices * sizeof(aiVector3D));
memcpy(tmesh->mColors[0], col_arr.data(), tmesh->mNumVertices * sizeof(aiColor4D));
if(texcoord_arr.size() > 0)
{
tmesh->mTextureCoords[0] = new aiVector3D[tmesh->mNumVertices];
memcpy(tmesh->mTextureCoords[0], texcoord_arr.data(), tmesh->mNumVertices * sizeof(aiVector3D));
tmesh->mNumUVComponents[0] = 2;// U and V stored in "x", "y" of aiVector3D.
}
size_t idx_face = 0;
for(const SComplexFace& face_cur: face_list_cur) tmesh->mFaces[idx_face++] = face_cur.Face;
// store new aiMesh
mesh_idx.push_back(static_cast<unsigned int>(pMeshList.size()));
pMeshList.push_back(tmesh);
}// for(const std::list<SComplexFace>& face_list_cur: complex_faces_toplist)
}// if(ne_child->Type == CAMFImporter_NodeElement::ENET_Volume)
}// for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
// if meshes was created then assign new indices with current aiNode
if(mesh_idx.size() > 0)
{
std::list<unsigned int>::const_iterator mit = mesh_idx.begin();
pSceneNode.mNumMeshes = static_cast<unsigned int>(mesh_idx.size());
pSceneNode.mMeshes = new unsigned int[pSceneNode.mNumMeshes];
for(size_t i = 0; i < pSceneNode.mNumMeshes; i++) pSceneNode.mMeshes[i] = *mit++;
}// if(mesh_idx.size() > 0)
}
void AMFImporter::Postprocess_BuildMaterial(const CAMFImporter_NodeElement_Material& pMaterial)
{
SPP_Material new_mat;
new_mat.ID = pMaterial.ID;
for(const CAMFImporter_NodeElement* mat_child: pMaterial.Child)
{
if(mat_child->Type == CAMFImporter_NodeElement::ENET_Color)
{
new_mat.Color = (CAMFImporter_NodeElement_Color*)mat_child;
}
else if(mat_child->Type == CAMFImporter_NodeElement::ENET_Metadata)
{
new_mat.Metadata.push_back((CAMFImporter_NodeElement_Metadata*)mat_child);
}
}// for(const CAMFImporter_NodeElement* mat_child; pMaterial.Child)
// place converted material to special list
mMaterial_Converted.push_back(new_mat);
}
void AMFImporter::Postprocess_BuildConstellation(CAMFImporter_NodeElement_Constellation& pConstellation, std::list<aiNode*>& pNodeList) const
{
aiNode* con_node;
std::list<aiNode*> ch_node;
// We will build next hierarchy:
// aiNode as parent (<constellation>) for set of nodes as a children
// |- aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid")
// ...
// \_ aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid")
con_node = new aiNode;
con_node->mName = pConstellation.ID;
// Walk through children and search for instances of another objects, constellations.
for(const CAMFImporter_NodeElement* ne: pConstellation.Child)
{
aiMatrix4x4 tmat;
aiNode* t_node;
aiNode* found_node;
if(ne->Type == CAMFImporter_NodeElement::ENET_Metadata) continue;
if(ne->Type != CAMFImporter_NodeElement::ENET_Instance) throw DeadlyImportError("Only <instance> nodes can be in <constellation>.");
// create alias for conveniance
CAMFImporter_NodeElement_Instance& als = *((CAMFImporter_NodeElement_Instance*)ne);
// find referenced object
if(!Find_ConvertedNode(als.ObjectID, pNodeList, &found_node)) Throw_ID_NotFound(als.ObjectID);
// create node for apllying transformation
t_node = new aiNode;
t_node->mParent = con_node;
// apply transformation
aiMatrix4x4::Translation(als.Delta, tmat), t_node->mTransformation *= tmat;
aiMatrix4x4::RotationX(als.Rotation.x, tmat), t_node->mTransformation *= tmat;
aiMatrix4x4::RotationY(als.Rotation.y, tmat), t_node->mTransformation *= tmat;
aiMatrix4x4::RotationZ(als.Rotation.z, tmat), t_node->mTransformation *= tmat;
// create array for one child node
t_node->mNumChildren = 1;
t_node->mChildren = new aiNode*[t_node->mNumChildren];
SceneCombiner::Copy(&t_node->mChildren[0], found_node);
t_node->mChildren[0]->mParent = t_node;
ch_node.push_back(t_node);
}// for(const CAMFImporter_NodeElement* ne: pConstellation.Child)
// copy found aiNode's as children
if(ch_node.size() == 0) throw DeadlyImportError("<constellation> must have at least one <instance>.");
size_t ch_idx = 0;
con_node->mNumChildren = static_cast<unsigned int>(ch_node.size());
con_node->mChildren = new aiNode*[con_node->mNumChildren];
for(aiNode* node: ch_node) con_node->mChildren[ch_idx++] = node;
// and place "root" of <constellation> node to node list
pNodeList.push_back(con_node);
}
void AMFImporter::Postprocess_BuildScene(aiScene* pScene)
{
std::list<aiNode*> node_list;
std::list<aiMesh*> mesh_list;
std::list<CAMFImporter_NodeElement_Metadata*> meta_list;
//
// Because for AMF "material" is just complex colors mixing so aiMaterial will not be used.
// For building aiScene we are must to do few steps:
// at first creating root node for aiScene.
pScene->mRootNode = new aiNode;
pScene->mRootNode->mParent = nullptr;
pScene->mFlags |= AI_SCENE_FLAGS_ALLOW_SHARED;
// search for root(<amf>) element
CAMFImporter_NodeElement* root_el = nullptr;
for(CAMFImporter_NodeElement* ne: mNodeElement_List)
{
if(ne->Type != CAMFImporter_NodeElement::ENET_Root) continue;
root_el = ne;
break;
}// for(const CAMFImporter_NodeElement* ne: mNodeElement_List)
// Check if root element are found.
if(root_el == nullptr) throw DeadlyImportError("Root(<amf>) element not found.");
// after that walk through children of root and collect data. Five types of nodes can be placed at top level - in <amf>: <object>, <material>, <texture>,
// <constellation> and <metadata>. But at first we must read <material> and <texture> because they will be used in <object>. <metadata> can be read
// at any moment.
//
// 1. <material>
// 2. <texture> will be converted later when processing triangles list. \sa Postprocess_BuildMeshSet
for(const CAMFImporter_NodeElement* root_child: root_el->Child)
{
if(root_child->Type == CAMFImporter_NodeElement::ENET_Material) Postprocess_BuildMaterial(*((CAMFImporter_NodeElement_Material*)root_child));
}
// After "appearance" nodes we must read <object> because it will be used in <constellation> -> <instance>.
//
// 3. <object>
for(const CAMFImporter_NodeElement* root_child: root_el->Child)
{
if(root_child->Type == CAMFImporter_NodeElement::ENET_Object)
{
aiNode* tnode = nullptr;
// for <object> mesh and node must be built: object ID assigned to aiNode name and will be used in future for <instance>
Postprocess_BuildNodeAndObject(*((CAMFImporter_NodeElement_Object*)root_child), mesh_list, &tnode);
if(tnode != nullptr) node_list.push_back(tnode);
}
}// for(const CAMFImporter_NodeElement* root_child: root_el->Child)
// And finally read rest of nodes.
//
for(const CAMFImporter_NodeElement* root_child: root_el->Child)
{
// 4. <constellation>
if(root_child->Type == CAMFImporter_NodeElement::ENET_Constellation)
{
// <object> and <constellation> at top of self abstraction use aiNode. So we can use only aiNode list for creating new aiNode's.
Postprocess_BuildConstellation(*((CAMFImporter_NodeElement_Constellation*)root_child), node_list);
}
// 5, <metadata>
if(root_child->Type == CAMFImporter_NodeElement::ENET_Metadata) meta_list.push_back((CAMFImporter_NodeElement_Metadata*)root_child);
}// for(const CAMFImporter_NodeElement* root_child: root_el->Child)
// at now we can add collected metadata to root node
Postprocess_AddMetadata(meta_list, *pScene->mRootNode);
//
// Check constellation children
//
// As said in specification:
// "When multiple objects and constellations are defined in a single file, only the top level objects and constellations are available for printing."
// What that means? For example: if some object is used in constellation then you must show only constellation but not original object.
// And at this step we are checking that relations.
nl_clean_loop:
if(node_list.size() > 1)
{
// walk through all nodes
for(std::list<aiNode*>::iterator nl_it = node_list.begin(); nl_it != node_list.end(); nl_it++)
{
// and try to find them in another top nodes.
std::list<aiNode*>::const_iterator next_it = nl_it;
next_it++;
for(; next_it != node_list.end(); next_it++)
{
if((*next_it)->FindNode((*nl_it)->mName) != nullptr)
{
// if current top node(nl_it) found in another top node then erase it from node_list and restart search loop.
node_list.erase(nl_it);
goto nl_clean_loop;
}
}// for(; next_it != node_list.end(); next_it++)
}// for(std::list<aiNode*>::const_iterator nl_it = node_list.begin(); nl_it != node_list.end(); nl_it++)
}
//
// move created objects to aiScene
//
//
// Nodes
if(node_list.size() > 0)
{
std::list<aiNode*>::const_iterator nl_it = node_list.begin();
pScene->mRootNode->mNumChildren = static_cast<unsigned int>(node_list.size());
pScene->mRootNode->mChildren = new aiNode*[pScene->mRootNode->mNumChildren];
for(size_t i = 0; i < pScene->mRootNode->mNumChildren; i++)
{
// Objects and constellation that must be showed placed at top of hierarchy in <amf> node. So all aiNode's in node_list must have
// mRootNode only as parent.
(*nl_it)->mParent = pScene->mRootNode;
pScene->mRootNode->mChildren[i] = *nl_it++;
}
}// if(node_list.size() > 0)
//
// Meshes
if(mesh_list.size() > 0)
{
std::list<aiMesh*>::const_iterator ml_it = mesh_list.begin();
pScene->mNumMeshes = static_cast<unsigned int>(mesh_list.size());
pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
for(size_t i = 0; i < pScene->mNumMeshes; i++) pScene->mMeshes[i] = *ml_it++;
}// if(mesh_list.size() > 0)
//
// Textures
pScene->mNumTextures = static_cast<unsigned int>(mTexture_Converted.size());
if(pScene->mNumTextures > 0)
{
size_t idx;
idx = 0;
pScene->mTextures = new aiTexture*[pScene->mNumTextures];
for(const SPP_Texture& tex_convd: mTexture_Converted)
{
pScene->mTextures[idx] = new aiTexture;
pScene->mTextures[idx]->mWidth = static_cast<unsigned int>(tex_convd.Width);
pScene->mTextures[idx]->mHeight = static_cast<unsigned int>(tex_convd.Height);
pScene->mTextures[idx]->pcData = (aiTexel*)tex_convd.Data;
// texture format description.
strcpy(pScene->mTextures[idx]->achFormatHint, tex_convd.FormatHint);
idx++;
}// for(const SPP_Texture& tex_convd: mTexture_Converted)
// Create materials for embedded textures.
idx = 0;
pScene->mNumMaterials = static_cast<unsigned int>(mTexture_Converted.size());
pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
for(const SPP_Texture& tex_convd: mTexture_Converted)
{
const aiString texture_id(AI_EMBEDDED_TEXNAME_PREFIX + to_string(idx));
const int mode = aiTextureOp_Multiply;
const int repeat = tex_convd.Tiled ? 1 : 0;
pScene->mMaterials[idx] = new aiMaterial;
pScene->mMaterials[idx]->AddProperty(&texture_id, AI_MATKEY_TEXTURE_DIFFUSE(0));
pScene->mMaterials[idx]->AddProperty(&mode, 1, AI_MATKEY_TEXOP_DIFFUSE(0));
pScene->mMaterials[idx]->AddProperty(&repeat, 1, AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0));
pScene->mMaterials[idx]->AddProperty(&repeat, 1, AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0));
idx++;
}
}// if(pScene->mNumTextures > 0)
}// END: after that walk through children of root and collect data
}// namespace Assimp
#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -54,6 +55,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/IOSystem.hpp> #include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp> #include <assimp/DefaultLogger.hpp>
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/importerdesc.h>
#include <memory> #include <memory>

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -46,9 +47,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BaseImporter.h" #include "BaseImporter.h"
#include <assimp/types.h> #include <assimp/types.h>
#include "ASEParser.h"
struct aiNode; struct aiNode;
#include "ASEParser.h"
namespace Assimp { namespace Assimp {

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -25,8 +26,8 @@ conditions are met:
derived from this software without specific prior derived from this software without specific prior
written permission of the assimp team. written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
@ -49,7 +50,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// internal headers // internal headers
#include "TextureTransform.h" #include "TextureTransform.h"
#include "ASELoader.h" #include "ASELoader.h"
#include "MaterialSystem.h"
#include "fast_atof.h" #include "fast_atof.h"
#include <assimp/DefaultLogger.hpp> #include <assimp/DefaultLogger.hpp>
@ -618,7 +618,8 @@ void Parser::ParseLV2MaterialBlock(ASE::Material& mat)
if (TokenMatch(filePtr,"MATERIAL_TRANSPARENCY",21)) if (TokenMatch(filePtr,"MATERIAL_TRANSPARENCY",21))
{ {
ParseLV4MeshFloat(mat.mTransparency); ParseLV4MeshFloat(mat.mTransparency);
mat.mTransparency = 1.0 - mat.mTransparency;continue; mat.mTransparency = ai_real( 1.0 ) - mat.mTransparency;
continue;
} }
// material self illumination // material self illumination
if (TokenMatch(filePtr,"MATERIAL_SELFILLUM",18)) if (TokenMatch(filePtr,"MATERIAL_SELFILLUM",18))
@ -1134,7 +1135,7 @@ void Parser::ParseLV3ScaleAnimationBlock(ASE::Animation& anim)
bool b = false; bool b = false;
// For the moment we're just reading the three floats - // For the moment we're just reading the three floats -
// we ignore the <EFBFBD>dditional information for bezier's and TCBs // we ignore the additional information for bezier's and TCBs
// simple scaling keyframe // simple scaling keyframe
if (TokenMatch(filePtr,"CONTROL_SCALE_SAMPLE" ,20)) if (TokenMatch(filePtr,"CONTROL_SCALE_SAMPLE" ,20))
@ -1180,7 +1181,7 @@ void Parser::ParseLV3PosAnimationBlock(ASE::Animation& anim)
bool b = false; bool b = false;
// For the moment we're just reading the three floats - // For the moment we're just reading the three floats -
// we ignore the <EFBFBD>dditional information for bezier's and TCBs // we ignore the additional information for bezier's and TCBs
// simple scaling keyframe // simple scaling keyframe
if (TokenMatch(filePtr,"CONTROL_POS_SAMPLE" ,18)) if (TokenMatch(filePtr,"CONTROL_POS_SAMPLE" ,18))
@ -1226,7 +1227,7 @@ void Parser::ParseLV3RotAnimationBlock(ASE::Animation& anim)
bool b = false; bool b = false;
// For the moment we're just reading the floats - // For the moment we're just reading the floats -
// we ignore the <EFBFBD>dditional information for bezier's and TCBs // we ignore the additional information for bezier's and TCBs
// simple scaling keyframe // simple scaling keyframe
if (TokenMatch(filePtr,"CONTROL_ROT_SAMPLE" ,18)) if (TokenMatch(filePtr,"CONTROL_ROT_SAMPLE" ,18))
@ -1463,30 +1464,29 @@ void Parser::ParseLV2MeshBlock(ASE::Mesh& mesh)
continue; continue;
} }
// another mesh UV channel ... // another mesh UV channel ...
if (TokenMatch(filePtr,"MESH_MAPPINGCHANNEL" ,19)) if (TokenMatch(filePtr,"MESH_MAPPINGCHANNEL" ,19)) {
{ unsigned int iIndex( 0 );
unsigned int iIndex = 0;
ParseLV4MeshLong(iIndex); ParseLV4MeshLong(iIndex);
if ( 0 == iIndex ) {
if (iIndex < 2) LogWarning( "Mapping channel has an invalid index. Skipping UV channel" );
{
LogWarning("Mapping channel has an invalid index. Skipping UV channel");
// skip it ... // skip it ...
SkipSection(); SkipSection();
} else {
if ( iIndex < 2 ) {
LogWarning( "Mapping channel has an invalid index. Skipping UV channel" );
// skip it ...
SkipSection();
}
if ( iIndex > AI_MAX_NUMBER_OF_TEXTURECOORDS ) {
LogWarning( "Too many UV channels specified. Skipping channel .." );
// skip it ...
SkipSection();
} else {
// parse the mapping channel
ParseLV3MappingChannel( iIndex - 1, mesh );
}
continue;
} }
if (iIndex > AI_MAX_NUMBER_OF_TEXTURECOORDS)
{
LogWarning("Too many UV channels specified. Skipping channel ..");
// skip it ...
SkipSection();
}
else
{
// parse the mapping channel
ParseLV3MappingChannel(iIndex-1,mesh);
}
continue;
} }
// mesh animation keyframe. Not supported // mesh animation keyframe. Not supported
if (TokenMatch(filePtr,"MESH_ANIMATION" ,14)) if (TokenMatch(filePtr,"MESH_ANIMATION" ,14))
@ -1858,7 +1858,7 @@ void Parser::ParseLV3MeshCFaceListBlock(unsigned int iNumFaces, ASE::Mesh& mesh)
++filePtr; ++filePtr;
// Face entry // Face entry
if (TokenMatch(filePtr,"MESH_CFACE" ,11)) if (TokenMatch(filePtr,"MESH_CFACE" ,10))
{ {
unsigned int aiValues[3]; unsigned int aiValues[3];
unsigned int iIndex = 0; unsigned int iIndex = 0;

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -737,7 +738,7 @@ inline size_t WriteArray(IOStream * stream, const T* in, unsigned int size)
AssbinChunkWriter uncompressedStream( NULL, 0 ); AssbinChunkWriter uncompressedStream( NULL, 0 );
WriteBinaryScene( &uncompressedStream, pScene ); WriteBinaryScene( &uncompressedStream, pScene );
uLongf uncompressedSize = uncompressedStream.Tell(); uLongf uncompressedSize = static_cast<uLongf>(uncompressedStream.Tell());
uLongf compressedSize = (uLongf)(uncompressedStream.Tell() * 1.001 + 12.); uLongf compressedSize = (uLongf)(uncompressedStream.Tell() * 1.001 + 12.);
uint8_t* compressedBuffer = new uint8_t[ compressedSize ]; uint8_t* compressedBuffer = new uint8_t[ compressedSize ];

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -54,6 +55,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/mesh.h> #include <assimp/mesh.h>
#include <assimp/anim.h> #include <assimp/anim.h>
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/importerdesc.h>
#ifdef ASSIMP_BUILD_NO_OWN_ZLIB #ifdef ASSIMP_BUILD_NO_OWN_ZLIB
# include <zlib.h> # include <zlib.h>
@ -196,7 +198,7 @@ template <typename T> void ReadBounds( IOStream * stream, T* /*p*/, unsigned int
stream->Seek( sizeof(T) * n, aiOrigin_CUR ); stream->Seek( sizeof(T) * n, aiOrigin_CUR );
} }
void AssbinImporter::ReadBinaryNode( IOStream * stream, aiNode** node ) void AssbinImporter::ReadBinaryNode( IOStream * stream, aiNode** node, aiNode* parent )
{ {
uint32_t chunkID = Read<uint32_t>(stream); uint32_t chunkID = Read<uint32_t>(stream);
ai_assert(chunkID == ASSBIN_CHUNK_AINODE); ai_assert(chunkID == ASSBIN_CHUNK_AINODE);
@ -208,6 +210,10 @@ void AssbinImporter::ReadBinaryNode( IOStream * stream, aiNode** node )
(*node)->mTransformation = Read<aiMatrix4x4>(stream); (*node)->mTransformation = Read<aiMatrix4x4>(stream);
(*node)->mNumChildren = Read<unsigned int>(stream); (*node)->mNumChildren = Read<unsigned int>(stream);
(*node)->mNumMeshes = Read<unsigned int>(stream); (*node)->mNumMeshes = Read<unsigned int>(stream);
if(parent)
{
(*node)->mParent = parent;
}
if ((*node)->mNumMeshes) if ((*node)->mNumMeshes)
{ {
@ -221,7 +227,7 @@ void AssbinImporter::ReadBinaryNode( IOStream * stream, aiNode** node )
{ {
(*node)->mChildren = new aiNode*[(*node)->mNumChildren]; (*node)->mChildren = new aiNode*[(*node)->mNumChildren];
for (unsigned int i = 0; i < (*node)->mNumChildren; ++i) { for (unsigned int i = 0; i < (*node)->mNumChildren; ++i) {
ReadBinaryNode( stream, &(*node)->mChildren[i] ); ReadBinaryNode( stream, &(*node)->mChildren[i], *node );
} }
} }
@ -569,7 +575,7 @@ void AssbinImporter::ReadBinaryScene( IOStream * stream, aiScene* scene )
// Read node graph // Read node graph
scene->mRootNode = new aiNode[1]; scene->mRootNode = new aiNode[1];
ReadBinaryNode( stream, &scene->mRootNode ); ReadBinaryNode( stream, &scene->mRootNode, (aiNode*)NULL );
// Read all meshes // Read all meshes
if (scene->mNumMeshes) if (scene->mNumMeshes)
@ -659,7 +665,7 @@ void AssbinImporter::InternReadFile( const std::string& pFile, aiScene* pScene,
if (compressed) if (compressed)
{ {
uLongf uncompressedSize = Read<uint32_t>(stream); uLongf uncompressedSize = Read<uint32_t>(stream);
uLongf compressedSize = stream->FileSize() - stream->Tell(); uLongf compressedSize = static_cast<uLongf>(stream->FileSize() - stream->Tell());
unsigned char * compressedData = new unsigned char[ compressedSize ]; unsigned char * compressedData = new unsigned char[ compressedSize ];
stream->Read( compressedData, 1, compressedSize ); stream->Read( compressedData, 1, compressedSize );

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -46,7 +47,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define AI_ASSBINIMPORTER_H_INC #define AI_ASSBINIMPORTER_H_INC
#include "BaseImporter.h" #include "BaseImporter.h"
#include <assimp/types.h>
struct aiMesh; struct aiMesh;
struct aiNode; struct aiNode;
@ -86,7 +86,7 @@ public:
IOSystem* pIOHandler IOSystem* pIOHandler
); );
void ReadBinaryScene( IOStream * stream, aiScene* pScene ); void ReadBinaryScene( IOStream * stream, aiScene* pScene );
void ReadBinaryNode( IOStream * stream, aiNode** mRootNode ); void ReadBinaryNode( IOStream * stream, aiNode** mRootNode, aiNode* parent );
void ReadBinaryMesh( IOStream * stream, aiMesh* mesh ); void ReadBinaryMesh( IOStream * stream, aiMesh* mesh );
void ReadBinaryBone( IOStream * stream, aiBone* bone ); void ReadBinaryBone( IOStream * stream, aiBone* bone );
void ReadBinaryMaterial(IOStream * stream, aiMaterial* mat); void ReadBinaryMaterial(IOStream * stream, aiMaterial* mat);

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -65,8 +66,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
using namespace Assimp; using namespace Assimp;
namespace Assimp namespace Assimp {
{
// underlying structure for aiPropertyStore // underlying structure for aiPropertyStore
typedef BatchLoader::PropertyMap PropertyMap; typedef BatchLoader::PropertyMap PropertyMap;
@ -109,12 +109,11 @@ static std::mutex gLogStreamMutex;
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Custom LogStream implementation for the C-API // Custom LogStream implementation for the C-API
class LogToCallbackRedirector : public LogStream class LogToCallbackRedirector : public LogStream {
{
public: public:
explicit LogToCallbackRedirector(const aiLogStream& s) explicit LogToCallbackRedirector(const aiLogStream& s)
: stream (s) { : stream (s) {
ai_assert(NULL != s.callback); ai_assert(NULL != s.callback);
} }
~LogToCallbackRedirector() { ~LogToCallbackRedirector() {
@ -145,32 +144,27 @@ private:
}; };
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
void ReportSceneNotFoundError() void ReportSceneNotFoundError() {
{
DefaultLogger::get()->error("Unable to find the Assimp::Importer for this aiScene. " DefaultLogger::get()->error("Unable to find the Assimp::Importer for this aiScene. "
"The C-API does not accept scenes produced by the C++ API and vice versa"); "The C-API does not accept scenes produced by the C++ API and vice versa");
assert(false); ai_assert(false);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Reads the given file and returns its content. // Reads the given file and returns its content.
const aiScene* aiImportFile( const char* pFile, unsigned int pFlags) const aiScene* aiImportFile( const char* pFile, unsigned int pFlags) {
{
return aiImportFileEx(pFile,pFlags,NULL); return aiImportFileEx(pFile,pFlags,NULL);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
const aiScene* aiImportFileEx( const char* pFile, unsigned int pFlags, aiFileIO* pFS) const aiScene* aiImportFileEx( const char* pFile, unsigned int pFlags, aiFileIO* pFS) {
{
return aiImportFileExWithProperties(pFile, pFlags, pFS, NULL); return aiImportFileExWithProperties(pFile, pFlags, pFS, NULL);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
const aiScene* aiImportFileExWithProperties( const char* pFile, unsigned int pFlags, const aiScene* aiImportFileExWithProperties( const char* pFile, unsigned int pFlags,
aiFileIO* pFS, aiFileIO* pFS, const aiPropertyStore* props) {
const aiPropertyStore* props)
{
ai_assert(NULL != pFile); ai_assert(NULL != pFile);
const aiScene* scene = NULL; const aiScene* scene = NULL;
@ -189,7 +183,7 @@ const aiScene* aiImportFileExWithProperties( const char* pFile, unsigned int pFl
pimpl->mMatrixProperties = pp->matrices; pimpl->mMatrixProperties = pp->matrices;
} }
// setup a custom IO system if necessary // setup a custom IO system if necessary
if (pFS) { if (pFS) {
imp->SetIOHandler( new CIOSystemWrapper (pFS) ); imp->SetIOHandler( new CIOSystemWrapper (pFS) );
} }
@ -200,8 +194,7 @@ const aiScene* aiImportFileExWithProperties( const char* pFile, unsigned int pFl
if( scene) { if( scene) {
ScenePrivateData* priv = const_cast<ScenePrivateData*>( ScenePriv(scene) ); ScenePrivateData* priv = const_cast<ScenePrivateData*>( ScenePriv(scene) );
priv->mOrigImporter = imp; priv->mOrigImporter = imp;
} } else {
else {
// if failed, extract error code and destroy the import // if failed, extract error code and destroy the import
gLastErrorString = imp->GetErrorString(); gLastErrorString = imp->GetErrorString();
delete imp; delete imp;
@ -209,6 +202,7 @@ const aiScene* aiImportFileExWithProperties( const char* pFile, unsigned int pFl
// return imported data. If the import failed the pointer is NULL anyways // return imported data. If the import failed the pointer is NULL anyways
ASSIMP_END_EXCEPTION_REGION(const aiScene*); ASSIMP_END_EXCEPTION_REGION(const aiScene*);
return scene; return scene;
} }

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -70,11 +71,11 @@ ASSIMP_API const aiExportFormatDesc* aiGetExportFormatDescription( size_t index)
} }
aiExportFormatDesc *desc = new aiExportFormatDesc; aiExportFormatDesc *desc = new aiExportFormatDesc;
desc->description = new char[ strlen( orig->description ) + 1 ]; desc->description = new char[ strlen( orig->description ) + 1 ]();
::strncpy( (char*) desc->description, orig->description, strlen( orig->description ) ); ::strncpy( (char*) desc->description, orig->description, strlen( orig->description ) );
desc->fileExtension = new char[ strlen( orig->fileExtension ) + 1 ]; desc->fileExtension = new char[ strlen( orig->fileExtension ) + 1 ]();
::strncpy( ( char* ) desc->fileExtension, orig->fileExtension, strlen( orig->fileExtension ) ); ::strncpy( ( char* ) desc->fileExtension, orig->fileExtension, strlen( orig->fileExtension ) );
desc->id = new char[ strlen( orig->id ) + 1 ]; desc->id = new char[ strlen( orig->id ) + 1 ]();
::strncpy( ( char* ) desc->id, orig->id, strlen( orig->id ) ); ::strncpy( ( char* ) desc->id, orig->id, strlen( orig->id ) );
return desc; return desc;

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -41,7 +42,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ASSXML exporter main code * ASSXML exporter main code
*/ */
#include <stdarg.h> #include <stdarg.h>
#include "./../include/assimp/version.h" #include <assimp/version.h>
#include "ProcessHelper.h" #include "ProcessHelper.h"
#include <assimp/IOStream.hpp> #include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp> #include <assimp/IOSystem.hpp>
@ -72,13 +73,12 @@ static int ioprintf( IOStream * io, const char *format, ... ) {
return -1; return -1;
} }
static const size_t Size = 4096; static const int Size = 4096;
char sz[ Size ]; char sz[ Size ];
size_t len( strlen( format ) );
::memset( sz, '\0', Size ); ::memset( sz, '\0', Size );
va_list va; va_list va;
va_start( va, format ); va_start( va, format );
int nSize = vsnprintf( sz, Size-1, format, va ); const unsigned int nSize = vsnprintf( sz, Size-1, format, va );
ai_assert( nSize < Size ); ai_assert( nSize < Size );
va_end( va ); va_end( va );
@ -300,7 +300,7 @@ void WriteDump(const aiScene* scene, IOStream* io, bool shortened) {
else if (!shortened){ else if (!shortened){
ioprintf(io,"\t\t<Data length=\"%i\"> \n",tex->mWidth*tex->mHeight*4); ioprintf(io,"\t\t<Data length=\"%i\"> \n",tex->mWidth*tex->mHeight*4);
// const unsigned int width = (unsigned int)log10((double)std::max(tex->mHeight,tex->mWidth))+1; // const unsigned int width = (unsigned int)std::log10((double)std::max(tex->mHeight,tex->mWidth))+1;
for (unsigned int y = 0; y < tex->mHeight;++y) { for (unsigned int y = 0; y < tex->mHeight;++y) {
for (unsigned int x = 0; x < tex->mWidth;++x) { for (unsigned int x = 0; x < tex->mWidth;++x) {
aiTexel* tx = tex->pcData + y*tex->mWidth+x; aiTexel* tx = tex->pcData + y*tex->mWidth+x;
@ -458,7 +458,7 @@ void WriteDump(const aiScene* scene, IOStream* io, bool shortened) {
ioprintf(io,"<MeshList num=\"%i\">\n",scene->mNumMeshes); ioprintf(io,"<MeshList num=\"%i\">\n",scene->mNumMeshes);
for (unsigned int i = 0; i < scene->mNumMeshes;++i) { for (unsigned int i = 0; i < scene->mNumMeshes;++i) {
aiMesh* mesh = scene->mMeshes[i]; aiMesh* mesh = scene->mMeshes[i];
// const unsigned int width = (unsigned int)log10((double)mesh->mNumVertices)+1; // const unsigned int width = (unsigned int)std::log10((double)mesh->mNumVertices)+1;
// mesh header // mesh header
ioprintf(io,"\t<Mesh types=\"%s %s %s %s\" material_index=\"%i\">\n", ioprintf(io,"\t<Mesh types=\"%s %s %s %s\" material_index=\"%i\">\n",

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -56,7 +57,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/anim.h> #include <assimp/anim.h>
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp> #include <assimp/DefaultLogger.hpp>
#include <assimp/importerdesc.h>
using namespace Assimp; using namespace Assimp;
using namespace std; using namespace std;
@ -331,7 +332,7 @@ void B3DImporter::ReadVRTS(){
int sz=12+(_vflags&1?12:0)+(_vflags&2?16:0)+(_tcsets*_tcsize*4); int sz=12+(_vflags&1?12:0)+(_vflags&2?16:0)+(_tcsets*_tcsize*4);
int n_verts=ChunkSize()/sz; int n_verts=ChunkSize()/sz;
int v0=_vertices.size(); int v0=static_cast<int>(_vertices.size());
_vertices.resize( v0+n_verts ); _vertices.resize( v0+n_verts );
for( int i=0;i<n_verts;++i ){ for( int i=0;i<n_verts;++i ){
@ -404,7 +405,7 @@ void B3DImporter::ReadTRIS( int v0 ){
void B3DImporter::ReadMESH(){ void B3DImporter::ReadMESH(){
/*int matid=*/ReadInt(); /*int matid=*/ReadInt();
int v0=_vertices.size(); int v0= static_cast<int>(_vertices.size());
while( ChunkSize() ){ while( ChunkSize() ){
string t=ReadChunk(); string t=ReadChunk();
@ -462,17 +463,17 @@ void B3DImporter::ReadKEYS( aiNodeAnim *nodeAnim ){
} }
if( flags & 1 ){ if( flags & 1 ){
nodeAnim->mNumPositionKeys=trans.size(); nodeAnim->mNumPositionKeys=static_cast<unsigned int>(trans.size());
nodeAnim->mPositionKeys=to_array( trans ); nodeAnim->mPositionKeys=to_array( trans );
} }
if( flags & 2 ){ if( flags & 2 ){
nodeAnim->mNumScalingKeys=scale.size(); nodeAnim->mNumScalingKeys=static_cast<unsigned int>(scale.size());
nodeAnim->mScalingKeys=to_array( scale ); nodeAnim->mScalingKeys=to_array( scale );
} }
if( flags & 4 ){ if( flags & 4 ){
nodeAnim->mNumRotationKeys=rot.size(); nodeAnim->mNumRotationKeys=static_cast<unsigned int>(rot.size());
nodeAnim->mRotationKeys=to_array( rot ); nodeAnim->mRotationKeys=to_array( rot );
} }
} }
@ -506,7 +507,7 @@ aiNode *B3DImporter::ReadNODE( aiNode *parent ){
aiMatrix4x4 tform=trans * rot * scale; aiMatrix4x4 tform=trans * rot * scale;
int nodeid=_nodes.size(); int nodeid=static_cast<int>(_nodes.size());
aiNode *node=new aiNode( name ); aiNode *node=new aiNode( name );
_nodes.push_back( node ); _nodes.push_back( node );
@ -521,9 +522,9 @@ aiNode *B3DImporter::ReadNODE( aiNode *parent ){
while( ChunkSize() ){ while( ChunkSize() ){
string t=ReadChunk(); string t=ReadChunk();
if( t=="MESH" ){ if( t=="MESH" ){
int n=_meshes.size(); unsigned int n= static_cast<unsigned int>(_meshes.size());
ReadMESH(); ReadMESH();
for( int i=n;i<(int)_meshes.size();++i ){ for( unsigned int i=n;i<static_cast<unsigned int>(_meshes.size());++i ){
meshes.push_back( i ); meshes.push_back( i );
} }
}else if( t=="BONE" ){ }else if( t=="BONE" ){
@ -544,10 +545,10 @@ aiNode *B3DImporter::ReadNODE( aiNode *parent ){
ExitChunk(); ExitChunk();
} }
node->mNumMeshes=meshes.size(); node->mNumMeshes= static_cast<unsigned int>(meshes.size());
node->mMeshes=to_array( meshes ); node->mMeshes=to_array( meshes );
node->mNumChildren=children.size(); node->mNumChildren=static_cast<unsigned int>(children.size());
node->mChildren=to_array( children ); node->mChildren=to_array( children );
return node; return node;
@ -645,7 +646,7 @@ void B3DImporter::ReadBB3D( aiScene *scene ){
aiNode *bnode=_nodes[i]; aiNode *bnode=_nodes[i];
bone->mName=bnode->mName; bone->mName=bnode->mName;
bone->mNumWeights=weights.size(); bone->mNumWeights= static_cast<unsigned int>(weights.size());
bone->mWeights=to_array( weights ); bone->mWeights=to_array( weights );
aiMatrix4x4 mat=bnode->mTransformation; aiMatrix4x4 mat=bnode->mTransformation;
@ -655,7 +656,7 @@ void B3DImporter::ReadBB3D( aiScene *scene ){
} }
bone->mOffsetMatrix=mat.Inverse(); bone->mOffsetMatrix=mat.Inverse();
} }
mesh->mNumBones=bones.size(); mesh->mNumBones= static_cast<unsigned int>(bones.size());
mesh->mBones=to_array( bones ); mesh->mBones=to_array( bones );
} }
} }
@ -667,21 +668,21 @@ void B3DImporter::ReadBB3D( aiScene *scene ){
if( !_materials.size() ){ if( !_materials.size() ){
_materials.push_back( new aiMaterial ); _materials.push_back( new aiMaterial );
} }
scene->mNumMaterials=_materials.size(); scene->mNumMaterials= static_cast<unsigned int>(_materials.size());
scene->mMaterials=to_array( _materials ); scene->mMaterials=to_array( _materials );
//meshes //meshes
scene->mNumMeshes=_meshes.size(); scene->mNumMeshes= static_cast<unsigned int>(_meshes.size());
scene->mMeshes=to_array( _meshes ); scene->mMeshes=to_array( _meshes );
//animations //animations
if( _animations.size()==1 && _nodeAnims.size() ){ if( _animations.size()==1 && _nodeAnims.size() ){
aiAnimation *anim=_animations.back(); aiAnimation *anim=_animations.back();
anim->mNumChannels=_nodeAnims.size(); anim->mNumChannels=static_cast<unsigned int>(_nodeAnims.size());
anim->mChannels=to_array( _nodeAnims ); anim->mChannels=to_array( _nodeAnims );
scene->mNumAnimations=_animations.size(); scene->mNumAnimations=static_cast<unsigned int>(_animations.size());
scene->mAnimations=to_array( _animations ); scene->mAnimations=to_array( _animations );
} }

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -48,7 +49,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/material.h> #include <assimp/material.h>
#include "BaseImporter.h" #include "BaseImporter.h"
#include <string>
#include <vector> #include <vector>
struct aiNodeAnim; struct aiNodeAnim;

View File

@ -4,7 +4,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -51,6 +52,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "TinyFormatter.h" #include "TinyFormatter.h"
#include <assimp/IOSystem.hpp> #include <assimp/IOSystem.hpp>
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/importerdesc.h>
using namespace Assimp; using namespace Assimp;
using namespace Assimp::Formatter; using namespace Assimp::Formatter;
@ -237,7 +239,7 @@ aiNode* BVHLoader::ReadNode()
// add the child nodes if there are any // add the child nodes if there are any
if( childNodes.size() > 0) if( childNodes.size() > 0)
{ {
node->mNumChildren = childNodes.size(); node->mNumChildren = static_cast<unsigned int>(childNodes.size());
node->mChildren = new aiNode*[node->mNumChildren]; node->mChildren = new aiNode*[node->mNumChildren];
std::copy( childNodes.begin(), childNodes.end(), node->mChildren); std::copy( childNodes.begin(), childNodes.end(), node->mChildren);
} }
@ -443,7 +445,7 @@ void BVHLoader::CreateAnimation( aiScene* pScene)
anim->mDuration = double( mAnimNumFrames - 1); anim->mDuration = double( mAnimNumFrames - 1);
// now generate the tracks for all nodes // now generate the tracks for all nodes
anim->mNumChannels = mNodes.size(); anim->mNumChannels = static_cast<unsigned int>(mNodes.size());
anim->mChannels = new aiNodeAnim*[anim->mNumChannels]; anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
// FIX: set the array elements to NULL to ensure proper deletion if an exception is thrown // FIX: set the array elements to NULL to ensure proper deletion if an exception is thrown

View File

@ -4,7 +4,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -50,13 +51,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/Importer.hpp> #include <assimp/Importer.hpp>
#include <assimp/postprocess.h> #include <assimp/postprocess.h>
#include <assimp/importerdesc.h>
#include <ios> #include <ios>
#include <list> #include <list>
#include <memory> #include <memory>
#include <sstream> #include <sstream>
#include <cctype> #include <cctype>
using namespace Assimp; using namespace Assimp;
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -137,14 +138,17 @@ void BaseImporter::GetExtensionList(std::set<std::string>& extensions)
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
/*static*/ bool BaseImporter::SearchFileHeaderForToken(IOSystem* pIOHandler, /*static*/ bool BaseImporter::SearchFileHeaderForToken( IOSystem* pIOHandler,
const std::string& pFile, const std::string& pFile,
const char** tokens, const char** tokens,
unsigned int numTokens, unsigned int numTokens,
unsigned int searchBytes /* = 200 */, unsigned int searchBytes /* = 200 */,
bool tokensSol /* false */) bool tokensSol /* false */)
{ {
ai_assert(NULL != tokens && 0 != numTokens && 0 != searchBytes); ai_assert( NULL != tokens );
ai_assert( 0 != numTokens );
ai_assert( 0 != searchBytes);
if (!pIOHandler) if (!pIOHandler)
return false; return false;
@ -179,8 +183,6 @@ void BaseImporter::GetExtensionList(std::set<std::string>& extensions)
for (unsigned int i = 0; i < numTokens;++i) { for (unsigned int i = 0; i < numTokens;++i) {
ai_assert(NULL != tokens[i]); ai_assert(NULL != tokens[i]);
const char* r = strstr(buffer,tokens[i]); const char* r = strstr(buffer,tokens[i]);
if( !r ) { if( !r ) {
continue; continue;
@ -301,24 +303,13 @@ void BaseImporter::GetExtensionList(std::set<std::string>& extensions)
return false; return false;
} }
#include "../contrib/ConvertUTF/ConvertUTF.h" #include "../contrib/utf8cpp/source/utf8.h"
// ------------------------------------------------------------------------------------------------
void ReportResult(ConversionResult res)
{
if(res == sourceExhausted) {
DefaultLogger::get()->error("Source ends with incomplete character sequence, transformation to UTF-8 fails");
}
else if(res == sourceIllegal) {
DefaultLogger::get()->error("Source contains illegal character sequence, transformation to UTF-8 fails");
}
}
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Convert to UTF8 data // Convert to UTF8 data
void BaseImporter::ConvertToUTF8(std::vector<char>& data) void BaseImporter::ConvertToUTF8(std::vector<char>& data)
{ {
ConversionResult result; //ConversionResult result;
if(data.size() < 8) { if(data.size() < 8) {
throw DeadlyImportError("File is too small"); throw DeadlyImportError("File is too small");
} }
@ -331,7 +322,8 @@ void BaseImporter::ConvertToUTF8(std::vector<char>& data)
data.resize(data.size()-3); data.resize(data.size()-3);
return; return;
} }
// UTF 32 BE with BOM // UTF 32 BE with BOM
if(*((uint32_t*)&data.front()) == 0xFFFE0000) { if(*((uint32_t*)&data.front()) == 0xFFFE0000) {
@ -346,20 +338,10 @@ void BaseImporter::ConvertToUTF8(std::vector<char>& data)
DefaultLogger::get()->debug("Found UTF-32 BOM ..."); DefaultLogger::get()->debug("Found UTF-32 BOM ...");
const uint32_t* sstart = (uint32_t*)&data.front()+1, *send = (uint32_t*)&data.back()+1; const uint32_t* sstart = (uint32_t*)&data.front()+1, *send = (uint32_t*)&data.back()+1;
char* dstart,*dend;
std::vector<char> output; std::vector<char> output;
do { int *ptr = (int*)&data[ 0 ];
output.resize(output.size()?output.size()*3/2:data.size()/2); int *end = ptr + ( data.size() / sizeof(int) ) +1;
dstart = &output.front(),dend = &output.back()+1; utf8::utf32to8( ptr, end, back_inserter(output));
result = ConvertUTF32toUTF8((const UTF32**)&sstart,(const UTF32*)send,(UTF8**)&dstart,(UTF8*)dend,lenientConversion);
} while(result == targetExhausted);
ReportResult(result);
// copy to output buffer.
const size_t outlen = (size_t)(dstart-&output.front());
data.assign(output.begin(),output.begin()+outlen);
return; return;
} }
@ -377,20 +359,11 @@ void BaseImporter::ConvertToUTF8(std::vector<char>& data)
DefaultLogger::get()->debug("Found UTF-16 BOM ..."); DefaultLogger::get()->debug("Found UTF-16 BOM ...");
const uint16_t* sstart = (uint16_t*)&data.front()+1, *send = (uint16_t*)(&data.back()+1); const uint16_t* sstart = (uint16_t*)&data.front()+1, *send = (uint16_t*)(&data.back()+1);
char* dstart,*dend; std::vector<unsigned char> output;
std::vector<char> output; int16_t *ptr = (int16_t*) &data[ 0 ];
do { int16_t *end = ptr + (data.size() / sizeof(int)) + 1;
output.resize(output.size()?output.size()*3/2:data.size()*3/4);
dstart = &output.front(),dend = &output.back()+1;
result = ConvertUTF16toUTF8((const UTF16**)&sstart,(const UTF16*)send,(UTF8**)&dstart,(UTF8*)dend,lenientConversion); utf8::utf16to8(data.begin(), data.end(), back_inserter(output));
} while(result == targetExhausted);
ReportResult(result);
// copy to output buffer.
const size_t outlen = (size_t)(dstart-&output.front());
data.assign(output.begin(),output.begin()+outlen);
return; return;
} }
} }
@ -461,41 +434,53 @@ void BaseImporter::TextFileToBuffer(IOStream* stream,
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
namespace Assimp namespace Assimp {
{
// Represents an import request // Represents an import request
struct LoadRequest struct LoadRequest {
{
LoadRequest(const std::string& _file, unsigned int _flags,const BatchLoader::PropertyMap* _map, unsigned int _id) LoadRequest(const std::string& _file, unsigned int _flags,const BatchLoader::PropertyMap* _map, unsigned int _id)
: file(_file), flags(_flags), refCnt(1),scene(NULL), loaded(false), id(_id) : file(_file)
{ , flags(_flags)
if (_map) , refCnt(1)
, scene(NULL)
, loaded(false)
, id(_id) {
if ( _map ) {
map = *_map; map = *_map;
}
} }
const std::string file; bool operator== ( const std::string& f ) const {
unsigned int flags;
unsigned int refCnt;
aiScene* scene;
bool loaded;
BatchLoader::PropertyMap map;
unsigned int id;
bool operator== (const std::string& f) {
return file == f; return file == f;
} }
const std::string file;
unsigned int flags;
unsigned int refCnt;
aiScene *scene;
bool loaded;
BatchLoader::PropertyMap map;
unsigned int id;
}; };
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// BatchLoader::pimpl data structure // BatchLoader::pimpl data structure
struct Assimp::BatchData struct Assimp::BatchData {
{ BatchData( IOSystem* pIO, bool validate )
BatchData() : pIOSystem( pIO )
: pIOSystem() , pImporter( nullptr )
, pImporter() , next_id(0xffff)
, next_id(0xffff) , validate( validate ) {
{} ai_assert( NULL != pIO );
pImporter = new Importer();
pImporter->SetIOHandler( pIO );
}
~BatchData() {
pImporter->SetIOHandler( NULL ); /* get pointer back into our possession */
delete pImporter;
}
// IO system to be used for all imports // IO system to be used for all imports
IOSystem* pIOSystem; IOSystem* pIOSystem;
@ -511,53 +496,59 @@ struct Assimp::BatchData
// Id for next item // Id for next item
unsigned int next_id; unsigned int next_id;
// Validation enabled state
bool validate;
}; };
typedef std::list<LoadRequest>::iterator LoadReqIt;
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
BatchLoader::BatchLoader(IOSystem* pIO) BatchLoader::BatchLoader(IOSystem* pIO, bool validate )
{ {
ai_assert(NULL != pIO); ai_assert(NULL != pIO);
data = new BatchData(); m_data = new BatchData( pIO, validate );
data->pIOSystem = pIO;
data->pImporter = new Importer();
data->pImporter->SetIOHandler(data->pIOSystem);
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
BatchLoader::~BatchLoader() BatchLoader::~BatchLoader()
{ {
// delete all scenes wthat have not been polled by the user // delete all scenes what have not been polled by the user
for (std::list<LoadRequest>::iterator it = data->requests.begin();it != data->requests.end(); ++it) { for ( LoadReqIt it = m_data->requests.begin();it != m_data->requests.end(); ++it) {
delete (*it).scene; delete (*it).scene;
} }
data->pImporter->SetIOHandler(NULL); /* get pointer back into our possession */ delete m_data;
delete data->pImporter;
delete data;
} }
// ------------------------------------------------------------------------------------------------
void BatchLoader::setValidation( bool enabled ) {
m_data->validate = enabled;
}
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
unsigned int BatchLoader::AddLoadRequest (const std::string& file, bool BatchLoader::getValidation() const {
return m_data->validate;
}
// ------------------------------------------------------------------------------------------------
unsigned int BatchLoader::AddLoadRequest(const std::string& file,
unsigned int steps /*= 0*/, const PropertyMap* map /*= NULL*/) unsigned int steps /*= 0*/, const PropertyMap* map /*= NULL*/)
{ {
ai_assert(!file.empty()); ai_assert(!file.empty());
// check whether we have this loading request already // check whether we have this loading request already
std::list<LoadRequest>::iterator it; for ( LoadReqIt it = m_data->requests.begin();it != m_data->requests.end(); ++it) {
for (it = data->requests.begin();it != data->requests.end(); ++it) {
// Call IOSystem's path comparison function here // Call IOSystem's path comparison function here
if (data->pIOSystem->ComparePaths((*it).file,file)) { if ( m_data->pIOSystem->ComparePaths((*it).file,file)) {
if (map) { if (map) {
if (!((*it).map == *map)) if ( !( ( *it ).map == *map ) ) {
continue; continue;
}
} }
else if (!(*it).map.empty()) else if ( !( *it ).map.empty() ) {
continue; continue;
}
(*it).refCnt++; (*it).refCnt++;
return (*it).id; return (*it).id;
@ -565,20 +556,18 @@ unsigned int BatchLoader::AddLoadRequest (const std::string& file,
} }
// no, we don't have it. So add it to the queue ... // no, we don't have it. So add it to the queue ...
data->requests.push_back(LoadRequest(file,steps,map,data->next_id)); m_data->requests.push_back(LoadRequest(file,steps,map, m_data->next_id));
return data->next_id++; return m_data->next_id++;
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
aiScene* BatchLoader::GetImport (unsigned int which) aiScene* BatchLoader::GetImport( unsigned int which )
{ {
for (std::list<LoadRequest>::iterator it = data->requests.begin();it != data->requests.end(); ++it) { for ( LoadReqIt it = m_data->requests.begin();it != m_data->requests.end(); ++it) {
if ((*it).id == which && (*it).loaded) { if ((*it).id == which && (*it).loaded) {
aiScene* sc = (*it).scene; aiScene* sc = (*it).scene;
if (!(--(*it).refCnt)) { if (!(--(*it).refCnt)) {
data->requests.erase(it); m_data->requests.erase(it);
} }
return sc; return sc;
} }
@ -590,14 +579,15 @@ aiScene* BatchLoader::GetImport (unsigned int which)
void BatchLoader::LoadAll() void BatchLoader::LoadAll()
{ {
// no threaded implementation for the moment // no threaded implementation for the moment
for (std::list<LoadRequest>::iterator it = data->requests.begin();it != data->requests.end(); ++it) { for ( LoadReqIt it = m_data->requests.begin();it != m_data->requests.end(); ++it) {
// force validation in debug builds // force validation in debug builds
unsigned int pp = (*it).flags; unsigned int pp = (*it).flags;
#ifdef ASSIMP_BUILD_DEBUG if ( m_data->validate ) {
pp |= aiProcess_ValidateDataStructure; pp |= aiProcess_ValidateDataStructure;
#endif }
// setup config properties if necessary // setup config properties if necessary
ImporterPimpl* pimpl = data->pImporter->Pimpl(); ImporterPimpl* pimpl = m_data->pImporter->Pimpl();
pimpl->mFloatProperties = (*it).map.floats; pimpl->mFloatProperties = (*it).map.floats;
pimpl->mIntProperties = (*it).map.ints; pimpl->mIntProperties = (*it).map.ints;
pimpl->mStringProperties = (*it).map.strings; pimpl->mStringProperties = (*it).map.strings;
@ -608,8 +598,8 @@ void BatchLoader::LoadAll()
DefaultLogger::get()->info("%%% BEGIN EXTERNAL FILE %%%"); DefaultLogger::get()->info("%%% BEGIN EXTERNAL FILE %%%");
DefaultLogger::get()->info("File: " + (*it).file); DefaultLogger::get()->info("File: " + (*it).file);
} }
data->pImporter->ReadFile((*it).file,pp); m_data->pImporter->ReadFile((*it).file,pp);
(*it).scene = data->pImporter->GetOrphanedScene(); (*it).scene = m_data->pImporter->GetOrphanedScene();
(*it).loaded = true; (*it).loaded = true;
DefaultLogger::get()->info("%%% END EXTERNAL FILE %%%"); DefaultLogger::get()->info("%%% END EXTERNAL FILE %%%");

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -44,14 +45,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "Exceptional.h" #include "Exceptional.h"
#include <string>
#include <map>
#include <vector> #include <vector>
#include <set> #include <set>
#include <assimp/types.h> #include <assimp/types.h>
#include <assimp/ProgressHandler.hpp> #include <assimp/ProgressHandler.hpp>
struct aiScene; struct aiScene;
struct aiImporterDesc;
namespace Assimp { namespace Assimp {
@ -61,7 +61,6 @@ class BaseProcess;
class SharedPostProcessInfo; class SharedPostProcessInfo;
class IOStream; class IOStream;
// utility to do char4 to uint32 in a portable manner // utility to do char4 to uint32 in a portable manner
#define AI_MAKE_MAGIC(string) ((uint32_t)((string[0] << 24) + \ #define AI_MAKE_MAGIC(string) ((uint32_t)((string[0] << 24) + \
(string[1] << 16) + (string[2] << 8) + string[3])) (string[1] << 16) + (string[2] << 8) + string[3]))
@ -194,14 +193,11 @@ public:
const Importer* pImp const Importer* pImp
); );
// ------------------------------------------------------------------- // -------------------------------------------------------------------
/** Called by #Importer::GetImporterInfo to get a description of /** Called by #Importer::GetImporterInfo to get a description of
* some loader features. Importers must provide this information. */ * some loader features. Importers must provide this information. */
virtual const aiImporterDesc* GetInfo() const = 0; virtual const aiImporterDesc* GetInfo() const = 0;
// ------------------------------------------------------------------- // -------------------------------------------------------------------
/** Called by #Importer::GetExtensionList for each loaded importer. /** Called by #Importer::GetExtensionList for each loaded importer.
* Take the extension list contained in the structure returned by * Take the extension list contained in the structure returned by
@ -317,7 +313,7 @@ public: // static utilities
* @param Size of one token, in bytes. Maximally 16 bytes. * @param Size of one token, in bytes. Maximally 16 bytes.
* @return true if one of the given tokens was found * @return true if one of the given tokens was found
* *
* @note For convinence, the check is also performed for the * @note For convenience, the check is also performed for the
* byte-swapped variant of all tokens (big endian). Only for * byte-swapped variant of all tokens (big endian). Only for
* tokens of size 2,4. * tokens of size 2,4.
*/ */
@ -347,7 +343,12 @@ public: // static utilities
static void ConvertUTF8toISO8859_1( static void ConvertUTF8toISO8859_1(
std::string& data); std::string& data);
enum TextFileMode { ALLOW_EMPTY, FORBID_EMPTY }; // -------------------------------------------------------------------
/// @brief Enum to define, if empty files are ok or not.
enum TextFileMode {
ALLOW_EMPTY,
FORBID_EMPTY
};
// ------------------------------------------------------------------- // -------------------------------------------------------------------
/** Utility for text file loaders which copies the contents of the /** Utility for text file loaders which copies the contents of the
@ -382,14 +383,10 @@ public: // static utilities
} }
} }
protected: protected:
/// Error description in case there was one.
/** Error description in case there was one. */
std::string m_ErrorText; std::string m_ErrorText;
/// Currently set progress handler.
/** Currently set progress handler */
ProgressHandler* m_progress; ProgressHandler* m_progress;
}; };

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -43,8 +44,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define INCLUDED_AI_BASEPROCESS_H #define INCLUDED_AI_BASEPROCESS_H
#include <map> #include <map>
#include <assimp/types.h>
#include "GenericProperty.h" #include "GenericProperty.h"
struct aiScene; struct aiScene;

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -50,93 +51,71 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdint.h> #include <stdint.h>
#include <cstddef> #include <cstddef>
struct aiTexture; struct aiTexture;
namespace Assimp { namespace Assimp {
class IOStream; class IOStream;
class Bitmap { class Bitmap {
protected:
protected: struct Header {
uint16_t type;
uint32_t size;
uint16_t reserved1;
uint16_t reserved2;
uint32_t offset;
struct Header { // We define the struct size because sizeof(Header) might return a wrong result because of structure padding.
// Moreover, we must use this ugly and error prone syntax because Visual Studio neither support constexpr or sizeof(name_of_field).
static const std::size_t header_size =
sizeof(uint16_t) + // type
sizeof(uint32_t) + // size
sizeof(uint16_t) + // reserved1
sizeof(uint16_t) + // reserved2
sizeof(uint32_t); // offset
};
uint16_t type; struct DIB {
uint32_t size;
int32_t width;
int32_t height;
uint16_t planes;
uint16_t bits_per_pixel;
uint32_t compression;
uint32_t image_size;
int32_t x_resolution;
int32_t y_resolution;
uint32_t nb_colors;
uint32_t nb_important_colors;
uint32_t size; // We define the struct size because sizeof(DIB) might return a wrong result because of structure padding.
// Moreover, we must use this ugly and error prone syntax because Visual Studio neither support constexpr or sizeof(name_of_field).
static const std::size_t dib_size =
sizeof(uint32_t) + // size
sizeof(int32_t) + // width
sizeof(int32_t) + // height
sizeof(uint16_t) + // planes
sizeof(uint16_t) + // bits_per_pixel
sizeof(uint32_t) + // compression
sizeof(uint32_t) + // image_size
sizeof(int32_t) + // x_resolution
sizeof(int32_t) + // y_resolution
sizeof(uint32_t) + // nb_colors
sizeof(uint32_t); // nb_important_colors
};
uint16_t reserved1; static const std::size_t mBytesPerPixel = 4;
uint16_t reserved2; public:
static void Save(aiTexture* texture, IOStream* file);
uint32_t offset;
// We define the struct size because sizeof(Header) might return a wrong result because of structure padding.
// Moreover, we must use this ugly and error prone syntax because Visual Studio neither support constexpr or sizeof(name_of_field).
static const std::size_t header_size =
sizeof(uint16_t) + // type
sizeof(uint32_t) + // size
sizeof(uint16_t) + // reserved1
sizeof(uint16_t) + // reserved2
sizeof(uint32_t); // offset
};
struct DIB {
uint32_t size;
int32_t width;
int32_t height;
uint16_t planes;
uint16_t bits_per_pixel;
uint32_t compression;
uint32_t image_size;
int32_t x_resolution;
int32_t y_resolution;
uint32_t nb_colors;
uint32_t nb_important_colors;
// We define the struct size because sizeof(DIB) might return a wrong result because of structure padding.
// Moreover, we must use this ugly and error prone syntax because Visual Studio neither support constexpr or sizeof(name_of_field).
static const std::size_t dib_size =
sizeof(uint32_t) + // size
sizeof(int32_t) + // width
sizeof(int32_t) + // height
sizeof(uint16_t) + // planes
sizeof(uint16_t) + // bits_per_pixel
sizeof(uint32_t) + // compression
sizeof(uint32_t) + // image_size
sizeof(int32_t) + // x_resolution
sizeof(int32_t) + // y_resolution
sizeof(uint32_t) + // nb_colors
sizeof(uint32_t); // nb_important_colors
};
static const std::size_t mBytesPerPixel = 4;
public:
static void Save(aiTexture* texture, IOStream* file);
protected:
static void WriteHeader(Header& header, IOStream* file);
static void WriteDIB(DIB& dib, IOStream* file);
static void WriteData(aiTexture* texture, IOStream* file);
protected:
static void WriteHeader(Header& header, IOStream* file);
static void WriteDIB(DIB& dib, IOStream* file);
static void WriteData(aiTexture* texture, IOStream* file);
}; };
} }

View File

@ -180,7 +180,7 @@ void BlenderBMeshConverter::AddFace( int v1, int v2, int v3, int v4 )
// TODO - Work out how materials work // TODO - Work out how materials work
face.mat_nr = 0; face.mat_nr = 0;
triMesh->mface.push_back( face ); triMesh->mface.push_back( face );
triMesh->totface = triMesh->mface.size( ); triMesh->totface = static_cast<int>(triMesh->mface.size( ));
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -48,6 +49,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderDNA.h" #include "BlenderDNA.h"
#include "StreamReader.h" #include "StreamReader.h"
#include "fast_atof.h" #include "fast_atof.h"
#include "TinyFormatter.h"
using namespace Assimp; using namespace Assimp;
using namespace Assimp::Blender; using namespace Assimp::Blender;
@ -56,10 +58,10 @@ using namespace Assimp::Formatter;
static bool match4(StreamReaderAny& stream, const char* string) { static bool match4(StreamReaderAny& stream, const char* string) {
ai_assert( nullptr != string ); ai_assert( nullptr != string );
char tmp[] = { char tmp[] = {
(stream).GetI1(), (const char)(stream).GetI1(),
(stream).GetI1(), (const char)(stream).GetI1(),
(stream).GetI1(), (const char)(stream).GetI1(),
(stream).GetI1() (const char)(stream).GetI1()
}; };
return (tmp[0]==string[0] && tmp[1]==string[1] && tmp[2]==string[2] && tmp[3]==string[3]); return (tmp[0]==string[0] && tmp[1]==string[1] && tmp[2]==string[2] && tmp[3]==string[3]);
} }
@ -346,10 +348,10 @@ void SectionParser :: Next()
stream.SetCurrentPos(current.start + current.size); stream.SetCurrentPos(current.start + current.size);
const char tmp[] = { const char tmp[] = {
stream.GetI1(), (const char)stream.GetI1(),
stream.GetI1(), (const char)stream.GetI1(),
stream.GetI1(), (const char)stream.GetI1(),
stream.GetI1() (const char)stream.GetI1()
}; };
current.id = std::string(tmp,tmp[3]?4:tmp[2]?3:tmp[1]?2:1); current.id = std::string(tmp,tmp[3]?4:tmp[2]?3:tmp[1]?2:1);

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -46,12 +47,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define INCLUDED_AI_BLEND_DNA_H #define INCLUDED_AI_BLEND_DNA_H
#include "BaseImporter.h" #include "BaseImporter.h"
#include "TinyFormatter.h"
#include "StreamReader.h" #include "StreamReader.h"
#include <assimp/DefaultLogger.hpp> #include <assimp/DefaultLogger.hpp>
#include <stdint.h> #include <stdint.h>
#include <memory> #include <memory>
#include <map>
// enable verbose log output. really verbose, so be careful. // enable verbose log output. really verbose, so be careful.
#ifdef ASSIMP_BUILD_DEBUG #ifdef ASSIMP_BUILD_DEBUG

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -46,9 +47,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define INCLUDED_AI_BLEND_DNA_INL #define INCLUDED_AI_BLEND_DNA_INL
#include <memory> #include <memory>
#include "TinyFormatter.h"
namespace Assimp { namespace Assimp {
namespace Blender { namespace Blender {
//-------------------------------------------------------------------------------- //--------------------------------------------------------------------------------
const Field& Structure :: operator [] (const std::string& ss) const const Field& Structure :: operator [] (const std::string& ss) const

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -48,9 +49,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderLoader.h" #include "BlenderLoader.h"
#include "BlenderDNA.h" #include "BlenderDNA.h"
#include "BlenderScene.h" #include "BlenderScene.h"
#include "BlenderSceneGen.h"
#include <deque> #include <deque>
#include "./../include/assimp/material.h" #include <assimp/material.h>
struct aiTexture; struct aiTexture;
@ -123,7 +123,6 @@ namespace Blender {
struct ObjectCompare { struct ObjectCompare {
bool operator() (const Object* left, const Object* right) const { bool operator() (const Object* left, const Object* right) const {
printf( "left: %s, right: %s\n", left->id.name, right->id.name );
return ::strncmp(left->id.name, right->id.name, strlen( left->id.name ) ) == 0; return ::strncmp(left->id.name, right->id.name, strlen( left->id.name ) ) == 0;
} }
}; };
@ -145,7 +144,6 @@ namespace Blender {
struct ObjectCompare { struct ObjectCompare {
bool operator() (const Object* left, const Object* right) const { bool operator() (const Object* left, const Object* right) const {
printf( "left: %s, right: %s\n", left->id.name, right->id.name );
return ::strncmp( left->id.name, right->id.name, strlen( left->id.name ) ) == 0; return ::strncmp( left->id.name, right->id.name, strlen( left->id.name ) ) == 0;
} }
}; };

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -54,10 +55,12 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BlenderBMesh.h" #include "BlenderBMesh.h"
#include "StringUtils.h" #include "StringUtils.h"
#include <assimp/scene.h> #include <assimp/scene.h>
#include "StringComparison.h" #include <assimp/importerdesc.h>
#include "StringComparison.h"
#include "StreamReader.h" #include "StreamReader.h"
#include "MemoryIOWrapper.h" #include "MemoryIOWrapper.h"
#include <cctype> #include <cctype>
@ -95,8 +98,9 @@ static const aiImporterDesc blenderDesc = {
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer // Constructor to be privately used by Importer
BlenderImporter::BlenderImporter() BlenderImporter::BlenderImporter()
: modifier_cache(new BlenderModifierShowcase()) : modifier_cache(new BlenderModifierShowcase()) {
{} // empty
}
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Destructor, private as well // Destructor, private as well
@ -105,6 +109,9 @@ BlenderImporter::~BlenderImporter()
delete modifier_cache; delete modifier_cache;
} }
static const char* Tokens[] = { "BLENDER" };
static const char* TokensForSearch[] = { "blender" };
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file. // Returns whether the class can handle the format of the given file.
bool BlenderImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const bool BlenderImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
@ -116,8 +123,7 @@ bool BlenderImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, b
else if ((!extension.length() || checkSig) && pIOHandler) { else if ((!extension.length() || checkSig) && pIOHandler) {
// note: this won't catch compressed files // note: this won't catch compressed files
const char* tokens[] = {"BLENDER"}; return SearchFileHeaderForToken(pIOHandler,pFile, TokensForSearch,1);
return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
} }
return false; return false;
} }
@ -143,8 +149,7 @@ void BlenderImporter::SetupProperties(const Importer* /*pImp*/)
// nothing to be done for the moment // nothing to be done for the moment
} }
struct free_it struct free_it {
{
free_it(void* free) : free(free) {} free_it(void* free) : free(free) {}
~free_it() { ~free_it() {
::free(this->free); ::free(this->free);
@ -163,6 +168,7 @@ void BlenderImporter::InternReadFile( const std::string& pFile,
free_it free_it_really(dest); free_it free_it_really(dest);
#endif #endif
FileDatabase file; FileDatabase file;
std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile,"rb")); std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile,"rb"));
if (!stream) { if (!stream) {
@ -171,7 +177,7 @@ void BlenderImporter::InternReadFile( const std::string& pFile,
char magic[8] = {0}; char magic[8] = {0};
stream->Read(magic,7,1); stream->Read(magic,7,1);
if (strcmp(magic,"BLENDER")) { if (strcmp(magic, Tokens[0] )) {
// Check for presence of the gzip header. If yes, assume it is a // Check for presence of the gzip header. If yes, assume it is a
// compressed blend file and try uncompressing it, else fail. This is to // compressed blend file and try uncompressing it, else fail. This is to
// avoid uncompressing random files which our loader might end up with. // avoid uncompressing random files which our loader might end up with.
@ -346,8 +352,9 @@ void BlenderImporter::ConvertBlendFile(aiScene* out, const Scene& in,const FileD
if (cur->object) { if (cur->object) {
if(!cur->object->parent) { if(!cur->object->parent) {
no_parents.push_back(cur->object.get()); no_parents.push_back(cur->object.get());
} else {
conv.objects.insert( cur->object.get() );
} }
else conv.objects.insert(cur->object.get());
} }
} }
for (std::shared_ptr<Base> cur = in.basact; cur; cur = cur->next) { for (std::shared_ptr<Base> cur = in.basact; cur; cur = cur->next) {
@ -404,7 +411,7 @@ void BlenderImporter::ConvertBlendFile(aiScene* out, const Scene& in,const FileD
} }
// acknowledge that the scene might come out incomplete // acknowledge that the scene might come out incomplete
// by Assimps definition of `complete`: blender scenes // by Assimp's definition of `complete`: blender scenes
// can consist of thousands of cameras or lights with // can consist of thousands of cameras or lights with
// not a single mesh between them. // not a single mesh between them.
if (!out->mNumMeshes) { if (!out->mNumMeshes) {
@ -421,7 +428,7 @@ void BlenderImporter::ResolveImage(aiMaterial* out, const Material* mat, const M
// check if the file contents are bundled with the BLEND file // check if the file contents are bundled with the BLEND file
if (img->packedfile) { if (img->packedfile) {
name.data[0] = '*'; name.data[0] = '*';
name.length = 1+ ASSIMP_itoa10(name.data+1,MAXLEN-1,conv_data.textures->size()); name.length = 1+ ASSIMP_itoa10(name.data+1,static_cast<unsigned int>(MAXLEN-1), static_cast<int32_t>(conv_data.textures->size()));
conv_data.textures->push_back(new aiTexture()); conv_data.textures->push_back(new aiTexture());
aiTexture* tex = conv_data.textures->back(); aiTexture* tex = conv_data.textures->back();
@ -430,8 +437,9 @@ void BlenderImporter::ResolveImage(aiMaterial* out, const Material* mat, const M
// so we can extract the file extension from it. // so we can extract the file extension from it.
const size_t nlen = strlen( img->name ); const size_t nlen = strlen( img->name );
const char* s = img->name+nlen, *e = s; const char* s = img->name+nlen, *e = s;
while ( s >= img->name && *s != '.' ) {
while (s >= img->name && *s != '.')--s; --s;
}
tex->achFormatHint[0] = s+1>e ? '\0' : ::tolower( s[1] ); tex->achFormatHint[0] = s+1>e ? '\0' : ::tolower( s[1] );
tex->achFormatHint[1] = s+2>e ? '\0' : ::tolower( s[2] ); tex->achFormatHint[1] = s+2>e ? '\0' : ::tolower( s[2] );
@ -448,8 +456,7 @@ void BlenderImporter::ResolveImage(aiMaterial* out, const Material* mat, const M
tex->pcData = reinterpret_cast<aiTexel*>(ch); tex->pcData = reinterpret_cast<aiTexel*>(ch);
LogInfo("Reading embedded texture, original file was "+std::string(img->name)); LogInfo("Reading embedded texture, original file was "+std::string(img->name));
} } else {
else {
name = aiString( img->name ); name = aiString( img->name );
} }
@ -790,7 +797,7 @@ void BlenderImporter::ConvertMesh(const Scene& /*in*/, const Object* /*obj*/, co
ConversionData& conv_data, TempArray<std::vector,aiMesh>& temp ConversionData& conv_data, TempArray<std::vector,aiMesh>& temp
) )
{ {
// TODO: Resolve various problems with BMesh triangluation before re-enabling. // TODO: Resolve various problems with BMesh triangulation before re-enabling.
// See issues #400, #373, #318 #315 and #132. // See issues #400, #373, #318 #315 and #132.
#if defined(TODO_FIX_BMESH_CONVERSION) #if defined(TODO_FIX_BMESH_CONVERSION)
BlenderBMeshConverter BMeshConverter( mesh ); BlenderBMeshConverter BMeshConverter( mesh );
@ -852,7 +859,7 @@ void BlenderImporter::ConvertMesh(const Scene& /*in*/, const Object* /*obj*/, co
//out->mNumVertices = 0 //out->mNumVertices = 0
out->mFaces = new aiFace[it.second](); out->mFaces = new aiFace[it.second]();
// all submeshes created from this mesh are named equally. this allows // all sub-meshes created from this mesh are named equally. this allows
// curious users to recover the original adjacency. // curious users to recover the original adjacency.
out->mName = aiString(mesh->id.name+2); out->mName = aiString(mesh->id.name+2);
// skip over the name prefix 'ME' // skip over the name prefix 'ME'
@ -1143,7 +1150,7 @@ aiCamera* BlenderImporter::ConvertCamera(const Scene& /*in*/, const Object* obj,
out->mUp = aiVector3D(0.f, 1.f, 0.f); out->mUp = aiVector3D(0.f, 1.f, 0.f);
out->mLookAt = aiVector3D(0.f, 0.f, -1.f); out->mLookAt = aiVector3D(0.f, 0.f, -1.f);
if (cam->sensor_x && cam->lens) { if (cam->sensor_x && cam->lens) {
out->mHorizontalFOV = atan2(cam->sensor_x, 2.f * cam->lens); out->mHorizontalFOV = std::atan2(cam->sensor_x, 2.f * cam->lens);
} }
out->mClipPlaneNear = cam->clipsta; out->mClipPlaneNear = cam->clipsta;
out->mClipPlaneFar = cam->clipend; out->mClipPlaneFar = cam->clipend;
@ -1228,7 +1235,7 @@ aiNode* BlenderImporter::ConvertNode(const Scene& in, const Object* obj, Convers
if (conv_data.meshes->size() > old) { if (conv_data.meshes->size() > old) {
node->mMeshes = new unsigned int[node->mNumMeshes = static_cast<unsigned int>(conv_data.meshes->size()-old)]; node->mMeshes = new unsigned int[node->mNumMeshes = static_cast<unsigned int>(conv_data.meshes->size()-old)];
for (unsigned int i = 0; i < node->mNumMeshes; ++i) { for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
node->mMeshes[i] = i + old; node->mMeshes[i] = static_cast<unsigned int>(i + old);
} }
}} }}
break; break;
@ -1304,5 +1311,4 @@ aiNode* BlenderImporter::ConvertNode(const Scene& in, const Object* obj, Convers
return node.dismiss(); return node.dismiss();
} }
#endif // ASSIMP_BUILD_NO_BLEND_IMPORTER
#endif

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -105,7 +106,6 @@ public:
BlenderImporter(); BlenderImporter();
~BlenderImporter(); ~BlenderImporter();
public: public:
// -------------------- // --------------------

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -275,9 +276,6 @@ void BlenderModifier_Mirror :: DoIt(aiNode& out, ConversionData& conv_data, co
orig_object.id.name,"`"); orig_object.id.name,"`");
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
bool BlenderModifier_Subdivision :: IsActive (const ModifierData& modin) bool BlenderModifier_Subdivision :: IsActive (const ModifierData& modin)
{ {
@ -323,4 +321,4 @@ void BlenderModifier_Subdivision :: DoIt(aiNode& out, ConversionData& conv_data
orig_object.id.name,"`"); orig_object.id.name,"`");
} }
#endif #endif // ASSIMP_BUILD_NO_BLEND_IMPORTER

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -44,9 +44,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef ASSIMP_BUILD_NO_BLEND_IMPORTER #ifndef ASSIMP_BUILD_NO_BLEND_IMPORTER
#include "BlenderDNA.h"
#include "BlenderScene.h" #include "BlenderScene.h"
#include "BlenderSceneGen.h" #include "BlenderSceneGen.h"
#include "BlenderDNA.h"
using namespace Assimp; using namespace Assimp;
using namespace Assimp::Blender; using namespace Assimp::Blender;
@ -522,7 +522,7 @@ template <> void Structure :: Convert<MVert> (
ReadFieldArray<ErrorPolicy_Fail>(dest.co,"co",db); ReadFieldArray<ErrorPolicy_Fail>(dest.co,"co",db);
ReadFieldArray<ErrorPolicy_Fail>(dest.no,"no",db); ReadFieldArray<ErrorPolicy_Fail>(dest.no,"no",db);
ReadField<ErrorPolicy_Igno>(dest.flag,"flag",db); ReadField<ErrorPolicy_Igno>(dest.flag,"flag",db);
ReadField<ErrorPolicy_Warn>(dest.mat_nr,"mat_nr",db); //ReadField<ErrorPolicy_Warn>(dest.mat_nr,"mat_nr",db);
ReadField<ErrorPolicy_Igno>(dest.bweight,"bweight",db); ReadField<ErrorPolicy_Igno>(dest.bweight,"bweight",db);
db.reader->IncPtr(size); db.reader->IncPtr(size);
@ -805,5 +805,5 @@ void DNA::RegisterConverters() {
converters["Image"] = DNA::FactoryPair( &Structure::Allocate<Image>, &Structure::Convert<Image> ); converters["Image"] = DNA::FactoryPair( &Structure::Allocate<Image>, &Structure::Convert<Image> );
} }
#endif // ASSIMP_BUILD_NO_BLEND_IMPORTER
#endif

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -64,7 +65,7 @@ namespace Blender {
// * C++ style comments only // * C++ style comments only
// //
// * Structures may include the primitive types char, int, short, // * Structures may include the primitive types char, int, short,
// float, double. Signedness specifiers are not allowed on // float, double. Signed specifiers are not allowed on
// integers. Enum types are allowed, but they must have been // integers. Enum types are allowed, but they must have been
// defined in this header. // defined in this header.
// //
@ -85,14 +86,23 @@ namespace Blender {
// provided they are neither pointers nor arrays. // provided they are neither pointers nor arrays.
// //
// * One of WARN, FAIL can be appended to the declaration ( // * One of WARN, FAIL can be appended to the declaration (
// prior to the semiolon to specifiy the error handling policy if // prior to the semicolon to specify the error handling policy if
// this field is missing in the input DNA). If none of those // this field is missing in the input DNA). If none of those
// is specified the default policy is to subtitute a default // is specified the default policy is to substitute a default
// value for the field. // value for the field.
// //
#define WARN // warn if field is missing, substitute default value // warn if field is missing, substitute default value
#define FAIL // fail the import if the field does not exist #ifdef WARN
# undef WARN
#endif
#define WARN
// fail the import if the field does not exist
#ifdef FAIL
# undef FAIL
#endif
#define FAIL
struct Object; struct Object;
struct MTex; struct MTex;
@ -102,16 +112,16 @@ struct Image;
#define AI_BLEND_MESH_MAX_VERTS 2000000000L #define AI_BLEND_MESH_MAX_VERTS 2000000000L
static const size_t MaxNameLen = 1024;
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct ID : ElemBase { struct ID : ElemBase {
char name[ MaxNameLen ] WARN;
char name[1024] WARN;
short flag; short flag;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct ListBase : ElemBase { struct ListBase : ElemBase {
std::shared_ptr<ElemBase> first; std::shared_ptr<ElemBase> first;
std::shared_ptr<ElemBase> last; std::shared_ptr<ElemBase> last;
}; };
@ -126,7 +136,6 @@ struct PackedFile : ElemBase {
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct GroupObject : ElemBase { struct GroupObject : ElemBase {
std::shared_ptr<GroupObject> prev,next FAIL; std::shared_ptr<GroupObject> prev,next FAIL;
std::shared_ptr<Object> ob; std::shared_ptr<Object> ob;
}; };
@ -142,7 +151,6 @@ struct Group : ElemBase {
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct World : ElemBase { struct World : ElemBase {
ID id FAIL; ID id FAIL;
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -217,7 +225,6 @@ struct TFace : ElemBase {
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct MTFace : ElemBase { struct MTFace : ElemBase {
float uv[4][2] FAIL; float uv[4][2] FAIL;
char flag; char flag;
short mode; short mode;
@ -235,7 +242,6 @@ struct MDeformWeight : ElemBase {
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct MDeformVert : ElemBase { struct MDeformVert : ElemBase {
vector<MDeformWeight> dw WARN; vector<MDeformWeight> dw WARN;
int totweight; int totweight;
}; };
@ -264,7 +270,6 @@ struct Material : ElemBase {
float darkness; float darkness;
float refrac; float refrac;
float amb; float amb;
float ang; float ang;
float spectra; float spectra;
@ -612,6 +617,17 @@ struct Object : ElemBase {
std::shared_ptr<ElemBase> data FAIL; std::shared_ptr<ElemBase> data FAIL;
ListBase modifiers; ListBase modifiers;
Object()
: ElemBase()
, type( Type_EMPTY )
, parent( nullptr )
, track()
, proxy()
, proxy_from()
, data() {
// empty
}
}; };
@ -620,6 +636,15 @@ struct Base : ElemBase {
Base* prev WARN; Base* prev WARN;
std::shared_ptr<Base> next WARN; std::shared_ptr<Base> next WARN;
std::shared_ptr<Object> object WARN; std::shared_ptr<Object> object WARN;
Base()
: ElemBase()
, prev( nullptr )
, next()
, object() {
// empty
// empty
}
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -631,8 +656,15 @@ struct Scene : ElemBase {
std::shared_ptr<Base> basact WARN; std::shared_ptr<Base> basact WARN;
ListBase base; ListBase base;
};
Scene()
: ElemBase()
, camera()
, world()
, basact() {
// empty
}
};
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
struct Image : ElemBase { struct Image : ElemBase {
@ -660,6 +692,11 @@ struct Image : ElemBase {
short animspeed; short animspeed;
short gen_x, gen_y, gen_type; short gen_x, gen_y, gen_type;
Image()
: ElemBase() {
// empty
}
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -747,6 +784,14 @@ struct Tex : ElemBase {
//VoxelData *vd; //VoxelData *vd;
//char use_nodes; //char use_nodes;
Tex()
: ElemBase()
, imaflag( ImageFlags_INTERPOL )
, type( Type_CLOUDS )
, ima() {
// empty
}
}; };
// ------------------------------------------------------------------------------- // -------------------------------------------------------------------------------
@ -835,9 +880,13 @@ struct MTex : ElemBase {
//float lifefac, sizefac, ivelfac, pvelfac; //float lifefac, sizefac, ivelfac, pvelfac;
//float shadowfac; //float shadowfac;
//float zenupfac, zendownfac, blendfac; //float zenupfac, zendownfac, blendfac;
MTex()
: ElemBase() {
// empty
}
}; };
}
}
} }
#endif #endif

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -412,9 +413,9 @@ float BlenderTessellatorP2T::FindLargestMatrixElem( const aiMatrix3x3& mtx ) con
{ {
float result = 0.0f; float result = 0.0f;
for ( size_t x = 0; x < 3; ++x ) for ( unsigned int x = 0; x < 3; ++x )
{ {
for ( size_t y = 0; y < 3; ++y ) for ( unsigned int y = 0; y < 3; ++y )
{ {
result = p2tMax( std::fabs( mtx[ x ][ y ] ), result ); result = p2tMax( std::fabs( mtx[ x ][ y ] ), result );
} }
@ -429,9 +430,9 @@ aiMatrix3x3 BlenderTessellatorP2T::ScaleMatrix( const aiMatrix3x3& mtx, float sc
{ {
aiMatrix3x3 result; aiMatrix3x3 result;
for ( size_t x = 0; x < 3; ++x ) for ( unsigned int x = 0; x < 3; ++x )
{ {
for ( size_t y = 0; y < 3; ++y ) for ( unsigned int y = 0; y < 3; ++y )
{ {
result[ x ][ y ] = mtx[ x ][ y ] * scale; result[ x ][ y ] = mtx[ x ][ y ] * scale;
} }

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -45,10 +46,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef AI_BLOBIOSYSTEM_H_INCLUDED #ifndef AI_BLOBIOSYSTEM_H_INCLUDED
#define AI_BLOBIOSYSTEM_H_INCLUDED #define AI_BLOBIOSYSTEM_H_INCLUDED
#include "./../include/assimp/IOStream.hpp" #include <assimp/IOStream.hpp>
#include "./../include/assimp/cexport.h" #include <assimp/cexport.h>
#include "./../include/assimp/IOSystem.hpp" #include <assimp/IOSystem.hpp>
#include "./../include/assimp/DefaultLogger.hpp" #include <assimp/DefaultLogger.hpp>
#include <stdint.h> #include <stdint.h>
#include <set> #include <set>
#include <vector> #include <vector>

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -0,0 +1,135 @@
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 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 DAMAGE.
---------------------------------------------------------------------------
*/
/** @file aiFileIO -> IOSystem wrapper*/
#include "CInterfaceIOWrapper.h"
namespace Assimp {
CIOStreamWrapper::~CIOStreamWrapper(void)
{
/* Various places depend on this destructor to close the file */
if (mFile) {
mIO->mFileSystem->CloseProc(mIO->mFileSystem, mFile);
mFile = nullptr;
}
}
// ...................................................................
size_t CIOStreamWrapper::Read(void* pvBuffer,
size_t pSize,
size_t pCount
){
// need to typecast here as C has no void*
return mFile->ReadProc(mFile,(char*)pvBuffer,pSize,pCount);
}
// ...................................................................
size_t CIOStreamWrapper::Write(const void* pvBuffer,
size_t pSize,
size_t pCount
){
// need to typecast here as C has no void*
return mFile->WriteProc(mFile,(const char*)pvBuffer,pSize,pCount);
}
// ...................................................................
aiReturn CIOStreamWrapper::Seek(size_t pOffset,
aiOrigin pOrigin
){
return mFile->SeekProc(mFile,pOffset,pOrigin);
}
// ...................................................................
size_t CIOStreamWrapper::Tell(void) const {
return mFile->TellProc(mFile);
}
// ...................................................................
size_t CIOStreamWrapper::FileSize() const {
return mFile->FileSizeProc(mFile);
}
// ...................................................................
void CIOStreamWrapper::Flush () {
return mFile->FlushProc(mFile);
}
// ------------------------------------------------------------------------------------------------
// Custom IOStream implementation for the C-API
bool CIOSystemWrapper::Exists( const char* pFile) const {
aiFile* p = mFileSystem->OpenProc(mFileSystem,pFile,"rb");
if (p){
mFileSystem->CloseProc(mFileSystem,p);
return true;
}
return false;
}
// ...................................................................
char CIOSystemWrapper::getOsSeparator() const {
#ifndef _WIN32
return '/';
#else
return '\\';
#endif
}
// ...................................................................
IOStream* CIOSystemWrapper::Open(const char* pFile,const char* pMode) {
aiFile* p = mFileSystem->OpenProc(mFileSystem,pFile,pMode);
if (!p) {
return NULL;
}
return new CIOStreamWrapper(p, this);
}
// ...................................................................
void CIOSystemWrapper::Close( IOStream* pFile) {
if (!pFile) {
return;
}
delete pFile;
}
}

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -50,106 +51,43 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Assimp { namespace Assimp {
class CIOSystemWrapper;
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Custom IOStream implementation for the C-API // Custom IOStream implementation for the C-API
class CIOStreamWrapper : public IOStream class CIOStreamWrapper : public IOStream
{ {
friend class CIOSystemWrapper;
public: public:
explicit CIOStreamWrapper(aiFile* pFile, CIOSystemWrapper* io)
explicit CIOStreamWrapper(aiFile* pFile) : mFile(pFile),
: mFile(pFile) mIO(io)
{} {}
~CIOStreamWrapper(void);
// ................................................................... size_t Read(void* pvBuffer, size_t pSize, size_t pCount);
size_t Read(void* pvBuffer, size_t Write(const void* pvBuffer, size_t pSize, size_t pCount);
size_t pSize, aiReturn Seek(size_t pOffset, aiOrigin pOrigin);
size_t pCount size_t Tell(void) const;
){ size_t FileSize() const;
// need to typecast here as C has no void* void Flush();
return mFile->ReadProc(mFile,(char*)pvBuffer,pSize,pCount);
}
// ...................................................................
size_t Write(const void* pvBuffer,
size_t pSize,
size_t pCount
){
// need to typecast here as C has no void*
return mFile->WriteProc(mFile,(const char*)pvBuffer,pSize,pCount);
}
// ...................................................................
aiReturn Seek(size_t pOffset,
aiOrigin pOrigin
){
return mFile->SeekProc(mFile,pOffset,pOrigin);
}
// ...................................................................
size_t Tell(void) const {
return mFile->TellProc(mFile);
}
// ...................................................................
size_t FileSize() const {
return mFile->FileSizeProc(mFile);
}
// ...................................................................
void Flush () {
return mFile->FlushProc(mFile);
}
private: private:
aiFile* mFile; aiFile* mFile;
CIOSystemWrapper* mIO;
}; };
// ------------------------------------------------------------------------------------------------
// Custom IOStream implementation for the C-API
class CIOSystemWrapper : public IOSystem class CIOSystemWrapper : public IOSystem
{ {
friend class CIOStreamWrapper;
public: public:
explicit CIOSystemWrapper(aiFileIO* pFile) explicit CIOSystemWrapper(aiFileIO* pFile)
: mFileSystem(pFile) : mFileSystem(pFile)
{} {}
// ................................................................... bool Exists( const char* pFile) const;
bool Exists( const char* pFile) const { char getOsSeparator() const;
aiFile* p = mFileSystem->OpenProc(mFileSystem,pFile,"rb"); IOStream* Open(const char* pFile,const char* pMode = "rb");
if (p){ void Close( IOStream* pFile);
mFileSystem->CloseProc(mFileSystem,p);
return true;
}
return false;
}
// ...................................................................
char getOsSeparator() const {
#ifndef _WIN32
return '/';
#else
return '\\';
#endif
}
// ...................................................................
IOStream* Open(const char* pFile,const char* pMode = "rb") {
aiFile* p = mFileSystem->OpenProc(mFileSystem,pFile,pMode);
if (!p) {
return NULL;
}
return new CIOStreamWrapper(p);
}
// ...................................................................
void Close( IOStream* pFile) {
if (!pFile) {
return;
}
mFileSystem->CloseProc(mFileSystem,((CIOStreamWrapper*) pFile)->mFile);
delete pFile;
}
private: private:
aiFileIO* mFileSystem; aiFileIO* mFileSystem;
}; };

View File

@ -1,7 +1,8 @@
# Open Asset Import Library (assimp) # Open Asset Import Library (assimp)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# #
# Copyright (c) 2006-2016, assimp team # Copyright (c) 2006-2017, assimp team
# All rights reserved. # All rights reserved.
# #
# Redistribution and use of this software in source and binary forms, # Redistribution and use of this software in source and binary forms,
@ -58,7 +59,7 @@ SET( PUBLIC_HEADERS
${HEADER_PATH}/camera.h ${HEADER_PATH}/camera.h
${HEADER_PATH}/color4.h ${HEADER_PATH}/color4.h
${HEADER_PATH}/color4.inl ${HEADER_PATH}/color4.inl
${HEADER_PATH}/config.h ${CMAKE_CURRENT_BINARY_DIR}/../include/assimp/config.h
${HEADER_PATH}/defs.h ${HEADER_PATH}/defs.h
${HEADER_PATH}/cfileio.h ${HEADER_PATH}/cfileio.h
${HEADER_PATH}/light.h ${HEADER_PATH}/light.h
@ -93,6 +94,8 @@ SET( PUBLIC_HEADERS
${HEADER_PATH}/NullLogger.hpp ${HEADER_PATH}/NullLogger.hpp
${HEADER_PATH}/cexport.h ${HEADER_PATH}/cexport.h
${HEADER_PATH}/Exporter.hpp ${HEADER_PATH}/Exporter.hpp
${HEADER_PATH}/DefaultIOStream.h
${HEADER_PATH}/DefaultIOSystem.h
) )
SET( Core_SRCS SET( Core_SRCS
@ -125,9 +128,8 @@ SET( Common_SRCS
ByteSwapper.h ByteSwapper.h
DefaultProgressHandler.h DefaultProgressHandler.h
DefaultIOStream.cpp DefaultIOStream.cpp
DefaultIOStream.h
DefaultIOSystem.cpp DefaultIOSystem.cpp
DefaultIOSystem.h CInterfaceIOWrapper.cpp
CInterfaceIOWrapper.h CInterfaceIOWrapper.h
Hash.h Hash.h
Importer.cpp Importer.cpp
@ -162,6 +164,7 @@ SET( Common_SRCS
RemoveComments.h RemoveComments.h
Subdivision.cpp Subdivision.cpp
Subdivision.h Subdivision.h
scene.cpp
Vertex.h Vertex.h
LineSplitter.h LineSplitter.h
TinyFormatter.h TinyFormatter.h
@ -171,6 +174,9 @@ SET( Common_SRCS
Bitmap.h Bitmap.h
XMLTools.h XMLTools.h
Version.cpp Version.cpp
IOStreamBuffer.h
CreateAnimMesh.h
CreateAnimMesh.cpp
) )
SOURCE_GROUP(Common FILES ${Common_SRCS}) SOURCE_GROUP(Common FILES ${Common_SRCS})
@ -182,10 +188,16 @@ IF ( ASSIMP_BUILD_NONFREE_C4D_IMPORTER )
SOURCE_GROUP( C4D FILES ${C4D_SRCS}) SOURCE_GROUP( C4D FILES ${C4D_SRCS})
ENDIF ( ASSIMP_BUILD_NONFREE_C4D_IMPORTER ) ENDIF ( ASSIMP_BUILD_NONFREE_C4D_IMPORTER )
# if this variable is set to TRUE, the user can manually disable importers by setting
# ASSIMP_BUILD_XXX_IMPORTER to FALSE for each importer
# if this variable is set to FALSE, the user can manually enable importers by setting
# ASSIMP_BUILD_XXX_IMPORTER to TRUE for each importer
OPTION(ASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT "default value of all ASSIMP_BUILD_XXX_IMPORTER value" TRUE)
# macro to add the CMake Option ADD_ASSIMP_IMPORTER_<name> which enables compile of loader # macro to add the CMake Option ADD_ASSIMP_IMPORTER_<name> which enables compile of loader
# this way selective loaders can be compiled (reduces filesize + compile time) # this way selective loaders can be compiled (reduces filesize + compile time)
MACRO(ADD_ASSIMP_IMPORTER name) MACRO(ADD_ASSIMP_IMPORTER name)
OPTION(ASSIMP_BUILD_${name}_IMPORTER "build the ${name} importer" TRUE) OPTION(ASSIMP_BUILD_${name}_IMPORTER "build the ${name} importer" ${ASSIMP_BUILD_ALL_IMPORTERS_BY_DEFAULT})
IF(ASSIMP_BUILD_${name}_IMPORTER) IF(ASSIMP_BUILD_${name}_IMPORTER)
LIST(APPEND ASSIMP_LOADER_SRCS ${ARGN}) LIST(APPEND ASSIMP_LOADER_SRCS ${ARGN})
SET(ASSIMP_IMPORTERS_ENABLED "${ASSIMP_IMPORTERS_ENABLED} ${name}") SET(ASSIMP_IMPORTERS_ENABLED "${ASSIMP_IMPORTERS_ENABLED} ${name}")
@ -195,6 +207,7 @@ MACRO(ADD_ASSIMP_IMPORTER name)
SET(${name}_SRC "") SET(${name}_SRC "")
SET(ASSIMP_IMPORTERS_DISABLED "${ASSIMP_IMPORTERS_DISABLED} ${name}") SET(ASSIMP_IMPORTERS_DISABLED "${ASSIMP_IMPORTERS_DISABLED} ${name}")
add_definitions(-DASSIMP_BUILD_NO_${name}_IMPORTER) add_definitions(-DASSIMP_BUILD_NO_${name}_IMPORTER)
add_definitions(-DASSIMP_BUILD_NO_${name}_EXPORTER)
ENDIF() ENDIF()
ENDMACRO() ENDMACRO()
@ -202,6 +215,16 @@ SET(ASSIMP_LOADER_SRCS "")
SET(ASSIMP_IMPORTERS_ENABLED "") # list of enabled importers SET(ASSIMP_IMPORTERS_ENABLED "") # list of enabled importers
SET(ASSIMP_IMPORTERS_DISABLED "") # disabled list (used to print) SET(ASSIMP_IMPORTERS_DISABLED "") # disabled list (used to print)
ADD_ASSIMP_IMPORTER( AMF
AMFImporter.hpp
AMFImporter_Macro.hpp
AMFImporter_Node.hpp
AMFImporter.cpp
AMFImporter_Geometry.cpp
AMFImporter_Material.cpp
AMFImporter_Postprocess.cpp
)
ADD_ASSIMP_IMPORTER( 3DS ADD_ASSIMP_IMPORTER( 3DS
3DSConverter.cpp 3DSConverter.cpp
3DSHelper.h 3DSHelper.h
@ -433,7 +456,8 @@ ADD_ASSIMP_IMPORTER( BLEND
ADD_ASSIMP_IMPORTER( IFC ADD_ASSIMP_IMPORTER( IFC
IFCLoader.cpp IFCLoader.cpp
IFCLoader.h IFCLoader.h
IFCReaderGen.cpp IFCReaderGen1.cpp
IFCReaderGen2.cpp
IFCReaderGen.h IFCReaderGen.h
IFCUtil.h IFCUtil.h
IFCUtil.cpp IFCUtil.cpp
@ -449,9 +473,13 @@ ADD_ASSIMP_IMPORTER( IFC
STEPFileEncoding.cpp STEPFileEncoding.cpp
STEPFileEncoding.h STEPFileEncoding.h
) )
if (MSVC AND ASSIMP_BUILD_IFC_IMPORTER) if (ASSIMP_BUILD_IFC_IMPORTER)
set_source_files_properties(IFCReaderGen.cpp PROPERTIES COMPILE_FLAGS "/bigobj") if (MSVC)
endif (MSVC AND ASSIMP_BUILD_IFC_IMPORTER) set_source_files_properties(IFCReaderGen1.cpp IFCReaderGen2.cpp PROPERTIES COMPILE_FLAGS "/bigobj")
elseif(CMAKE_COMPILER_IS_MINGW)
set_source_files_properties(IFCReaderGen1.cpp IFCReaderGen2.cpp PROPERTIES COMPILE_FLAGS "-O2 -Wa,-mbig-obj")
endif()
endif (ASSIMP_BUILD_IFC_IMPORTER)
ADD_ASSIMP_IMPORTER( XGL ADD_ASSIMP_IMPORTER( XGL
XGLLoader.cpp XGLLoader.cpp
@ -542,6 +570,9 @@ SET( PostProcessing_SRCS
) )
SOURCE_GROUP( PostProcessing FILES ${PostProcessing_SRCS}) SOURCE_GROUP( PostProcessing FILES ${PostProcessing_SRCS})
SET( IrrXML_SRCS irrXMLWrapper.h )
SOURCE_GROUP( IrrXML FILES ${IrrXML_SRCS})
ADD_ASSIMP_IMPORTER( Q3D ADD_ASSIMP_IMPORTER( Q3D
Q3DLoader.cpp Q3DLoader.cpp
Q3DLoader.h Q3DLoader.h
@ -599,6 +630,25 @@ ADD_ASSIMP_IMPORTER( X
XFileExporter.cpp XFileExporter.cpp
) )
ADD_ASSIMP_IMPORTER(X3D
X3DExporter.cpp
X3DExporter.hpp
X3DImporter.cpp
X3DImporter.hpp
X3DImporter_Geometry2D.cpp
X3DImporter_Geometry3D.cpp
X3DImporter_Group.cpp
X3DImporter_Light.cpp
X3DImporter_Macro.hpp
X3DImporter_Metadata.cpp
X3DImporter_Networking.cpp
X3DImporter_Node.hpp
X3DImporter_Postprocess.cpp
X3DImporter_Rendering.cpp
X3DImporter_Shape.cpp
X3DImporter_Texturing.cpp
)
ADD_ASSIMP_IMPORTER( GLTF ADD_ASSIMP_IMPORTER( GLTF
glTFAsset.h glTFAsset.h
glTFAsset.inl glTFAsset.inl
@ -610,7 +660,6 @@ ADD_ASSIMP_IMPORTER( GLTF
glTFExporter.cpp glTFExporter.cpp
) )
ADD_ASSIMP_IMPORTER( 3MF ADD_ASSIMP_IMPORTER( 3MF
D3MFImporter.h D3MFImporter.h
D3MFImporter.cpp D3MFImporter.cpp
@ -618,6 +667,15 @@ ADD_ASSIMP_IMPORTER( 3MF
D3MFOpcPackage.cpp D3MFOpcPackage.cpp
) )
ADD_ASSIMP_IMPORTER( MMD
MMDCpp14.h
MMDImporter.cpp
MMDImporter.h
MMDPmdParser.h
MMDPmxParser.h
MMDPmxParser.cpp
MMDVmdParser.h
)
SET( Step_SRCS SET( Step_SRCS
StepExporter.h StepExporter.h
@ -637,23 +695,6 @@ SET( Extra_SRCS
) )
SOURCE_GROUP( Extra FILES ${Extra_SRCS}) SOURCE_GROUP( Extra FILES ${Extra_SRCS})
SET( IrrXML_SRCS
irrXMLWrapper.h
../contrib/irrXML/CXMLReaderImpl.h
../contrib/irrXML/heapsort.h
../contrib/irrXML/irrArray.h
../contrib/irrXML/irrString.h
../contrib/irrXML/irrTypes.h
../contrib/irrXML/irrXML.cpp
../contrib/irrXML/irrXML.h
)
SOURCE_GROUP( IrrXML FILES ${IrrXML_SRCS})
SET( ConvertUTF_SRCS
../contrib/ConvertUTF/ConvertUTF.h
../contrib/ConvertUTF/ConvertUTF.c
)
SOURCE_GROUP( ConvertUTF FILES ${ConvertUTF_SRCS})
SET( Clipper_SRCS SET( Clipper_SRCS
../contrib/clipper/clipper.hpp ../contrib/clipper/clipper.hpp
@ -661,7 +702,6 @@ SET( Clipper_SRCS
) )
SOURCE_GROUP( Clipper FILES ${Clipper_SRCS}) SOURCE_GROUP( Clipper FILES ${Clipper_SRCS})
SET( Poly2Tri_SRCS SET( Poly2Tri_SRCS
../contrib/poly2tri/poly2tri/common/shapes.cc ../contrib/poly2tri/poly2tri/common/shapes.cc
../contrib/poly2tri/poly2tri/common/shapes.h ../contrib/poly2tri/poly2tri/common/shapes.h
@ -701,7 +741,54 @@ SET ( openddl_parser_SRCS
) )
SOURCE_GROUP( openddl_parser FILES ${openddl_parser_SRCS}) SOURCE_GROUP( openddl_parser FILES ${openddl_parser_SRCS})
SET ( open3dgc_SRCS
../contrib/Open3DGC/o3dgcAdjacencyInfo.h
../contrib/Open3DGC/o3dgcArithmeticCodec.cpp
../contrib/Open3DGC/o3dgcArithmeticCodec.h
../contrib/Open3DGC/o3dgcBinaryStream.h
../contrib/Open3DGC/o3dgcCommon.h
../contrib/Open3DGC/o3dgcDVEncodeParams.h
../contrib/Open3DGC/o3dgcDynamicVectorDecoder.cpp
../contrib/Open3DGC/o3dgcDynamicVectorDecoder.h
../contrib/Open3DGC/o3dgcDynamicVectorEncoder.cpp
../contrib/Open3DGC/o3dgcDynamicVectorEncoder.h
../contrib/Open3DGC/o3dgcDynamicVector.h
../contrib/Open3DGC/o3dgcFIFO.h
../contrib/Open3DGC/o3dgcIndexedFaceSet.h
../contrib/Open3DGC/o3dgcIndexedFaceSet.inl
../contrib/Open3DGC/o3dgcSC3DMCDecoder.h
../contrib/Open3DGC/o3dgcSC3DMCDecoder.inl
../contrib/Open3DGC/o3dgcSC3DMCEncodeParams.h
../contrib/Open3DGC/o3dgcSC3DMCEncoder.h
../contrib/Open3DGC/o3dgcSC3DMCEncoder.inl
../contrib/Open3DGC/o3dgcTimer.h
../contrib/Open3DGC/o3dgcTools.cpp
../contrib/Open3DGC/o3dgcTriangleFans.cpp
../contrib/Open3DGC/o3dgcTriangleFans.h
../contrib/Open3DGC/o3dgcTriangleListDecoder.h
../contrib/Open3DGC/o3dgcTriangleListDecoder.inl
../contrib/Open3DGC/o3dgcTriangleListEncoder.h
../contrib/Open3DGC/o3dgcTriangleListEncoder.inl
../contrib/Open3DGC/o3dgcVector.h
../contrib/Open3DGC/o3dgcVector.inl
)
SOURCE_GROUP( open3dgc FILES ${open3dgc_SRCS})
# Check dependencies for glTF importer with Open3DGC-compression.
# RT-extensions is used in "contrib/Open3DGC/o3dgcTimer.h" for collecting statistics. Pointed file
# has implementation for different platforms: WIN32, __MACH__ and other ("else" block).
FIND_PACKAGE(RT QUIET)
IF (RT_FOUND OR MSVC)
SET( ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC 1 )
ADD_DEFINITIONS( -DASSIMP_IMPORTER_GLTF_USE_OPEN3DGC=1 )
ELSE ()
SET (open3dgc_SRCS "")
MESSAGE (INFO " RT-extension not found. glTF import/export will be built without Open3DGC-compression.")
#!TODO: off course is better to remove statistics timers from o3dgc codec. Or propose to choose what to use.
ENDIF ()
INCLUDE_DIRECTORIES( "../contrib/rapidjson/include" ) INCLUDE_DIRECTORIES( "../contrib/rapidjson/include" )
INCLUDE_DIRECTORIES( "../contrib" )
# VC2010 fixes # VC2010 fixes
if(MSVC10) if(MSVC10)
@ -722,6 +809,7 @@ if (UNZIP_FOUND)
SET (unzip_compile_SRCS "") SET (unzip_compile_SRCS "")
else (UNZIP_FOUND) else (UNZIP_FOUND)
SET (unzip_compile_SRCS ${unzip_SRCS}) SET (unzip_compile_SRCS ${unzip_SRCS})
INCLUDE_DIRECTORIES( "../contrib/unzip/" )
endif (UNZIP_FOUND) endif (UNZIP_FOUND)
MESSAGE(STATUS "Enabled formats:${ASSIMP_IMPORTERS_ENABLED}") MESSAGE(STATUS "Enabled formats:${ASSIMP_IMPORTERS_ENABLED}")
@ -742,11 +830,11 @@ SET( assimp_src
# Third-party libraries # Third-party libraries
${IrrXML_SRCS} ${IrrXML_SRCS}
${ConvertUTF_SRCS}
${unzip_compile_SRCS} ${unzip_compile_SRCS}
${Poly2Tri_SRCS} ${Poly2Tri_SRCS}
${Clipper_SRCS} ${Clipper_SRCS}
${openddl_parser_SRCS} ${openddl_parser_SRCS}
${open3dgc_SRCS}
# Necessary to show the headers in the project when using the VC++ generator: # Necessary to show the headers in the project when using the VC++ generator:
${PUBLIC_HEADERS} ${PUBLIC_HEADERS}
@ -756,7 +844,8 @@ SET( assimp_src
ADD_DEFINITIONS( -DOPENDDLPARSER_BUILD ) ADD_DEFINITIONS( -DOPENDDLPARSER_BUILD )
INCLUDE_DIRECTORIES( INCLUDE_DIRECTORIES(
../contrib/openddlparser/include ${IRRXML_INCLUDE_DIR}
../contrib/openddlparser/include
) )
IF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER) IF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER)
@ -766,7 +855,7 @@ ENDIF (ASSIMP_BUILD_NONFREE_C4D_IMPORTER)
ADD_LIBRARY( assimp ${assimp_src} ) ADD_LIBRARY( assimp ${assimp_src} )
TARGET_LINK_LIBRARIES(assimp ${ZLIB_LIBRARIES} ${OPENDDL_PARSER_LIBRARIES} ) TARGET_LINK_LIBRARIES(assimp ${ZLIB_LIBRARIES} ${OPENDDL_PARSER_LIBRARIES} ${IRRXML_LIBRARY} )
if(ANDROID AND ASSIMP_ANDROID_JNIIOSYSTEM) if(ANDROID AND ASSIMP_ANDROID_JNIIOSYSTEM)
set(ASSIMP_ANDROID_JNIIOSYSTEM_PATH port/AndroidJNI) set(ASSIMP_ANDROID_JNIIOSYSTEM_PATH port/AndroidJNI)
@ -821,6 +910,11 @@ else (UNZIP_FOUND)
INCLUDE_DIRECTORIES("../") INCLUDE_DIRECTORIES("../")
endif (UNZIP_FOUND) endif (UNZIP_FOUND)
# Add RT-extension library for glTF importer with Open3DGC-compression.
IF (RT_FOUND AND ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC)
TARGET_LINK_LIBRARIES(assimp ${RT_LIBRARY})
ENDIF (RT_FOUND AND ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC)
INSTALL( TARGETS assimp INSTALL( TARGETS assimp
LIBRARY DESTINATION ${ASSIMP_LIB_INSTALL_DIR} LIBRARY DESTINATION ${ASSIMP_LIB_INSTALL_DIR}
ARCHIVE DESTINATION ${ASSIMP_LIB_INSTALL_DIR} ARCHIVE DESTINATION ${ASSIMP_LIB_INSTALL_DIR}
@ -839,8 +933,20 @@ if(MSVC AND ASSIMP_INSTALL_PDB)
DESTINATION ${ASSIMP_LIB_INSTALL_DIR} DESTINATION ${ASSIMP_LIB_INSTALL_DIR}
CONFIGURATIONS Debug CONFIGURATIONS Debug
) )
install(FILES ${Assimp_BINARY_DIR}/code/RelWithDebInfo/assimp.pdb install(FILES ${Assimp_BINARY_DIR}/code/RelWithDebInfo/assimp${LIBRARY_SUFFIX}.pdb
DESTINATION ${ASSIMP_LIB_INSTALL_DIR} DESTINATION ${ASSIMP_LIB_INSTALL_DIR}
CONFIGURATIONS RelWithDebInfo CONFIGURATIONS RelWithDebInfo
) )
endif () endif ()
if (ASSIMP_COVERALLS)
include(Coveralls)
set(COVERAGE_SRCS ${assimp_src} ${TEST_SRCS} )
# Create the coveralls target.
coveralls_setup(
"${COVERAGE_SRCS}" # The source files.
ON # If we should upload.
"${PROJECT_SOURCE_DIR}/cmake-modules/") # (Optional) Alternate project cmake module path.
endif()

View File

@ -2,7 +2,7 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -57,7 +57,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/IOSystem.hpp> #include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp> #include <assimp/DefaultLogger.hpp>
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/importerdesc.h>
using namespace Assimp; using namespace Assimp;
using namespace Assimp::COB; using namespace Assimp::COB;
@ -181,7 +181,7 @@ void COBImporter::InternReadFile( const std::string& pFile,
if (n->type == Node::TYPE_MESH) { if (n->type == Node::TYPE_MESH) {
Mesh& mesh = (Mesh&)(*n.get()); Mesh& mesh = (Mesh&)(*n.get());
if (mesh.vertex_positions.size() && mesh.texture_coords.size()) { if (mesh.vertex_positions.size() && mesh.texture_coords.size()) {
pScene->mNumMeshes += mesh.temp_map.size(); pScene->mNumMeshes += static_cast<unsigned int>(mesh.temp_map.size());
} }
} }
} }
@ -941,20 +941,22 @@ void COBImporter::UnsupportedChunk_Binary( StreamReaderLE& reader, const ChunkIn
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// tiny utility guard to aid me at staying within chunk boundaries. // tiny utility guard to aid me at staying within chunk boundaries.
class chunk_guard { class chunk_guard {
public: public:
chunk_guard(const COB::ChunkInfo& nfo, StreamReaderLE& reader) chunk_guard(const COB::ChunkInfo& nfo, StreamReaderLE& reader)
: nfo(nfo) : nfo(nfo)
, reader(reader) , reader(reader)
, cur(reader.GetCurrentPos()) , cur(reader.GetCurrentPos()) {
{
} }
~chunk_guard() { ~chunk_guard() {
// don't do anything if the size is not given // don't do anything if the size is not given
if(nfo.size != static_cast<unsigned int>(-1)) { if(nfo.size != static_cast<unsigned int>(-1)) {
reader.IncPtr(static_cast<int>(nfo.size)-reader.GetCurrentPos()+cur); try {
reader.IncPtr( static_cast< int >( nfo.size ) - reader.GetCurrentPos() + cur );
} catch ( DeadlyImportError e ) {
// out of limit so correct the value
reader.IncPtr( reader.GetReadLimit() );
}
} }
} }

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -46,12 +47,13 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <memory> #include <memory>
#include <deque> #include <deque>
#include <map>
#include "BaseImporter.h" #include "BaseImporter.h"
#include "./../include/assimp/material.h" #include <assimp/material.h>
namespace Assimp { namespace Assimp {
namespace COB { namespace COB {
// ------------------ // ------------------
/** Represents a single vertex index in a face */ /** Represents a single vertex index in a face */

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -57,7 +58,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/anim.h> #include <assimp/anim.h>
#include <assimp/DefaultLogger.hpp> #include <assimp/DefaultLogger.hpp>
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/importerdesc.h>
using namespace Assimp; using namespace Assimp;
@ -179,7 +180,7 @@ void CSMImporter::InternReadFile( const std::string& pFile,
nda->mNodeName.length = (size_t)(ot-nda->mNodeName.data); nda->mNodeName.length = (size_t)(ot-nda->mNodeName.data);
} }
anim->mNumChannels = anims_temp.size(); anim->mNumChannels = static_cast<unsigned int>(anims_temp.size());
if (!anim->mNumChannels) if (!anim->mNumChannels)
throw DeadlyImportError("CSM: Empty $order section"); throw DeadlyImportError("CSM: Empty $order section");

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -256,7 +257,7 @@ bool CalcTangentsProcess::ProcessMesh( aiMesh* pMesh, unsigned int meshIndex)
} }
std::vector<unsigned int> verticesFound; std::vector<unsigned int> verticesFound;
const float fLimit = cosf(configMaxAngle); const float fLimit = std::cos(configMaxAngle);
std::vector<unsigned int> closeVertices; std::vector<unsigned int> closeVertices;
// in the second pass we now smooth out all tangents and bitangents at the same local position // in the second pass we now smooth out all tangents and bitangents at the same local position

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -38,17 +39,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
#ifndef ASSIMP_BUILD_NO_EXPORT #ifndef ASSIMP_BUILD_NO_EXPORT
#ifndef ASSIMP_BUILD_NO_COLLADA_EXPORTER #ifndef ASSIMP_BUILD_NO_COLLADA_EXPORTER
#include "ColladaExporter.h"
#include "ColladaExporter.h"
#include "Bitmap.h" #include "Bitmap.h"
#include "fast_atof.h" #include "fast_atof.h"
#include "SceneCombiner.h" #include "SceneCombiner.h"
#include "DefaultIOSystem.h" #include "StringUtils.h"
#include "XMLTools.h" #include "XMLTools.h"
#include <assimp/DefaultIOSystem.h>
#include <assimp/IOSystem.hpp> #include <assimp/IOSystem.hpp>
#include <assimp/Exporter.hpp> #include <assimp/Exporter.hpp>
#include <assimp/scene.h> #include <assimp/scene.h>
@ -58,6 +58,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <memory> #include <memory>
#include <ctime> #include <ctime>
#include <set> #include <set>
#include <vector>
#include <iostream>
using namespace Assimp; using namespace Assimp;
@ -132,6 +134,7 @@ void ColladaExporter::WriteFile()
WriteLightsLibrary(); WriteLightsLibrary();
WriteMaterials(); WriteMaterials();
WriteGeometryLibrary(); WriteGeometryLibrary();
WriteControllerLibrary();
WriteSceneLibrary(); WriteSceneLibrary();
@ -149,7 +152,7 @@ void ColladaExporter::WriteFile()
// Writes the asset header // Writes the asset header
void ColladaExporter::WriteHeader() void ColladaExporter::WriteHeader()
{ {
static const ai_real epsilon = 0.00001; static const ai_real epsilon = ai_real( 0.00001 );
static const aiQuaternion x_rot(aiMatrix3x3( static const aiQuaternion x_rot(aiMatrix3x3(
0, -1, 0, 0, -1, 0,
1, 0, 0, 1, 0, 0,
@ -383,6 +386,7 @@ void ColladaExporter::WriteLight(size_t pIndex){
case aiLightSource_SPOT: case aiLightSource_SPOT:
WriteSpotLight(light); WriteSpotLight(light);
break; break;
case aiLightSource_AREA:
case aiLightSource_UNDEFINED: case aiLightSource_UNDEFINED:
case _aiLightSource_Force32Bit: case _aiLightSource_Force32Bit:
break; break;
@ -523,7 +527,7 @@ void ColladaExporter::ReadMaterialSurface( Surface& poSurface, const aiMaterial*
} else } else
{ {
if( pKey ) if( pKey )
poSurface.exist = pSrcMat->Get( pKey, pType, pIndex, poSurface.color) == aiReturn_SUCCESS; poSurface.exist = pSrcMat->Get( pKey, static_cast<unsigned int>(pType), static_cast<unsigned int>(pIndex), poSurface.color) == aiReturn_SUCCESS;
} }
} }
@ -635,9 +639,24 @@ void ColladaExporter::WriteMaterials()
const aiMaterial* mat = mScene->mMaterials[a]; const aiMaterial* mat = mScene->mMaterials[a];
aiString name; aiString name;
if( mat->Get( AI_MATKEY_NAME, name) != aiReturn_SUCCESS ) if( mat->Get( AI_MATKEY_NAME, name) != aiReturn_SUCCESS ) {
name = "mat"; name = "mat";
materials[a].name = std::string( "m") + std::to_string(a) + name.C_Str(); materials[a].name = std::string( "m") + to_string(a) + name.C_Str();
} else {
// try to use the material's name if no other material has already taken it, else append #
std::string testName = name.C_Str();
size_t materialCountWithThisName = 0;
for( size_t i = 0; i < a; i ++ ) {
if( materials[i].name == testName ) {
materialCountWithThisName ++;
}
}
if( materialCountWithThisName == 0 ) {
materials[a].name = name.C_Str();
} else {
materials[a].name = std::string(name.C_Str()) + to_string(materialCountWithThisName);
}
}
for( std::string::iterator it = materials[a].name.begin(); it != materials[a].name.end(); ++it ) { for( std::string::iterator it = materials[a].name.begin(); it != materials[a].name.end(); ++it ) {
if( !isalnum_C( *it ) ) { if( !isalnum_C( *it ) ) {
*it = '_'; *it = '_';
@ -675,7 +694,6 @@ void ColladaExporter::WriteMaterials()
materials[a].shininess.exist = mat->Get( AI_MATKEY_SHININESS, materials[a].shininess.value) == aiReturn_SUCCESS; materials[a].shininess.exist = mat->Get( AI_MATKEY_SHININESS, materials[a].shininess.value) == aiReturn_SUCCESS;
materials[a].transparency.exist = mat->Get( AI_MATKEY_OPACITY, materials[a].transparency.value) == aiReturn_SUCCESS; materials[a].transparency.exist = mat->Get( AI_MATKEY_OPACITY, materials[a].transparency.value) == aiReturn_SUCCESS;
materials[a].transparency.value = 1 - materials[a].transparency.value;
materials[a].index_refraction.exist = mat->Get( AI_MATKEY_REFRACTI, materials[a].index_refraction.value) == aiReturn_SUCCESS; materials[a].index_refraction.exist = mat->Get( AI_MATKEY_REFRACTI, materials[a].index_refraction.value) == aiReturn_SUCCESS;
} }
@ -770,6 +788,177 @@ void ColladaExporter::WriteMaterials()
} }
} }
// ------------------------------------------------------------------------------------------------
// Writes the controller library
void ColladaExporter::WriteControllerLibrary()
{
mOutput << startstr << "<library_controllers>" << endstr;
PushTag();
for( size_t a = 0; a < mScene->mNumMeshes; ++a)
WriteController( a);
PopTag();
mOutput << startstr << "</library_controllers>" << endstr;
}
// ------------------------------------------------------------------------------------------------
// Writes a skin controller of the given mesh
void ColladaExporter::WriteController( size_t pIndex)
{
const aiMesh* mesh = mScene->mMeshes[pIndex];
const std::string idstr = GetMeshId( pIndex);
const std::string idstrEscaped = XMLEscape(idstr);
if ( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
return;
if ( mesh->mNumBones == 0 )
return;
mOutput << startstr << "<controller id=\"" << idstrEscaped << "-skin\" ";
mOutput << "name=\"skinCluster" << pIndex << "\">"<< endstr;
PushTag();
mOutput << startstr << "<skin source=\"#" << idstrEscaped << "\">" << endstr;
PushTag();
// bind pose matrix
mOutput << startstr << "<bind_shape_matrix>" << endstr;
PushTag();
// I think it is identity in general cases.
aiMatrix4x4 mat;
mOutput << startstr << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << endstr;
mOutput << startstr << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << endstr;
mOutput << startstr << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << endstr;
mOutput << startstr << mat.d1 << " " << mat.d2 << " " << mat.d3 << " " << mat.d4 << endstr;
PopTag();
mOutput << startstr << "</bind_shape_matrix>" << endstr;
mOutput << startstr << "<source id=\"" << idstrEscaped << "-skin-joints\" name=\"" << idstrEscaped << "-skin-joints\">" << endstr;
PushTag();
mOutput << startstr << "<Name_array id=\"" << idstrEscaped << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\">";
for( size_t i = 0; i < mesh->mNumBones; ++i )
mOutput << XMLEscape(mesh->mBones[i]->mName.C_Str()) << " ";
mOutput << "</Name_array>" << endstr;
mOutput << startstr << "<technique_common>" << endstr;
PushTag();
mOutput << startstr << "<accessor source=\"#" << idstrEscaped << "-skin-joints-array\" count=\"" << mesh->mNumBones << "\" stride=\"" << 1 << "\">" << endstr;
PushTag();
mOutput << startstr << "<param name=\"JOINT\" type=\"Name\"></param>" << endstr;
PopTag();
mOutput << startstr << "</accessor>" << endstr;
PopTag();
mOutput << startstr << "</technique_common>" << endstr;
PopTag();
mOutput << startstr << "</source>" << endstr;
std::vector<ai_real> bind_poses;
bind_poses.reserve(mesh->mNumBones * 16);
for( size_t i = 0; i < mesh->mNumBones; ++i)
for( size_t j = 0; j < 4; ++j)
bind_poses.insert(bind_poses.end(), mesh->mBones[i]->mOffsetMatrix[j], mesh->mBones[i]->mOffsetMatrix[j] + 4);
WriteFloatArray( idstr + "-skin-bind_poses", FloatType_Mat4x4, (const ai_real*) bind_poses.data(), bind_poses.size() / 16);
bind_poses.clear();
std::vector<ai_real> skin_weights;
skin_weights.reserve(mesh->mNumVertices * mesh->mNumBones);
for( size_t i = 0; i < mesh->mNumBones; ++i)
for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
skin_weights.push_back(mesh->mBones[i]->mWeights[j].mWeight);
WriteFloatArray( idstr + "-skin-weights", FloatType_Weight, (const ai_real*) skin_weights.data(), skin_weights.size());
skin_weights.clear();
mOutput << startstr << "<joints>" << endstr;
PushTag();
mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstrEscaped << "-skin-joints\"></input>" << endstr;
mOutput << startstr << "<input semantic=\"INV_BIND_MATRIX\" source=\"#" << idstrEscaped << "-skin-bind_poses\"></input>" << endstr;
PopTag();
mOutput << startstr << "</joints>" << endstr;
mOutput << startstr << "<vertex_weights count=\"" << mesh->mNumVertices << "\">" << endstr;
PushTag();
mOutput << startstr << "<input semantic=\"JOINT\" source=\"#" << idstrEscaped << "-skin-joints\" offset=\"0\"></input>" << endstr;
mOutput << startstr << "<input semantic=\"WEIGHT\" source=\"#" << idstrEscaped << "-skin-weights\" offset=\"1\"></input>" << endstr;
mOutput << startstr << "<vcount>";
std::vector<ai_uint> num_influences(mesh->mNumVertices, (ai_uint)0);
for( size_t i = 0; i < mesh->mNumBones; ++i)
for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
++num_influences[mesh->mBones[i]->mWeights[j].mVertexId];
for( size_t i = 0; i < mesh->mNumVertices; ++i)
mOutput << num_influences[i] << " ";
mOutput << "</vcount>" << endstr;
mOutput << startstr << "<v>";
ai_uint joint_weight_indices_length = 0;
std::vector<ai_uint> accum_influences;
accum_influences.reserve(num_influences.size());
for( size_t i = 0; i < num_influences.size(); ++i)
{
accum_influences.push_back(joint_weight_indices_length);
joint_weight_indices_length += num_influences[i];
}
ai_uint weight_index = 0;
std::vector<ai_int> joint_weight_indices(2 * joint_weight_indices_length, (ai_int)-1);
for( size_t i = 0; i < mesh->mNumBones; ++i)
for( size_t j = 0; j < mesh->mBones[i]->mNumWeights; ++j)
{
unsigned int vId = mesh->mBones[i]->mWeights[j].mVertexId;
for( size_t k = 0; k < num_influences[vId]; ++k)
{
if (joint_weight_indices[2 * (accum_influences[vId] + k)] == -1)
{
joint_weight_indices[2 * (accum_influences[vId] + k)] = i;
joint_weight_indices[2 * (accum_influences[vId] + k) + 1] = weight_index;
break;
}
}
++weight_index;
}
for( size_t i = 0; i < joint_weight_indices.size(); ++i)
mOutput << joint_weight_indices[i] << " ";
num_influences.clear();
accum_influences.clear();
joint_weight_indices.clear();
mOutput << "</v>" << endstr;
PopTag();
mOutput << startstr << "</vertex_weights>" << endstr;
PopTag();
mOutput << startstr << "</skin>" << endstr;
PopTag();
mOutput << startstr << "</controller>" << endstr;
}
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Writes the geometry library // Writes the geometry library
void ColladaExporter::WriteGeometryLibrary() void ColladaExporter::WriteGeometryLibrary()
@ -792,8 +981,8 @@ void ColladaExporter::WriteGeometry( size_t pIndex)
const std::string idstr = GetMeshId( pIndex); const std::string idstr = GetMeshId( pIndex);
const std::string idstrEscaped = XMLEscape(idstr); const std::string idstrEscaped = XMLEscape(idstr);
if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 ) if ( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
return; return;
// opening tag // opening tag
mOutput << startstr << "<geometry id=\"" << idstrEscaped << "\" name=\"" << idstrEscaped << "_name\" >" << endstr; mOutput << startstr << "<geometry id=\"" << idstrEscaped << "\" name=\"" << idstrEscaped << "_name\" >" << endstr;
@ -811,9 +1000,9 @@ void ColladaExporter::WriteGeometry( size_t pIndex)
// texture coords // texture coords
for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
{ {
if( mesh->HasTextureCoords( a) ) if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
{ {
WriteFloatArray( idstr + "-tex" + std::to_string(a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2, WriteFloatArray( idstr + "-tex" + to_string(a), mesh->mNumUVComponents[a] == 3 ? FloatType_TexCoord3 : FloatType_TexCoord2,
(ai_real*) mesh->mTextureCoords[a], mesh->mNumVertices); (ai_real*) mesh->mTextureCoords[a], mesh->mNumVertices);
} }
} }
@ -821,27 +1010,15 @@ void ColladaExporter::WriteGeometry( size_t pIndex)
// vertex colors // vertex colors
for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a) for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a)
{ {
if( mesh->HasVertexColors( a) ) if( mesh->HasVertexColors(static_cast<unsigned int>(a)) )
WriteFloatArray( idstr + "-color" + std::to_string(a), FloatType_Color, (ai_real*) mesh->mColors[a], mesh->mNumVertices); WriteFloatArray( idstr + "-color" + to_string(a), FloatType_Color, (ai_real*) mesh->mColors[a], mesh->mNumVertices);
} }
// assemble vertex structure // assemble vertex structure
// Only write input for POSITION since we will write other as shared inputs in polygon definition
mOutput << startstr << "<vertices id=\"" << idstrEscaped << "-vertices" << "\">" << endstr; mOutput << startstr << "<vertices id=\"" << idstrEscaped << "-vertices" << "\">" << endstr;
PushTag(); PushTag();
mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << idstrEscaped << "-positions\" />" << endstr; mOutput << startstr << "<input semantic=\"POSITION\" source=\"#" << idstrEscaped << "-positions\" />" << endstr;
if( mesh->HasNormals() )
mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << idstrEscaped << "-normals\" />" << endstr;
for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
{
if( mesh->HasTextureCoords( a) )
mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" " /*<< "set=\"" << a << "\"" */ << " />" << endstr;
}
for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
{
if( mesh->HasVertexColors( a) )
mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << idstrEscaped << "-color" << a << "\" " /*<< set=\"" << a << "\"" */ << " />" << endstr;
}
PopTag(); PopTag();
mOutput << startstr << "</vertices>" << endstr; mOutput << startstr << "</vertices>" << endstr;
@ -860,6 +1037,19 @@ void ColladaExporter::WriteGeometry( size_t pIndex)
mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr; mOutput << startstr << "<lines count=\"" << countLines << "\" material=\"defaultMaterial\">" << endstr;
PushTag(); PushTag();
mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr; mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
if( mesh->HasNormals() )
mOutput << startstr << "<input semantic=\"NORMAL\" source=\"#" << idstrEscaped << "-normals\" />" << endstr;
for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
{
if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
mOutput << startstr << "<input semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
}
for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
{
if( mesh->HasVertexColors(static_cast<unsigned int>(a) ) )
mOutput << startstr << "<input semantic=\"COLOR\" source=\"#" << idstrEscaped << "-color" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
}
mOutput << startstr << "<p>"; mOutput << startstr << "<p>";
for( size_t a = 0; a < mesh->mNumFaces; ++a ) for( size_t a = 0; a < mesh->mNumFaces; ++a )
{ {
@ -881,10 +1071,17 @@ void ColladaExporter::WriteGeometry( size_t pIndex)
mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr; mOutput << startstr << "<polylist count=\"" << countPoly << "\" material=\"defaultMaterial\">" << endstr;
PushTag(); PushTag();
mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr; mOutput << startstr << "<input offset=\"0\" semantic=\"VERTEX\" source=\"#" << idstrEscaped << "-vertices\" />" << endstr;
if( mesh->HasNormals() )
mOutput << startstr << "<input offset=\"0\" semantic=\"NORMAL\" source=\"#" << idstrEscaped << "-normals\" />" << endstr;
for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a ) for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
{ {
if( mesh->HasTextureCoords( a) ) if( mesh->HasTextureCoords(static_cast<unsigned int>(a)) )
mOutput << startstr << "<input offset=\"0\" semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" set=\"" << a << "\" />" << endstr; mOutput << startstr << "<input offset=\"0\" semantic=\"TEXCOORD\" source=\"#" << idstrEscaped << "-tex" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
}
for( size_t a = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; ++a )
{
if( mesh->HasVertexColors(static_cast<unsigned int>(a) ) )
mOutput << startstr << "<input offset=\"0\" semantic=\"COLOR\" source=\"#" << idstrEscaped << "-color" << a << "\" " << "set=\"" << a << "\"" << " />" << endstr;
} }
mOutput << startstr << "<vcount>"; mOutput << startstr << "<vcount>";
@ -926,6 +1123,8 @@ void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataTy
case FloatType_TexCoord2: floatsPerElement = 2; break; case FloatType_TexCoord2: floatsPerElement = 2; break;
case FloatType_TexCoord3: floatsPerElement = 3; break; case FloatType_TexCoord3: floatsPerElement = 3; break;
case FloatType_Color: floatsPerElement = 3; break; case FloatType_Color: floatsPerElement = 3; break;
case FloatType_Mat4x4: floatsPerElement = 16; break;
case FloatType_Weight: floatsPerElement = 1; break;
default: default:
return; return;
} }
@ -994,6 +1193,14 @@ void ColladaExporter::WriteFloatArray( const std::string& pIdString, FloatDataTy
mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr; mOutput << startstr << "<param name=\"G\" type=\"float\" />" << endstr;
mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr; mOutput << startstr << "<param name=\"B\" type=\"float\" />" << endstr;
break; break;
case FloatType_Mat4x4:
mOutput << startstr << "<param name=\"TRANSFORM\" type=\"float4x4\" />" << endstr;
break;
case FloatType_Weight:
mOutput << startstr << "<param name=\"WEIGHT\" type=\"float\" />" << endstr;
break;
} }
PopTag(); PopTag();
@ -1055,16 +1262,24 @@ void ColladaExporter::WriteNode( const aiScene* pScene, aiNode* pNode)
// If the node is associated with a bone, it is a joint node (JOINT) // If the node is associated with a bone, it is a joint node (JOINT)
// otherwise it is a normal node (NODE) // otherwise it is a normal node (NODE)
const char * node_type; const char * node_type;
bool is_joint, is_skeleton_root = false;
if (NULL == findBone(pScene, pNode->mName.C_Str())) { if (NULL == findBone(pScene, pNode->mName.C_Str())) {
node_type = "NODE"; node_type = "NODE";
is_joint = false;
} else { } else {
node_type = "JOINT"; node_type = "JOINT";
is_joint = true;
if(!pNode->mParent || NULL == findBone(pScene, pNode->mParent->mName.C_Str()))
is_skeleton_root = true;
} }
const std::string node_name_escaped = XMLEscape(pNode->mName.data); const std::string node_name_escaped = XMLEscape(pNode->mName.data);
mOutput << startstr mOutput << startstr
<< "<node id=\"" << node_name_escaped << "<node ";
<< "\" name=\"" << node_name_escaped if(is_skeleton_root)
mOutput << "id=\"" << "skeleton_root" << "\" "; // For now, only support one skeleton in a scene.
mOutput << (is_joint ? "s" : "") << "id=\"" << node_name_escaped;
mOutput << "\" name=\"" << node_name_escaped
<< "\" type=\"" << node_type << "\" type=\"" << node_type
<< "\">" << endstr; << "\">" << endstr;
PushTag(); PushTag();
@ -1072,7 +1287,7 @@ void ColladaExporter::WriteNode( const aiScene* pScene, aiNode* pNode)
// write transformation - we can directly put the matrix there // write transformation - we can directly put the matrix there
// TODO: (thom) decompose into scale - rot - quad to allow addressing it by animations afterwards // TODO: (thom) decompose into scale - rot - quad to allow addressing it by animations afterwards
const aiMatrix4x4& mat = pNode->mTransformation; const aiMatrix4x4& mat = pNode->mTransformation;
mOutput << startstr << "<matrix>"; mOutput << startstr << "<matrix sid=\"transform\">";
mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " "; mOutput << mat.a1 << " " << mat.a2 << " " << mat.a3 << " " << mat.a4 << " ";
mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " "; mOutput << mat.b1 << " " << mat.b2 << " " << mat.b3 << " " << mat.b4 << " ";
mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " "; mOutput << mat.c1 << " " << mat.c2 << " " << mat.c3 << " " << mat.c4 << " ";
@ -1100,33 +1315,50 @@ void ColladaExporter::WriteNode( const aiScene* pScene, aiNode* pNode)
for( size_t a = 0; a < pNode->mNumMeshes; ++a ) for( size_t a = 0; a < pNode->mNumMeshes; ++a )
{ {
const aiMesh* mesh = mScene->mMeshes[pNode->mMeshes[a]]; const aiMesh* mesh = mScene->mMeshes[pNode->mMeshes[a]];
// do not instanciate mesh if empty. I wonder how this could happen // do not instanciate mesh if empty. I wonder how this could happen
if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 ) if( mesh->mNumFaces == 0 || mesh->mNumVertices == 0 )
continue; continue;
mOutput << startstr << "<instance_geometry url=\"#" << XMLEscape(GetMeshId( pNode->mMeshes[a])) << "\">" << endstr;
PushTag(); if( mesh->mNumBones == 0 )
mOutput << startstr << "<bind_material>" << endstr; {
PushTag(); mOutput << startstr << "<instance_geometry url=\"#" << XMLEscape(GetMeshId( pNode->mMeshes[a])) << "\">" << endstr;
mOutput << startstr << "<technique_common>" << endstr; PushTag();
PushTag(); }
mOutput << startstr << "<instance_material symbol=\"defaultMaterial\" target=\"#" << XMLEscape(materials[mesh->mMaterialIndex].name) << "\">" << endstr; else
PushTag(); {
for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a ) mOutput << startstr
{ << "<instance_controller url=\"#" << XMLEscape(GetMeshId( pNode->mMeshes[a])) << "-skin\">"
if( mesh->HasTextureCoords( a) ) << endstr;
// semantic as in <texture texcoord=...> PushTag();
// input_semantic as in <input semantic=...>
// input_set as in <input set=...> mOutput << startstr << "<skeleton>#skeleton_root</skeleton>" << endstr;
mOutput << startstr << "<bind_vertex_input semantic=\"CHANNEL" << a << "\" input_semantic=\"TEXCOORD\" input_set=\"" << a << "\"/>" << endstr; }
} mOutput << startstr << "<bind_material>" << endstr;
PopTag(); PushTag();
mOutput << startstr << "</instance_material>" << endstr; mOutput << startstr << "<technique_common>" << endstr;
PopTag(); PushTag();
mOutput << startstr << "</technique_common>" << endstr; mOutput << startstr << "<instance_material symbol=\"defaultMaterial\" target=\"#" << XMLEscape(materials[mesh->mMaterialIndex].name) << "\">" << endstr;
PopTag(); PushTag();
mOutput << startstr << "</bind_material>" << endstr; for( size_t a = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++a )
PopTag(); {
mOutput << startstr << "</instance_geometry>" << endstr; if( mesh->HasTextureCoords( static_cast<unsigned int>(a) ) )
// semantic as in <texture texcoord=...>
// input_semantic as in <input semantic=...>
// input_set as in <input set=...>
mOutput << startstr << "<bind_vertex_input semantic=\"CHANNEL" << a << "\" input_semantic=\"TEXCOORD\" input_set=\"" << a << "\"/>" << endstr;
}
PopTag();
mOutput << startstr << "</instance_material>" << endstr;
PopTag();
mOutput << startstr << "</technique_common>" << endstr;
PopTag();
mOutput << startstr << "</bind_material>" << endstr;
PopTag();
if( mesh->mNumBones == 0)
mOutput << startstr << "</instance_geometry>" << endstr;
else
mOutput << startstr << "</instance_controller>" << endstr;
} }
// recurse into subnodes // recurse into subnodes

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -53,6 +54,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <vector> #include <vector>
#include <map> #include <map>
#include "StringUtils.h"
struct aiScene; struct aiScene;
struct aiNode; struct aiNode;
@ -99,13 +102,19 @@ protected:
void WriteSpotLight(const aiLight *const light); void WriteSpotLight(const aiLight *const light);
void WriteAmbienttLight(const aiLight *const light); void WriteAmbienttLight(const aiLight *const light);
/// Writes the controller library
void WriteControllerLibrary();
/// Writes a skin controller of the given mesh
void WriteController( size_t pIndex);
/// Writes the geometry library /// Writes the geometry library
void WriteGeometryLibrary(); void WriteGeometryLibrary();
/// Writes the given mesh /// Writes the given mesh
void WriteGeometry( size_t pIndex); void WriteGeometry( size_t pIndex);
enum FloatDataType { FloatType_Vector, FloatType_TexCoord2, FloatType_TexCoord3, FloatType_Color }; enum FloatDataType { FloatType_Vector, FloatType_TexCoord2, FloatType_TexCoord3, FloatType_Color, FloatType_Mat4x4, FloatType_Weight };
/// Writes a float array of the given type /// Writes a float array of the given type
void WriteFloatArray( const std::string& pIdString, FloatDataType pType, const ai_real* pData, size_t pElementCount); void WriteFloatArray( const std::string& pIdString, FloatDataType pType, const ai_real* pData, size_t pElementCount);
@ -122,7 +131,9 @@ protected:
void PopTag() { ai_assert( startstr.length() > 1); startstr.erase( startstr.length() - 2); } void PopTag() { ai_assert( startstr.length() > 1); startstr.erase( startstr.length() - 2); }
/// Creates a mesh ID for the given mesh /// Creates a mesh ID for the given mesh
std::string GetMeshId( size_t pIndex) const { return std::string( "meshId" ) + std::to_string(pIndex); } std::string GetMeshId( size_t pIndex) const {
return std::string( "meshId" ) + to_string(pIndex);
}
public: public:
/// Stringstream to write all output into /// Stringstream to write all output into

View File

@ -4,7 +4,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -43,7 +44,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef AI_COLLADAHELPER_H_INC #ifndef AI_COLLADAHELPER_H_INC
#define AI_COLLADAHELPER_H_INC #define AI_COLLADAHELPER_H_INC
#include <string>
#include <map> #include <map>
#include <vector> #include <vector>
#include <stdint.h> #include <stdint.h>
@ -89,6 +89,21 @@ enum InputType
IT_Bitangent IT_Bitangent
}; };
/** Supported controller types */
enum ControllerType
{
Skin,
Morph
};
/** Supported morph methods */
enum MorphMethod
{
Normalized,
Relative
};
/** Contains all data for one of the different transformation types */ /** Contains all data for one of the different transformation types */
struct Transform struct Transform
{ {
@ -380,6 +395,12 @@ enum PrimitiveType
/** A skeleton controller to deform a mesh with the use of joints */ /** A skeleton controller to deform a mesh with the use of joints */
struct Controller struct Controller
{ {
// controller type
ControllerType mType;
// Morphing method if type is Morph
MorphMethod mMethod;
// the URL of the mesh deformed by the controller. // the URL of the mesh deformed by the controller.
std::string mMeshId; std::string mMeshId;
@ -402,6 +423,9 @@ struct Controller
// JointIndex-WeightIndex pairs for all vertices // JointIndex-WeightIndex pairs for all vertices
std::vector< std::pair<size_t, size_t> > mWeights; std::vector< std::pair<size_t, size_t> > mWeights;
std::string mMorphTarget;
std::string mMorphWeight;
}; };
/** A collada material. Pretty much the only member is a reference to an effect. */ /** A collada material. Pretty much the only member is a reference to an effect. */
@ -577,6 +601,12 @@ struct AnimationChannel
std::string mSourceTimes; std::string mSourceTimes;
/** Source URL of the value values. Collada calls them "output". */ /** Source URL of the value values. Collada calls them "output". */
std::string mSourceValues; std::string mSourceValues;
/** Source URL of the IN_TANGENT semantic values. */
std::string mInTanValues;
/** Source URL of the OUT_TANGENT semantic values. */
std::string mOutTanValues;
/** Source URL of the INTERPOLATION semantic values. */
std::string mInterpolationValues;
}; };
/** An animation. Container for 0-x animation channels or 0-x animations */ /** An animation. Container for 0-x animation channels or 0-x animations */
@ -645,6 +675,7 @@ struct Animation
struct ChannelEntry struct ChannelEntry
{ {
const Collada::AnimationChannel* mChannel; ///> the source channel const Collada::AnimationChannel* mChannel; ///> the source channel
std::string mTargetId;
std::string mTransformId; // the ID of the transformation step of the node which is influenced std::string mTransformId; // the ID of the transformation step of the node which is influenced
size_t mTransformIndex; // Index into the node's transform chain to apply the channel to size_t mTransformIndex; // Index into the node's transform chain to apply the channel to
size_t mSubElement; // starting index inside the transform data size_t mSubElement; // starting index inside the transform data

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -49,18 +50,19 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp> #include <assimp/DefaultLogger.hpp>
#include <assimp/Importer.hpp> #include <assimp/Importer.hpp>
#include "ColladaParser.h" #include <assimp/importerdesc.h>
#include "ColladaParser.h"
#include "fast_atof.h" #include "fast_atof.h"
#include "ParsingUtils.h" #include "ParsingUtils.h"
#include "SkeletonMeshBuilder.h" #include "SkeletonMeshBuilder.h"
#include "Defines.h" #include "CreateAnimMesh.h"
#include "time.h" #include "time.h"
#include "math.h" #include "math.h"
#include <algorithm>
#include <numeric> #include <numeric>
#include "Defines.h" #include <assimp/Defines.h>
using namespace Assimp; using namespace Assimp;
using namespace Assimp::Formatter; using namespace Assimp::Formatter;
@ -148,6 +150,7 @@ void ColladaLoader::InternReadFile( const std::string& pFile, aiScene* pScene, I
mMeshIndexByID.clear(); mMeshIndexByID.clear();
mMaterialIndexByName.clear(); mMaterialIndexByName.clear();
mMeshes.clear(); mMeshes.clear();
mTargetMeshes.clear();
newMats.clear(); newMats.clear();
mLights.clear(); mLights.clear();
mCameras.clear(); mCameras.clear();
@ -240,7 +243,7 @@ aiNode* ColladaLoader::BuildHierarchy( const ColladaParser& pParser, const Colla
ResolveNodeInstances(pParser,pNode,instances); ResolveNodeInstances(pParser,pNode,instances);
// add children. first the *real* ones // add children. first the *real* ones
node->mNumChildren = pNode->mChildren.size()+instances.size(); node->mNumChildren = static_cast<unsigned int>(pNode->mChildren.size()+instances.size());
node->mChildren = new aiNode*[node->mNumChildren]; node->mChildren = new aiNode*[node->mNumChildren];
for( size_t a = 0; a < pNode->mChildren.size(); a++) for( size_t a = 0; a < pNode->mChildren.size(); a++)
@ -420,13 +423,13 @@ void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Col
out->mHorizontalFOV = srcCamera->mHorFov; out->mHorizontalFOV = srcCamera->mHorFov;
if (srcCamera->mVerFov != 10e10f && srcCamera->mAspect == 10e10f) { if (srcCamera->mVerFov != 10e10f && srcCamera->mAspect == 10e10f) {
out->mAspect = tan(AI_DEG_TO_RAD(srcCamera->mHorFov)) / out->mAspect = std::tan(AI_DEG_TO_RAD(srcCamera->mHorFov)) /
tan(AI_DEG_TO_RAD(srcCamera->mVerFov)); std::tan(AI_DEG_TO_RAD(srcCamera->mVerFov));
} }
} }
else if (srcCamera->mAspect != 10e10f && srcCamera->mVerFov != 10e10f) { else if (srcCamera->mAspect != 10e10f && srcCamera->mVerFov != 10e10f) {
out->mHorizontalFOV = 2.0f * AI_RAD_TO_DEG(atan(srcCamera->mAspect * out->mHorizontalFOV = 2.0f * AI_RAD_TO_DEG(std::atan(srcCamera->mAspect *
tan(AI_DEG_TO_RAD(srcCamera->mVerFov) * 0.5f))); std::tan(AI_DEG_TO_RAD(srcCamera->mVerFov) * 0.5f)));
} }
// Collada uses degrees, we use radians // Collada uses degrees, we use radians
@ -506,7 +509,7 @@ void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Coll
std::map<std::string, size_t>::const_iterator matIt = mMaterialIndexByName.find( meshMaterial); std::map<std::string, size_t>::const_iterator matIt = mMaterialIndexByName.find( meshMaterial);
unsigned int matIdx; unsigned int matIdx;
if( matIt != mMaterialIndexByName.end()) if( matIt != mMaterialIndexByName.end())
matIdx = matIt->second; matIdx = static_cast<unsigned int>(matIt->second);
else else
matIdx = 0; matIdx = 0;
@ -553,14 +556,37 @@ void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Coll
} }
// now place all mesh references we gathered in the target node // now place all mesh references we gathered in the target node
pTarget->mNumMeshes = newMeshRefs.size(); pTarget->mNumMeshes = static_cast<unsigned int>(newMeshRefs.size());
if( newMeshRefs.size()) if( newMeshRefs.size())
{ {
struct UIntTypeConverter
{
unsigned int operator()(const size_t& v) const
{
return static_cast<unsigned int>(v);
}
};
pTarget->mMeshes = new unsigned int[pTarget->mNumMeshes]; pTarget->mMeshes = new unsigned int[pTarget->mNumMeshes];
std::copy( newMeshRefs.begin(), newMeshRefs.end(), pTarget->mMeshes); std::transform( newMeshRefs.begin(), newMeshRefs.end(), pTarget->mMeshes, UIntTypeConverter());
} }
} }
// ------------------------------------------------------------------------------------------------
// Find mesh from either meshes or morph target meshes
aiMesh *ColladaLoader::findMesh(std::string meshid)
{
for (unsigned int i = 0; i < mMeshes.size(); i++)
if (std::string(mMeshes[i]->mName.data) == meshid)
return mMeshes[i];
for (unsigned int i = 0; i < mTargetMeshes.size(); i++)
if (std::string(mTargetMeshes[i]->mName.data) == meshid)
return mTargetMeshes[i];
return NULL;
}
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh // Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh
aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::Mesh* pSrcMesh, const Collada::SubMesh& pSubMesh, aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::Mesh* pSrcMesh, const Collada::SubMesh& pSubMesh,
@ -572,10 +598,10 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::
// count the vertices addressed by its faces // count the vertices addressed by its faces
const size_t numVertices = std::accumulate( pSrcMesh->mFaceSize.begin() + pStartFace, const size_t numVertices = std::accumulate( pSrcMesh->mFaceSize.begin() + pStartFace,
pSrcMesh->mFaceSize.begin() + pStartFace + pSubMesh.mNumFaces, 0); pSrcMesh->mFaceSize.begin() + pStartFace + pSubMesh.mNumFaces, size_t(0));
// copy positions // copy positions
dstMesh->mNumVertices = numVertices; dstMesh->mNumVertices = static_cast<unsigned int>(numVertices);
dstMesh->mVertices = new aiVector3D[numVertices]; dstMesh->mVertices = new aiVector3D[numVertices];
std::copy( pSrcMesh->mPositions.begin() + pStartVertex, pSrcMesh->mPositions.begin() + std::copy( pSrcMesh->mPositions.begin() + pStartVertex, pSrcMesh->mPositions.begin() +
pStartVertex + numVertices, dstMesh->mVertices); pStartVertex + numVertices, dstMesh->mVertices);
@ -634,20 +660,82 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::
// create faces. Due to the fact that each face uses unique vertices, we can simply count up on each vertex // create faces. Due to the fact that each face uses unique vertices, we can simply count up on each vertex
size_t vertex = 0; size_t vertex = 0;
dstMesh->mNumFaces = pSubMesh.mNumFaces; dstMesh->mNumFaces = static_cast<unsigned int>(pSubMesh.mNumFaces);
dstMesh->mFaces = new aiFace[dstMesh->mNumFaces]; dstMesh->mFaces = new aiFace[dstMesh->mNumFaces];
for( size_t a = 0; a < dstMesh->mNumFaces; ++a) for( size_t a = 0; a < dstMesh->mNumFaces; ++a)
{ {
size_t s = pSrcMesh->mFaceSize[ pStartFace + a]; size_t s = pSrcMesh->mFaceSize[ pStartFace + a];
aiFace& face = dstMesh->mFaces[a]; aiFace& face = dstMesh->mFaces[a];
face.mNumIndices = s; face.mNumIndices = static_cast<unsigned int>(s);
face.mIndices = new unsigned int[s]; face.mIndices = new unsigned int[s];
for( size_t b = 0; b < s; ++b) for( size_t b = 0; b < s; ++b)
face.mIndices[b] = vertex++; face.mIndices[b] = static_cast<unsigned int>(vertex++);
}
// create morph target meshes if any
std::vector<aiMesh*> targetMeshes;
std::vector<float> targetWeights;
Collada::MorphMethod method;
for(std::map<std::string, Collada::Controller>::const_iterator it = pParser.mControllerLibrary.begin();
it != pParser.mControllerLibrary.end(); it++)
{
const Collada::Controller &c = it->second;
const Collada::Mesh* baseMesh = pParser.ResolveLibraryReference( pParser.mMeshLibrary, c.mMeshId);
if (c.mType == Collada::Morph && baseMesh->mName == pSrcMesh->mName)
{
const Collada::Accessor& targetAccessor = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, c.mMorphTarget);
const Collada::Accessor& weightAccessor = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, c.mMorphWeight);
const Collada::Data& targetData = pParser.ResolveLibraryReference( pParser.mDataLibrary, targetAccessor.mSource);
const Collada::Data& weightData = pParser.ResolveLibraryReference( pParser.mDataLibrary, weightAccessor.mSource);
// take method
method = c.mMethod;
if (!targetData.mIsStringArray)
throw DeadlyImportError( "target data must contain id. ");
if (weightData.mIsStringArray)
throw DeadlyImportError( "target weight data must not be textual ");
for (unsigned int i = 0; i < targetData.mStrings.size(); ++i)
{
const Collada::Mesh* targetMesh = pParser.ResolveLibraryReference(pParser.mMeshLibrary, targetData.mStrings.at(i));
aiMesh *aimesh = findMesh(targetMesh->mName);
if (!aimesh)
{
if (targetMesh->mSubMeshes.size() > 1)
throw DeadlyImportError( "Morhing target mesh must be a single");
aimesh = CreateMesh(pParser, targetMesh, targetMesh->mSubMeshes.at(0), NULL, 0, 0);
mTargetMeshes.push_back(aimesh);
}
targetMeshes.push_back(aimesh);
}
for (unsigned int i = 0; i < weightData.mValues.size(); ++i)
targetWeights.push_back(weightData.mValues.at(i));
}
}
if (targetMeshes.size() > 0 && targetWeights.size() == targetMeshes.size())
{
std::vector<aiAnimMesh*> animMeshes;
for (unsigned int i = 0; i < targetMeshes.size(); i++)
{
aiAnimMesh *animMesh = aiCreateAnimMesh(targetMeshes.at(i));
animMesh->mWeight = targetWeights[i];
animMeshes.push_back(animMesh);
}
dstMesh->mMethod = (method == Collada::Relative)
? aiMorphingMethod_MORPH_RELATIVE
: aiMorphingMethod_MORPH_NORMALIZED;
dstMesh->mAnimMeshes = new aiAnimMesh*[animMeshes.size()];
dstMesh->mNumAnimMeshes = animMeshes.size();
for (unsigned int i = 0; i < animMeshes.size(); i++)
dstMesh->mAnimMeshes[i] = animMeshes.at(i);
} }
// create bones if given // create bones if given
if( pSrcController) if( pSrcController && pSrcController->mType == Collada::Skin)
{ {
// refuse if the vertex count does not match // refuse if the vertex count does not match
// if( pSrcController->mWeightCounts.size() != dstMesh->mNumVertices) // if( pSrcController->mWeightCounts.size() != dstMesh->mNumVertices)
@ -710,7 +798,7 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::
if( weight > 0.0f) if( weight > 0.0f)
{ {
aiVertexWeight w; aiVertexWeight w;
w.mVertexId = a - pStartVertex; w.mVertexId = static_cast<unsigned int>(a - pStartVertex);
w.mWeight = weight; w.mWeight = weight;
dstBones[jointIndex].push_back( w); dstBones[jointIndex].push_back( w);
} }
@ -724,7 +812,7 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::
numRemainingBones++; numRemainingBones++;
// create bone array and copy bone weights one by one // create bone array and copy bone weights one by one
dstMesh->mNumBones = numRemainingBones; dstMesh->mNumBones = static_cast<unsigned int>(numRemainingBones);
dstMesh->mBones = new aiBone*[numRemainingBones]; dstMesh->mBones = new aiBone*[numRemainingBones];
size_t boneCount = 0; size_t boneCount = 0;
for( size_t a = 0; a < numBones; ++a) for( size_t a = 0; a < numBones; ++a)
@ -748,7 +836,7 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::
bone->mOffsetMatrix.c2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 9); bone->mOffsetMatrix.c2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 9);
bone->mOffsetMatrix.c3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 10); bone->mOffsetMatrix.c3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 10);
bone->mOffsetMatrix.c4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 11); bone->mOffsetMatrix.c4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 11);
bone->mNumWeights = dstBones[a].size(); bone->mNumWeights = static_cast<unsigned int>(dstBones[a].size());
bone->mWeights = new aiVertexWeight[bone->mNumWeights]; bone->mWeights = new aiVertexWeight[bone->mNumWeights];
std::copy( dstBones[a].begin(), dstBones[a].end(), bone->mWeights); std::copy( dstBones[a].begin(), dstBones[a].end(), bone->mWeights);
@ -798,7 +886,7 @@ aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::
// Stores all meshes in the given scene // Stores all meshes in the given scene
void ColladaLoader::StoreSceneMeshes( aiScene* pScene) void ColladaLoader::StoreSceneMeshes( aiScene* pScene)
{ {
pScene->mNumMeshes = mMeshes.size(); pScene->mNumMeshes = static_cast<unsigned int>(mMeshes.size());
if( mMeshes.size() > 0) if( mMeshes.size() > 0)
{ {
pScene->mMeshes = new aiMesh*[mMeshes.size()]; pScene->mMeshes = new aiMesh*[mMeshes.size()];
@ -811,7 +899,7 @@ void ColladaLoader::StoreSceneMeshes( aiScene* pScene)
// Stores all cameras in the given scene // Stores all cameras in the given scene
void ColladaLoader::StoreSceneCameras( aiScene* pScene) void ColladaLoader::StoreSceneCameras( aiScene* pScene)
{ {
pScene->mNumCameras = mCameras.size(); pScene->mNumCameras = static_cast<unsigned int>(mCameras.size());
if( mCameras.size() > 0) if( mCameras.size() > 0)
{ {
pScene->mCameras = new aiCamera*[mCameras.size()]; pScene->mCameras = new aiCamera*[mCameras.size()];
@ -824,7 +912,7 @@ void ColladaLoader::StoreSceneCameras( aiScene* pScene)
// Stores all lights in the given scene // Stores all lights in the given scene
void ColladaLoader::StoreSceneLights( aiScene* pScene) void ColladaLoader::StoreSceneLights( aiScene* pScene)
{ {
pScene->mNumLights = mLights.size(); pScene->mNumLights = static_cast<unsigned int>(mLights.size());
if( mLights.size() > 0) if( mLights.size() > 0)
{ {
pScene->mLights = new aiLight*[mLights.size()]; pScene->mLights = new aiLight*[mLights.size()];
@ -837,7 +925,7 @@ void ColladaLoader::StoreSceneLights( aiScene* pScene)
// Stores all textures in the given scene // Stores all textures in the given scene
void ColladaLoader::StoreSceneTextures( aiScene* pScene) void ColladaLoader::StoreSceneTextures( aiScene* pScene)
{ {
pScene->mNumTextures = mTextures.size(); pScene->mNumTextures = static_cast<unsigned int>(mTextures.size());
if( mTextures.size() > 0) if( mTextures.size() > 0)
{ {
pScene->mTextures = new aiTexture*[mTextures.size()]; pScene->mTextures = new aiTexture*[mTextures.size()];
@ -850,7 +938,7 @@ void ColladaLoader::StoreSceneTextures( aiScene* pScene)
// Stores all materials in the given scene // Stores all materials in the given scene
void ColladaLoader::StoreSceneMaterials( aiScene* pScene) void ColladaLoader::StoreSceneMaterials( aiScene* pScene)
{ {
pScene->mNumMaterials = newMats.size(); pScene->mNumMaterials = static_cast<unsigned int>(newMats.size());
if (newMats.size() > 0) { if (newMats.size() > 0) {
pScene->mMaterials = new aiMaterial*[newMats.size()]; pScene->mMaterials = new aiMaterial*[newMats.size()];
@ -891,7 +979,7 @@ void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pPars
combinedAnim->mName = aiString( std::string( "combinedAnim_") + char( '0' + a)); combinedAnim->mName = aiString( std::string( "combinedAnim_") + char( '0' + a));
combinedAnim->mDuration = templateAnim->mDuration; combinedAnim->mDuration = templateAnim->mDuration;
combinedAnim->mTicksPerSecond = templateAnim->mTicksPerSecond; combinedAnim->mTicksPerSecond = templateAnim->mTicksPerSecond;
combinedAnim->mNumChannels = collectedAnimIndices.size() + 1; combinedAnim->mNumChannels = static_cast<unsigned int>(collectedAnimIndices.size() + 1);
combinedAnim->mChannels = new aiNodeAnim*[combinedAnim->mNumChannels]; combinedAnim->mChannels = new aiNodeAnim*[combinedAnim->mNumChannels];
// add the template anim as first channel by moving its aiNodeAnim to the combined animation // add the template anim as first channel by moving its aiNodeAnim to the combined animation
combinedAnim->mChannels[0] = templateAnim->mChannels[0]; combinedAnim->mChannels[0] = templateAnim->mChannels[0];
@ -923,7 +1011,7 @@ void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pPars
// now store all anims in the scene // now store all anims in the scene
if( !mAnims.empty()) if( !mAnims.empty())
{ {
pScene->mNumAnimations = mAnims.size(); pScene->mNumAnimations = static_cast<unsigned int>(mAnims.size());
pScene->mAnimations = new aiAnimation*[mAnims.size()]; pScene->mAnimations = new aiAnimation*[mAnims.size()];
std::copy( mAnims.begin(), mAnims.end(), pScene->mAnimations); std::copy( mAnims.begin(), mAnims.end(), pScene->mAnimations);
} }
@ -946,6 +1034,68 @@ void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pPars
CreateAnimation( pScene, pParser, pSrcAnim, animName); CreateAnimation( pScene, pParser, pSrcAnim, animName);
} }
struct MorphTimeValues
{
float mTime;
struct key
{
float mWeight;
unsigned int mValue;
};
std::vector<key> mKeys;
};
void insertMorphTimeValue(std::vector<MorphTimeValues> &values, float time, float weight, unsigned int value)
{
MorphTimeValues::key k;
k.mValue = value;
k.mWeight = weight;
if (values.size() == 0 || time < values[0].mTime)
{
MorphTimeValues val;
val.mTime = time;
val.mKeys.push_back(k);
values.insert(values.begin(), val);
return;
}
if (time > values.back().mTime)
{
MorphTimeValues val;
val.mTime = time;
val.mKeys.push_back(k);
values.insert(values.end(), val);
return;
}
for (unsigned int i = 0; i < values.size(); i++)
{
if (std::abs(time - values[i].mTime) < 1e-6f)
{
values[i].mKeys.push_back(k);
return;
} else if (time > values[i].mTime && time < values[i+1].mTime)
{
MorphTimeValues val;
val.mTime = time;
val.mKeys.push_back(k);
values.insert(values.begin() + i, val);
return;
}
}
// should not get here
}
float getWeightAtKey(const std::vector<MorphTimeValues> &values, int key, unsigned int value)
{
for (unsigned int i = 0; i < values[key].mKeys.size(); i++)
{
if (values[key].mKeys[i].mValue == value)
return values[key].mKeys[i].mWeight;
}
// no value at key found, try to interpolate if present at other keys. if not, return zero
// TODO: interpolation
return 0.0f;
}
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
// Constructs the animation for the given source anim // Constructs the animation for the given source anim
void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string& pName) void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string& pName)
@ -955,6 +1105,8 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
CollectNodes( pScene->mRootNode, nodes); CollectNodes( pScene->mRootNode, nodes);
std::vector<aiNodeAnim*> anims; std::vector<aiNodeAnim*> anims;
std::vector<aiMeshMorphAnim*> morphAnims;
for( std::vector<const aiNode*>::const_iterator nit = nodes.begin(); nit != nodes.end(); ++nit) for( std::vector<const aiNode*>::const_iterator nit = nodes.begin(); nit != nodes.end(); ++nit)
{ {
// find all the collada anim channels which refer to the current node // find all the collada anim channels which refer to the current node
@ -978,7 +1130,20 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
// find the slash that separates the node name - there should be only one // find the slash that separates the node name - there should be only one
std::string::size_type slashPos = srcChannel.mTarget.find( '/'); std::string::size_type slashPos = srcChannel.mTarget.find( '/');
if( slashPos == std::string::npos) if( slashPos == std::string::npos)
{
std::string::size_type targetPos = srcChannel.mTarget.find(srcNode->mID);
if (targetPos == std::string::npos)
continue;
// not node transform, but something else. store as unknown animation channel for now
entry.mChannel = &(*cit);
entry.mTargetId = srcChannel.mTarget.substr(targetPos + pSrcAnim->mName.length(),
srcChannel.mTarget.length() - targetPos - pSrcAnim->mName.length());
if (entry.mTargetId.front() == '-')
entry.mTargetId = entry.mTargetId.substr(1);
entries.push_back(entry);
continue; continue;
}
if( srcChannel.mTarget.find( '/', slashPos+1) != std::string::npos) if( srcChannel.mTarget.find( '/', slashPos+1) != std::string::npos)
continue; continue;
std::string targetID = srcChannel.mTarget.substr( 0, slashPos); std::string targetID = srcChannel.mTarget.substr( 0, slashPos);
@ -1058,8 +1223,14 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
if( srcNode->mTransforms[a].mID == entry.mTransformId) if( srcNode->mTransforms[a].mID == entry.mTransformId)
entry.mTransformIndex = a; entry.mTransformIndex = a;
if( entry.mTransformIndex == SIZE_MAX) { if( entry.mTransformIndex == SIZE_MAX)
continue; {
if (entry.mTransformId.find("morph-weights") != std::string::npos)
{
entry.mTargetId = entry.mTransformId;
entry.mTransformId = "";
} else
continue;
} }
entry.mChannel = &(*cit); entry.mChannel = &(*cit);
@ -1071,7 +1242,7 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
continue; continue;
// resolve the data pointers for all anim channels. Find the minimum time while we're at it // resolve the data pointers for all anim channels. Find the minimum time while we're at it
ai_real startTime = 1e20, endTime = -1e20; ai_real startTime = ai_real( 1e20 ), endTime = ai_real( -1e20 );
for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it) for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
{ {
Collada::ChannelEntry& e = *it; Collada::ChannelEntry& e = *it;
@ -1152,7 +1323,7 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
resultTrafos.push_back( mat); resultTrafos.push_back( mat);
// find next point in time to evaluate. That's the closest frame larger than the current in any channel // find next point in time to evaluate. That's the closest frame larger than the current in any channel
ai_real nextTime = 1e20; ai_real nextTime = ai_real( 1e20 );
for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it) for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
{ {
Collada::ChannelEntry& channelElement = *it; Collada::ChannelEntry& channelElement = *it;
@ -1181,7 +1352,7 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
const ai_real last_eval_angle = last_key_angle + (cur_key_angle - last_key_angle) * (time - last_key_time) / (cur_key_time - last_key_time); const ai_real last_eval_angle = last_key_angle + (cur_key_angle - last_key_angle) * (time - last_key_time) / (cur_key_time - last_key_time);
const ai_real delta = std::abs(cur_key_angle - last_eval_angle); const ai_real delta = std::abs(cur_key_angle - last_eval_angle);
if (delta >= 180.0) { if (delta >= 180.0) {
const int subSampleCount = static_cast<int>(floorf(delta / 90.0)); const int subSampleCount = static_cast<int>(std::floor(delta / 90.0));
if (cur_key_time != time) { if (cur_key_time != time) {
const ai_real nextSampleTime = time + (cur_key_time - time) / subSampleCount; const ai_real nextSampleTime = time + (cur_key_time - time) / subSampleCount;
nextTime = std::min(nextTime, nextSampleTime); nextTime = std::min(nextTime, nextSampleTime);
@ -1203,49 +1374,125 @@ void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pPars
// ai_assert( resultTrafos.size() > 0); // ai_assert( resultTrafos.size() > 0);
// build an animation channel for the given node out of these trafo keys // build an animation channel for the given node out of these trafo keys
if( !resultTrafos.empty() ) if( !resultTrafos.empty() )
{ {
aiNodeAnim* dstAnim = new aiNodeAnim; aiNodeAnim* dstAnim = new aiNodeAnim;
dstAnim->mNodeName = nodeName; dstAnim->mNodeName = nodeName;
dstAnim->mNumPositionKeys = resultTrafos.size(); dstAnim->mNumPositionKeys = resultTrafos.size();
dstAnim->mNumRotationKeys= resultTrafos.size(); dstAnim->mNumRotationKeys= resultTrafos.size();
dstAnim->mNumScalingKeys = resultTrafos.size(); dstAnim->mNumScalingKeys = resultTrafos.size();
dstAnim->mPositionKeys = new aiVectorKey[resultTrafos.size()]; dstAnim->mPositionKeys = new aiVectorKey[resultTrafos.size()];
dstAnim->mRotationKeys = new aiQuatKey[resultTrafos.size()]; dstAnim->mRotationKeys = new aiQuatKey[resultTrafos.size()];
dstAnim->mScalingKeys = new aiVectorKey[resultTrafos.size()]; dstAnim->mScalingKeys = new aiVectorKey[resultTrafos.size()];
for( size_t a = 0; a < resultTrafos.size(); ++a) for( size_t a = 0; a < resultTrafos.size(); ++a)
{ {
aiMatrix4x4 mat = resultTrafos[a]; aiMatrix4x4 mat = resultTrafos[a];
double time = double( mat.d4); // remember? time is stored in mat.d4 double time = double( mat.d4); // remember? time is stored in mat.d4
mat.d4 = 1.0f; mat.d4 = 1.0f;
dstAnim->mPositionKeys[a].mTime = time; dstAnim->mPositionKeys[a].mTime = time;
dstAnim->mRotationKeys[a].mTime = time; dstAnim->mRotationKeys[a].mTime = time;
dstAnim->mScalingKeys[a].mTime = time; dstAnim->mScalingKeys[a].mTime = time;
mat.Decompose( dstAnim->mScalingKeys[a].mValue, dstAnim->mRotationKeys[a].mValue, dstAnim->mPositionKeys[a].mValue); mat.Decompose( dstAnim->mScalingKeys[a].mValue, dstAnim->mRotationKeys[a].mValue, dstAnim->mPositionKeys[a].mValue);
} }
anims.push_back( dstAnim); anims.push_back( dstAnim);
} else } else
{ {
DefaultLogger::get()->warn( "Collada loader: found empty animation channel, ignored. Please check your exporter."); DefaultLogger::get()->warn( "Collada loader: found empty animation channel, ignored. Please check your exporter.");
} }
if( !entries.empty() && entries.front().mTimeAccessor->mCount > 0 )
{
std::vector<Collada::ChannelEntry> morphChannels;
for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
{
Collada::ChannelEntry& e = *it;
// skip non-transform types
if (e.mTargetId.empty())
continue;
if (e.mTargetId.find("morph-weights") != std::string::npos)
morphChannels.push_back(e);
}
if (morphChannels.size() > 0)
{
// either 1) morph weight animation count should contain morph target count channels
// or 2) one channel with morph target count arrays
// assume first
aiMeshMorphAnim *morphAnim = new aiMeshMorphAnim;
morphAnim->mName.Set(nodeName);
std::vector<MorphTimeValues> morphTimeValues;
int morphAnimChannelIndex = 0;
for( std::vector<Collada::ChannelEntry>::iterator it = morphChannels.begin(); it != morphChannels.end(); ++it)
{
Collada::ChannelEntry& e = *it;
std::string::size_type apos = e.mTargetId.find('(');
std::string::size_type bpos = e.mTargetId.find(')');
if (apos == std::string::npos || bpos == std::string::npos)
// unknown way to specify weight -> ignore this animation
continue;
// weight target can be in format Weight_M_N, Weight_N, WeightN, or some other way
// we ignore the name and just assume the channels are in the right order
for (unsigned int i = 0; i < e.mTimeData->mValues.size(); i++)
insertMorphTimeValue(morphTimeValues, e.mTimeData->mValues.at(i), e.mValueData->mValues.at(i), morphAnimChannelIndex);
++morphAnimChannelIndex;
}
morphAnim->mNumKeys = morphTimeValues.size();
morphAnim->mKeys = new aiMeshMorphKey[morphAnim->mNumKeys];
for (unsigned int key = 0; key < morphAnim->mNumKeys; key++)
{
morphAnim->mKeys[key].mNumValuesAndWeights = morphChannels.size();
morphAnim->mKeys[key].mValues = new unsigned int [morphChannels.size()];
morphAnim->mKeys[key].mWeights = new double [morphChannels.size()];
morphAnim->mKeys[key].mTime = morphTimeValues[key].mTime;
for (unsigned int valueIndex = 0; valueIndex < morphChannels.size(); valueIndex++)
{
morphAnim->mKeys[key].mValues[valueIndex] = valueIndex;
morphAnim->mKeys[key].mWeights[valueIndex] = getWeightAtKey(morphTimeValues, key, valueIndex);
}
}
morphAnims.push_back(morphAnim);
}
}
} }
if( !anims.empty()) if( !anims.empty() || !morphAnims.empty())
{ {
aiAnimation* anim = new aiAnimation; aiAnimation* anim = new aiAnimation;
anim->mName.Set( pName); anim->mName.Set( pName);
anim->mNumChannels = anims.size(); anim->mNumChannels = anims.size();
anim->mChannels = new aiNodeAnim*[anims.size()]; if (anim->mNumChannels > 0)
std::copy( anims.begin(), anims.end(), anim->mChannels); {
anim->mChannels = new aiNodeAnim*[anims.size()];
std::copy( anims.begin(), anims.end(), anim->mChannels);
}
anim->mNumMorphMeshChannels = morphAnims.size();
if (anim->mNumMorphMeshChannels > 0)
{
anim->mMorphMeshChannels = new aiMeshMorphAnim*[anim->mNumMorphMeshChannels];
std::copy( morphAnims.begin(), morphAnims.end(), anim->mMorphMeshChannels);
}
anim->mDuration = 0.0f; anim->mDuration = 0.0f;
for( size_t a = 0; a < anims.size(); ++a) for( size_t a = 0; a < anims.size(); ++a)
{ {
anim->mDuration = std::max( anim->mDuration, anims[a]->mPositionKeys[anims[a]->mNumPositionKeys-1].mTime); anim->mDuration = std::max( anim->mDuration, anims[a]->mPositionKeys[anims[a]->mNumPositionKeys-1].mTime);
anim->mDuration = std::max( anim->mDuration, anims[a]->mRotationKeys[anims[a]->mNumRotationKeys-1].mTime); anim->mDuration = std::max( anim->mDuration, anims[a]->mRotationKeys[anims[a]->mNumRotationKeys-1].mTime);
anim->mDuration = std::max( anim->mDuration, anims[a]->mScalingKeys[anims[a]->mNumScalingKeys-1].mTime); anim->mDuration = std::max( anim->mDuration, anims[a]->mScalingKeys[anims[a]->mNumScalingKeys-1].mTime);
}
for (size_t a = 0; a < morphAnims.size(); ++a)
{
anim->mDuration = std::max(anim->mDuration, morphAnims[a]->mKeys[morphAnims[a]->mNumKeys-1].mTime);
} }
anim->mTicksPerSecond = 1; anim->mTicksPerSecond = 1;
mAnims.push_back( anim); mAnims.push_back( anim);
@ -1479,6 +1726,8 @@ void ColladaLoader::BuildMaterials( ColladaParser& pParser, aiScene* /*pScene*/)
aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pParser, aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pParser,
const Collada::Effect& pEffect, const std::string& pName) const Collada::Effect& pEffect, const std::string& pName)
{ {
aiString result;
// recurse through the param references until we end up at an image // recurse through the param references until we end up at an image
std::string name = pName; std::string name = pName;
while( 1) while( 1)
@ -1497,11 +1746,17 @@ aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pPars
ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find( name); ColladaParser::ImageLibrary::const_iterator imIt = pParser.mImageLibrary.find( name);
if( imIt == pParser.mImageLibrary.end()) if( imIt == pParser.mImageLibrary.end())
{ {
throw DeadlyImportError( format() << //missing texture should not stop the conversion
"Collada: Unable to resolve effect texture entry \"" << pName << "\", ended up at ID \"" << name << "\"." ); //throw DeadlyImportError( format() <<
} // "Collada: Unable to resolve effect texture entry \"" << pName << "\", ended up at ID \"" << name << "\"." );
aiString result; DefaultLogger::get()->warn("Collada: Unable to resolve effect texture entry \"" + pName + "\", ended up at ID \"" + name + "\".");
//set default texture file name
result.Set(name + ".jpg");
ConvertPath(result);
return result;
}
// if this is an embedded texture image setup an aiTexture for it // if this is an embedded texture image setup an aiTexture for it
if (imIt->second.mFileName.empty()) if (imIt->second.mFileName.empty())
@ -1520,13 +1775,13 @@ aiString ColladaLoader::FindFilenameForEffectTexture( const ColladaParser& pPars
// and copy texture data // and copy texture data
tex->mHeight = 0; tex->mHeight = 0;
tex->mWidth = imIt->second.mImageData.size(); tex->mWidth = static_cast<unsigned int>(imIt->second.mImageData.size());
tex->pcData = (aiTexel*)new char[tex->mWidth]; tex->pcData = (aiTexel*)new char[tex->mWidth];
memcpy(tex->pcData,&imIt->second.mImageData[0],tex->mWidth); memcpy(tex->pcData,&imIt->second.mImageData[0],tex->mWidth);
// setup texture reference string // setup texture reference string
result.data[0] = '*'; result.data[0] = '*';
result.length = 1 + ASSIMP_itoa10(result.data+1,MAXLEN-1,mTextures.size()); result.length = 1 + ASSIMP_itoa10(result.data+1,static_cast<unsigned int>(MAXLEN-1),static_cast<int32_t>(mTextures.size()));
// and add this texture to the list // and add this texture to the list
mTextures.push_back(tex); mTextures.push_back(tex);

View File

@ -4,7 +4,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -117,6 +118,8 @@ protected:
/** Builds meshes for the given node and references them */ /** Builds meshes for the given node and references them */
void BuildMeshesForNode( const ColladaParser& pParser, const Collada::Node* pNode, void BuildMeshesForNode( const ColladaParser& pParser, const Collada::Node* pNode,
aiNode* pTarget); aiNode* pTarget);
aiMesh *findMesh(std::string meshid);
/** Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh */ /** Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh */
aiMesh* CreateMesh( const ColladaParser& pParser, const Collada::Mesh* pSrcMesh, const Collada::SubMesh& pSubMesh, aiMesh* CreateMesh( const ColladaParser& pParser, const Collada::Mesh* pSrcMesh, const Collada::SubMesh& pSubMesh,
@ -223,6 +226,9 @@ protected:
/** Accumulated meshes for the target scene */ /** Accumulated meshes for the target scene */
std::vector<aiMesh*> mMeshes; std::vector<aiMesh*> mMeshes;
/** Accumulated morph target meshes */
std::vector<aiMesh*> mTargetMeshes;
/** Temporary material list */ /** Temporary material list */
std::vector<std::pair<Collada::Effect*, aiMaterial*> > newMats; std::vector<std::pair<Collada::Effect*, aiMaterial*> > newMats;

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
@ -59,7 +60,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <memory> #include <memory>
using namespace Assimp; using namespace Assimp;
using namespace Assimp::Collada; using namespace Assimp::Collada;
using namespace Assimp::Formatter; using namespace Assimp::Formatter;
@ -300,7 +300,7 @@ void ColladaParser::ReadAnimationClipLibrary()
else if (indexID >= 0) else if (indexID >= 0)
animName = mReader->getAttributeValue(indexID); animName = mReader->getAttributeValue(indexID);
else else
animName = std::string("animation_") + std::to_string(mAnimationClipLibrary.size()); animName = std::string("animation_") + to_string(mAnimationClipLibrary.size());
std::pair<std::string, std::vector<std::string> > clip; std::pair<std::string, std::vector<std::string> > clip;
@ -586,6 +586,12 @@ void ColladaParser::ReadAnimationSampler( Collada::AnimationChannel& pChannel)
pChannel.mSourceTimes = source; pChannel.mSourceTimes = source;
else if( strcmp( semantic, "OUTPUT") == 0) else if( strcmp( semantic, "OUTPUT") == 0)
pChannel.mSourceValues = source; pChannel.mSourceValues = source;
else if( strcmp( semantic, "IN_TANGENT") == 0)
pChannel.mInTanValues = source;
else if( strcmp( semantic, "OUT_TANGENT") == 0)
pChannel.mOutTanValues = source;
else if( strcmp( semantic, "INTERPOLATION") == 0)
pChannel.mInterpolationValues = source;
if( !mReader->isEmptyElement()) if( !mReader->isEmptyElement())
SkipElement(); SkipElement();
@ -648,6 +654,9 @@ void ColladaParser::ReadControllerLibrary()
// Reads a controller into the given mesh structure // Reads a controller into the given mesh structure
void ColladaParser::ReadController( Collada::Controller& pController) void ColladaParser::ReadController( Collada::Controller& pController)
{ {
// initial values
pController.mType = Skin;
pController.mMethod = Normalized;
while( mReader->read()) while( mReader->read())
{ {
if( mReader->getNodeType() == irr::io::EXN_ELEMENT) if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
@ -655,8 +664,15 @@ void ColladaParser::ReadController( Collada::Controller& pController)
// two types of controllers: "skin" and "morph". Only the first one is relevant, we skip the other // two types of controllers: "skin" and "morph". Only the first one is relevant, we skip the other
if( IsElement( "morph")) if( IsElement( "morph"))
{ {
// should skip everything inside, so there's no danger of catching elements inbetween pController.mType = Morph;
SkipElement(); int baseIndex = GetAttribute("source");
pController.mMeshId = mReader->getAttributeValue(baseIndex) + 1;
int methodIndex = GetAttribute("method");
if (methodIndex > 0) {
const char *method = mReader->getAttributeValue(methodIndex);
if (strcmp(method, "RELATIVE") == 0)
pController.mMethod = Relative;
}
} }
else if( IsElement( "skin")) else if( IsElement( "skin"))
{ {
@ -668,18 +684,18 @@ void ColladaParser::ReadController( Collada::Controller& pController)
else if( IsElement( "bind_shape_matrix")) else if( IsElement( "bind_shape_matrix"))
{ {
// content is 16 floats to define a matrix... it seems to be important for some models // content is 16 floats to define a matrix... it seems to be important for some models
const char* content = GetTextContent(); const char* content = GetTextContent();
// read the 16 floats // read the 16 floats
for( unsigned int a = 0; a < 16; a++) for( unsigned int a = 0; a < 16; a++)
{ {
// read a number // read a number
content = fast_atoreal_move<ai_real>( content, pController.mBindShapeMatrix[a]); content = fast_atoreal_move<ai_real>( content, pController.mBindShapeMatrix[a]);
// skip whitespace after it // skip whitespace after it
SkipSpacesAndLineEnd( &content); SkipSpacesAndLineEnd( &content);
} }
TestClosing( "bind_shape_matrix"); TestClosing( "bind_shape_matrix");
} }
else if( IsElement( "source")) else if( IsElement( "source"))
{ {
@ -694,6 +710,32 @@ void ColladaParser::ReadController( Collada::Controller& pController)
{ {
ReadControllerWeights( pController); ReadControllerWeights( pController);
} }
else if ( IsElement( "targets" ))
{
while (mReader->read()) {
if( mReader->getNodeType() == irr::io::EXN_ELEMENT) {
if ( IsElement( "input")) {
int semanticsIndex = GetAttribute("semantic");
int sourceIndex = GetAttribute("source");
const char *semantics = mReader->getAttributeValue(semanticsIndex);
const char *source = mReader->getAttributeValue(sourceIndex);
if (strcmp(semantics, "MORPH_TARGET") == 0) {
pController.mMorphTarget = source + 1;
}
else if (strcmp(semantics, "MORPH_WEIGHT") == 0)
{
pController.mMorphWeight = source + 1;
}
}
} else if( mReader->getNodeType() == irr::io::EXN_ELEMENT_END) {
if( strcmp( mReader->getNodeName(), "targets") == 0)
break;
else
ThrowException( "Expected end of <targets> element.");
}
}
}
else else
{ {
// ignore the rest // ignore the rest
@ -704,7 +746,7 @@ void ColladaParser::ReadController( Collada::Controller& pController)
{ {
if( strcmp( mReader->getNodeName(), "controller") == 0) if( strcmp( mReader->getNodeName(), "controller") == 0)
break; break;
else if( strcmp( mReader->getNodeName(), "skin") != 0) else if( strcmp( mReader->getNodeName(), "skin") != 0 && strcmp( mReader->getNodeName(), "morph") != 0)
ThrowException( "Expected end of <controller> element."); ThrowException( "Expected end of <controller> element.");
} }
} }
@ -1593,7 +1635,7 @@ void ColladaParser::ReadEffectColor( aiColor4D& pColor, Sampler& pSampler)
} }
else if( IsElement( "texture")) else if( IsElement( "texture"))
{ {
// get name of source textur/sampler // get name of source texture/sampler
int attrTex = GetAttribute( "texture"); int attrTex = GetAttribute( "texture");
pSampler.mName = mReader->getAttributeValue( attrTex); pSampler.mName = mReader->getAttributeValue( attrTex);
@ -2312,9 +2354,9 @@ size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pP
ThrowException( "Expected different index count in <p> element."); ThrowException( "Expected different index count in <p> element.");
// find the data for all sources // find the data for all sources
for( std::vector<InputChannel>::iterator it = pMesh->mPerVertexData.begin(); it != pMesh->mPerVertexData.end(); ++it) for( std::vector<InputChannel>::iterator it = pMesh->mPerVertexData.begin(); it != pMesh->mPerVertexData.end(); ++it)
{ {
InputChannel& input = *it; InputChannel& input = *it;
if( input.mResolved) if( input.mResolved)
continue; continue;
@ -2326,9 +2368,9 @@ size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pP
acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource); acc->mData = &ResolveLibraryReference( mDataLibrary, acc->mSource);
} }
// and the same for the per-index channels // and the same for the per-index channels
for( std::vector<InputChannel>::iterator it = pPerIndexChannels.begin(); it != pPerIndexChannels.end(); ++it) for( std::vector<InputChannel>::iterator it = pPerIndexChannels.begin(); it != pPerIndexChannels.end(); ++it)
{ {
InputChannel& input = *it; InputChannel& input = *it;
if( input.mResolved) if( input.mResolved)
continue; continue;
@ -2410,6 +2452,9 @@ size_t ColladaParser::ReadPrimitives( Mesh* pMesh, std::vector<InputChannel>& pP
return numPrimitives; return numPrimitives;
} }
///@note This function willn't work correctly if both PerIndex and PerVertex channels have same channels.
///For example if TEXCOORD present in both <vertices> and <polylist> tags this function will create wrong uv coordinates.
///It's not clear from COLLADA documentation is this allowed or not. For now only exporter fixed to avoid such behavior
void ColladaParser::CopyVertex(size_t currentVertex, size_t numOffsets, size_t numPoints, size_t perVertexOffset, Mesh* pMesh, std::vector<InputChannel>& pPerIndexChannels, size_t currentPrimitive, const std::vector<size_t>& indices){ void ColladaParser::CopyVertex(size_t currentVertex, size_t numOffsets, size_t numPoints, size_t perVertexOffset, Mesh* pMesh, std::vector<InputChannel>& pPerIndexChannels, size_t currentPrimitive, const std::vector<size_t>& indices){
// calculate the base offset of the vertex whose attributes we ant to copy // calculate the base offset of the vertex whose attributes we ant to copy
size_t baseOffset = currentPrimitive * numOffsets * numPoints + currentVertex * numOffsets; size_t baseOffset = currentPrimitive * numOffsets * numPoints + currentVertex * numOffsets;
@ -2535,7 +2580,7 @@ void ColladaParser::ExtractDataObjectFromChannel( const InputChannel& pInput, si
aiColor4D result(0, 0, 0, 1); aiColor4D result(0, 0, 0, 1);
for (size_t i = 0; i < pInput.mResolved->mSize; ++i) for (size_t i = 0; i < pInput.mResolved->mSize; ++i)
{ {
result[i] = obj[pInput.mResolved->mSubOffset[i]]; result[static_cast<unsigned int>(i)] = obj[pInput.mResolved->mSubOffset[i]];
} }
pMesh->mColors[pInput.mIndex].push_back(result); pMesh->mColors[pInput.mIndex].push_back(result);
} else } else
@ -2828,7 +2873,7 @@ void ColladaParser::ReadNodeGeometry( Node* pNode)
if( !mReader->isEmptyElement()) if( !mReader->isEmptyElement())
{ {
// read material associations. Ignore additional elements inbetween // read material associations. Ignore additional elements in between
while( mReader->read()) while( mReader->read())
{ {
if( mReader->getNodeType() == irr::io::EXN_ELEMENT) if( mReader->getNodeType() == irr::io::EXN_ELEMENT)
@ -3075,7 +3120,7 @@ aiMatrix4x4 ColladaParser::CalculateResultTransform( const std::vector<Transform
case TF_ROTATE: case TF_ROTATE:
{ {
aiMatrix4x4 rot; aiMatrix4x4 rot;
ai_real angle = tf.f[3] * ai_real( AI_MATH_PI) / 180.0; ai_real angle = tf.f[3] * ai_real( AI_MATH_PI) / ai_real( 180.0 );
aiVector3D axis( tf.f[0], tf.f[1], tf.f[2]); aiVector3D axis( tf.f[0], tf.f[1], tf.f[2]);
aiMatrix4x4::Rotation( angle, axis, rot); aiMatrix4x4::Rotation( angle, axis, rot);
res *= rot; res *= rot;

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -49,7 +50,6 @@
#include "ColladaHelper.h" #include "ColladaHelper.h"
#include <assimp/ai_assert.h> #include <assimp/ai_assert.h>
#include "TinyFormatter.h" #include "TinyFormatter.h"
#include <memory>
namespace Assimp namespace Assimp
{ {
@ -268,8 +268,7 @@ namespace Assimp
Collada::InputType GetTypeForSemantic( const std::string& pSemantic); Collada::InputType GetTypeForSemantic( const std::string& pSemantic);
/** Finds the item in the given library by its reference, throws if not found */ /** Finds the item in the given library by its reference, throws if not found */
template <typename Type> const Type& ResolveLibraryReference( template <typename Type> const Type& ResolveLibraryReference( const std::map<std::string, Type>& pLibrary, const std::string& pURL) const;
const std::map<std::string, Type>& pLibrary, const std::string& pURL) const;
protected: protected:
/** Filename, for a verbose error message */ /** Filename, for a verbose error message */

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -52,7 +53,7 @@ namespace {
const static aiVector3D base_axis_y(0.0,1.0,0.0); const static aiVector3D base_axis_y(0.0,1.0,0.0);
const static aiVector3D base_axis_x(1.0,0.0,0.0); const static aiVector3D base_axis_x(1.0,0.0,0.0);
const static aiVector3D base_axis_z(0.0,0.0,1.0); const static aiVector3D base_axis_z(0.0,0.0,1.0);
const static ai_real angle_epsilon = 0.95; const static ai_real angle_epsilon = ai_real( 0.95 );
} }
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
@ -109,11 +110,11 @@ void RemoveUVSeams (aiMesh* mesh, aiVector3D* out)
// much easier, but I don't know how and am currently too tired to // much easier, but I don't know how and am currently too tired to
// to think about a better solution. // to think about a better solution.
const static ai_real LOWER_LIMIT = 0.1; const static ai_real LOWER_LIMIT = ai_real( 0.1 );
const static ai_real UPPER_LIMIT = 0.9; const static ai_real UPPER_LIMIT = ai_real( 0.9 );
const static ai_real LOWER_EPSILON = 10e-3; const static ai_real LOWER_EPSILON = ai_real( 10e-3 );
const static ai_real UPPER_EPSILON = 1.0-10e-3; const static ai_real UPPER_EPSILON = ai_real( 1.0-10e-3 );
for (unsigned int fidx = 0; fidx < mesh->mNumFaces;++fidx) for (unsigned int fidx = 0; fidx < mesh->mNumFaces;++fidx)
{ {
@ -206,7 +207,7 @@ void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,const aiVector3D
// lon = arctan (y/x) // lon = arctan (y/x)
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize(); const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize();
out[pnt] = aiVector3D((atan2 (diff.z, diff.y) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, out[pnt] = aiVector3D((std::atan2(diff.z, diff.y) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
(std::asin (diff.x) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0); (std::asin (diff.x) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
} }
} }
@ -214,7 +215,7 @@ void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,const aiVector3D
// ... just the same again // ... just the same again
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize(); const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize();
out[pnt] = aiVector3D((atan2 (diff.x, diff.z) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, out[pnt] = aiVector3D((std::atan2(diff.x, diff.z) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
(std::asin (diff.y) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0); (std::asin (diff.y) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
} }
} }
@ -222,7 +223,7 @@ void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,const aiVector3D
// ... just the same again // ... just the same again
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize(); const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize();
out[pnt] = aiVector3D((atan2 (diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, out[pnt] = aiVector3D((std::atan2(diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
(std::asin (diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0); (std::asin (diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
} }
} }
@ -234,8 +235,8 @@ void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,const aiVector3D
// again the same, except we're applying a transformation now // again the same, except we're applying a transformation now
for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) {
const aiVector3D diff = ((mTrafo*mesh->mVertices[pnt])-center).Normalize(); const aiVector3D diff = ((mTrafo*mesh->mVertices[pnt])-center).Normalize();
out[pnt] = aiVector3D((atan2 (diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, out[pnt] = aiVector3D((std::atan2(diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F,
(asin (diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0); (std::asin(diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0);
} }
} }
@ -268,7 +269,7 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
aiVector3D& uv = out[pnt]; aiVector3D& uv = out[pnt];
uv.y = (pos.x - min.x) / diff; uv.y = (pos.x - min.x) / diff;
uv.x = (atan2 ( pos.z - center.z, pos.y - center.y) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI; uv.x = (std::atan2( pos.z - center.z, pos.y - center.y) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
} }
} }
else if (axis * base_axis_y >= angle_epsilon) { else if (axis * base_axis_y >= angle_epsilon) {
@ -281,7 +282,7 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
aiVector3D& uv = out[pnt]; aiVector3D& uv = out[pnt];
uv.y = (pos.y - min.y) / diff; uv.y = (pos.y - min.y) / diff;
uv.x = (atan2 ( pos.x - center.x, pos.z - center.z) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI; uv.x = (std::atan2( pos.x - center.x, pos.z - center.z) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
} }
} }
else if (axis * base_axis_z >= angle_epsilon) { else if (axis * base_axis_z >= angle_epsilon) {
@ -294,7 +295,7 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
aiVector3D& uv = out[pnt]; aiVector3D& uv = out[pnt];
uv.y = (pos.z - min.z) / diff; uv.y = (pos.z - min.z) / diff;
uv.x = (atan2 ( pos.y - center.y, pos.x - center.x) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI; uv.x = (std::atan2( pos.y - center.y, pos.x - center.x) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
} }
} }
// slower code path in case the mapping axis is not one of the coordinate system axes // slower code path in case the mapping axis is not one of the coordinate system axes
@ -310,7 +311,7 @@ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector
aiVector3D& uv = out[pnt]; aiVector3D& uv = out[pnt];
uv.y = (pos.y - min.y) / diff; uv.y = (pos.y - min.y) / diff;
uv.x = (atan2 ( pos.x - center.x, pos.z - center.z) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI; uv.x = (std::atan2( pos.x - center.x, pos.z - center.z) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI;
} }
} }
@ -437,7 +438,7 @@ void ComputeUVMappingProcess::Execute( aiScene* pScene)
} }
} }
unsigned int idx; unsigned int idx( 99999999 );
// Check whether we have this mapping mode already // Check whether we have this mapping mode already
std::list<MappingInfo>::iterator it = std::find (mappingStack.begin(),mappingStack.end(), info); std::list<MappingInfo>::iterator it = std::find (mappingStack.begin(),mappingStack.end(), info);

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -3,7 +3,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,

View File

@ -0,0 +1,92 @@
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (C) 2016 The Qt Company Ltd.
Copyright (c) 2006-2012, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 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 DAMAGE.
---------------------------------------------------------------------------
*/
#include "CreateAnimMesh.h"
namespace Assimp {
aiAnimMesh *aiCreateAnimMesh(const aiMesh *mesh)
{
aiAnimMesh *animesh = new aiAnimMesh;
animesh->mVertices = NULL;
animesh->mNormals = NULL;
animesh->mTangents = NULL;
animesh->mBitangents = NULL;
animesh->mNumVertices = mesh->mNumVertices;
if (mesh->mVertices) {
animesh->mVertices = new aiVector3D[animesh->mNumVertices];
std::memcpy(animesh->mVertices, mesh->mVertices, mesh->mNumVertices * sizeof(aiVector3D));
}
if (mesh->mNormals) {
animesh->mNormals = new aiVector3D[animesh->mNumVertices];
std::memcpy(animesh->mNormals, mesh->mNormals, mesh->mNumVertices * sizeof(aiVector3D));
}
if (mesh->mTangents) {
animesh->mTangents = new aiVector3D[animesh->mNumVertices];
std::memcpy(animesh->mTangents, mesh->mTangents, mesh->mNumVertices * sizeof(aiVector3D));
}
if (mesh->mBitangents) {
animesh->mBitangents = new aiVector3D[animesh->mNumVertices];
std::memcpy(animesh->mBitangents, mesh->mBitangents, mesh->mNumVertices * sizeof(aiVector3D));
}
for (int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) {
if (mesh->mColors[i]) {
animesh->mColors[i] = new aiColor4D[animesh->mNumVertices];
std::memcpy(animesh->mColors[i], mesh->mColors[i], mesh->mNumVertices * sizeof(aiColor4D));
} else {
animesh->mColors[i] = NULL;
}
}
for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
if (mesh->mTextureCoords[i]) {
animesh->mTextureCoords[i] = new aiVector3D[animesh->mNumVertices];
std::memcpy(animesh->mTextureCoords[i], mesh->mTextureCoords[i], mesh->mNumVertices * sizeof(aiVector3D));
} else {
animesh->mTextureCoords[i] = NULL;
}
}
return animesh;
}
} // end of namespace Assimp

View File

@ -0,0 +1,57 @@
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software 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.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 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 DAMAGE.
----------------------------------------------------------------------
*/
/** @file CreateAnimMesh.h
* Create AnimMesh from Mesh
*/
#ifndef INCLUDED_AI_CREATE_ANIM_MESH_H
#define INCLUDED_AI_CREATE_ANIM_MESH_H
#include <assimp/mesh.h>
namespace Assimp {
/** Create aiAnimMesh from aiMesh. */
aiAnimMesh *aiCreateAnimMesh(const aiMesh *mesh);
} // end of namespace Assimp
#endif // INCLUDED_AI_CREATE_ANIM_MESH_H

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -38,63 +39,53 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER
#include "D3MFImporter.h" #include "D3MFImporter.h"
#include <assimp/scene.h> #include <assimp/scene.h>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp> #include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp> #include <assimp/DefaultLogger.hpp>
#include <contrib/unzip/unzip.h> #include <assimp/importerdesc.h>
#include "irrXMLWrapper.h"
#include "StringComparison.h" #include "StringComparison.h"
#include "StringUtils.h" #include "StringUtils.h"
#include <string> #include <string>
#include <sstream>
#include <vector> #include <vector>
#include <map> #include <map>
#include <algorithm>
#include <cassert> #include <cassert>
#include <cstdlib>
#include <memory> #include <memory>
#include <assimp/ai_assert.h>
#include "D3MFOpcPackage.h" #include "D3MFOpcPackage.h"
#include <contrib/unzip/unzip.h>
#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER #include "irrXMLWrapper.h"
namespace Assimp { namespace Assimp {
namespace D3MF { namespace D3MF {
namespace XmlTag { namespace XmlTag {
static const std::string model = "model";
const std::string model = "model"; static const std::string metadata = "metadata";
const std::string metadata = "metadata"; static const std::string resources = "resources";
const std::string resources = "resources"; static const std::string object = "object";
const std::string object = "object"; static const std::string mesh = "mesh";
const std::string mesh = "mesh"; static const std::string vertices = "vertices";
const std::string vertices = "vertices"; static const std::string vertex = "vertex";
const std::string vertex = "vertex"; static const std::string triangles = "triangles";
const std::string triangles = "triangles"; static const std::string triangle = "triangle";
const std::string triangle = "triangle"; static const std::string x = "x";
const std::string x = "x"; static const std::string y = "y";
const std::string y = "y"; static const std::string z = "z";
const std::string z = "z"; static const std::string v1 = "v1";
const std::string v1 = "v1"; static const std::string v2 = "v2";
const std::string v2 = "v2"; static const std::string v3 = "v3";
const std::string v3 = "v3"; static const std::string id = "id";
const std::string id = "id"; static const std::string name = "name";
const std::string name = "name"; static const std::string type = "type";
const std::string type = "type"; static const std::string build = "build";
const std::string build = "build"; static const std::string item = "item";
const std::string item = "item"; static const std::string objectid = "objectid";
const std::string objectid = "objectid"; static const std::string transform = "transform";
const std::string transform = "transform";
} }
@ -116,7 +107,7 @@ public:
std::vector<aiNode*> children; std::vector<aiNode*> children;
while(ReadToEndElement(D3MF::XmlTag::model)) while(ReadToEndElement(D3MF::XmlTag::model))
{ {
if(xmlReader->getNodeName() == D3MF::XmlTag::object) if(xmlReader->getNodeName() == D3MF::XmlTag::object)
{ {
@ -126,7 +117,7 @@ public:
{ {
} }
} }
if(scene->mRootNode->mName.length == 0) if(scene->mRootNode->mName.length == 0)
scene->mRootNode->mName.Set("3MF"); scene->mRootNode->mName.Set("3MF");
@ -146,29 +137,36 @@ public:
private: private:
aiNode* ReadObject(aiScene* scene) aiNode* ReadObject(aiScene* scene)
{ {
ScopeGuard<aiNode> node(new aiNode()); ScopeGuard<aiNode> node(new aiNode());
std::vector<unsigned long> meshIds; std::vector<unsigned long> meshIds;
int id = std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::id.c_str())); const char *attrib( nullptr );
std::string name(xmlReader->getAttributeValue(D3MF::XmlTag::name.c_str())); std::string name, type;
std::string type(xmlReader->getAttributeValue(D3MF::XmlTag::type.c_str())); attrib = xmlReader->getAttributeValue( D3MF::XmlTag::name.c_str() );
if ( nullptr != attrib ) {
name = attrib;
}
attrib = xmlReader->getAttributeValue( D3MF::XmlTag::name.c_str() );
if ( nullptr != attrib ) {
type = attrib;
}
node->mParent = scene->mRootNode; node->mParent = scene->mRootNode;
node->mName.Set(name); node->mName.Set(name);
unsigned long meshIdx = meshes.size(); size_t meshIdx = meshes.size();
while(ReadToEndElement(D3MF::XmlTag::object)) while(ReadToEndElement(D3MF::XmlTag::object))
{ {
if(xmlReader->getNodeName() == D3MF::XmlTag::mesh) if(xmlReader->getNodeName() == D3MF::XmlTag::mesh)
{ {
auto mesh = ReadMesh(); auto mesh = ReadMesh();
mesh->mName.Set(name); mesh->mName.Set(name);
meshes.push_back(mesh); meshes.push_back(mesh);
meshIds.push_back(meshIdx); meshIds.push_back(static_cast<unsigned long>(meshIdx));
meshIdx++; meshIdx++;
} }
@ -189,7 +187,7 @@ private:
aiMesh* mesh = new aiMesh(); aiMesh* mesh = new aiMesh();
while(ReadToEndElement(D3MF::XmlTag::mesh)) while(ReadToEndElement(D3MF::XmlTag::mesh))
{ {
if(xmlReader->getNodeName() == D3MF::XmlTag::vertices) if(xmlReader->getNodeName() == D3MF::XmlTag::vertices)
{ {
ImportVertices(mesh); ImportVertices(mesh);
@ -207,12 +205,12 @@ private:
void ImportVertices(aiMesh* mesh) void ImportVertices(aiMesh* mesh)
{ {
std::vector<aiVector3D> vertices; std::vector<aiVector3D> vertices;
while(ReadToEndElement(D3MF::XmlTag::vertices)) while(ReadToEndElement(D3MF::XmlTag::vertices))
{ {
if(xmlReader->getNodeName() == D3MF::XmlTag::vertex) if(xmlReader->getNodeName() == D3MF::XmlTag::vertex)
{ {
vertices.push_back(ReadVertex()); vertices.push_back(ReadVertex());
} }
} }
@ -223,18 +221,19 @@ private:
} }
aiVector3D ReadVertex() aiVector3D ReadVertex()
{ {
aiVector3D vertex; aiVector3D vertex;
vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr); vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr);
vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr); vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr);
vertex.z = ai_strtof>(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr); vertex.z = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr);
return vertex; return vertex;
} }
void ImportTriangles(aiMesh* mesh) void ImportTriangles(aiMesh* mesh)
{ {
std::vector<aiFace> faces; std::vector<aiFace> faces;
while(ReadToEndElement(D3MF::XmlTag::triangles)) while(ReadToEndElement(D3MF::XmlTag::triangles))
@ -249,9 +248,7 @@ private:
mesh->mFaces = new aiFace[mesh->mNumFaces]; mesh->mFaces = new aiFace[mesh->mNumFaces];
mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
std::copy(faces.begin(), faces.end(), mesh->mFaces); std::copy(faces.begin(), faces.end(), mesh->mFaces);
} }
aiFace ReadTriangle() aiFace ReadTriangle()
@ -308,8 +305,6 @@ private:
private: private:
std::vector<aiMesh*> meshes; std::vector<aiMesh*> meshes;
XmlReader* xmlReader; XmlReader* xmlReader;
}; };
} //namespace D3MF } //namespace D3MF
@ -340,17 +335,14 @@ D3MFImporter::~D3MFImporter()
} }
bool D3MFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const bool D3MFImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const
{ {
const std::string extension = GetExtension(pFile); const std::string extension = GetExtension(pFile);
if(extension == "3mf") {
if(extension == "3mf")
{
return true; return true;
} } else if ( !extension.length() || checkSig ) {
else if(!extension.length() || checkSig) if (nullptr == pIOHandler ) {
{
if(!pIOHandler)
return true; return true;
}
} }
return false; return false;
@ -368,8 +360,6 @@ const aiImporterDesc *D3MFImporter::GetInfo() const
void D3MFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) void D3MFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler)
{ {
D3MF::D3MFOpcPackage opcPackage(pIOHandler, pFile); D3MF::D3MFOpcPackage opcPackage(pIOHandler, pFile);
std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream())); std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream()));
@ -377,12 +367,9 @@ void D3MFImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOS
D3MF::XmlSerializer xmlSerializer(xmlReader.get()); D3MF::XmlSerializer xmlSerializer(xmlReader.get());
xmlSerializer.ImportXml(pScene); xmlSerializer.ImportXml(pScene);
} }
} } // Namespace Assimp
#endif // ASSIMP_BUILD_NO_3MF_IMPORTER #endif // ASSIMP_BUILD_NO_3MF_IMPORTER

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -41,9 +42,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef AI_D3MFLOADER_H_INCLUDED #ifndef AI_D3MFLOADER_H_INCLUDED
#define AI_D3MFLOADER_H_INCLUDED #define AI_D3MFLOADER_H_INCLUDED
#include <vector>
#include <cstdint>
#include "BaseImporter.h" #include "BaseImporter.h"
namespace Assimp { namespace Assimp {

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -38,11 +39,11 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER
#include "D3MFOpcPackage.h" #include "D3MFOpcPackage.h"
#include "Exceptional.h" #include "Exceptional.h"
#include <contrib/unzip/unzip.h>
#include <assimp/IOStream.hpp> #include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp> #include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp> #include <assimp/DefaultLogger.hpp>
@ -53,34 +54,28 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <map> #include <map>
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
#include <cstdlib>
#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER #include <contrib/unzip/unzip.h>
namespace Assimp { namespace Assimp {
namespace D3MF { namespace D3MF {
namespace XmlTag { namespace XmlTag {
static const std::string CONTENT_TYPES_ARCHIVE = "[Content_Types].xml";
const std::string CONTENT_TYPES_ARCHIVE = "[Content_Types].xml"; static const std::string ROOT_RELATIONSHIPS_ARCHIVE = "_rels/.rels";
const std::string ROOT_RELATIONSHIPS_ARCHIVE = "_rels/.rels"; static const std::string SCHEMA_CONTENTTYPES = "http://schemas.openxmlformats.org/package/2006/content-types";
const std::string SCHEMA_CONTENTTYPES = "http://schemas.openxmlformats.org/package/2006/content-types"; static const std::string SCHEMA_RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships";
const std::string SCHEMA_RELATIONSHIPS = "http://schemas.openxmlformats.org/package/2006/relationships"; static const std::string RELS_RELATIONSHIP_CONTAINER = "Relationships";
const std::string RELS_RELATIONSHIP_CONTAINER = "Relationships"; static const std::string RELS_RELATIONSHIP_NODE = "Relationship";
const std::string RELS_RELATIONSHIP_NODE = "Relationship"; static const std::string RELS_ATTRIB_TARGET = "Target";
const std::string RELS_ATTRIB_TARGET = "Target"; static const std::string RELS_ATTRIB_TYPE = "Type";
const std::string RELS_ATTRIB_TYPE = "Type"; static const std::string RELS_ATTRIB_ID = "Id";
const std::string RELS_ATTRIB_ID = "Id"; static const std::string PACKAGE_START_PART_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";
const std::string PACKAGE_START_PART_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"; static const std::string PACKAGE_PRINT_TICKET_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/printticket";
const std::string PACKAGE_PRINT_TICKET_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/printticket"; static const std::string PACKAGE_TEXTURE_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture";
const std::string PACKAGE_TEXTURE_RELATIONSHIP_TYPE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture"; static const std::string PACKAGE_CORE_PROPERTIES_RELATIONSHIP_TYPE = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties";
const std::string PACKAGE_CORE_PROPERTIES_RELATIONSHIP_TYPE = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"; static const std::string PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";
const std::string PACKAGE_THUMBNAIL_RELATIONSHIP_TYPE = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail";
} }
class IOSystem2Unzip { class IOSystem2Unzip {
@ -127,19 +122,19 @@ voidpf IOSystem2Unzip::open(voidpf opaque, const char* filename, int mode) {
uLong IOSystem2Unzip::read(voidpf /*opaque*/, voidpf stream, void* buf, uLong size) { uLong IOSystem2Unzip::read(voidpf /*opaque*/, voidpf stream, void* buf, uLong size) {
IOStream* io_stream = (IOStream*) stream; IOStream* io_stream = (IOStream*) stream;
return io_stream->Read(buf, 1, size); return static_cast<uLong>(io_stream->Read(buf, 1, size));
} }
uLong IOSystem2Unzip::write(voidpf /*opaque*/, voidpf stream, const void* buf, uLong size) { uLong IOSystem2Unzip::write(voidpf /*opaque*/, voidpf stream, const void* buf, uLong size) {
IOStream* io_stream = (IOStream*) stream; IOStream* io_stream = (IOStream*) stream;
return io_stream->Write(buf, 1, size); return static_cast<uLong>(io_stream->Write(buf, 1, size));
} }
long IOSystem2Unzip::tell(voidpf /*opaque*/, voidpf stream) { long IOSystem2Unzip::tell(voidpf /*opaque*/, voidpf stream) {
IOStream* io_stream = (IOStream*) stream; IOStream* io_stream = (IOStream*) stream;
return io_stream->Tell(); return static_cast<long>(io_stream->Tell());
} }
long IOSystem2Unzip::seek(voidpf /*opaque*/, voidpf stream, uLong offset, int origin) { long IOSystem2Unzip::seek(voidpf /*opaque*/, voidpf stream, uLong offset, int origin) {
@ -461,9 +456,8 @@ public:
ParseRootNode(xmlReader); ParseRootNode(xmlReader);
} }
} }
} }
void ParseRootNode(XmlReader* xmlReader) void ParseRootNode(XmlReader* xmlReader)
{ {
ParseAttributes(xmlReader); ParseAttributes(xmlReader);
@ -476,13 +470,13 @@ public:
ParseChildNode(xmlReader); ParseChildNode(xmlReader);
} }
} }
} }
void ParseAttributes(XmlReader*) void ParseAttributes(XmlReader*)
{ {
} }
void ParseChildNode(XmlReader* xmlReader) void ParseChildNode(XmlReader* xmlReader)
{ {
OpcPackageRelationshipPtr relPtr(new OpcPackageRelationship()); OpcPackageRelationshipPtr relPtr(new OpcPackageRelationship());
@ -494,26 +488,22 @@ public:
m_relationShips.push_back(relPtr); m_relationShips.push_back(relPtr);
} }
std::vector<OpcPackageRelationshipPtr> m_relationShips; std::vector<OpcPackageRelationshipPtr> m_relationShips;
}; };
// ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------
D3MFOpcPackage::D3MFOpcPackage(IOSystem* pIOHandler, const std::string& rFile) D3MFOpcPackage::D3MFOpcPackage(IOSystem* pIOHandler, const std::string& rFile)
: m_RootStream(nullptr) : m_RootStream(nullptr)
{ {
zipArchive.reset(new D3MF::D3MFZipArchive( pIOHandler, rFile )); zipArchive.reset(new D3MF::D3MFZipArchive( pIOHandler, rFile ));
if(!zipArchive->isOpen()) if(!zipArchive->isOpen()) {
throw DeadlyImportError("Failed to open file " + rFile+ "."); throw DeadlyImportError("Failed to open file " + rFile+ ".");
}
std::vector<std::string> fileList; std::vector<std::string> fileList;
zipArchive->getFileList(fileList); zipArchive->getFileList(fileList);
for(auto& file: fileList){ for(auto& file: fileList){
if(file == D3MF::XmlTag::ROOT_RELATIONSHIPS_ARCHIVE) {
if(file == D3MF::XmlTag::ROOT_RELATIONSHIPS_ARCHIVE)
{
//PkgRelationshipReader pkgRelReader(file, archive); //PkgRelationshipReader pkgRelReader(file, archive);
ai_assert(zipArchive->Exists(file.c_str())); ai_assert(zipArchive->Exists(file.c_str()));

View File

@ -2,7 +2,8 @@
Open Asset Import Library (assimp) Open Asset Import Library (assimp)
---------------------------------------------------------------------- ----------------------------------------------------------------------
Copyright (c) 2006-2016, assimp team Copyright (c) 2006-2017, assimp team
All rights reserved. All rights reserved.
Redistribution and use of this software in source and binary forms, Redistribution and use of this software in source and binary forms,
@ -41,7 +42,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef D3MFOPCPACKAGE_H #ifndef D3MFOPCPACKAGE_H
#define D3MFOPCPACKAGE_H #define D3MFOPCPACKAGE_H
#include <string>
#include <memory> #include <memory>
#include <assimp/IOSystem.hpp> #include <assimp/IOSystem.hpp>

Some files were not shown because too many files have changed in this diff Show More